> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 감독 Agent와 함께 연구 코디네이터 구축 이 가이드에서는 감독 Agent를 사용하여 여러 전문 Agent를 조율하는 연구 코디네이터를 구축합니다. 코디네이터는 연구 업무를 연구 대리인에게, 집필 업무를 저술 대리인에게 위임한 후, 그 결과를 종합하여 상세한 보고서를 작성합니다. 명확한 역할을 가진 하위 Agent를 설정하고 감독 Agent를 구성하여 이를 조정합니다. 또한 위임 후크를 사용하여 실행을 제어하고 채점자를 사용하여 작업 완료를 검증합니다. ## 전제조건 - Node.js `v22.13.0` 이상 설치 - 지원되는 [Model Provider](https://mastra.zisheng.pro/ko/models)의 API 키 - 기존 Mastra 프로젝트(새 프로젝트를 설정하려면 [설치 가이드](https://mastra.zisheng.pro/ko/guides/getting-started/quickstart)를 따르세요) ## 연구 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` 필드는 매우 중요합니다. 감독자가 언제 이 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', }) ``` ## 감독자 Agent 만들기 감독자는 연구 및 작문 작업을 조정합니다. 해당 지침은 위임 전략, 즉 각 하위 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) }, }, }, }) ``` Mastra에 감독자를 등록합니다.`src/mastra/index.ts`: ```typescript import { Mastra } from '@mastra/core' import { supervisorAgent } from './agents/supervisor-agent' export const mastra = new Mastra({ agents: { supervisorAgent }, }) ``` 감독자 Agent의 `defaultOptions`는 위임 훅과 반복 모니터링을 구성합니다. - `onDelegationStart`최근 데이터를 요청하도록 연구 대리인의 Prompt를 수정합니다. - `onDelegationComplete`완료를 기록하고 오류가 발생하면 중지한 다음 피드백을 제공합니다. - `messageFilter`효율성을 위해 컨텍스트를 마지막 10개 메시지로 제한합니다. - `onIterationComplete`각 반복 후 진행 상황을 모니터링합니다. ## 기본 감독자 테스트 감독자와 상호 작용할 파일을 만듭니다.`src/index.ts`: ```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() ``` 감독자는 다음에 구성된 위임 후크 및 반복 모니터링을 사용합니다.`defaultOptions`. ## 작업 완료 점수 추가 작업 완료 채점자는 작업이 완료되었는지 자동으로 확인합니다. 이는 감독자가 조기에 끝내는 것을 방지합니다. 득점원 생성`src/mastra/scorers/task-complete-scorer.ts`: ```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 }) ``` 평가 패키지를 설치합니다: **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`의 `defaultOptions`에 작업 완료 채점기를 포함하도록 감독자 Agent를 업데이트하세요. ```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`) }, }, }, }) ``` 채점기는 실질적인 내용, 적절한 구조, 컨텍스트 정보를 확인합니다. 작업이 완료되지 않으면 감독자가 계속 반복합니다. 이제 모든 훅과 작업 완료 점수가 Agent의 `defaultOptions`에 포함되어 모든 호출에 자동으로 적용됩니다. ## 연구 코디네이터 테스트 코디네이터를 실행하여 실제로 작동하는 모습을 확인하세요. ```bash npx tsx src/index.ts ``` 위임 흐름을 보여주는 로그와 함께 감독자가 먼저 연구 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 추가(사실 확인기, 편집자, 인용 형식 지정자) - 품질 지표(가독성, 소스 품질)에 대한 사용자 정의 채점자 구현 - 웹 검색 또는 데이터베이스 액세스를 위한 Tool 추가 - 복잡한 다단계 연구 프로세스를 위한 Workflow 생성 - 구조화된 출력을 사용하여 특정 형식의 보고서 생성 자세히 알아보기: - [감독자 Agent](https://mastra.zisheng.pro/ko/docs/capabilities/subagents) - [Agent.stream() 참조](https://mastra.zisheng.pro/ko/reference/streaming/agents/stream)