Astreus

Sub-Agentes

Delegação inteligente de tarefas com agentes especializados trabalhando em coordenação Aprenda os padrões de configuração, as APIs e os exemplos práticos...

Delegação inteligente de tarefas com agentes especializados trabalhando em coordenação

Visão Geral

Sub-Agentes permitem uma coordenação sofisticada entre múltiplos agentes, na qual um agente principal delega tarefas de forma inteligente para sub-agentes especializados. Cada sub-agente tem sua própria especialidade, capacidades e papel, trabalhando em conjunto para concluir fluxos de trabalho complexos que seriam desafiadores para um único agente.

Novo: Sub-Agentes agora se integram perfeitamente com fluxos de trabalho em Grafo, permitindo distribuição hierárquica de tarefas em sistemas complexos de orquestração de fluxo de trabalho.

Criando Sub-Agentes

Sub-agentes são criados de forma independente e depois anexados a um agente coordenador principal:

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

Estratégias de Delegação

Delegação Automática

O agente principal usa a inteligência do LLM para analisar as tarefas e atribuí-las de forma otimizada:

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

Análise da Tarefa

O agente principal analisa a tarefa complexa usando raciocínio do LLM.

2

Correspondência de Agentes

Avalia as capacidades e especializações de cada sub-agente.

3

Atribuição Otimizada

Cria subtarefas específicas para os agentes mais apropriados.

4

Execução Coordenada

Gerencia o fluxo de execução e a agregação de resultados.

Delegação Manual

Atribua explicitamente tarefas específicas a agentes específicos usando seus IDs:

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

Delegação Sequencial

Sub-agentes trabalham em sequência, construindo sobre os resultados anteriores:

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

Padrões de Coordenação

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

Execução Paralela

Sub-agentes trabalham simultaneamente para máxima eficiência:

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

Execução Sequencial

Sub-agentes trabalham em ordem, com passagem de contexto:

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

Configuração de Sub-Agentes

Papéis Especializados

Configure sub-agentes para áreas específicas de especialização:

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

Integração com Graph

Sub-Agentes funcionam perfeitamente com fluxos de trabalho em Grafo para orquestração complexa:

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();

Recursos de Sub-Agente no Graph

  • Detecção Automática: Nós do grafo usam sub-agentes automaticamente quando é vantajoso
  • Passagem de Contexto: O contexto do fluxo de trabalho flui para os sub-agentes para melhor coordenação
  • Otimização de Desempenho: Monitoramento em tempo real e ajuste automático de estratégia
  • Configuração Flexível: Configurações de sub-agente por nó com herança da configuração do grafo

Exemplos Avançados

Pipeline de Produção de Conteúdo

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

Fluxo de Pesquisa de Mercado

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

Tipos de Resposta

Os métodos de sub-agente retornam formatos de resposta diferentes dependendo da operação.

Resposta de Execução com Sub-Agentes

A execução básica com sub-agentes retorna o resultado final combinado como uma string:

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."

Resposta de Delegação de Tarefa

A delegação de tarefa retorna a resposta do sub-agente como uma string:

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."

Resposta de Coordenação de Agentes

Coordenar múltiplos agentes retorna um array de pares tarefa-resultado:

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."
  }
]

Resposta de Agent.ask() com Sub-Agentes

Usar agent.ask() com opções de sub-agente retorna a string de resposta final:

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."

Resposta de Atribuição Manual de Tarefas

A atribuição manual também retorna uma string com os resultados combinados:

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."

Última atualização: 6 de julho de 2026