> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Agent.network() `.network()` 方法可啟用多 Agent 協作與路由。此方法接受訊息及選用的執行選項。 > **Deprecated:** `.network()` primitive 已棄用,並將於未來的主要版本中移除。請改用搭配 `agent.stream()` 或 `agent.generate()` 的 [supervisor Agent](https://mastra.zisheng.pro/zh-TW/docs/capabilities/subagents)。升級方式請參閱[遷移指南](https://mastra.zisheng.pro/zh-TW/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 的訊息。可以是單一字串、字串陣列或結構化訊息物件。 **options** (`MultiPrimitiveExecutionOptions`): network 流程的選用設定。 **options.maxSteps** (`number`): 執行期間最多可執行的步驟數。 **options.abortSignal** (`AbortSignal`): 用來中止 network 執行的 signal。中止時,network 會停止路由、取消所有進行中的子 Agent、Tool 或 Workflow 執行,且不會將部分結果儲存至記憶體。 **options.onAbort** (`(event: { primitiveType: string; primitiveId: string; iteration: number }) => void | Promise`): network 中止時觸發的 callback。它會收到一個 event,其中包含中止發生時正在執行之 primitive 的類型與 ID。 **options.memory** (`object`): 記憶體設定。這是管理記憶體的建議方式。 **options.memory.thread** (`string | { id: string; metadata?: Record, title?: string }`): 對話 thread,可以是字串 ID,或包含 id 與選用 metadata 的物件。 **options.memory.resource** (`string`): 與 thread 關聯之使用者或 resource 的識別碼。 **options.memory.options** (`MemoryConfig`): 記憶體行為設定,例如訊息歷程與語意回想。 **options.tracingContext** (`TracingContext`): 用於建立子 span 及新增 metadata 的 Tracing context。使用 Mastra 的 Tracing 系統時會自動注入。 **options.tracingContext.currentSpan** (`Span`): 目前的 span,用於建立子 span 及新增 metadata。可用來在執行期間建立自訂子 span 或更新 span 屬性。 **options.tracingOptions** (`TracingOptions`): Tracing 設定選項。 **options.tracingOptions.metadata** (`Record`): 要新增至根 Trace span 的 metadata。適合用來加入使用者 ID、session ID 或功能旗標等自訂屬性。 **options.tracingOptions.requestContextKeys** (`string[]`): 要擷取為此 Trace metadata 的其他 RequestContext key。巢狀值支援點號表示法(例如 'user.id')。 **options.tracingOptions.traceId** (`string`): 此執行作業要使用的 Trace ID(1 至 32 個十六進位字元)。若提供此值,這個 Trace 會成為指定 Trace 的一部分。 **options.tracingOptions.parentSpanId** (`string`): 此執行作業要使用的父 span ID(1 至 16 個十六進位字元)。若提供此值,根 span 會建立為此 span 的子項。 **options.tracingOptions.tags** (`string[]`): 要套用至此 Trace 的標籤。可用這些字串標籤將 Trace 分類及篩選。 **options.telemetry** (`TelemetrySettings`): 串流期間的 OTLP telemetry 收集設定(並非 Tracing)。 **options.telemetry.isEnabled** (`boolean`): 啟用或停用 telemetry。此功能仍為實驗性質,因此預設停用。 **options.telemetry.recordInputs** (`boolean`): 啟用或停用輸入記錄。預設為啟用。若要避免記錄敏感資訊,您可以停用輸入記錄。 **options.telemetry.recordOutputs** (`boolean`): 啟用或停用輸出記錄。預設為啟用。若要避免記錄敏感資訊,您可以停用輸出記錄。 **options.telemetry.functionId** (`string`): 此函式的識別碼,用來依函式將 telemetry 資料分組。 **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`): 用來生成結構化輸出的模型。預設使用 Agent 的模型。 **options.structuredOutput.instructions** (`string`): 用來生成結構化輸出的自訂指示。 **options.runId** (`string`): 此次生成 run 的唯一 ID,適合用於追蹤與偵錯。 **options.requestContext** (`RequestContext`): 用於相依性注入與情境資訊的 Request Context。 **options.traceId** (`string`): 啟用 Tracing 時,與此執行作業關聯的 Trace ID。可用來關聯 log 及對執行流程進行偵錯。 **options.spanId** (`string`): 啟用 Tracing 時,與此執行作業關聯的根 span ID。可用於 span 層級的查詢與關聯。 **options.onStepFinish** (`(event: any) => Promise | void`): 子 Agent 執行中的每個 LLM 步驟完成後觸發的 callback。它會收到步驟詳細資料,包括完成原因與 token 使用量。 **options.onError** (`({ error }: { error: Error | string }) => Promise | void`): 子 Agent 執行期間發生錯誤時觸發的 callback。 ## 回傳值 **stream** (`MastraAgentNetworkStream`): 擴充 ReadableStream\ 並加入 network 專用屬性的自訂 stream **status** (`Promise`): 解析為目前 Workflow run 狀態的 promise **result** (`Promise>`): 解析為最終 Workflow 結果的 promise **usage** (`Promise<{ promptTokens: number; completionTokens: number; totalTokens: number }>`): 解析為 token 使用統計資料的 promise **object** (`Promise`): 解析為結構化輸出物件的 promise。只有提供 structuredOutput 選項時才可用。若未指定 schema,則解析為 undefined。 **objectStream** (`ReadableStream>`): 結構化輸出生成期間的部分物件 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) ``` ### 串流部分物件 您也可以在部分物件生成時進行串流: ```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`:串流期間隨部分物件一併發出 - `network-object-result`:隨最終結構化物件一併發出 ## 中止 network 使用 `abortSignal` 取消執行中的 network。中止時,network 會停止路由、取消所有進行中的子 Agent、Tool 或 Workflow 執行,且不會將部分結果儲存至記憶體。 ```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') } } ```