從 .network() 遷移至 supervisor Agent
使用 Agent.stream() 及 Agent.generate() 的 supervisor Agent 是協調多個 Agent 的建議方式,並取代較舊的 .network() API。本指南會帶你完成遷移的每個步驟。
.network() 已棄用,並會在日後版本移除。在此之前,現有程式碼仍可繼續運作,但開發重點現已轉向 supervisor Agent。請盡快遷移至 supervisor Agent。
以 .stream() 或 .generate() 取代 .network()replace-network-with-stream-or-generate 的直接連結
核心變更是以 .stream()(串流)或 .generate()(非串流)取代 .network() 呼叫。Agent 設定維持不變,你仍會在 Agent 上定義 agents、workflows、tools 及 memory。差別在於呼叫方式及處理結果的方式。
使用 .network() 時,你會反覆處理 network-execution-event-step-finish 等自訂事件類型。使用 .stream() 時,則會使用標準 textStream 或 fullStream 迭代器。
遷移前:
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)
}
}
遷移後:
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(),並傳入相同選項:
const result = await supervisorAgent.generate('Research AI in education', {
maxSteps: 10,
})
console.log(result.text)
撰寫清晰的 supervisor 指示撰寫清晰的 supervisor 指示 的直接連結
使用 .network() 時,routing Agent 依靠一般指示及基本元件描述,決定要呼叫甚麼。supervisor Agent 的運作方式相同,但清晰具體的指示可提高委派準確度。
supervisor 的 instructions 應列明可用資源及各資源的使用時機,也應說明如何協調這些資源,以及如何判斷工作已完成。
遷移前:
const routingAgent = new Agent({
id: 'routing-agent',
instructions: 'You are a network of researchers and writers...',
agents: { researchAgent, writingAgent },
memory: new Memory(),
})
遷移後:
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 加入描述 的直接連結
每個 subagent 都應有 description 欄位,說明其用途及傳回格式。描述也應列明何時使用該 subagent。supervisor 會根據這些描述,決定將工作委派給哪個 Agent。
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加入委派 hook 的直接連結
supervisor Agent 讓你接入委派生命週期,以監察、修改或拒絕委派。這些 hook 可在 Agent 的 defaultOptions 中設定,亦可在每次呼叫時傳入。
onDelegationStart 會在 supervisor 委派給 subagent 前呼叫。你可以修改提示或限制 subagent 的步驟數目,hook 亦可完全拒絕委派:
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 的記憶體:
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 控制分享哪些訊息,例如移除敏感資料或限制訊息數目:
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 亦可提早停止執行:
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 了解遺漏了甚麼:
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)
},
},
})