跳至主要內容

Agent 網路

已棄用

Agent 網路已棄用,並將在未來的主要版本中移除。目前建議改用透過 agent.stream()agent.generate() 運作的 Supervisor Agent。它提供相同的多 Agent 協調能力,同時具備更完善的控制、更簡單的 API,也更容易偵錯。

請參閱遷移指南進行升級。

路由 Agent 使用 LLM 解讀請求,並決定要以何種順序、使用哪些資料來呼叫哪些基本元件(子 Agent、Workflow 或 Tool)。

建立 Agent 網路
「建立 Agent 網路」的直接連結

使用 agentsworkflowstools 設定路由 Agent。由於 .network() 會使用記憶來儲存任務歷程,並判斷任務何時完成,因此必須設定記憶。

每個基本元件都需要清楚的 description,路由 Agent 才能決定要使用哪一個。對 Workflow 與 Tool 而言,inputSchemaoutputSchema 也有助於路由器判斷正確的輸入。

src/mastra/agents/routing-agent.ts
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() 中提供 descriptioninputSchemaoutputSchema

呼叫網路
「呼叫網路」的直接連結

使用使用者訊息呼叫 .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-approvaltool-execution-approval 區塊。使用 approveNetworkToolCall()declineNetworkToolCall() 回應。

網路核准功能使用快照擷取執行狀態。請確保 Mastra 執行個體已啟用儲存 Provider

src/approve-network.ts
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() 提供所需資料並繼續執行。

src/resume-network.ts
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。
  • 相同討論串:後續訊息必須使用相同的 threadresource 識別碼。
  • 已定義 resumeSchema:Tool 必須定義 resumeSchema,網路才能從使用者訊息中擷取資料。
手動(resumeNetwork自動(autoResumeSuspendedTools
最適合具有核准按鈕的自訂 UI聊天式介面
控制完整控制繼續執行的時機與資料網路從使用者訊息擷取資料
設定處理暫停區塊、呼叫 resumeNetwork設定旗標,並在 Tool 上定義 resumeSchema