> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # 從 `.network()` 遷移至 supervisor Agent 使用 `Agent.stream()` 與 `Agent.generate()` 的 supervisor Agent 是協調多個 Agent 的建議方式,並取代舊版 `.network()` API。本指南會逐步帶你完成遷移。 > **棄用 .network():** `.network()` 已棄用,並將在未來版本移除。在那之前,現有程式碼仍可繼續運作,但開發工作現在著重於 supervisor Agent。請儘快遷移至 supervisor Agent。 ## 使用 `.stream()` 或 `.generate()` 取代 `.network()` 核心變更是將 `.network()` 呼叫替換成 `.stream()`(串流)或 `.generate()`(非串流)。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(), }) ``` ## 為 subagent 新增描述 每個 subagent 都應有 `description` 欄位,說明其用途與傳回格式。描述也應指出使用 subagent 的時機。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) | ## 新增委派 hook Supervisor Agent 可讓你掛接委派生命週期,以監控、修改或拒絕委派。這些 hook 可在 Agent 的 `defaultOptions` 中設定,也可以在每次呼叫時傳入。 `onDelegationStart` 會在 supervisor 委派給 subagent 前呼叫。你可以修改提示詞或限制 subagent 的步數;hook 也可以完全拒絕委派: ```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.`, } } }, }, }) ``` ## 新增訊息篩選 依預設,subagent 會從 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 的意見回饋。這個 hook 也可以提前停止執行: ```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 的意見回饋會納入對話內容,讓 subagent 知道缺少哪些內容: ```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/zh-TW/docs/capabilities/subagents) - [Agent network](https://mastra.zisheng.pro/zh-TW/docs/agents/networks) - [Agent.stream() 參考文件](https://mastra.zisheng.pro/zh-TW/reference/streaming/agents/stream) - [Agent.generate() 參考文件](https://mastra.zisheng.pro/zh-TW/reference/agents/generate) - [Agent 核准](https://mastra.zisheng.pro/zh-TW/docs/agents/agent-approval) - [指南:研究協調工具](https://mastra.zisheng.pro/zh-TW/guides/guide/research-coordinator)