拓十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

VoltAgent 多智能体研究助手实战:用 Workflow Chain 与 MCP 构建类型安全的调研报告生成流程

VoltAgent 多智能体研究助手实战:用 Workflow Chain 与 MCP 构建类型安全的调研报告生成流程 人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆【免费下载链接】voltagentAI Agent Engineering Platform built on an Open Source TypeScript AI Agent Framework项目地址https://gitcode.com/gh_mirrors/vo/voltagent点击查看免费下载本文以仓库中的官方配方文档 research-assistant.md 与配套示例 with-research-assistant 为主体讲解如何用 VoltAgent 的 workflow 系统构建一个研究助手多智能体应用一个 Assistant Agent 负责生成多样化搜索查询一个 Writer Agent 负责基于 Exa通过 MCP 接入检索结果撰写带引用脚注的调研报告。读完本文你将掌握createWorkflowChain的链式编排、Zod 输入/输出 Schema 的类型安全数据流、getStepData()跨步骤取数以及通过MCPConfiguration将外部搜索工具注入 Agent 的完整工程方法并可对照 packages/core 的源码理解底层实现。一、研究助手整体架构该示例构建的是一个两阶段多智能体研究流水线接收一个研究主题topic作为输入由 Assistant Agent 生成用于深度检索的多样化搜索查询由 Writer Agent 综合研究素材撰写一份带脚注引用[#]与 References 列表的专业报告全程通过 Zod Schema 管理 Agent 间的数据流保证类型安全通过 MCPModel Context Protocol接入 Exa 搜索服务作为外部数据源。对应的示例仓库结构为examples/with-research-assistant/src/index.ts完整实现代码examples/with-research-assistant/package.json依赖与启动脚本examples/with-research-assistant/.env.example环境变量模板。二、项目搭建与运行环境2.1 创建项目使用官方脚手架基于该示例初始化项目npm create voltagent-applatest -- --example with-research-assistant cd my-agent-app示例的 package.json 中核心依赖包括voltagent/core^2.9.2Agent、Workflow、MCP 编排能力voltagent/server-hono^2.0.14HTTP 服务voltagent/logger^2.0.2Pino 日志voltagent/libsql^2.1.2本地存储zod^3.25.76运行时校验开发脚本dev为tsx watch --env-file.env ./src即由 tsx 热加载并自动注入.env。2.2 配置环境变量需要准备两个 API KeyOpenAI 与 ExaExa 提供研究搜索 API注册后在其控制台获取密钥。创建.env文件OPENAI_API_KEYyour-openai-api-key EXA_API_KEYyour-exa-api-key这与仓库中的 .env.example 保持一致。前置条件为 Node.js推荐 v18与 npm/pnpm。2.3 启动开发服务器npm run dev服务器成功启动后终端将输出════════════════════════════════════════════ VOLTAGENT SERVER STARTED SUCCESSFULLY ════════════════════════════════════════════ ✓ HTTP Server: http://localhost:3141 VoltOps Platform: https://console.voltagent.dev ════════════════════════════════════════════ [VoltAgent] All packages are up to date随后 VoltOps 平台会在浏览器中自动打开用于与 Agent/Workflow 交互、查看执行轨迹与调试。三、完整实现代码下面是配方文档给出的完整实现后续将逐步拆解import { openai } from ai-sdk/openai; import { Agent, MCPConfiguration, VoltAgent, createWorkflowChain } from voltagent/core; import { createPinoLogger } from voltagent/logger; import { z } from zod; (async () { const mcpConfig new MCPConfiguration({ servers: { exa: { type: stdio, command: npx, args: [-y, mcp-remote, https://mcp.exa.ai/mcp?exaApiKey${process.env.EXA_API_KEY}], }, }, }); const assistantAgent new Agent({ id: assistant, name: Assistant, instructions: The user will ask you to help generate some search queries. Respond with only the suggested queries in plain text with no extra formatting, each on its own line. Use exa tools., model: openai(gpt-4o-mini), tools: await mcpConfig.getTools(), }); const writerAgent new Agent({ id: writer, name: Writer, instructions: Write a report according to the users instructions., model: openai(gpt-4o), tools: await mcpConfig.getTools(), markdown: true, maxSteps: 50, }); // Define the workflows shape: its inputs and final output const workflow createWorkflowChain({ id: research-assistant, name: Research Assistant Workflow, // A detailed description for VoltOps or team clarity purpose: A simple workflow to assist with research on a given topic., input: z.object({ topic: z.string() }), result: z.object({ text: z.string() }), }) .andThen({ id: research, execute: async ({ data }) { const { topic } data; const result await assistantAgent.generateText( Im writing a research report on ${topic} and need help coming up with diverse search queries. Please generate a list of 3 search queries that would be useful for writing a research report on ${topic}. These queries can be in various formats, from simple keywords to more complex phrases. Do not add any formatting or numbering to the queries., { provider: { temperature: 1 } } ); return { text: result.text }; }, }) .andThen({ id: writing, execute: async ({ data, getStepData }) { const { text } data; const stepData getStepData(research); const result await writerAgent.generateText( Input Data: ${text} Write a two paragraph research report about ${stepData?.input} based on the provided information. Include as many sources as possible. Provide citations in the text using footnote notation ([#]). First provide the report, followed by a single References section that lists all the URLs used, in the format [#] url. ); return { text: result.text }; }, }); // Create logger const logger createPinoLogger({ name: with-mcp, level: info, }); // Register with VoltOps new VoltAgent({ agents: { assistant: assistantAgent, writer: writerAgent, }, workflows: { assistant: workflow, }, logger, }); })();版本说明当前仓库的示例实现 src/index.ts 与上述代码高度一致有两处细节差异值得注意其一模型以字符串形式书写model: openai/gpt-4o-mini与ai-sdk/openai的openai(...)写法等价其二当前版本在new VoltAgent({...})中显式传入server: honoServer()来自voltagent/server-hono见 index.ts 第 91 行。按当前仓库代码为准即可。四、分步解析4.1 配置 MCP 接入 Exa 搜索const mcpConfig new MCPConfiguration({ servers: { exa: { type: stdio, command: npx, args: [-y, mcp-remote, https://mcp.exa.ai/mcp?exaApiKey${process.env.EXA_API_KEY}], }, }, });这段配置的作用创建一个 MCP 配置连接 Exa 的研究搜索 API使用stdio类型即通过npx -y mcp-remote拉起一个本地子进程再以标准输入/输出与远程 Exa MCP 服务通信Exa API Key 从环境变量EXA_API_KEY注入 URL 查询参数避免硬编码调用await mcpConfig.getTools()后Exa 的搜索能力即被转换为 VoltAgent 工具列表供 Agent 使用。从源码看MCPConfiguration定义在 packages/core/src/mcp/registry/index.ts其getTools(authContext?)方法见该文件 第 101 行负责从已注册的 MCP Server 拉取工具并返回Toolany[]这正是Agent的tools字段所接受的类型。4.2 创建 Assistant研究助手Agentconst assistantAgent new Agent({ id: assistant, name: Assistant, instructions: The user will ask you to help generate some search queries. Respond with only the suggested queries in plain text with no extra formatting, each on its own line. Use exa tools., model: openai(gpt-4o-mini), tools: await mcpConfig.getTools(), });关键配置项idAgent 的唯一标识也是后续在VoltAgent中注册与观测时的键instructions约束输出格式——纯文本、每条查询独占一行、无编号与多余格式并提示使用 exa 工具降低模型自由发挥的概率model选用gpt-4o-mini承担查询生成这类轻量任务控制成本tools继承 MCP 配置的全部工具Exa 搜索能力。4.3 创建 Writer写作Agentconst writerAgent new Agent({ id: writer, name: Writer, instructions: Write a report according to the users instructions., model: openai(gpt-4o), tools: await mcpConfig.getTools(), markdown: true, maxSteps: 50, });设计取舍使用更强的gpt-4o模型保证成文质量——写作是对质量敏感的任务与查询生成对成本敏感分而治之markdown: true开启 Markdown 输出格式化报告天然具备标题、列表等结构maxSteps: 50允许 Agent 在 agentic 循环中执行较多轮工具调用与推理例如多轮检索、补漏支撑复杂的多步研究写作同样挂载 MCP 工具写作阶段若发现素材不足仍可主动追加检索。4.4 定义 Workflow 结构与 Schemaconst workflow createWorkflowChain({ id: research-assistant, name: Research Assistant Workflow, purpose: A simple workflow to assist with research on a given topic., input: z.object({ topic: z.string() }), result: z.object({ text: z.string() }), });Schema 定义input工作流输入为包含topic字符串的对象result最终输出为包含text字符串的对象使用 Zod 做运行时类型校验同时推导 TypeScript 类型IDE 中有完整补全。purpose字段面向 VoltOps 平台与团队成员提供可读的用途说明便于在控制台识别工作流。从源码看createWorkflowChain的导出位于 packages/core/src/workflow/chain.ts 第 1089 行它接受INPUT_SCHEMA、RESULT_SCHEMA等泛型约束返回WorkflowChain实例链上每一步都会把数据流类型从当前步输出推进到下一步输入这正是整条链保持端到端类型推断的原因。4.5 第一步生成搜索查询research.andThen({ id: research, execute: async ({ data }) { const { topic } data; const result await assistantAgent.generateText( Im writing a research report on ${topic} and need help coming up with diverse search queries. Please generate a list of 3 search queries that would be useful for writing a research report on ${topic}. These queries can be in various formats, from simple keywords to more complex phrases. Do not add any formatting or numbering to the queries., { provider: { temperature: 1 } } ); return { text: result.text }; }, })工作流程data即工作流输入解构出topic调用 Assistant Agent 生成 3 条多样化搜索查询temperature设为 1 以获得更高多样性以{ text: result.text }返回该返回值自动成为下一步的data。4.6 第二步撰写报告writing.andThen({ id: writing, execute: async ({ data, getStepData }) { const { text } data; const stepData getStepData(research); const result await writerAgent.generateText( Input Data: ${text} Write a two paragraph research report about ${stepData?.input} based on the provided information. Include as many sources as possible. Provide citations in the text using footnote notation ([#]). First provide the report, followed by a single References section that lists all the URLs used, in the format [#] url. ); return { text: result.text }; }, })进阶能力点data包含上一步research的输出即搜索查询文本getStepData(research)按步骤 id 访问任意历史步骤的数据。注意此处访问的是stepData?.input——该步骤的输入侧数据包含原始topic而非仅输出。这样写作提示词中可以同时拿到查询素材text 原始主题topic提示词强制要求脚注引用[#]与文末 References 列表[#] url格式保证报告可溯源返回最终报告文本类型由工作流的resultSchema{ text: z.string() }约束。从源码看andThen的执行上下文在 chain.ts 第 406 行 的函数签名中定义除data与getStepData外还暴露state、workflowState、setWorkflowState、suspend/resumeData、retries、logger、writer等成员——也就是说同一套链式 API 还支持工作流状态持久化、暂停/恢复与重试等更复杂的能力本示例只用了其中最基础的部分。4.7 注册到 VoltAgent接入 VoltOpsconst logger createPinoLogger({ name: with-mcp, level: info, }); new VoltAgent({ agents: { assistant: assistantAgent, writer: writerAgent, }, workflows: { assistant: workflow, }, logger, });注册后的收益Agent 与 Workflow 在 VoltOps Console 中可见、可交互每次运行生成执行轨迹trace支持实时监控与调试Workflow 可通过 REST API 触发。五、运行工作流与交互方式一切就绪后可在 VoltOps Console 中直接操作名为Research Assistant Workflow的工作流输入研究主题。推荐尝试的提示来自配方文档Research the latest developments in quantum computingAnalyze the impact of AI on healthcare in 2024Investigate sustainable energy storage solutionsREADME 中还补充了一个Future of remote work technologies。执行时工作流依次完成生成相关搜索查询 → 基于查询检索信息经 MCP/Exa 工具→ 综合成文产出带引用与 References 的完整报告。六、核心概念小结6.1 Workflow 链式编排Chaining.andThen()构建顺序执行的链每一步的输出成为下一步的输入。从 chain.ts 的签名可以看到每个andThen返回一条新的WorkflowChainNEW_DATA泛型替换当前数据类型从而在编译期锁定数据流形状同时保留运行期的 Zod 校验。6.2 Zod 类型安全流经工作流的每份数据都会对照 Zod Schema 校验错误在运行早期被捕获且 TypeScript 获得完整的类型推导与补全体验。input/result/ 各步骤输入输出三者共同构成一条可验证的数据契约。6.3 步骤上下文访问getStepData(stepId)允许访问任意前序步骤而非仅直接上一步的数据包括该步骤的输入与输出使第 N 步引用第 1 步的原始主题这类跨步依赖可以用干净的代码表达。6.4 多 Agent 协作的收益按任务拆分 Agent研究 vs. 写作之后可以为每个任务选择最合适的模型成本/质量权衡本例即gpt-4o-minigpt-4o可以为每个角色提供专门化的 instructions工作流各部分可独立扩展与替换。七、下一步扩展方向配方文档给出的演进路径均对应框架已有能力可结合 chain.ts 中的 API 签名进一步确认增强 Agent加入更复杂的 instructions 或额外工具扩展工作流追加事实核查fact-checking、排版、翻译等步骤条件分支使用.andWhen()实现条件路由并行处理使用.andAll()同时执行多条研究查询错误处理利用步骤配置中的retrieschain.ts 第 422 行 可见retries?: number字段实现重试与回退策略。八、参考路径索引配方文档website/recipes/research-assistant.md示例源码examples/with-research-assistant/src/index.ts示例说明与运行步骤examples/with-research-assistant/README.md依赖与脚本examples/with-research-assistant/package.json环境变量模板examples/with-research-assistant/.env.example工作流链实现packages/core/src/workflow/chain.tsMCP 配置与工具拉取packages/core/src/mcp/registry/index.ts赞分享人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆【免费下载链接】voltagentAI Agent Engineering Platform built on an Open Source TypeScript AI Agent Framework项目地址https://gitcode.com/gh_mirrors/vo/voltagent点击查看免费下载相关推荐使用 VoltAgent 构建多智能体研究助手Workflow Chain 与 Exa MCP 集成实战使用 VoltAgent 构建多智能体研究助手Workflow Chain 与 Exa MCP 集成实战 VoltAgent 是一个开源的 TypeScrip人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆Agent 工作流AI 评测MCP 服务MCP Clients语音AI Agent 框架调研报告hello-agents 第十章多智能体 MCP 协作生成实战AI Agent 框架调研报告hello agents 第十章多智能体 MCP 协作生成实战 本篇以 hello agents 仓库第十章产出的《AI Age教程人工智能大模型AI AgentDeep Search 全栈研究 Agent 实战基于 ADK 构建带人工审核与内联引用的多智能体研究流程Deep Search 全栈研究 Agent 实战基于 ADK 构建带人工审核与内联引用的多智能体研究流程 导读 本文以仓库 core/python/deep示例工程上一篇LTX-Video技术解析从文本到电影级视频的300%质量提升指南下一篇CANN/driver设备芯片信息API创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表