> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 하위 Agent **추가된 항목:** `@mastra/core@1.8.0` 하위 Agent는 다른 Agent가 작업을 위임할 수 있는 특수 Agent입니다. 상위 Agent에 추가하세요.`agents` property, then call [`Agent.stream()`](https://mastra.zisheng.pro/ko/reference/streaming/agents/stream)또는[`Agent.generate()`](https://mastra.zisheng.pro/ko/reference/agents/generate). 상위 Agent는 자신의 지침과 각 하위 Agent의`description`작업을 위임할 시기와 방법을 결정합니다. ## 하위 Agent를 사용하는 경우 작업에 서로 다른 전문 분야를 가진 Agent가 함께 작업해야 하는 경우 하위 Agent를 사용합니다. 상위 Agent는 위임 시기를 결정하고 컨텍스트를 각 하위 Agent에 전달합니다. 그런 다음 결과를 종합합니다. 일반적인 사용 사례: - 한 Agent가 데이터를 수집하고 다른 Agent가 콘텐츠를 생성하는 연구 및 작성 Workflow - 각 단계마다 다른 전문성이 필요한 다단계 업무 - 위임 동작을 세밀하게 제어해야 하는 작업 > **노트:** 하위 Agent를 조정하는 상위 Agent를 종종 감독자라고 합니다. 감독자 패턴은 Mastra에서 다중 Agent 시스템을 구축하는 한 가지 접근 방식입니다. 다른 패턴에 대해서는 다음을 읽어보세요.[conceptual overview](https://mastra.zisheng.pro/ko/guides/concepts/multi-agent-systems). ## 빠른 시작 명확한 설명으로 하위 Agent를 정의한 후 상위 Agent에 추가합니다. ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' import { LibSQLStore } from '@mastra/libsql' const researchAgent = new Agent({ id: 'research-agent', description: 'Gathers factual information and returns bullet-point summaries.', model: 'openai/gpt-5-mini', }) const writingAgent = new Agent({ id: 'writing-agent', description: 'Transforms research into well-structured articles.', model: 'openai/gpt-5-mini', }) const parentAgent = new Agent({ id: 'parent-agent', instructions: `You coordinate research and writing using specialized agents. Delegate to research-agent for facts, then writing-agent for content.`, model: 'openai/gpt-5.6-sol', agents: { researchAgent, writingAgent }, memory: new Memory({ storage: new LibSQLStore({ id: 'storage', url: 'file:mastra.db' }), }), }) const stream = await parentAgent.stream('Research AI in education and write an article', { maxSteps: 10, }) for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` ## 위임 후크 위임 후크를 사용하면 위임이 발생할 때 이를 가로채거나 수정하거나 거부할 수 있습니다. 아래에서 구성하십시오.`delegation` option, either in the agent's `defaultOptions` or per-call. ### `onDelegationStart` 상위 Agent가 하위 Agent에 위임하기 전에 호출됩니다. 위임을 제어하기 위한 객체를 반환합니다: - `proceed: true`: 위임을 허용합니다(기본 동작). - `proceed: false`: 다음을 사용하여 위임을 거부합니다.`rejectionReason` - `modifiedPrompt`: 하위 Agent로 전송된 Prompt를 다시 작성합니다. - `modifiedMaxSteps`: 하위 Agent의 반복 횟수를 제한합니다. ```typescript const stream = await parentAgent.stream('Research AI trends', { maxSteps: 10, delegation: { onDelegationStart: async context => { console.log(`Delegating to: ${context.primitiveId}`) // Modify the prompt for a specific agent if (context.primitiveId === 'research-agent') { return { proceed: true, modifiedPrompt: `${context.prompt}\n\nFocus on 2024-2025 data.`, modifiedMaxSteps: 5, } } // Reject delegation after too many iterations if (context.iteration > 8) { return { proceed: false, rejectionReason: 'Max iterations reached. Synthesize current findings.', } } return { proceed: true } }, }, }) ``` 그만큼`context` object includes: | 부동산 | 설명 | | ---------------- | ----------------------------------------- | | `primitiveId` | The ID of the subagent being delegated to | | `prompt` | The prompt the parent agent is sending | | `iteration` | Current iteration number | | `requestContext` | subagent 실행이 전달받을 요청 컨텍스트 | ### 위임 경계에서 컨텍스트 요청 각 위임은 실행 범위 ID 키를 제외하고 상위 실행에서 항목이 얕게 복사된 요청 컨텍스트를 받습니다. 하위 Agent 실행 중에 항목을 설정하거나 삭제해도 상위 컨텍스트에는 영향을 주지 않습니다. 항목 설정`context.requestContext` in `onDelegationStart` to pass values to the delegated run: ```typescript const stream = await parentAgent.stream('Research AI trends', { maxSteps: 10, delegation: { onDelegationStart: async context => { context.requestContext.set('audience', 'technical') }, }, }) ``` 하위 Agent는 Tool 및 동적 구성에서 다음과 같은 항목을 읽습니다.`instructions: ({ requestContext }) => ...`. See [Request Context](https://mastra.zisheng.pro/ko/docs/server/request-context) 에서 자세한 내용을 확인하세요. 내구성 Agent에서 작동하려면 값이 JSON으로 직렬화 가능해야 합니다. ### `onDelegationComplete` 위임이 완료된 후 호출됩니다. 이를 사용하여 결과를 검사하거나 피드백을 제공하거나 실행을 중지합니다. - `context.bail()`: 상위 Agent의 루프를 즉시 중지합니다. - 반품`{ feedback: '...' }`: 상위 Agent의 Memory에 저장되고 후속 반복에서 확인할 수 있는 피드백을 추가합니다 ```typescript const stream = await parentAgent.stream('Research AI trends', { maxSteps: 10, delegation: { onDelegationComplete: async context => { console.log(`Completed: ${context.primitiveId}`) // Bail on errors if (context.error) { context.bail() return { feedback: `Delegation to ${context.primitiveId} failed: ${context.error}. Try a different approach.`, } } }, }, }) ``` 그만큼`context` object includes: | 부동산 | 설명 | | ------------- | ---------------------------------------- | | `primitiveId` | The ID of the subagent that ran | | `result` | The subagent's response | | `error` | Error if the delegation failed | | `bail()` | Function to stop the parent agent's loop | ## 메시지 필터링 기본적으로 하위 Agent는 상위 Agent로부터 전체 대화 컨텍스트를 받습니다. 사용`messageFilter` 를 사용하여 공유할 메시지를 제어할 수 있습니다. 예를 들어 민감한 데이터를 제거하거나 컨텍스트 크기를 제한할 수 있습니다. ```typescript const stream = await parentAgent.stream('Research AI trends', { maxSteps: 10, delegation: { messageFilter: ({ messages, primitiveId, prompt }) => { // Remove messages containing sensitive data return messages .filter(msg => { const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) return !content.includes('confidential') }) .slice(-10) // Only pass the last 10 messages }, }, }) ``` 콜백이 수신됩니다.`messages` (the full conversation history), `primitiveId` (the subagent ID), and `prompt` (위임 Prompt)입니다. 필터링된 메시지 배열을 반환합니다. ## 하위 Agent 결과 컨텍스트 하위 Agent가 완료되면 상위 Agent의 Model은 이후 반복에서 하위 Agent의 텍스트 응답을 받습니다. 중첩된 Tool 호출과 하위 Agent 메타데이터(예: 스레드 및 리소스 ID)는 상위 Agent의 Model 컨텍스트에 추가되지 않습니다. 애플리케이션 코드 및 UI 통합으로 계속 검사할 수 있습니다.`subAgentToolResults` 및 나머지 원시 위임 결과를 Tool 결과 페이로드에 포함합니다. 이렇게 하면 중첩된 Tool 인수나 출력을 상위 Agent의 다음 Model 호출로 다시 보내지 않고도 디버깅 및 표시 데이터를 계속 사용할 수 있습니다. 세트`includeSubAgentToolResultsInModelContext` 를 사용하여 중첩된 Tool 결과와 subagent 메타데이터를 포함한 전체 subagent 결과를 상위 Agent의 Model 컨텍스트에 포함합니다. ```typescript await parentAgent.generate('Research AI trends', { delegation: { includeSubAgentToolResultsInModelContext: true, }, }) ``` ## 반복 모니터링 `onIterationComplete`상위 Agent 루프가 반복될 때마다 호출됩니다. 이를 사용하여 실행을 모니터링하거나 다음 반복을 안내합니다. 실행을 일찍 중지할 수도 있습니다. ```typescript const stream = await parentAgent.stream('Research AI trends', { maxSteps: 10, onIterationComplete: async context => { console.log(`Iteration ${context.iteration}/${context.maxIterations}`) console.log(`Finish reason: ${context.finishReason}`) // Inject feedback to guide the agent if (!context.text.includes('recommendations')) { return { continue: true, feedback: 'Please include specific recommendations in your analysis.', } } // Stop early when the response is sufficient if (context.text.length > 1000 && context.finishReason === 'stop') { return { continue: false } } return { continue: true } }, }) ``` 반품`{ continue: true }` to keep iterating, or `{ continue: false }` to stop. Include optional `feedback` to inject guidance into the conversation. When `feedback` is combined with `continue: false`인 경우, Model이 피드백을 반영한 텍스트 응답을 생성하도록 마지막 턴을 한 번 더 받을 수 있습니다. 단, 현재 반복이 아직 활성 상태인 경우(예: Tool 호출 후)에만 가능하며, 그렇지 않으면 추가 턴이 제공되지 않습니다. ## Memory 격리 Mastra는 위임 중에 하위 Agent Memory를 격리합니다. 하위 Agent는 더 나은 의사 결정을 위해 전체 대화 컨텍스트를 받지만 특정 위임 Prompt와 응답만 Memory에 저장됩니다. 작동 방식: 1. **전체 컨텍스트 전달**: 상위 Agent가 위임하면 하위 Agent는 상위 Agent의 대화에서 모든 메시지를 받습니다. 2. **범위 Memory 저장**: 위임 Prompt와 하위 Agent의 응답만 하위 Agent의 Memory에 저장됩니다. 3. **호출당 신선한 스레드**: 각 위임은 고유한 스레드 ID를 사용하여 깔끔한 분리를 보장합니다. 결과적으로 하위 Agent는 상위 Agent의 전체 대화로 Memory를 복잡하게 만들지 않고도 필요한 컨텍스트를 갖게 됩니다. 방문하다[memory in multi-agent systems](https://mastra.zisheng.pro/ko/docs/memory/overview) for more details. ## Tool 승인 전파 Tool 승인은 위임 체인을 통해 전파됩니다. 하위 Agent가 다음과 같은 Tool을 사용하는 경우`requireApproval: true` or calls `suspend()`인 경우, 승인 요청이 상위 Agent의 스트림에 표시됩니다. ```typescript const sensitiveDataTool = createTool({ id: 'get-user-data', requireApproval: true, execute: async input => { return await database.getUserData(input.userId) }, }) const dataAgent = new Agent({ id: 'data-agent', tools: { sensitiveDataTool }, }) const parentAgent = new Agent({ id: 'parent-agent', agents: { dataAgent }, memory: new Memory(), }) const stream = await parentAgent.stream('Get data for user 123') for await (const chunk of stream.fullStream) { if (chunk.type === 'tool-call-approval') { console.log('Tool requires approval:', chunk.payload.toolName) } } ``` ## 해제 당신이`abortSignal` to the parent agent's [`stream()`](https://mastra.zisheng.pro/ko/reference/streaming/agents/stream) or [`generate()`](https://mastra.zisheng.pro/ko/reference/agents/generate) 호출 시 Mastra는 동일한 신호를 위임된 subagent에도 전달합니다. `AbortController.abort()` 를 호출하면 실행 중인 subagent 실행이 완료될 때까지 계속되지 않고 다음 단계에서 취소됩니다. ```typescript const controller = new AbortController() const stream = await parentAgent.stream('Research AI trends', { abortSignal: controller.signal, }) // Cancel the parent agent and any in-flight subagents controller.abort() ``` ## 작업 완료 점수 Agent가 첫 번째 시도에서 항상 완전하고 올바른 출력을 생성하는 것은 아닙니다. 작업 완료 채점자는 각 반복 후에 작업이 완료되었는지 확인하여 도움을 줄 수 있습니다. 유효성 검사가 실패하면 상위 Agent는 계속 반복합니다. 실패한 득점자의 피드백이 대화 컨텍스트에 포함되므로 하위 Agent가 누락된 내용을 확인할 수 있습니다. ```typescript 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 parentAgent.stream('Research AI in education', { maxSteps: 10, isTaskComplete: { scorers: [taskCompleteScorer], strategy: 'all', onComplete: async result => { console.log('Task complete:', result.complete) }, }, }) ``` ### 루브릭 채점자 내장된 루브릭 채점기를 사용하면 "올바른" 것이 무엇인지 체크리스트로 정의하고 Agent가 모든 기준이 충족될 때까지 자체 평가하고 반복하도록 할 수 있습니다.`maxSteps` is reached. 그것은로 작동합니다**LLM-as-judge** scorer입니다. 각 반복 후 별도의 grader Model이 rubric에 따라 Agent의 출력을 검토합니다. 모든 필수 기준을 통과하면 루프가 종료됩니다. 기준을 통과하지 못하면 해당 피드백이 대화에 추가되어 Agent가 다시 시도할 수 있습니다. 이는 명확하고 검증 가능한 성공 기준이 있는 작업에 가장 효과적입니다. 다음과 같이 사용할 수 있습니다. ```typescript import { Agent } from '@mastra/core/agent' import { createRubricScorer } from '@mastra/evals/scorers/prebuilt' const parentAgent = new Agent({ id: 'parent-agent', instructions: 'You coordinate research and writing using specialized agents.', model: 'openai/gpt-5.6-sol', agents: { researchAgent, writingAgent }, }) const rubricScorer = createRubricScorer({ model: 'openai/gpt-5-mini', criteria: [ { description: 'The response includes an analysis section' }, { description: 'The response includes concrete recommendations' }, ], }) const stream = await parentAgent.stream('Research AI in education', { maxSteps: 10, isTaskComplete: { scorers: [rubricScorer], strategy: 'all', }, }) ``` 전체 API 세부정보는 다음을 참조하세요.[rubric scorer reference](https://mastra.zisheng.pro/ko/reference/evals/rubric). ## 효과적인 지침 작성 효과적인 위임을 위해서는 명확한 지침이 필수적입니다. 모 대리인의`instructions` 에는 사용 가능한 리소스와 각 리소스를 사용해야 하는 시점을 명시해야 합니다. 또한 조정 방식과 성공 기준도 정의해야 합니다. 각 하위 Agent에는 명확한`description` 에는 목적과 반환 형식뿐 아니라 상위 Agent가 이를 사용해야 하는 시점도 설명해야 합니다. 상위 Agent는 이러한 설명을 사용하여 위임 결정을 내립니다. ```typescript const parentAgent = new Agent({ id: 'parent-agent', instructions: `You coordinate research and writing tasks. 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 3. For complex requests: Delegate to researchAgent first, then writingAgent Success criteria: - All user questions are fully answered - Response is well-formatted and complete`, agents: { researchAgent, writingAgent }, }) ``` ## 백그라운드에서 하위 Agent 실행 하위 Agent 호출은 Tool 호출로 전달되므로 다음과 같이 실행할 수 있습니다.[background tasks](https://mastra.zisheng.pro/ko/docs/long-running-agents/background-tasks)입니다. 하나 이상의 위임 작업이 오래 실행되고 상위 Agent의 응답을 차단하지 않도록 하려는 경우 유용합니다. 활성화[backgroundTasks manager](https://mastra.zisheng.pro/ko/reference/configuration) 를 Mastra 인스턴스에 설정한 다음 상위 Agent에서 subagent를 사용하도록 옵트인합니다: ```typescript const parentAgent = new Agent({ id: 'parent-agent', instructions: 'Coordinate research and writing using the available agents.', model: 'openai/gpt-5.6-sol', agents: { researchAgent, writingAgent }, backgroundTasks: { tools: { researchAgent: { enabled: true, timeoutMs: 900_000 }, writingAgent: { enabled: true, timeoutMs: 900_000 }, }, }, }) const stream = await parentAgent.streamUntilIdle('Research AI in education and write an article', { memory: { thread: 't1', resource: 'u1' }, }) ``` 사용[`streamUntilIdle()`](https://mastra.zisheng.pro/ko/reference/streaming/agents/streamUntilIdle) instead of `stream()` 를 사용하면 subagent가 완료되고 상위 Agent가 그 결과에 응답할 기회를 얻을 때까지 스트림이 열린 상태로 유지됩니다. 하위 Agent가 상위 Agent 아래에 나열되지 않은 경우`backgroundTasks.tools` 이지만 자체적으로 백그라운드 실행이 가능한 Tool이 있는 경우, 상위 Agent는 여전히 subagent를 백그라운드 작업으로 디스패치하고 해당 구성을 상속합니다. [Inheriting from the subagent](https://mastra.zisheng.pro/ko/docs/long-running-agents/background-tasks) for details. ## 하위 Agent 버전 관리 사용할 때[editor](https://mastra.zisheng.pro/ko/docs/editor/overview)을 사용하면 런타임에 상위 Agent가 각 subagent의 저장된 버전 중 어느 것을 사용할지 제어할 수 있습니다. Mastra 인스턴스 또는 호출별로 버전 재정의를 설정하세요: ```typescript const result = await parentAgent.generate('Research and write about AI safety', { versions: { agents: { 'research-agent': { status: 'published' }, 'writing-agent': { versionId: 'draft-456' }, }, }, }) ``` 버전 재정의는 위임을 통해 자동으로 전파됩니다. 보다[Subagent versioning](https://mastra.zisheng.pro/ko/reference/editor/versioning) 에서 결정 순서와 서버 API 사용법에 대한 자세한 내용을 확인하세요. ## 관련된 - [백그라운드 작업](https://mastra.zisheng.pro/ko/docs/long-running-agents/background-tasks) - [하위 Agent 버전 관리](https://mastra.zisheng.pro/ko/reference/editor/versioning) - [가이드: 연구 코디네이터](https://mastra.zisheng.pro/ko/guides/guide/research-coordinator) - [Agent.stream() 참조](https://mastra.zisheng.pro/ko/reference/streaming/agents/stream) - [Agent.streamUntilIdle() 참조](https://mastra.zisheng.pro/ko/reference/streaming/agents/streamUntilIdle) - [Agent.generate() 참조](https://mastra.zisheng.pro/ko/reference/agents/generate) - [대리인 승인](https://mastra.zisheng.pro/ko/docs/agents/agent-approval) - [다중 Agent 시스템의 Memory](https://mastra.zisheng.pro/ko/docs/memory/overview) - [개념: 다중 Agent 시스템](https://mastra.zisheng.pro/ko/guides/concepts/multi-agent-systems) - 📹 [Mastra supervisor agents workshop](https://www.youtube.com/watch?v=FNb2fL9WhQg\&t=1872s)