Agent 網絡
Agent 網絡已棄用,並將於未來的主要版本中移除。目前建議改用透過 agent.stream() 或 agent.generate() 運作的 Supervisor Agent。它能提供相同的多 Agent 協調功能,同時具備更完善的控制、更簡潔的 API,亦更容易除錯。
請參閱遷移指南進行升級。
路由 Agent 會使用 LLM 解讀請求,並決定要呼叫哪些基本單元(子 Agent、Workflow 或 Tool)、呼叫次序,以及要傳入的資料。
建立 Agent 網絡建立 Agent 網絡 的直接連結
使用 agents、workflows 和 tools 設定路由 Agent。由於 .network() 會使用記憶體儲存任務歷史記錄,並判斷任務何時完成,因此必須設定記憶體。
每個基本單元都需要清晰的 description,讓路由 Agent 可以決定應使用哪一個。對於 Workflow 和 Tool,inputSchema 和 outputSchema 亦有助路由器判斷正確的輸入。
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { LibSQLStore } from '@mastra/libsql'
import { researchAgent } from './research-agent'
import { writingAgent } from './writing-agent'
import { cityWorkflow } from '../workflows/city-workflow'
import { weatherTool } from '../tools/weather-tool'
export const routingAgent = new Agent({
id: 'routing-agent',
name: 'Routing Agent',
instructions: `
You are a network of writers and researchers. The user will ask you to research a topic. Always respond with a complete report—no bullet points. Write in full paragraphs, like a blog post. Do not answer with incomplete or uncertain information.`,
model: 'openai/gpt-5.6-sol',
agents: {
researchAgent,
writingAgent,
},
workflows: {
cityWorkflow,
},
tools: {
weatherTool,
},
memory: new Memory({
storage: new LibSQLStore({
id: 'mastra-storage',
url: 'file:../mastra.db',
}),
}),
})
子 Agent 的 Agent 實例需要有 description。Workflow 和 Tool 則需要在 createWorkflow() 或 createTool() 中設定 description,以及 inputSchema 和 outputSchema。
呼叫網絡呼叫網絡 的直接連結
以使用者訊息呼叫 .network()。此方法會傳回可供反覆運算的事件串流。
const result = await routingAgent.network('Tell me three cool ways to use Mastra')
for await (const chunk of result) {
console.log(chunk.type)
if (chunk.type === 'network-execution-event-step-finish') {
console.log(chunk.payload.result)
}
}
結構化輸出結構化輸出 的直接連結
傳入 structuredOutput 以取得具備型別並經過驗證的結果。在產生結果期間,可使用 objectStream 取得部分物件。
import { z } from 'zod'
const resultSchema = z.object({
summary: z.string().describe('A brief summary of the findings'),
recommendations: z.array(z.string()).describe('List of recommendations'),
confidence: z.number().min(0).max(1).describe('Confidence score'),
})
const stream = await routingAgent.network('Research AI trends', {
structuredOutput: { schema: resultSchema },
})
for await (const partial of stream.objectStream) {
console.log('Building result:', partial)
}
const final = await stream.object
console.log(final?.summary)
核准及拒絕 Tool 呼叫核准及拒絕 Tool 呼叫 的直接連結
當基本單元需要核准時,串流會發出 agent-execution-approval 或 tool-execution-approval 區塊。使用 approveNetworkToolCall() 或 declineNetworkToolCall() 作出回應。
網絡核准會使用快照擷取執行狀態。請確保你的 Mastra 實例已啟用儲存 Provider。
const stream = await routingAgent.network('Perform some sensitive action', {
memory: {
thread: 'user-123',
resource: 'my-app',
},
})
for await (const chunk of stream) {
if (chunk.type === 'agent-execution-approval' || chunk.type === 'tool-execution-approval') {
// Approve
const approvedStream = await routingAgent.approveNetworkToolCall(chunk.payload.toolCallId, {
runId: stream.runId,
memory: { thread: 'user-123', resource: 'my-app' },
})
for await (const c of approvedStream) {
if (c.type === 'network-execution-event-step-finish') {
console.log(c.payload.result)
}
}
}
}
如要拒絕,請改為使用相同的引數呼叫 declineNetworkToolCall()。
暫停及恢復暫停及恢復 的直接連結
當基本單元呼叫 suspend() 時,串流會發出暫停區塊(例如 tool-execution-suspended)。使用 resumeNetwork() 提供所需資料並繼續執行。
const stream = await routingAgent.network('Delete the old records', {
memory: { thread: 'user-123', resource: 'my-app' },
})
for await (const chunk of stream) {
if (chunk.type === 'workflow-execution-suspended') {
console.log(chunk.payload.suspendPayload)
}
}
// Resume with user confirmation
const resumedStream = await routingAgent.resumeNetwork(
{ confirmed: true },
{
runId: stream.runId,
memory: { thread: 'user-123', resource: 'my-app' },
},
)
for await (const chunk of resumedStream) {
if (chunk.type === 'network-execution-event-step-finish') {
console.log(chunk.payload.result)
}
}
自動恢復自動恢復 的直接連結
將 autoResumeSuspendedTools 設為 true,網絡便會根據使用者的下一則訊息恢復已暫停的基本單元。這會建立對話式流程,讓使用者能夠自然地提供所需資料。
const stream = await routingAgent.network('Delete the old records', {
autoResumeSuspendedTools: true,
memory: { thread: 'user-123', resource: 'my-app' },
})
自動恢復的要求:
- 已設定記憶體:Agent 需要記憶體,以跨訊息追蹤已暫停的 Tool。
- 相同對話串:後續訊息必須使用相同的
thread和resource識別碼。 - 已定義
resumeSchema:Tool 必須定義resumeSchema,讓網絡可以從使用者的訊息中擷取資料。
手動(resumeNetwork) | 自動(autoResumeSuspendedTools) | |
|---|---|---|
| 最適合 | 設有核准按鈕的自訂 UI | 聊天式介面 |
| 控制 | 完全控制恢復時間及資料 | 網絡從使用者的訊息中擷取資料 |
| 設定 | 處理暫停區塊,呼叫 resumeNetwork | 設定旗標,並在 Tool 上定義 resumeSchema |