> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 使用 supervisor Agent 构建研究协调器 本指南将介绍如何使用 supervisor Agent 构建一个编排多个专业 Agent 的研究协调器。协调器会将研究任务委派给研究 Agent,将写作任务委派给写作 Agent,然后将结果综合成详细报告。 你将设置职责明确的子 Agent,并配置 supervisor Agent 来协调它们。还会使用委派 hook 控制执行,并使用 scorer 验证任务完成情况。 ## 前提条件 - 已安装 Node.js `v22.13.0` 或更高版本 - 受支持的[模型 Provider](https://mastra.zisheng.pro/models)所提供的 API 密钥 - 现有 Mastra 项目(按照[安装指南](https://mastra.zisheng.pro/guides/getting-started/quickstart)设置新项目) ## 创建研究 Agent 研究 Agent 专门收集任意主题的事实信息,并以简洁的项目符号摘要返回关键事实和来源。 创建新文件 `src/mastra/agents/research-agent.ts`: ```typescript import { Agent } from '@mastra/core/agent' export const researchAgent = new Agent({ id: 'research-agent', name: 'Research Specialist', 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.', instructions: 'You are a research specialist. When given a topic, gather key facts, ' + 'statistics, and information. Present findings as clear bullet points. ' + 'Include sources when possible. Focus on accuracy and completeness.', model: 'openai/gpt-5-mini', }) ``` `description` 字段非常关键,它帮助 supervisor 判断何时将任务委派给此 Agent。清晰的描述可以提高委派准确性。 ## 创建写作 Agent 写作 Agent 将研究内容转换成结构良好、段落完整且行文流畅的文章。 创建新文件 `src/mastra/agents/writing-agent.ts`: ```typescript import { Agent } from '@mastra/core/agent' export const writingAgent = new Agent({ id: 'writing-agent', name: 'Writing Specialist', description: 'Transforms research material into well-structured written content. ' + 'Produces full paragraphs and complete articles with proper flow. ' + 'Best used after research has been gathered.', instructions: 'You are a writing specialist. Transform research and information into ' + 'well-written articles. Use complete paragraphs, clear structure, and ' + 'engaging language. Maintain a professional yet accessible tone. ' + 'Ensure the content flows naturally from introduction to conclusion.', model: 'openai/gpt-5-mini', }) ``` ## 创建 supervisor Agent Supervisor 负责协调研究和写作任务。其 instructions 定义委派策略,包括何时使用各个子 Agent 以及如何综合结果。Memory 直接在 Agent 上配置。 创建新文件 `src/mastra/agents/supervisor-agent.ts`: ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' import { LibSQLStore } from '@mastra/libsql' import { researchAgent } from './research-agent' import { writingAgent } from './writing-agent' export const supervisorAgent = new Agent({ id: 'supervisor-agent', name: 'Research Coordinator', instructions: `You coordinate research and writing tasks using specialized agents. Available resources: - research-agent: Gathers factual data and sources (returns bullet points) - writing-agent: Transforms research into well-structured articles (returns full paragraphs) Delegation strategy: 1. For research requests: Delegate to research-agent first to gather facts 2. For writing requests: Delegate to writing-agent with any available research context 3. For comprehensive reports: Delegate to research-agent first, then writing-agent 4. Always ensure you have gathered sufficient information before producing final output Success criteria: - All aspects of the user's request are addressed - Information is accurate and well-sourced - Final output is well-formatted and complete - If anything is missing or uncertain, continue gathering information`, model: 'openai/gpt-5.6-sol', agents: { researchAgent, writingAgent, }, memory: new Memory({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:mastra.db', }), }), defaultOptions: { maxSteps: 10, // Monitor progress after each iteration onIterationComplete: async context => { console.log(`\n✓ Iteration ${context.iteration} complete`) console.log(` Finish reason: ${context.finishReason}`) console.log(` Response length: ${context.text.length} chars\n`) // Continue until task is complete return { continue: true } }, // Control delegations delegation: { onDelegationStart: async context => { console.log(`→ Delegating to: ${context.primitiveId}`) // Add context for specific agents if (context.primitiveId === 'research-agent') { return { proceed: true, modifiedPrompt: `${context.prompt}\n\nFocus on recent developments (2024-2025) and include statistics.`, } } return { proceed: true } }, onDelegationComplete: async context => { console.log(`✓ Completed: ${context.primitiveId}\n`) // Handle errors: bail to stop execution and provide feedback if (context.error) { console.error('Delegation failed:', context.error) context.bail() // Stop further delegations return { feedback: `Delegation to ${context.primitiveId} failed: ${context.error}. Try a different approach.`, } } }, // Only pass last 10 messages to subagents messageFilter: ({ messages }) => { return messages.slice(-10) }, }, }, }) ``` 在 `src/mastra/index.ts` 中向 Mastra 注册 supervisor: ```typescript import { Mastra } from '@mastra/core' import { supervisorAgent } from './agents/supervisor-agent' export const mastra = new Mastra({ agents: { supervisorAgent }, }) ``` Supervisor Agent 上的 `defaultOptions` 用于配置委派 hook 和迭代监控: - `onDelegationStart` 修改研究 Agent 的提示词,要求提供近期数据 - `onDelegationComplete` 记录完成状态,并在出错时停止,然后提供反馈 - `messageFilter` 将上下文限制为最近 10 条消息以提高效率 - `onIterationComplete` 在每次迭代后监控进度 ## 测试基本 supervisor 创建 `src/index.ts` 文件以与 supervisor 交互: ```typescript import { supervisorAgent } from './mastra/agents/supervisor-agent' async function main() { const topic = 'artificial intelligence in education' console.log(`\nTopic: ${topic}\n`) const stream = await supervisorAgent.stream( `Research ${topic} and write a comprehensive article about it`, ) // Stream the response console.log('📝 Final Report:\n') for await (const chunk of stream.textStream) { process.stdout.write(chunk) } console.log('\n') } main() ``` Supervisor 使用 `defaultOptions` 中配置的委派 hook 和迭代监控。 ## 添加任务完成度评分 任务完成度 scorer 会自动验证任务是否完成,防止 supervisor 过早结束。 在 `src/mastra/scorers/task-complete-scorer.ts` 中创建 scorer: ```typescript import { createScorer } from '@mastra/core/evals' export const taskCompleteScorer = createScorer({ id: 'task-complete', name: 'Task Completeness', description: 'Checks if the research and writing task has been fully completed', }).generateScore(async context => { const text = (context.run.output || '').toString() // Check if response contains required elements const hasSubstantialContent = text.length > 500 const hasStructure = text.includes('\n\n') // Multiple paragraphs const hasContext = /\d{4}/.test(text) // Contains years/dates // Return 1 if complete, 0 if not if (hasSubstantialContent && hasStructure && hasContext) { return 1 } return 0 }) ``` 安装 Evals 软件包: **npm**: ```bash npm install @mastra/evals ``` **pnpm**: ```bash pnpm add @mastra/evals ``` **Yarn**: ```bash yarn add @mastra/evals ``` **Bun**: ```bash bun add @mastra/evals ``` 更新 `src/mastra/agents/supervisor-agent.ts` 中的 supervisor Agent,在 `defaultOptions` 中加入任务完成度评分: ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' import { LibSQLStore } from '@mastra/libsql' import { researchAgent } from './research-agent' import { writingAgent } from './writing-agent' import { taskCompleteScorer } from '../scorers/task-complete-scorer' export const supervisorAgent = new Agent({ id: 'supervisor-agent', name: 'Research Coordinator', instructions: `You coordinate research and writing tasks using specialized agents. Available resources: - research-agent: Gathers factual data and sources (returns bullet points) - writing-agent: Transforms research into well-structured articles (returns full paragraphs) Delegation strategy: 1. For research requests: Delegate to research-agent first to gather facts 2. For writing requests: Delegate to writing-agent with any available research context 3. For comprehensive reports: Delegate to research-agent first, then writing-agent 4. Always ensure you have gathered sufficient information before producing final output Success criteria: - All aspects of the user's request are addressed - Information is accurate and well-sourced - Final output is well-formatted and complete - If anything is missing or uncertain, continue gathering information`, model: 'openai/gpt-5.6-sol', agents: { researchAgent, writingAgent, }, memory: new Memory({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:mastra.db', }), }), defaultOptions: { maxSteps: 10, onIterationComplete: async context => { console.log(`\n✓ Iteration ${context.iteration} complete`) console.log(` Finish reason: ${context.finishReason}`) console.log(` Response length: ${context.text.length} chars\n`) return { continue: true } }, delegation: { onDelegationStart: async context => { console.log(`→ Delegating to: ${context.primitiveId}`) if (context.primitiveId === 'research-agent') { return { proceed: true, modifiedPrompt: `${context.prompt}\n\nFocus on recent developments (2024-2025) and include statistics.`, } } return { proceed: true } }, onDelegationComplete: async context => { console.log(`✓ Completed: ${context.primitiveId}\n`) if (context.error) { console.error('Delegation failed:', context.error) context.bail() // Stop further delegations return { feedback: `Delegation to ${context.primitiveId} failed: ${context.error}. Try a different approach.`, } } }, messageFilter: ({ messages }) => { return messages.slice(-10) }, }, // Validate task completion isTaskComplete: { scorers: [taskCompleteScorer], strategy: 'all', onComplete: async result => { console.log('\n🎯 Completion Check:') console.log(` Complete: ${result.complete}`) console.log(` Score: ${result.scorers[0]?.score}\n`) }, }, }, }) ``` Scorer 会检查内容是否充实、结构是否合理以及是否包含上下文信息。如果任务尚未完成,supervisor 会继续迭代。现在,所有 hook 和任务完成度评分都已在 Agent 的 `defaultOptions` 中配置,并会自动应用于每次调用。 ## 测试研究协调器 运行协调器以查看其实际效果: ```bash npx tsx src/index.ts ``` 你会看到 supervisor 先将任务委派给研究 Agent,再委派给写作 Agent,日志会显示委派流程: ```text Topic: artificial intelligence in education → Delegating to: research-agent ✓ Iteration 1 complete Finish reason: tool-calls Response length: 0 chars ✓ Completed: research-agent → Delegating to: writing-agent ✓ Iteration 2 complete Finish reason: tool-calls Response length: 0 chars ✓ Completed: writing-agent 🎯 Completion Check: Complete: true Score: 1 ✓ Iteration 3 complete Finish reason: stop Response length: 1247 chars 📝 Final Report: Artificial Intelligence in Education: Transforming Learning in 2024-2025 [The coordinator will produce a comprehensive article combining research findings with well-structured writing...] ``` 由于 Agent 响应具有非确定性,实际输出可能不同,但委派模式会保持一致。 ## 后续步骤 你可以通过以下方式扩展研究协调器: - 添加更多专业 Agent(事实核查员、编辑、引用格式化工具) - 为质量指标(可读性、来源质量)实现自定义 scorer - 添加用于 Web 搜索或数据库访问的 Tool - 为复杂的多步骤研究流程创建 Workflow - 使用结构化输出生成特定格式的报告 了解更多: - [Supervisor Agent](https://mastra.zisheng.pro/docs/capabilities/subagents) - [Agent.stream() 参考](https://mastra.zisheng.pro/reference/streaming/agents/stream)