Agent.network()
.network() 方法支持多 Agent 协作和路由。该方法接受消息和可选的执行选项。
已弃用
.network() primitive 已弃用,并将在未来的主版本中移除。请改用带有 agent.stream() 或 agent.generate() 的 supervisor Agent。升级方法请参阅迁移指南。
使用示例使用示例的直接链接
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 流程的可选配置。
MultiPrimitiveExecutionOptions
maxSteps?:
number
执行期间运行的最大步骤数。
abortSignal?:
AbortSignal
用于中止 network 执行的信号。中止时,network 会停止路由,取消任何正在进行的 subagent、Tool 或 Workflow 执行,并跳过将部分结果保存到 memory。
onAbort?:
(event: { primitiveType: string; primitiveId: string; iteration: number }) => void | Promise<void>
network 中止时触发的回调。接收一个事件,其中包含中止发生时正在执行的 primitive 的类型和 ID。
memory?:
object
memory 配置。这是管理 memory 的首选方式。
object
thread:
string | { id: string; metadata?: Record<string, any>, title?: string }
对话 thread,可以是字符串 ID,也可以是带有
id 和可选 metadata 的对象。resource:
string
与 thread 关联的用户或资源标识符。
options?:
MemoryConfig
memory 行为配置,例如消息历史记录和语义召回。
tracingContext?:
TracingContext
用于创建子 span 和添加元数据的 Tracing context。使用 Mastra 的 tracing 系统时会自动注入。
TracingContext
currentSpan?:
Span
用于创建子 span 和添加元数据的当前 span。可用于创建自定义子 span,或在执行期间更新 span 属性。
tracingOptions?:
TracingOptions
Tracing 配置选项。
TracingOptions
metadata?:
Record<string, any>
要添加到根 trace span 的元数据。适合添加用户 ID、会话 ID 或功能标志等自定义属性。
requestContextKeys?:
string[]
要提取为此 trace 元数据的其他 RequestContext 键。嵌套值支持点号表示法(例如 'user.id')。
traceId?:
string
此次执行使用的 Trace ID(1–32 个十六进制字符)。如有提供,此 trace 将成为指定 trace 的一部分。
parentSpanId?:
string
此次执行使用的父 span ID(1–16 个十六进制字符)。如有提供,根 span 将创建为该 span 的子 span。
tags?:
string[]
应用于此 trace 的标签。用于对 trace 进行分类和筛选的字符串标签。
telemetry?:
TelemetrySettings
streaming 期间的 OTLP telemetry 收集设置(不是 Tracing)。
TelemetrySettings
isEnabled?:
boolean
启用或禁用 telemetry。实验阶段默认禁用。
recordInputs?:
boolean
启用或禁用输入记录。默认启用。为避免记录敏感信息,你可能需要禁用输入记录。
recordOutputs?:
boolean
启用或禁用输出记录。默认启用。为避免记录敏感信息,你可能需要禁用输出记录。
functionId?:
string
此函数的标识符。用于按函数对 telemetry 数据分组。
modelSettings?:
CallSettings
Model-specific settings like temperature, maxOutputTokens, topP, etc. These settings control how the language model generates responses.
temperature?:
number
Controls randomness in generation (0-2). Higher values make output more random.
maxOutputTokens?:
number
Maximum number of tokens to generate in the response. Note: Use maxOutputTokens (not maxTokens) as per AI SDK v5 convention.
maxRetries?:
number
Maximum number of retry attempts for failed requests.
topP?:
number
Nucleus sampling parameter (0-1). Controls diversity of generated text.
topK?:
number
Top-k sampling parameter. Limits vocabulary to k most likely tokens.
presencePenalty?:
number
Penalty for token presence (-2 to 2). Reduces repetition.
frequencyPenalty?:
number
Penalty for token frequency (-2 to 2). Reduces repetition of frequent tokens.
stopSequences?:
string[]
Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.
structuredOutput?:
StructuredOutputOptions
从 network 结果生成类型化 structured output 的配置。
StructuredOutputOptions
schema:
ZodSchema | JSONSchema7
用于验证输出的 schema。可以是 Zod schema 或 JSON Schema。
model?:
MastraModelConfig
用于生成 structured output 的 Model。默认为 Agent 的 Model。
instructions?:
string
用于生成 structured output 的自定义指令。
runId?:
string
此次生成运行的唯一 ID。适用于跟踪和调试。
requestContext?:
RequestContext
用于依赖注入和上下文信息的 Request Context。
traceId?:
string
启用 Tracing 时与此次执行关联的 trace ID。可用于关联日志和调试执行流程。
spanId?:
string
启用 Tracing 时与此次执行关联的根 span ID。可用于 span 级查找和关联。
onStepFinish?:
(event: any) => Promise<void> | void
subagent 执行中的每个 LLM 步骤结束后触发的回调。接收包括完成原因和 token 用量在内的步骤详情。
onError?:
({ error }: { error: Error | string }) => Promise<void> | void
subagent 执行期间发生错误时触发的回调。
返回值返回值的直接链接
stream:
MastraAgentNetworkStream<NetworkChunkType>
扩展 ReadableStream<NetworkChunkType> 并添加 network 特有属性的自定义 stream
status:
Promise<RunStatus>
一个 Promise,解析为当前 Workflow 运行状态
result:
Promise<WorkflowResult<TState, TOutput, TSteps>>
一个 Promise,解析为最终 Workflow 结果
usage:
Promise<{ promptTokens: number; completionTokens: number; totalTokens: number }>
一个 Promise,解析为 token 用量统计信息
object:
Promise<OUTPUT | undefined>
一个解析为 structured output 对象的 Promise。仅在提供 structuredOutput 选项时可用。如果未指定 schema,则解析为 undefined。
objectStream:
ReadableStream<Partial<OUTPUT>>
structured output 生成期间的部分对象 stream。适合在生成过程中以 streaming 方式传输部分结果。
结构化输出结构化输出的直接链接
当你需要从 network 获得经过验证的类型化结果时,请使用 structuredOutput 选项。任务完成后,network 会生成与 schema 匹配的响应。
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 方式传输部分对象的直接链接
你也可以在部分对象生成时以 streaming 方式传输它们:
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 类型的直接链接
使用 structured output 时,还会发出以下 chunk 类型:
network-object:streaming 期间随部分对象发出network-object-result:随最终结构化对象发出
中止 network中止 network的直接链接
使用 abortSignal 取消正在运行的 network。中止时,network 会停止路由,取消任何正在进行的 subagent、Tool 或 Workflow 执行,并且不会将部分结果保存到 memory。
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')
}
}