Sub-Agenti
Delega intelligente dei task con agent specializzati che lavorano in coordinazione Scopri i pattern di configurazione, le API e gli esempi pratici necessari...
Delega intelligente dei task con agent specializzati che lavorano in coordinazione
Panoramica
I Sub-Agent abilitano un coordinamento multi-agent sofisticato in cui un agent principale delega in modo intelligente i task a sub-agent specializzati. Ogni sub-agent ha la propria expertise, capacità e ruolo, e lavora insieme agli altri per completare workflow complessi che sarebbero difficili da gestire per un singolo agent.
Novità: i Sub-Agent ora si integrano perfettamente con i workflow Graph, abilitando la distribuzione gerarchica dei task attraverso sistemi complessi di orchestrazione dei workflow.
Creare i Sub-Agent
I sub-agent vengono creati in modo indipendente e poi collegati a un agent coordinatore principale:
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]
});Strategie di delega
Delega automatica
L'agent principale usa l'intelligenza dell'LLM per analizzare i task e assegnarli in modo ottimale:
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
}
);Analisi del task
L'agent principale analizza il task complesso usando il ragionamento dell'LLM.
Corrispondenza degli agent
Valuta le capacità e le specializzazioni di ciascun sub-agent.
Assegnazione ottimale
Crea subtask specifici per gli agent più appropriati.
Esecuzione coordinata
Gestisce il flusso di esecuzione e l'aggregazione dei risultati.
Delega manuale
Assegna esplicitamente task specifici ad agent specifici usando i loro 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'
}
}
);Delega sequenziale
I sub-agent lavorano in sequenza, costruendo sui risultati precedenti:
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
}
);Pattern di coordinamento
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:2pxEsecuzione parallela
I sub-agent lavorano simultaneamente per la massima efficienza:
const result = await mainAgent.ask(
'Multi-faceted analysis task',
{
useSubAgents: true,
delegation: 'auto',
coordination: 'parallel' // All agents work concurrently
}
);Esecuzione sequenziale
I sub-agent lavorano in ordine con passaggio del contesto:
const result = await mainAgent.ask(
'Research → Analyze → Report workflow',
{
useSubAgents: true,
delegation: 'auto',
coordination: 'sequential' // Agents work in dependency order
}
);Configurazione dei Sub-Agent
Ruoli specializzati
Configura i sub-agent per aree di expertise specifiche:
// 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
});Integrazione con Graph
I Sub-Agent funzionano perfettamente con i workflow Graph per un'orchestrazione complessa:
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();Funzionalità Sub-Agent nel Graph
- Rilevamento automatico: i nodi del grafo usano automaticamente i sub-agent quando è vantaggioso
- Passaggio del contesto: il contesto del workflow fluisce verso i sub-agent per un coordinamento migliore
- Ottimizzazione delle prestazioni: monitoraggio in tempo reale e adattamento automatico della strategia
- Configurazione flessibile: impostazioni sub-agent per nodo con ereditarietà dalla configurazione del grafo
Esempi avanzati
Pipeline di produzione contenuti
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'
}
);Workflow di ricerca di mercato
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'
}
}
);Tipi di risposta
I metodi dei sub-agent restituiscono formati di risposta diversi a seconda dell'operazione.
Risposta di Execute With Sub-Agents
L'esecuzione base con sub-agent restituisce il risultato combinato finale come stringa:
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."Risposta di Delegate Task
La delega dei task restituisce la risposta del sub-agent come stringa:
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."Risposta di Coordinate Agents
Il coordinamento di più agent restituisce un array di coppie task-risultato:
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."
}
]Risposta di Agent.ask() con Sub-Agent
Usare agent.ask() con opzioni sub-agent restituisce la stringa di risposta finale:
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."Risposta dell'assegnazione manuale dei task
Anche l'assegnazione manuale restituisce una stringa con i risultati combinati:
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."Ultimo aggiornamento: 6 luglio 2026
In questa sezione
Introduzione
Framework AI agent open-source per costruire sistemi autonomi che risolvono in modo efficace problemi del mondo reale.
Installazione
Installa Astreus con npm, yarn o pnpm, verifica la versione richiesta di Node.js e prepara un progetto locale per costruire agenti AI con il framework.
Avvio rapido
Costruisci il tuo primo agente AI con Astreus in meno di 2 minuti Scopri i pattern di configurazione, le API e gli esempi pratici necessari per creare...
Contesto
Gestione intelligente del contesto per conversazioni lunghe con compressione automatica Scopri i pattern di configurazione, le API e gli esempi pratici...