> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 从 `.network()` 迁移到 supervisor Agent 使用 `Agent.stream()` 和 `Agent.generate()` 的 supervisor Agent 是协调多个 Agent 的推荐方式,可替代旧版 `.network()` API。本指南将带你完成迁移的每个步骤。 > **.network() 已弃用:** `.network()` 已弃用,并将在未来版本中移除。在此之前,现有代码仍可继续运行,但后续开发重点现已转向 supervisor Agent。请尽快迁移。 ## 用 `.stream()` 或 `.generate()` 替换 `.network()` 核心变更是用 `.stream()`(流式)或 `.generate()`(非流式)替换 `.network()` 调用。Agent 配置保持不变,仍需在 Agent 上定义 `agents`、`workflows`、`tools` 和 `memory`。变化的是调用方式和结果处理方式。 使用 `.network()` 时,你会遍历 `network-execution-event-step-finish` 等自定义事件类型。使用 `.stream()` 时,则使用标准的 `textStream` 或 `fullStream` 迭代器。 **迁移前:** ```typescript const result = await routingAgent.network('Research AI in education') for await (const chunk of result) { if (chunk.type === 'network-execution-event-step-finish') { console.log(chunk.payload.result) } } ``` **迁移后:** ```typescript const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` `maxSteps` 选项限制 supervisor 可进行的迭代次数,替代 `.network()` 中的隐式迭代限制。 对于非流式用例,请使用具有相同选项的 `generate()`: ```typescript const result = await supervisorAgent.generate('Research AI in education', { maxSteps: 10, }) console.log(result.text) ``` ## 编写清晰的 supervisor 指令 使用 `.network()` 时,路由 Agent 依靠通用指令和原语描述来决定调用内容。supervisor Agent 的工作方式相同,但清晰具体的指令可提高委派准确性。 supervisor 的 `instructions` 应列明可用资源及各资源的使用时机,还应说明如何协调这些资源以及如何判断任务已经完成。 **迁移前:** ```typescript const routingAgent = new Agent({ id: 'routing-agent', instructions: 'You are a network of researchers and writers...', agents: { researchAgent, writingAgent }, memory: new Memory(), }) ``` **迁移后:** ```typescript const supervisorAgent = new Agent({ id: 'supervisor-agent', instructions: `You coordinate research and writing tasks using specialized agents. Available resources: - researchAgent: Gathers factual data and sources (returns bullet points) - writingAgent: Transforms research into narrative content (returns full paragraphs) Delegation strategy: 1. For research requests: Delegate to researchAgent first 2. For writing requests: Delegate to writingAgent (provide research if available) 3. For complex requests: Delegate to researchAgent first, then writingAgent Success criteria: - All user questions are fully answered - Response is well-formatted and complete - If information is incomplete, continue iterating`, agents: { researchAgent, writingAgent }, memory: new Memory(), }) ``` ## 为子 Agent 添加描述 每个子 Agent 都应提供 `description` 字段,用于说明其用途和返回格式。描述还应说明何时使用该子 Agent。supervisor 会根据这些描述决定将任务委派给哪个 Agent。 ```typescript const researchAgent = new Agent({ id: 'research-agent', description: `Specializes in gathering factual information and data on any topic. Returns concise bullet-point summaries with key facts and sources. Does not write full articles or narrative content.`, }) const writingAgent = new Agent({ id: 'writing-agent', description: `Transforms research material into well-structured written content. Produces full paragraphs and complete articles. Best used after research has been gathered.`, }) ``` ## 更新事件处理 如果之前处理特定的 `.network()` 事件,请将其更新为使用标准流式数据块类型: | `.network()` 事件 | supervisor Agent 数据块 | | ------------------------------------- | -------------------------------------- | | `routing-agent-start` | `step-start` | | `routing-agent-end` | `step-finish` | | `agent-execution-start` | `step-start`(委派时) | | `agent-execution-event-text-delta` | `text-delta` | | `agent-execution-event-finish` | `step-finish` | | `network-execution-event-step-finish` | `step-finish` + `finishReason: 'stop'` | | `network-object` | `object-delta`(使用 structuredOutput) | | `network-object-result` | `object`(使用 structuredOutput) | ## 添加委派钩子 supervisor Agent 允许你接入委派生命周期,以监控、修改或拒绝委派。这些钩子可以在 Agent 的 `defaultOptions` 中配置,也可以在每次调用时传入。 `onDelegationStart` 会在 supervisor 向子 Agent 委派任务前调用。你可以修改提示词或限制子 Agent 的步骤数,该钩子也可以完全拒绝委派: ```typescript const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, delegation: { onDelegationStart: async context => { console.log(`Delegating to: ${context.primitiveId}`) if (context.primitiveId === 'research-agent') { return { proceed: true, modifiedPrompt: `${context.prompt}\n\nFocus on 2024-2025 data.`, modifiedMaxSteps: 5, } } if (context.iteration > 8) { return { proceed: false, rejectionReason: 'Max iterations reached. Synthesize current findings.', } } return { proceed: true } }, }, }) ``` `onDelegationComplete` 会在委派完成后调用。请检查结果,并在应停止 supervisor 循环时调用 `context.bail()`。你还可以返回将保存到 supervisor Memory 的反馈: ```typescript const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, delegation: { onDelegationComplete: async context => { if (context.error) { context.bail() // Stop further delegations return { feedback: `Delegation to ${context.primitiveId} failed: ${context.error}. Try a different approach.`, } } }, }, }) ``` ## 添加消息过滤 默认情况下,子 Agent 会从 supervisor 接收完整的对话上下文。使用 `messageFilter` 可控制共享哪些消息,例如移除敏感数据或限制消息数量: ```typescript const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, delegation: { messageFilter: ({ messages, primitiveId, prompt }) => { return messages .filter(msg => { const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) return !content.includes('confidential') }) .slice(-10) }, }, }) ``` ## 添加迭代监控 `onIterationComplete` 会在 supervisor 循环的每次迭代后调用。可用它记录进度或提供反馈以引导 Agent。该钩子也可以提前停止执行: ```typescript const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, onIterationComplete: async context => { console.log(`Iteration ${context.iteration}/${context.maxIterations}`) if (!context.text.includes('recommendations')) { return { continue: true, feedback: 'Please include specific recommendations in your analysis.', } } if (context.text.length > 1000 && context.finishReason === 'stop') { return { continue: false } } return { continue: true } }, }) ``` ## 添加任务完成度评分 任务完成度 scorer 会自动验证任务是否完成。如果验证失败,supervisor 会继续迭代。未通过 scorer 的反馈会加入对话上下文,使子 Agent 能够了解缺少了什么: ```typescript import { createScorer } from '@mastra/core/evals' const taskCompleteScorer = createScorer({ id: 'task-complete', name: 'Task Completeness', }).generateScore(async context => { const text = (context.run.output || '').toString() const hasAnalysis = text.includes('analysis') const hasRecommendations = text.includes('recommendation') return hasAnalysis && hasRecommendations ? 1 : 0 }) const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, isTaskComplete: { scorers: [taskCompleteScorer], strategy: 'all', onComplete: async result => { console.log('Task complete:', result.complete) }, }, }) ``` ## 另请参阅 - [supervisor Agent](https://mastra.zisheng.pro/docs/capabilities/subagents) - [Agent 网络](https://mastra.zisheng.pro/docs/agents/networks) - [Agent.stream() 参考](https://mastra.zisheng.pro/reference/streaming/agents/stream) - [Agent.generate() 参考](https://mastra.zisheng.pro/reference/agents/generate) - [Agent 审批](https://mastra.zisheng.pro/docs/agents/agent-approval) - [指南:研究协调器](https://mastra.zisheng.pro/guides/guide/research-coordinator)