Astreus

子智能体

在 Astreus 文档中了解 子智能体,获取用于构建智能体系统的设置指导、API 模式和实用示例。 了解构建可靠的 Astreus 智能体系统所需的设置模式、API 和实用示例。

由多个专业化代理协同工作实现的智能任务委派

概述

子代理(Sub-Agents)支持复杂的多代理协作,由主代理智能地将任务委派给专业化的子代理。每个子代理都有自己的专长、能力和角色,协同完成对单个代理来说颇具挑战的复杂工作流。

新特性:子代理现已能与 Graph 工作流无缝集成,可在复杂的工作流编排系统中实现分层任务分发。

创建子代理

子代理是独立创建的,然后附加到一个主协调代理上:

import { Agent } from '@astreus-ai/astreus';

// Create specialized sub-agents
const researcher = await Agent.create({
  name: 'ResearcherBot',
  model: 'gpt-4o',
  systemPrompt: 'You are an expert researcher who gathers and analyzes information thoroughly.',
  memory: true,
  knowledge: true
});

const writer = await Agent.create({
  name: 'WriterBot',
  model: 'gpt-4o',
  systemPrompt: 'You are a skilled content writer who creates engaging, well-structured content.',
  vision: true
});

const analyst = await Agent.create({
  name: 'AnalystBot', 
  model: 'gpt-4o',
  systemPrompt: 'You are a data analyst who provides insights and recommendations.',
  useTools: true
});

// Create main agent with sub-agents
const mainAgent = await Agent.create({
  name: 'CoordinatorAgent',
  model: 'gpt-4o',
  systemPrompt: 'You coordinate complex tasks between specialized sub-agents.',
  subAgents: [researcher, writer, analyst]
});

委派策略

自动委派

主代理使用 LLM 智能分析任务并进行最优分配:

const result = await mainAgent.ask(
  'Research AI market trends, analyze the data, and write an executive summary',
  {
    useSubAgents: true,
    delegation: 'auto'  // AI-powered task distribution
  }
);
1

任务分析

主代理使用 LLM 推理分析复杂任务。

2

代理匹配

评估每个子代理的能力和专长领域。

3

最优分配

为最合适的代理创建具体的子任务。

4

协同执行

管理执行流程并汇总结果。

手动委派

使用代理 ID 明确地将特定任务分配给特定代理:

const result = await mainAgent.ask(
  'Complex multi-step project',
  {
    useSubAgents: true,
    delegation: 'manual',
    taskAssignment: {
      [researcher.id]: 'Research market opportunities in healthcare AI',
      [analyst.id]: 'Analyze market size and growth potential',
      [writer.id]: 'Create executive summary with recommendations'
    }
  }
);

顺序委派

子代理按顺序工作,基于前一个结果进行处理:

const result = await mainAgent.ask(
  'Create a comprehensive business plan for an AI startup',
  {
    useSubAgents: true,
    delegation: 'sequential'  // Each agent builds on the previous work
  }
);

协作模式

graph TD
    A[Main Coordinator Agent] --> B{Task Analysis}
    B -->|Research Tasks| C[ResearcherBot]
    B -->|Analysis Tasks| D[AnalystBot]
    B -->|Content Tasks| E[WriterBot]
    
    C --> F[Research Results]
    D --> G[Analysis Results]
    E --> H[Written Content]
    
    F --> I[Result Aggregation]
    G --> I
    H --> I
    
    I --> J[Final Output]
    
    style A fill:#333,stroke:#333,stroke-width:4px
    style C fill:#333,stroke:#333,stroke-width:2px
    style D fill:#333,stroke:#333,stroke-width:2px
    style E fill:#333,stroke:#333,stroke-width:2px

并行执行

子代理同时工作以实现最高效率:

const result = await mainAgent.ask(
  'Multi-faceted analysis task',
  {
    useSubAgents: true,
    delegation: 'auto',
    coordination: 'parallel'  // All agents work concurrently
  }
);

顺序执行

子代理按顺序工作,并传递上下文:

const result = await mainAgent.ask(
  'Research → Analyze → Report workflow',
  {
    useSubAgents: true,
    delegation: 'auto', 
    coordination: 'sequential'  // Agents work in dependency order
  }
);

子代理配置

专业化角色

为特定的专业领域配置子代理:

// Research Specialist
const researcher = await Agent.create({
  name: 'ResearchSpecialist',
  systemPrompt: 'You conduct thorough research using multiple sources and methodologies.',
  knowledge: true,  // Access to knowledge base
  memory: true,     // Remember research context
  useTools: true    // Use research tools
});

// Content Creator
const creator = await Agent.create({
  name: 'ContentCreator', 
  systemPrompt: 'You create compelling content across different formats and audiences.',
  vision: true,     // Process visual content
  useTools: true    // Use content creation tools
});

// Technical Analyst
const analyst = await Agent.create({
  name: 'TechnicalAnalyst',
  systemPrompt: 'You analyze technical data and provide actionable insights.',
  useTools: true    // Use analysis tools
});

与 Graph 集成

子代理可与 Graph 工作流无缝协作,实现复杂编排:

import { Agent, Graph } from '@astreus-ai/astreus';

// Create specialized sub-agents
const researcher = await Agent.create({
  name: 'ResearchBot',
  systemPrompt: 'You conduct thorough research and analysis.',
  knowledge: true
});

const writer = await Agent.create({
  name: 'WriterBot',
  systemPrompt: 'You create compelling content and reports.',
  vision: true
});

