> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Agent.network() `.network()` 方法可啟用多 Agent 協作及路由。此方法接受訊息及可選的執行選項。 > **已棄用:** `.network()` primitive 已棄用,並會在未來的主要版本中移除。請改用搭配 `agent.stream()` 或 `agent.generate()` 的 [supervisor Agent](https://mastra.zisheng.pro/zh-HK/docs/capabilities/subagents)。請參閱[遷移指南](https://mastra.zisheng.pro/zh-HK/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`): 網絡程序的可選配置。 **options.maxSteps** (`number`): 執行期間最多可運行的步驟數目。 **options.abortSignal** (`AbortSignal`): 用於中止網絡執行的訊號。中止時,網絡會停止路由、取消任何進行中的子 Agent、Tool 或 Workflow 執行,並略過將部分結果儲存至記憶體。 **options.onAbort** (`(event: { primitiveType: string; primitiveId: string; iteration: number }) => void | Promise`): 網絡中止時觸發的回呼。接收一個事件,當中包含中止發生時正在執行的 primitive 類型及 ID。 **options.memory** (`object`): 記憶體配置。這是管理記憶體的建議方式。 **options.memory.thread** (`string | { id: string; metadata?: Record, title?: string }`): 對話 thread,可以是字串 ID,或包含 id 及可選 metadata 的物件。 **options.memory.resource** (`string`): 與 thread 關聯的用戶或資源識別碼。 **options.memory.options** (`MemoryConfig`): 記憶體行為的配置,例如訊息記錄及語意回憶。 **options.tracingContext** (`TracingContext`): 用於建立子 span 及加入 metadata 的 tracing context。使用 Mastra tracing 系統時會自動注入。 **options.tracingContext.currentSpan** (`Span`): 用於建立子 span 及加入 metadata 的目前 span。可用於建立自訂子 span,或在執行期間更新 span 屬性。 **options.tracingOptions** (`TracingOptions`): Tracing 配置的選項。 **options.tracingOptions.metadata** (`Record`): 要加入根 trace span 的 metadata。適合用於加入用戶 ID、工作階段 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 遙測收集設定(並非 Tracing)。 **options.telemetry.isEnabled** (`boolean`): 啟用或停用遙測。實驗階段預設為停用。 **options.telemetry.recordInputs** (`boolean`): 啟用或停用輸入記錄。預設為啟用。為免記錄敏感資料,你可能需要停用輸入記錄。 **options.telemetry.recordOutputs** (`boolean`): 啟用或停用輸出記錄。預設為啟用。為免記錄敏感資料,你可能需要停用輸出記錄。 **options.telemetry.functionId** (`string`): 此函式的識別碼,用於按函式將遙測資料分組。 **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`): 從網絡結果產生具型別結構化輸出的配置。 **options.structuredOutput.schema** (`ZodSchema | JSONSchema7`): 用於驗證輸出的 schema。可以是 Zod schema 或 JSON Schema。 **options.structuredOutput.model** (`MastraModelConfig`): 用於產生結構化輸出的模型。預設使用 Agent 的模型。 **options.structuredOutput.instructions** (`string`): 用於產生結構化輸出的自訂指示。 **options.runId** (`string`): 此次產生運行的唯一 ID,適合用於追蹤及除錯。 **options.requestContext** (`RequestContext`): 用於依賴注入及情境資訊的 Request Context。 **options.traceId** (`string`): 啟用 Tracing 時與此執行關聯的 Trace ID。可用於關聯記錄及除錯執行流程。 **options.spanId** (`string`): 啟用 Tracing 時與此執行關聯的根 span ID。可用於 span 層級的查找及關聯。 **options.onStepFinish** (`(event: any) => Promise | void`): 子 Agent 執行中每個 LLM 步驟完成後觸發的回呼。接收步驟詳情,包括完成原因及 token 用量。 **options.onError** (`({ error }: { error: Error | string }) => Promise | void`): 子 Agent 執行期間發生錯誤時觸發的回呼。 ## 傳回值 **stream** (`MastraAgentNetworkStream`): 擴充 ReadableStream\ 並加入網絡特定屬性的自訂 stream **status** (`Promise`): 解析為目前 Workflow 運行狀態的 promise **result** (`Promise>`): 解析為最終 Workflow 結果的 promise **usage** (`Promise<{ promptTokens: number; completionTokens: number; totalTokens: number }>`): 解析為 token 用量統計資料的 promise **object** (`Promise`): 解析為結構化輸出物件的 promise。只有在提供 structuredOutput 選項時才可用。如未指定 schema,則解析為 undefined。 **objectStream** (`ReadableStream>`): 產生結構化輸出期間的部分物件 stream,適合在產生部分結果時串流傳送。 ## 結構化輸出 如需從網絡取得具型別並經驗證的結果,請使用 `structuredOutput` 選項。網絡會在任務完成後產生符合 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`:隨最終結構化物件發出 ## 中止網絡 使用 `abortSignal` 取消正在運行的網絡。中止時,網絡會停止路由、取消任何進行中的子 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') } } ```