跳至主要內容

使用 supervisor agents 建置研究協調器

在本指南中,你將建置一個研究協調器,使用 supervisor agents 協調多個專門的 Agents。協調器會將研究任務委派給研究 Agent,將寫作任務委派給寫作 Agent,再將結果整合成詳細報告。

你將設定職責明確的 subagents,並設定 supervisor Agent 來協調它們。你也會使用 delegation hooks 控制執行作業,並透過 scorers 驗證任務是否完成。

先決條件
「先決條件」的直接連結

  • 已安裝 Node.js v22.13.0 或更新版本
  • 具備支援的 Model Provider 所提供的 API key
  • 已有 Mastra 專案(請依照安裝指南設定新專案)

建立研究 Agent
「建立研究 Agent」的直接連結

研究 Agent 專門收集任何主題的事實資訊,並以簡潔的條列摘要傳回重要事實與來源。

建立新檔案 src/mastra/agents/research-agent.ts

src/mastra/agents/research-agent.ts
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。清楚的 descriptions 可提高委派準確度。

建立寫作 Agent
「建立寫作 Agent」的直接連結

寫作 Agent 會將研究資料轉換成結構完善、段落完整且行文流暢的文章。

建立新檔案 src/mastra/agents/writing-agent.ts

src/mastra/agents/writing-agent.ts
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 Agent」的直接連結

supervisor 會協調研究與寫作任務。其 instructions 定義委派策略,包括何時使用各個 subagent,以及如何整合結果。Memory 會直接設定在 Agent 上。

建立新檔案 src/mastra/agents/supervisor-agent.ts

src/mastra/agents/supervisor-agent.ts
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:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { supervisorAgent } from './agents/supervisor-agent'

export const mastra = new Mastra({
agents: { supervisorAgent },
})

supervisor Agent 上的 defaultOptions 會設定 delegation hooks 與 iteration monitoring:

  • onDelegationStart 會修改研究 Agent 的 prompt,要求提供近期資料
  • onDelegationComplete 會記錄完成狀態、在發生錯誤時停止,然後提供 feedback
  • messageFilter 會將情境限制為最後 10 則訊息,以提升效率
  • onIterationComplete 會在每次 iteration 後監控進度

測試基本 supervisor
「測試基本 supervisor」的直接連結

建立 src/index.ts 檔案,與 supervisor 互動:

src/index.ts
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 中設定的 delegation hooks 與 iteration monitoring。

加入任務完成評分
「加入任務完成評分」的直接連結

任務完成 scorers 會自動驗證任務是否完成,避免 supervisor 過早結束。

src/mastra/scorers/task-complete-scorer.ts 中建立 scorer:

src/mastra/scorers/task-complete-scorer.ts
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 install @mastra/evals

更新 supervisor Agent,在 src/mastra/agents/supervisor-agent.tsdefaultOptions 中加入任務完成評分:

src/mastra/agents/supervisor-agent.ts
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 會繼續 iteration。現在所有 hooks 與任務完成評分都設定在 Agent 的 defaultOptions 中,因此會自動套用至每次呼叫。

測試研究協調器
「測試研究協調器」的直接連結

執行協調器,查看其實際運作:

npx tsx src/index.ts

你會看到 supervisor 先將任務委派給研究 Agent,再委派給寫作 Agent;log 會顯示委派流程:

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 回應並非確定性輸出,你的結果可能不同,但委派模式會保持一致。

後續步驟
「後續步驟」的直接連結

你可以透過下列方式擴充此研究協調器:

  • 加入更多專門的 Agents(fact-checker、editor、citation-formatter)
  • 為品質指標(readability、source quality)實作自訂 scorers
  • 加入用於網頁搜尋或資料庫存取的 tools
  • 為複雜的多步驟研究流程建立 Workflows
  • 使用 structured output,以特定格式產生報告

深入了解: