> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Agent.network() `.network()` 方法支持多 Agent 协作和路由。该方法接受消息和可选的执行选项。 > **已弃用:** `.network()` primitive 已弃用,并将在未来的主版本中移除。请改用带有 `agent.stream()` 或 `agent.generate()` 的 [supervisor Agent](https://mastra.zisheng.pro/docs/capabilities/subagents)。升级方法请参阅[迁移指南](https://mastra.zisheng.pro/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 执行的信号。中止时,network 会停止路由,取消任何正在进行的 subagent、Tool 或 Workflow 执行,并跳过将部分结果保存到 memory。 **options.onAbort** (`(event: { primitiveType: string; primitiveId: string; iteration: number }) => void | Promise`): network 中止时触发的回调。接收一个事件,其中包含中止发生时正在执行的 primitive 的类型和 ID。 **options.memory** (`object`): memory 配置。这是管理 memory 的首选方式。 **options.memory.thread** (`string | { id: string; metadata?: Record, title?: string }`): 对话 thread,可以是字符串 ID,也可以是带有 id 和可选 metadata 的对象。 **options.memory.resource** (`string`): 与 thread 关联的用户或资源标识符。 **options.memory.options** (`MemoryConfig`): memory 行为配置,例如消息历史记录和语义召回。 **options.tracingContext** (`TracingContext`): 用于创建子 span 和添加元数据的 Tracing context。使用 Mastra 的 tracing 系统时会自动注入。 **options.tracingContext.currentSpan** (`Span`): 用于创建子 span 和添加元数据的当前 span。可用于创建自定义子 span,或在执行期间更新 span 属性。 **options.tracingOptions** (`TracingOptions`): Tracing 配置选项。 **options.tracingOptions.metadata** (`Record`): 要添加到根 trace span 的元数据。适合添加用户 ID、会话 ID 或功能标志等自定义属性。 **options.tracingOptions.requestContextKeys** (`string[]`): 要提取为此 trace 元数据的其他 RequestContext 键。嵌套值支持点号表示法(例如 'user.id')。 **options.tracingOptions.traceId** (`string`): 此次执行使用的 Trace ID(1–32 个十六进制字符)。如有提供,此 trace 将成为指定 trace 的一部分。 **options.tracingOptions.parentSpanId** (`string`): 此次执行使用的父 span ID(1–16 个十六进制字符)。如有提供,根 span 将创建为该 span 的子 span。 **options.tracingOptions.tags** (`string[]`): 应用于此 trace 的标签。用于对 trace 进行分类和筛选的字符串标签。 **options.telemetry** (`TelemetrySettings`): streaming 期间的 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 结果生成类型化 structured output 的配置。 **options.structuredOutput.schema** (`ZodSchema | JSONSchema7`): 用于验证输出的 schema。可以是 Zod schema 或 JSON Schema。 **options.structuredOutput.model** (`MastraModelConfig`): 用于生成 structured output 的 Model。默认为 Agent 的 Model。 **options.structuredOutput.instructions** (`string`): 用于生成 structured output 的自定义指令。 **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`): subagent 执行中的每个 LLM 步骤结束后触发的回调。接收包括完成原因和 token 用量在内的步骤详情。 **options.onError** (`({ error }: { error: Error | string }) => Promise | void`): subagent 执行期间发生错误时触发的回调。 ## 返回值 **stream** (`MastraAgentNetworkStream`): 扩展 ReadableStream\ 并添加 network 特有属性的自定义 stream **status** (`Promise`): 一个 Promise,解析为当前 Workflow 运行状态 **result** (`Promise>`): 一个 Promise,解析为最终 Workflow 结果 **usage** (`Promise<{ promptTokens: number; completionTokens: number; totalTokens: number }>`): 一个 Promise,解析为 token 用量统计信息 **object** (`Promise`): 一个解析为 structured output 对象的 Promise。仅在提供 structuredOutput 选项时可用。如果未指定 schema,则解析为 undefined。 **objectStream** (`ReadableStream>`): structured output 生成期间的部分对象 stream。适合在生成过程中以 streaming 方式传输部分结果。 ## 结构化输出 当你需要从 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) ``` ### 以 streaming 方式传输部分对象 你也可以在部分对象生成时以 streaming 方式传输它们: ```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 类型 使用 structured output 时,还会发出以下 chunk 类型: - `network-object`:streaming 期间随部分对象发出 - `network-object-result`:随最终结构化对象发出 ## 中止 network 使用 `abortSignal` 取消正在运行的 network。中止时,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') } } ```