メインコンテンツへ移動

Agent network

非推奨

Agent network は非推奨であり、今後のメジャーリリースで削除されます。現在は agent.stream() または agent.generate() を使用する Supervisor Agent が推奨されます。同じマルチ Agent 連携を、より優れた制御、シンプルな API、容易なデバッグで実現できます。

移行方法は移行ガイドを参照してください。

ルーティング Agent は LLM でリクエストを解釈し、呼び出すプリミティブ(サブ Agent、Workflow、Tool)、順序、渡すデータを判断します。

Agent network を作成する
Agent network を作成するへの直接リンク

ルーティング Agent に agentsworkflowstools を設定します。.network() はタスク履歴の保存と完了判定に Memory を使用するため、Memory が必要です。

ルーティング Agent が使用対象を判断できるよう、各プリミティブには明確な description が必要です。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 を呼び出す
network を呼び出すへの直接リンク

ユーザーメッセージを指定して .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() を使用します。

network の承認では、実行状態を保存するためにスナップショットを使用します。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)
}
}

自動再開
自動再開への直接リンク

autoResumeSuspendedToolstrue に設定すると、network はユーザーの次のメッセージに基づいて一時停止中のプリミティブを再開します。ユーザーが必要な情報を自然に提供できる会話フローになります。

const stream = await routingAgent.network('Delete the old records', {
autoResumeSuspendedTools: true,
memory: { thread: 'user-123', resource: 'my-app' },
})

自動再開の要件は次のとおりです。

  • Memory の設定:メッセージ間で一時停止中の Tool を追跡するため、Agent に Memory が必要です。
  • 同じスレッド:後続メッセージでは同じ threadresource 識別子を使用する必要があります。
  • resumeSchema の定義:network がユーザーのメッセージからデータを抽出できるよう、Tool に resumeSchema を定義する必要があります。
手動(resumeNetwork自動(autoResumeSuspendedTools
最適な用途承認ボタンを備えたカスタム UIチャット形式のインターフェース
制御再開のタイミングとデータを完全に制御network がユーザーのメッセージからデータを抽出
設定一時停止チャンクを処理し、resumeNetwork を呼び出すフラグを設定し、Tool に resumeSchema を定義