본문으로 건너뛰기

다음에서 마이그레이션.network()감독 Agent에게

Agent.stream()Agent.generate()를 사용하는 감독자 Agent는 여러 Agent를 조정하고 기존 Agent .network() API를 대체하는 데 권장되는 접근 방식입니다. 이 가이드에서는 마이그레이션의 각 단계를 안내합니다. :::warning[.network() 지원 중단]

.network()더 이상 사용되지 않으며 향후 릴리스에서 제거될 예정입니다. 기존 코드는 그때까지 계속 작동하지만 현재 개발은 감독자 Agent에 중점을 두고 있습니다. 가능한 한 빨리 감독 Agent으로 마이그레이션하세요.

:::

.network().stream() 또는 .generate()로 교체
replace-network-with-stream-or-generate에 대한 직접 링크

핵심 변경 사항은 .network() 호출을 .stream()(스트리밍) 또는 .generate()(비스트리밍)로 교체하는 것입니다. Agent 구성은 그대로 유지됩니다. 계속해서 Agent에 agents, workflows, tools, memory를 정의합니다. 차이점은 호출 방법과 결과 처리 방법입니다. .network()에서는 network-execution-event-step-finish와 같은 사용자 지정 이벤트 타입을 순회했습니다. .stream()에서는 표준 textStream 또는 fullStream 반복자를 사용합니다. 전에:

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)
}
}

후에:

const stream = await supervisorAgent.stream('Research AI in education', {
maxSteps: 10,
})

for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}

maxSteps 옵션은 감독자가 수행할 수 있는 반복 횟수를 제한합니다. 이 옵션은 .network()의 암시적 반복 제한을 대체합니다. 비스트리밍 사용 사례에서는 동일한 옵션과 함께 generate()를 사용하세요.

const result = await supervisorAgent.generate('Research AI in education', {
maxSteps: 10,
})

console.log(result.text)

명확한 감독자 지침 작성
명확한 감독자 지침 작성에 대한 직접 링크

.network()에서는 라우팅 Agent가 일반적인 지침과 프리미티브 설명을 바탕으로 호출 대상을 결정했습니다. 감독자 Agent도 같은 방식으로 작동하지만, 명확하고 구체적인 지침을 제공하면 위임 정확도가 높아집니다. 감독자의 instructions에는 사용 가능한 리소스와 각 리소스를 사용해야 하는 시점을 명시해야 합니다. 또한 이러한 리소스를 조정하는 방법과 작업 완료 여부를 판단하는 방법도 설명해야 합니다. 전에:

const routingAgent = new Agent({
id: 'routing-agent',
instructions: 'You are a network of researchers and writers...',
agents: { researchAgent, writingAgent },
memory: new Memory(),
})

후에:

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에 설명 추가
하위 Agent에 설명 추가에 대한 직접 링크

각 하위 Agent에는 목적과 반환 형식을 설명하는 description 필드가 필요합니다. 설명에는 하위 Agent를 사용해야 하는 시점도 명시해야 합니다. 감독자는 이러한 설명을 사용하여 위임할 Agent를 결정합니다.

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.`,
})

이벤트 처리 업데이트
이벤트 처리 업데이트에 대한 직접 링크

특정 .network() 이벤트를 처리하고 있다면 표준 스트림 청크 타입을 사용하도록 업데이트하세요.

.network() 이벤트감독자 Agent 청크
routing-agent-startstep-start
routing-agent-endstep-finish
agent-execution-startstep-start(위임 시)
agent-execution-event-text-deltatext-delta
agent-execution-event-finishstep-finish
network-execution-event-step-finishstep-finish + finishReason: 'stop'
network-objectobject-delta(구조화된 출력 사용)
network-object-resultobject(구조화된 출력 사용)

위임 후크 추가
위임 후크 추가에 대한 직접 링크

감독 Agent를 사용하면 위임 수명 주기에 연결하여 위임을 모니터링하거나 수정하거나 거부할 수 있습니다. 이러한 후크는 Agent의 defaultOptions에서 설정하거나 호출별로 전달할 수 있습니다. onDelegationStart감독자가 하위 Agent에게 위임하기 전에 호출됩니다. Prompt를 수정하거나 하위 Agent의 단계를 제한할 수 있습니다. 후크는 위임을 완전히 거부할 수도 있습니다.

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()을 호출하세요. 감독자의 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.`,
}
}
},
},
})

메시지 필터링 추가
메시지 필터링 추가에 대한 직접 링크

기본적으로 하위 Agent는 감독자로부터 전체 대화 컨텍스트를 받습니다. 공유할 메시지를 제어하려면 messageFilter를 사용하세요. 예를 들어 민감한 데이터를 제거하거나 메시지 수를 제한할 수 있습니다.

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감독자 루프가 반복될 때마다 호출됩니다. 이를 사용하여 진행 상황을 기록하거나 상담사를 안내하는 피드백을 제공하세요. 후크는 실행을 조기에 중지할 수도 있습니다.

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 }
},
})

작업 완료 점수 추가
작업 완료 점수 추가에 대한 직접 링크

작업 완료 채점자는 작업이 완료되었는지 자동으로 확인합니다. 검증이 실패하면 감독자는 계속해서 반복합니다. 실패한 득점자의 피드백이 대화 컨텍스트에 포함되어 하위 Agent가 누락된 내용을 확인할 수 있습니다.

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)
},
},
})

또한보십시오
또한보십시오에 대한 직접 링크