// Main coordinator with sub-agents
const coordinator = await Agent.create({
  name: 'ProjectCoordinator',
  systemPrompt: 'You coordinate complex projects using specialized teams.',
  subAgents: [researcher, writer]
});

// Create sub-agent aware graph
const projectGraph = new Graph({
  name: 'Market Analysis Project',
  defaultAgentId: coordinator.id,
  subAgentAware: true,
  optimizeSubAgentUsage: true
}, coordinator);

// Add tasks with intelligent sub-agent delegation
const researchTask = projectGraph.addTaskNode({
  name: 'Market Research',
  prompt: 'Research AI healthcare market trends and opportunities',
  useSubAgents: true,
  subAgentDelegation: 'auto'
});

const reportTask = projectGraph.addTaskNode({
  name: 'Executive Report',
  prompt: 'Create comprehensive executive report based on research',
  dependencies: [researchTask],
  useSubAgents: true,
  subAgentCoordination: 'sequential'
});

// Execute the graph
const result = await projectGraph.run();

Graph 子代理特性

  • 自动检测:当有益时,Graph 节点会自动使用子代理
  • 上下文传递:工作流上下文会传递给子代理,以实现更好的协作
  • 性能优化:实时监控并自动调整策略
  • 灵活配置:每个节点均可单独配置子代理设置,并可继承 Graph 的全局配置

高级示例

内容生产流水线

const contentPipeline = await Agent.create({
  name: 'ContentPipeline',
  model: 'gpt-4o',
  subAgents: [researcher, writer, analyst]
});

const blogPost = await contentPipeline.ask(
  'Create a comprehensive blog post about quantum computing applications in finance',
  {
    useSubAgents: true,
    delegation: 'auto',
    coordination: 'sequential'
  }
);

市场研究工作流

const marketResearch = await Agent.create({
  name: 'MarketResearchTeam',
  model: 'gpt-4o',
  subAgents: [researcher, analyst, writer]
});

const report = await marketResearch.ask(
  'Analyze the fintech market and create investor presentation',
  {
    useSubAgents: true,
    delegation: 'manual',
    coordination: 'parallel',
    taskAssignment: {
      [researcher.id]: 'Research fintech market trends and competitors',
      [analyst.id]: 'Analyze market data and financial projections',
      [writer.id]: 'Create compelling investor presentation'
    }
  }
);

响应类型

子代理相关方法根据操作类型返回不同的响应格式。

使用子代理执行的响应

基础的子代理执行会以字符串形式返回最终的综合结果:

const result = await mainAgent.executeWithSubAgents(
  "Research renewable energy and create comprehensive report",
  [researchAgent, writerAgent],
  { coordination: 'sequential' }
);

// Response: string
"Research complete: Solar and wind energy show 23% growth year-over-year. Report includes market analysis, technology trends, and investment opportunities across 15 regions."

委派任务的响应

任务委派会将子代理的响应以字符串形式返回:

const result = await mainAgent.delegateTask(
  "Translate this document to Spanish",
  translatorAgent
);

// Response: string
"Documento traducido exitosamente. El contenido ha sido adaptado para audiencia hispanohablante manteniendo el tono profesional original."

协调代理的响应

协调多个代理会返回一个任务-结果对的数组:

const results = await mainAgent.coordinateAgents([
  { agent: analyzerAgent, prompt: "Analyze Q4 sales data" },
  { agent: reportAgent, prompt: "Create executive summary" },
  { agent: visualizerAgent, prompt: "Generate performance charts" }
], 'sequential');

// Response structure:
[
  {
    task: {
      agent: analyzerAgent,  // IAgent object
      prompt: "Analyze Q4 sales data"
    },
    result: "Q4 analysis complete: Revenue increased 18%, top products identified, seasonal trends mapped."
  },
  {
    task: {
      agent: reportAgent,
      prompt: "Create executive summary"
    },
    result: "Executive summary created with key findings: 18% growth driven by product line expansion..."
  },
  {
    task: {
      agent: visualizerAgent,
      prompt: "Generate performance charts"
    },
    result: "Performance visualizations generated: 5 charts showing revenue trends, product mix, and regional distribution."
  }
]

使用子代理的 Agent.ask() 响应

使用带有子代理选项的 agent.ask() 会返回最终的响应字符串:

const result = await mainAgent.ask(
  "Create market analysis presentation",
  {
    useSubAgents: true,
    delegation: 'auto',
    coordination: 'parallel'
  }
);

// Response: string
"Market analysis presentation completed with 3 specialized teams: Research team gathered competitor data, Analysis team processed financial metrics (showing 12% market growth), and Content team created 25-slide deck with executive summary."

手动任务分配的响应

手动分配同样会返回一个包含综合结果的字符串:

const result = await coordinatorAgent.ask(
  "Develop comprehensive product launch strategy",
  {
    useSubAgents: true,
    delegation: 'manual',
    coordination: 'sequential',
    taskAssignment: {
      [marketResearcher.id]: "Research target market and competitors",
      [strategyAnalyst.id]: "Develop go-to-market strategy",
      [contentCreator.id]: "Create launch materials and messaging"
    }
  }
);

// Response: string
"Product launch strategy complete: Target market identified (tech-savvy professionals 25-40), competitive positioning defined (premium quality, mid-tier pricing), go-to-market plan created with 3-phase rollout, and launch materials prepared including website, social media, and press kit."

最后更新时间:2026年7月6日