> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # Agent.network() `.network()` メソッドは、複数 Agent の連携とルーティングを可能にします。このメソッドは Message と、省略可能な実行オプションを受け取ります。 > **非推奨:** `.network()` Primitive は非推奨となり、将来のメジャーリリースで削除される予定です。代わりに、`agent.stream()` または `agent.generate()` とともに [Supervisor Agent](https://mastra.zisheng.pro/ja/docs/capabilities/subagents) を使用してください。移行方法については、[移行ガイド](https://mastra.zisheng.pro/ja/guides/migrations/network-to-supervisor)を参照してください。 ## 使用例 ```typescript import { Agent } from '@mastra/core/agent' import { agent1, agent2 } from './agents' import { workflow1 } from './workflows' import { tool1, tool2 } from './tools' const agent = new Agent({ id: 'network-agent', name: 'Network Agent', instructions: 'You are a network agent that can help users with a variety of tasks.', model: 'openai/gpt-5.6-sol', agents: { agent1, agent2, }, workflows: { workflow1, }, tools: { tool1, tool2, }, }) await agent.network(` Find me the weather in Tokyo. Based on the weather, plan an activity for me. `) ``` ## パラメーター **messages** (`string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]`): Agent に送信する Message。単一の文字列、文字列の配列、または構造化された Message オブジェクトを指定できます。 **options** (`MultiPrimitiveExecutionOptions`): Network プロセスの省略可能な設定。 **options.maxSteps** (`number`): 実行中の最大 Step 数。 **options.abortSignal** (`AbortSignal`): Network の実行を中止する Signal。中止すると、Network はルーティングを停止し、実行中の Subagent、Tool、Workflow をすべてキャンセルして、途中結果を Memory に保存しません。 **options.onAbort** (`(event: { primitiveType: string; primitiveId: string; iteration: number }) => void | Promise`): Network が中止されたときに呼び出される Callback。中止時に実行されていた Primitive の種類と ID を含むイベントを受け取ります。 **options.memory** (`object`): Memory の設定。Memory の管理にはこの方法を推奨します。 **options.memory.thread** (`string | { id: string; metadata?: Record, title?: string }`): Conversation Thread。文字列 ID、または id と省略可能な metadata を含むオブジェクトとして指定します。 **options.memory.resource** (`string`): Thread に関連付けられたユーザーまたは Resource の識別子。 **options.memory.options** (`MemoryConfig`): Message History や Semantic Recall など、Memory の動作に関する設定。 **options.tracingContext** (`TracingContext`): Child Span の作成とメタデータの追加に使用する Tracing Context。Mastra の Tracing システムを使用すると自動的に注入されます。 **options.tracingContext.currentSpan** (`Span`): Child Span の作成とメタデータの追加に使用する現在の Span。実行中に独自の Child Span を作成したり、Span 属性を更新したりする場合に使用します。 **options.tracingOptions** (`TracingOptions`): Tracing 設定のオプション。 **options.tracingOptions.metadata** (`Record`): Root Trace Span に追加するメタデータ。ユーザー ID、Session ID、Feature Flag などのカスタム属性を追加する場合に役立ちます。 **options.tracingOptions.requestContextKeys** (`string[]`): この Trace のメタデータとして抽出する追加の RequestContext Key。ネストされた値には Dot Notation(例:'user.id')を使用できます。 **options.tracingOptions.traceId** (`string`): この実行で使用する Trace ID(1〜32文字の16進数)。指定すると、この Trace は指定した Trace の一部になります。 **options.tracingOptions.parentSpanId** (`string`): この実行で使用する Parent Span ID(1〜16文字の16進数)。指定すると、Root Span はこの Span の Child として作成されます。 **options.tracingOptions.tags** (`string[]`): この Trace に適用する Tag。Trace の分類と絞り込みに使用する文字列 Label です。 **options.telemetry** (`TelemetrySettings`): ストリーミング中に OTLP Telemetry を収集するための設定(Tracing ではありません)。 **options.telemetry.isEnabled** (`boolean`): Telemetry を有効または無効にします。実験的機能のため、デフォルトでは無効です。 **options.telemetry.recordInputs** (`boolean`): 入力の記録を有効または無効にします。デフォルトでは有効です。機密情報を記録しないように、入力の記録を無効にすることもできます。 **options.telemetry.recordOutputs** (`boolean`): 出力の記録を有効または無効にします。デフォルトでは有効です。機密情報を記録しないように、出力の記録を無効にすることもできます。 **options.telemetry.functionId** (`string`): この Function の識別子。Function ごとに Telemetry Data をグループ化するために使用します。 **options.modelSettings** (`CallSettings`): Model-specific settings like temperature, maxOutputTokens, topP, etc. These settings control how the language model generates responses. **options.modelSettings.temperature** (`number`): Controls randomness in generation (0-2). Higher values make output more random. **options.modelSettings.maxOutputTokens** (`number`): Maximum number of tokens to generate in the response. Note: Use maxOutputTokens (not maxTokens) as per AI SDK v5 convention. **options.modelSettings.maxRetries** (`number`): Maximum number of retry attempts for failed requests. **options.modelSettings.topP** (`number`): Nucleus sampling parameter (0-1). Controls diversity of generated text. **options.modelSettings.topK** (`number`): Top-k sampling parameter. Limits vocabulary to k most likely tokens. **options.modelSettings.presencePenalty** (`number`): Penalty for token presence (-2 to 2). Reduces repetition. **options.modelSettings.frequencyPenalty** (`number`): Penalty for token frequency (-2 to 2). Reduces repetition of frequent tokens. **options.modelSettings.stopSequences** (`string[]`): Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated. **options.structuredOutput** (`StructuredOutputOptions`): Network の結果から型付きの構造化出力を生成するための設定。 **options.structuredOutput.schema** (`ZodSchema | JSONSchema7`): 出力の検証に使用する Schema。Zod Schema または JSON Schema を指定できます。 **options.structuredOutput.model** (`MastraModelConfig`): 構造化出力の生成に使用する Model。デフォルトでは Agent の Model を使用します。 **options.structuredOutput.instructions** (`string`): 構造化出力を生成するためのカスタム instructions。 **options.runId** (`string`): この Generation Run の一意の ID。追跡や Debug に役立ちます。 **options.requestContext** (`RequestContext`): 依存性注入とコンテキスト情報に使用する Request Context。 **options.traceId** (`string`): Tracing が有効な場合に、この実行に関連付けられる Trace ID。Log の関連付けや実行フローの Debug に使用します。 **options.spanId** (`string`): Tracing が有効な場合に、この実行に関連付けられる Root Span ID。Span 単位の検索と関連付けに使用します。 **options.onStepFinish** (`(event: any) => Promise | void`): Subagent の実行中に各 LLM Step が完了した後で呼び出される Callback。終了理由や Token 使用量など、Step の詳細を受け取ります。 **options.onError** (`({ error }: { error: Error | string }) => Promise | void`): Subagent の実行中にエラーが発生したときに呼び出される Callback。 ## 戻り値 **stream** (`MastraAgentNetworkStream`): ReadableStream\ を Network 固有の追加プロパティで拡張したカスタム Stream **status** (`Promise`): 現在の Workflow Run Status に解決される Promise **result** (`Promise>`): 最終的な Workflow の結果に解決される Promise **usage** (`Promise<{ promptTokens: number; completionTokens: number; totalTokens: number }>`): Token 使用量の統計に解決される Promise **object** (`Promise`): 構造化出力オブジェクトに解決される Promise。structuredOutput オプションを指定した場合のみ利用できます。Schema が指定されていない場合は undefined に解決されます。 **objectStream** (`ReadableStream>`): 構造化出力の生成中に Partial Object を配信する Stream。生成途中の結果をストリーミングする場合に役立ちます。 ## 構造化出力 Network から型付きで検証済みの結果を取得するには、`structuredOutput` オプションを使用します。Network はタスクの完了後、Schema に一致するレスポンスを生成します。 ```typescript 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 agent.network('Research AI trends and summarize', { structuredOutput: { schema: resultSchema, }, }) // Consume the stream for await (const chunk of stream) { // Handle streaming events } // Get the typed result const result = await stream.object // result is typed as { summary: string; recommendations: string[]; confidence: number } console.log(result?.summary) console.log(result?.recommendations) ``` ### Partial Object のストリーミング 生成中の Partial Object をストリーミングすることもできます。 ```typescript const stream = await agent.network('Analyze data', { structuredOutput: { schema: resultSchema }, }) // Stream partial objects for await (const partial of stream.objectStream) { console.log('Partial result:', partial) } // Get final result const final = await stream.object ``` ### Chunk の種類 構造化出力を使用すると、次の種類の Chunk も出力されます。 - `network-object`:ストリーミング中に Partial Object とともに出力されます - `network-object-result`:最終的な構造化オブジェクトとともに出力されます ## Network の中止 実行中の Network をキャンセルするには、`abortSignal` を使用します。中止すると、Network はルーティングを停止し、実行中の Subagent、Tool、Workflow をすべてキャンセルして、途中結果を Memory に保存しません。 ```typescript const controller = new AbortController() // Abort after 30 seconds setTimeout(() => controller.abort(), 30_000) const stream = await agent.network('Research this topic thoroughly', { abortSignal: controller.signal, onAbort: ({ primitiveType, primitiveId, iteration }) => { console.log(`Aborted ${primitiveType} "${primitiveId}" at iteration ${iteration}`) }, }) for await (const chunk of stream) { if ( chunk.type === 'routing-agent-abort' || chunk.type === 'agent-execution-abort' || chunk.type === 'tool-execution-abort' || chunk.type === 'workflow-execution-abort' ) { console.log('Network was aborted') } } ```