如何把 Mastra 的 .network() 调用迁移到 supervisor agents 的 stream 与 generate 调用
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
如果你还在用Agent.network()(agent network 的 routing agent)来协调多个子 agent、workflow 和 tool,现在应该把它迁移到 supervisor agents 模式:把.network()调用替换为Agent.stream()(流式)或Agent.generate()(非流式),并改用标准流式 chunk 处理结果。Mastra 官方文档明确标注 agent networks 已废弃(deprecated),将在未来的版本中移除,.network()代码在移除之前仍可运行,但新开发已聚焦于 supervisor agents。
适用前提:
- 项目使用
@mastra/core中的Agent,且现有代码通过.network()做多 agent 协调; - supervisor agents(subagents 模式)从
@mastra/core@1.8.0开始提供,迁移前需确认本地@mastra/core版本不低于该版本; - 现有的 agent 配置(
agents、workflows、tools、memory)保持不变,迁移只改变调用方式和结果处理。
迁移前的现状检查:确认代码属于 .network() 模式
.network()的典型写法是:给一个 routing agent 配置agents/workflows/tools和Memory(.network()依赖 memory 存储任务历史并判断任务是否完成),然后调用.network()并迭代自定义事件流:
const result = await routingAgent.network('Research AI in education') for await (const chunk of result) { if (chunk.type === 'network-execution-event-step-finish') { console.log(chunk.payload.result) } }如果代码中同时出现approveNetworkToolCall()、declineNetworkToolCall()或resumeNetwork(),说明你还有工具审批和挂起恢复流程,迁移时需要对齐新的流式 chunk(tool-call-approval等,见 Supervisor Agents 文档 的 Tool approval propagation 一节),本文主路径只覆盖常规调用与事件处理。
第一步:把 .network() 换成 .stream() 或 .generate()
核心改动只有一处:调用入口。流式场景用.stream(),通过stream.textStream(或stream.fullStream)迭代标准 chunk;非流式场景用.generate(),直接读取result.text。
Before(.network()):
const result = await routingAgent.network('Research AI in education') for await (const chunk of result) { if (chunk.type === 'network-execution-event-step-finish') { console.log(chunk.payload.result) } }After(supervisor agent +.stream()):
const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) }maxSteps选项限制 supervisor 的迭代次数,它取代了.network()中隐式的迭代上限。非流式用法同样传入该选项:
const result = await supervisorAgent.generate('Research AI in education', { maxSteps: 10, }) console.log(result.text)两个方法的参数细节可分别参考 Agent.stream() Reference 和 Agent.generate() Reference。
第二步:把路由指令改写为明确的 supervisor 指令
.network()的 routing agent 靠通用指令和子 agent 描述来决定调用什么;supervisor agents 机制相同,但文档建议指令更具体:说明有哪些可用资源、什么情况下用哪个、如何协调、以及何时认为任务完成。
Before(.network()时代的 routing agent):
const routingAgent = new Agent({ id: 'routing-agent', instructions: 'You are a network of researchers and writers...', agents: { researchAgent, writingAgent }, memory: new Memory(), })After(supervisor agent):
const supervisorAgent = new Agent({ id: 'supervisor-agent', instructions: `You coordinate research and writing tasks using specialized agents. Available resources: - researchAgent: Gathers factual data and sources (returns bullet points) - writingAgent: Transforms research into narrative content (returns full paragraphs) Delegation strategy: 1. For research requests: Delegate to researchAgent first 2. For writing requests: Delegate to writingAgent (provide research if available) 3. For complex requests: Delegate to researchAgent first, then writingAgent Success criteria: - All user questions are fully answered - Response is well-formatted and complete - If information is incomplete, continue iterating`, agents: { researchAgent, writingAgent }, memory: new Memory(), })同时给每个子 agent 增加description字段,说明用途、返回格式和使用时机——supervisor 依据这些描述决定委派给谁:
const researchAgent = new Agent({ id: 'research-agent', description: `Specializes in gathering factual information and data on any topic. Returns concise bullet-point summaries with key facts and sources. Does not write full articles or narrative content.`, }) const writingAgent = new Agent({ id: 'writing-agent', description: `Transforms research material into well-structured written content. Produces full paragraphs and complete articles. Best used after research has been gathered.`, })注意:agent 实例本身不再依赖name: 'Routing Agent'这类网络式配置;迁移指南中 after 示例保留了agents与memory,与你原有配置一致,无需删除。
第三步:按映射表替换 .network() 事件处理
如果你在处理特定的.network()事件类型,把它们替换为 supervisor agent 的标准 stream chunk 类型:
|.network()事件 | Supervisor agent chunk | | - | - | |routing-agent-start|step-start| |routing-agent-end|step-finish| |agent-execution-start|step-start(委派时) | |agent-execution-event-text-delta|text-delta| |agent-execution-event-finish|step-finish| |network-execution-event-step-finish|step-finish+finishReason: 'stop'| |network-object|object-delta(配合 structuredOutput) | |network-object-result|object(配合 structuredOutput) |
也就是说:判断"最终步骤结束"的条件从chunk.type === 'network-execution-event-step-finish'变为检测step-finish且finishReason: 'stop'的 chunk;结构化输出场景下,.network()的objectStream/stream.object对应object-delta/objectchunk(仍需传入structuredOutput选项)。
可选:补齐 .network() 没有的委派控制
以下能力是 supervisor agents 新增的,不属于最小迁移路径,按需添加。它们可以配置在 agent 的defaultOptions里,也可以按调用传入:
委派钩子onDelegationStart/onDelegationComplete——在委派前后拦截、修改或拒绝委派:
const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, delegation: { onDelegationStart: async context => { console.log(`Delegating to: ${context.primitiveId}`) if (context.primitiveId === 'research-agent') { return { proceed: true, modifiedPrompt: `${context.prompt}\n\nFocus on 2024-2025 data.`, modifiedMaxSteps: 5, } } if (context.iteration > 8) { return { proceed: false, rejectionReason: 'Max iterations reached. Synthesize current findings.', } } return { proceed: true } }, }, })onDelegationComplete在委派结束后触发,可调用context.bail()停止 supervisor 循环,或返回{ feedback: '...' }把反馈写入 supervisor 的 memory:
const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, delegation: { onDelegationComplete: async context => { if (context.error) { context.bail() // Stop further delegations return { feedback: `Delegation to ${context.primitiveId} failed: ${context.error}. Try a different approach.`, } } }, }, })消息过滤messageFilter——默认子 agent 会收到完整会话上下文,可用messageFilter过滤敏感内容或限制消息数量(示例中剔除含confidential的消息并只保留最近 10 条):
const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, delegation: { messageFilter: ({ messages, primitiveId, prompt }) => { return messages .filter(msg => { const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) return !content.includes('confidential') }) .slice(-10) }, }, })迭代监控onIterationComplete——每次 supervisor 循环迭代后触发,可用于记录进度、注入反馈,或提前停止(返回{ continue: false }):
const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, onIterationComplete: async context => { console.log(`Iteration ${context.iteration}/${context.maxIterations}`) if (!context.text.includes('recommendations')) { return { continue: true, feedback: 'Please include specific recommendations in your analysis.', } } if (context.text.length > 1000 && context.finishReason === 'stop') { return { continue: false } } return { continue: true } }, })任务完成评分isTaskComplete——用 scorer 自动校验任务是否完成,校验失败时 supervisor 继续迭代,失败反馈会进入会话上下文。示例使用createScorer检查输出是否同时包含analysis和recommendation,并通过onComplete打印完成状态:
import { createScorer } from '@mastra/core/evals' const taskCompleteScorer = createScorer({ id: 'task-complete', name: 'Task Completeness', }).generateScore(async context => { const text = (context.run.output || '').toString() const hasAnalysis = text.includes('analysis') const hasRecommendations = text.includes('recommendation') return hasAnalysis && hasRecommendations ? 1 : 0 }) const stream = await supervisorAgent.stream('Research AI in education', { maxSteps: 10, isTaskComplete: { scorers: [taskCompleteScorer], strategy: 'all', onComplete: async result => { console.log('Task complete:', result.complete) }, }, })验证迁移结果
文档给出的成功表现按调用方式区分:
- 流式:
for await (const chunk of stream.textStream)持续输出文本 chunk;step-finish且finishReason: 'stop'的 chunk 表示一次完整执行结束(对应旧network-execution-event-step-finish); - 非流式:
const result = await supervisorAgent.generate(...)后读取result.text即得到最终回答; - 若接入了
isTaskComplete,onComplete回调中result.complete会给出任务完成判定。
如果迁移后行为异常,先对照上面第三步的事件映射表检查 chunk 类型是否写对——旧事件名(如network-execution-event-step-finish)在新 API 中不会再出现。
限制与后续
.network()已废弃且将随版本移除(Agent networks 文档 写明 "will be removed in a future major release"),现有代码在移除前可继续运行,官方建议尽快迁移;- supervisor agents 需要
@mastra/core1.8.0 及以上版本; .network()的approveNetworkToolCall()/resumeNetwork()等审批与恢复流程没有出现在迁移指南中,遇到这类代码请结合 Supervisor Agents 文档 的 Tool approval propagation(子 agent 的审批请求会以tool-call-approval等 chunk 出现在父 agent 流中)处理;- 更完整的委派选项(request context、结果引用、后台任务、版本覆盖等)见 Subagents 文档。
参考文档
- Migration: .network() to supervisor agents
- Agent networks
- Supervisor Agents (Subagents)
- Agent.stream() Reference
- Agent.generate() Reference
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考