Building Advanced Sub-Agents in Astreus
Create sophisticated multi-agent workflows with complex coordination patterns. Learn to build specialist agents using different models, implement delegation strategies, and orchestrate teams for production-grade AI systems.
Advanced multi-agent systems enable sophisticated workflows where specialized agents coordinate to solve complex problems. This guide explores building production-ready agent teams using the Astreus framework with real-world patterns for delegation, coordination, and orchestration.
## Environment Setup
Before building advanced sub-agent systems, configure your environment with the necessary API keys and database connection.
```bash
# .env file
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key
DB_URL=sqlite://./astreus.db
```
The database URL enables memory and knowledge base features. SQLite works well for development, while PostgreSQL is recommended for production deployments.
## Multi-Model Agent Architecture
Different AI models excel at different tasks. GPT-4o provides strong analytical reasoning, while Claude 3.5 Sonnet produces more natural, creative content. Advanced systems combine multiple models strategically based on task requirements.
The coordinator pattern works best for multi-model systems. A coordinator agent analyzes requests and delegates subtasks to specialist agents, each using the model that best fits their role.
## Creating the Strategic Planner Agent
The strategic planner handles high-level analytical reasoning and planning tasks. Memory and knowledge base integration enable contextual decision-making.
```typescript
const strategicPlanner = await Agent.create({
name: 'StrategicPlanner',
model: 'gpt-4o',
systemPrompt: 'You are a strategic planner. Analyze complex problems and develop comprehensive plans.',
memory: true,
knowledge: true
});
```
The `Agent.create()` method instantiates agents with full configuration support. Memory enables learning from past interactions, while knowledge bases provide access to curated information.
## Building the Creative Writer Agent
Claude excels at creative writing and narrative generation. Vision capabilities allow processing images alongside text for richer content creation.
```typescript
const creativeWriter = await Agent.create({
name: 'CreativeWriter',
model: 'claude-3-5-sonnet-20241022',
systemPrompt: 'You are a creative writer. Generate engaging, natural prose that connects with readers.',
vision: true
});
```
Vision support means the writer can analyze images, screenshots, or diagrams and incorporate visual context into written content.
## Implementing the Data Scientist Agent
The data scientist agent combines analytical capabilities with tool integration for statistical analysis and data processing. Tools are registered using `registerPlugin()` after agent creation.
```typescript
const dataScientist = await Agent.create({
name: 'DataScientist',
model: 'gpt-4o',
systemPrompt: 'You are a data scientist. Perform statistical analysis and extract insights from data.'
});
// Register tools via plugin system
await dataScientist.registerPlugin({
name: 'analytics',
version: '1.0.0',
description: 'Data analysis tools',
tools: [
{
name: 'analyzeDataset',
description: 'Perform statistical analysis on datasets',
parameters: {
dataset: { name: 'dataset', type: 'string', description: 'Dataset name or path', required: true },
metrics: { name: 'metrics', type: 'array', description: 'Metrics to calculate' }
},
handler: async (params) => {
// Implementation here
return { success: true, data: { /* analysis results */ } };
}
}
]
});
```
Tools extend agent capabilities beyond text generation. The data scientist can call custom functions for specialized operations like statistical calculations or database queries. Tools are registered via the plugin system using `registerPlugin()`, which provides a clean separation between agent configuration and tool definitions.
## Assembling the Executive Coordinator
The coordinator orchestrates specialist agents to handle complex, multi-faceted requests. It accepts sub-agents through the `subAgents` parameter.
```typescript
const executiveCoordinator = await Agent.create({
name: 'ExecutiveCoordinator',
model: 'gpt-4o',
systemPrompt: `You coordinate a team of specialist agents:
- StrategicPlanner: for analytical reasoning and planning
- CreativeWriter: for content creation and narrative
- DataScientist: for data analysis and insights
Analyze requests, delegate to appropriate specialists, and synthesize results.`,
subAgents: [strategicPlanner, creativeWriter, dataScientist]
});
```
By passing agents to the `subAgents` array, the coordinator gains the ability to delegate tasks. The framework handles routing and execution automatically.
## Delegation Strategies
The coordinator uses different delegation strategies depending on the task. Sequential execution processes subtasks in order, while parallel delegation handles independent work simultaneously.
```typescript
const result = await executiveCoordinator.ask(
'Analyze market trends and create an executive summary',
{
useSubAgents: true,
delegation: 'auto',
coordination: 'sequential'
}
);
```
The `delegation: 'auto'` setting lets the coordinator decide which specialists to involve. Sequential coordination ensures subtasks complete in order, which matters when later tasks depend on earlier results.
## Implementing Parallel Coordination
When subtasks are independent, parallel coordination reduces total execution time significantly.
```typescript
const parallelResult = await executiveCoordinator.ask(
'Research competitors A, B, and C',
{
useSubAgents: true,
delegation: 'auto',
coordination: 'parallel'
}
);
```
The coordinator dispatches multiple specialists simultaneously. Each researches a different competitor, and the coordinator waits for all results before synthesizing the final response.
## Memory Integration
Memory allows agents to learn from conversations and recall important context. The `extractionLevel` parameter controls how aggressively the agent extracts facts.
```typescript
const accountManager = await Agent.create({
name: 'AccountManager',
model: 'gpt-4o',
systemPrompt: 'You manage client relationships. Remember preferences, history, and needs.',
memory: true
});
```
Moderate extraction balances coverage with precision. The agent remembers key facts without overwhelming storage with trivial details. Settings range from 'minimal' to 'aggressive'.
## Knowledge Base Setup
Knowledge bases provide agents with curated information. Unlike memory, which comes from conversations, knowledge bases contain documents you explicitly add.
```typescript
const supportAgent = await Agent.create({
name: 'SupportAgent',
model: 'gpt-4o',
systemPrompt: 'You help customers with product questions. Search the knowledge base for accurate information.',
knowledge: true
});
```
The agent searches the knowledge base semantically when answering questions. This grounds responses in authoritative sources rather than relying solely on training data.
## Error Handling and Retries
Production systems need resilience. Configure retry logic and fallback models for when primary models fail.
```typescript
const resilientAgent = await Agent.create({
name: 'ResilientAgent',
model: 'gpt-4o',
systemPrompt: 'You handle customer requests reliably.',
debug: true
});
```
If the primary model fails after retries, the agent automatically switches to the fallback. Exponential backoff prevents overwhelming rate limits during temporary outages.
## Cost Optimization with Model Selection
Model costs vary dramatically. Strategic selection can reduce costs by 50-70% without sacrificing quality where it matters.
```typescript
// Premium model for complex analysis
const analyst = await Agent.create({
name: 'Analyst',
model: 'gpt-4o',
systemPrompt: 'You analyze complex business problems.'
});
// Cost-effective model for routine tasks
const formatter = await Agent.create({
name: 'Formatter',
model: 'gpt-4o-mini',
systemPrompt: 'You format data into structured outputs.'
});
```
GPT-4o-mini costs a fraction of GPT-4o per token. Use it for tasks like formatting, validation, or basic transformations where advanced reasoning isn't required.
## The Triage Pattern
Use a fast, cheap model to filter requests before engaging expensive models. This pattern dramatically reduces costs for high-volume systems.
```typescript
const triageAgent = await Agent.create({
name: 'TriageAgent',
model: 'gpt-4o-mini',
systemPrompt: `Classify requests as:
- simple: handle directly
- complex: escalate to specialist
- out-of-scope: not something we handle`
});
const coordinator = await Agent.create({
name: 'Coordinator',
model: 'gpt-4o',
systemPrompt: 'Handle escalated complex requests.',
subAgents: [triageAgent]
});
```
The coordinator asks the triage agent to assess each request first. Simple requests never hit the expensive model, significantly reducing overall costs.
## Consensus Voting Pattern
For high-stakes decisions, have multiple agents independently analyze the question. Make decisions based on agreement levels.
```typescript
const riskAnalyst1 = await Agent.create({
name: 'RiskAnalyst1',
model: 'gpt-4o',
systemPrompt: 'You assess financial risk conservatively.'
});
const riskAnalyst2 = await Agent.create({
name: 'RiskAnalyst2',
model: 'claude-3-5-sonnet-20241022',
systemPrompt: 'You assess financial risk conservatively.'
});
const decisionMaker = await Agent.create({
name: 'DecisionMaker',
model: 'gpt-4o',
systemPrompt: 'Review risk assessments and make decisions. If analysts disagree, flag for human review.',
subAgents: [riskAnalyst1, riskAnalyst2]
});
```
Using different models for each analyst reduces the risk of shared biases. Disagreement between analysts signals that the decision needs human judgment.
## Monitoring Token Usage
For detailed token tracking, use the task-based API which provides usage statistics.
```typescript
const task = await executiveCoordinator.createTask({
prompt: 'Generate quarterly market analysis',
useSubAgents: true
});
const result = await executiveCoordinator.executeTask(task.id);
console.log(`Response: ${result.response}`);
console.log(`Total tokens: ${result.usage?.totalTokens}`);
```
The task-based API returns detailed execution information including token usage. Use this data to optimize prompts and understand costs.
## Crafting Effective System Prompts
Clear system prompts define agent behavior precisely. Specify role, responsibilities, and boundaries.
```typescript
const contractAnalyzer = await Agent.create({
name: 'ContractAnalyzer',
model: 'gpt-4o',
systemPrompt: `You analyze legal contracts for business clients.
Responsibilities:
- Identify key terms, obligations, and deadlines
- Flag unusual or risky clauses
- Summarize in plain English
Boundaries:
- Never provide legal advice, only analysis
- Cite specific sections when flagging issues
- Acknowledge limitations of automated review`
});
```
Explicit boundaries prevent agents from overstepping their expertise. The contract analyzer won't attempt legal advice, keeping outputs within appropriate scope.
## Real-World Example: Research Pipeline
Here's a complete multi-agent system for generating research reports with parallel processing and quality assurance.
```typescript
import { Agent } from '@astreus-ai/astreus';
// Data collection agent
const dataCollector = await Agent.create({
name: 'DataCollector',
model: 'gpt-4o',
systemPrompt: 'You gather and analyze market data.'
});
// Competitive intelligence agent
const competitiveIntel = await Agent.create({
name: 'CompetitiveIntel',
model: 'gpt-4o',
systemPrompt: 'You analyze competitors and market positioning.'
});
// Report writer using Claude
const reportWriter = await Agent.create({
name: 'ReportWriter',
model: 'claude-3-5-sonnet-20241022',
systemPrompt: 'You write executive reports. Create clear, compelling narratives.'
});
// Quality assurance with cost-effective model
const qualityChecker = await Agent.create({
name: 'QualityChecker',
model: 'gpt-4o-mini',
systemPrompt: 'You check reports for errors and clarity issues.'
});
// Research coordinator
const researchCoordinator = await Agent.create({
name: 'ResearchCoordinator',
model: 'gpt-4o',
systemPrompt: `You coordinate research projects.
Workflow:
1. DataCollector and CompetitiveIntel work in parallel
2. ReportWriter synthesizes their findings
3. QualityChecker reviews final output
4. Return polished report`,
subAgents: [dataCollector, competitiveIntel, reportWriter, qualityChecker]
});
// Execute the pipeline
const report = await researchCoordinator.ask(
'Generate market research for electric vehicles in North America',
{
useSubAgents: true,
coordination: 'sequential'
}
);
console.log(report);
```
This system combines GPT-4o's analytical capabilities for data and competitive analysis, Claude's writing strength for report generation, and a cost-effective model for QA. The coordinator handles the entire workflow automatically.
## Running the Examples
You can run the official examples by cloning the repository or installing the package independently.
```bash
# Clone and run examples
git clone https://github.com/astreus-ai/sub-agents-advanced
cd sub-agents-advanced
npm install
npm run dev
# Or install package for your own project
npm install @astreus-ai/astreus
```
The repository contains complete working examples demonstrating all patterns discussed in this guide.
## Testing Multi-Agent Systems
Test individual agents first, then test coordination logic with integration tests.
```typescript
// Test individual agent
const writerResult = await creativeWriter.ask(
'Write a product description for wireless headphones'
);
assert(writerResult.length > 100);
assert(writerResult.includes('wireless'));
// Test coordination
const coordinatedResult = await executiveCoordinator.ask(
'Create a marketing campaign for wireless headphones',
{ useSubAgents: true }
);
assert(coordinatedResult.length > 0);
assert(coordinatedResult.includes('target audience'));
```
Integration tests verify that agents collaborate correctly and the coordinator routes tasks to appropriate specialists.
## Production Instrumentation
Add comprehensive logging and monitoring for production deployments.
```typescript
const productionAgent = await Agent.create({
name: 'ProductionAgent',
model: 'gpt-4o',
systemPrompt: 'You handle customer requests.',
debug: true
});
```
Comprehensive instrumentation enables debugging issues, understanding usage patterns, and optimizing performance based on real-world behavior.
## Key Takeaways
Advanced sub-agent systems leverage multiple models strategically through coordination patterns. Use `Agent.create()` to instantiate agents with full configuration support including memory, knowledge bases, and tools.
Implement delegation with the `useSubAgents` option and coordination strategies like sequential or parallel execution. Monitor token usage and costs to optimize model selection.
Add memory for agents that need conversation context. Integrate knowledge bases for grounding in authoritative sources. Implement error handling with retries and fallback models for production resilience.
Start with clear system prompts that define roles and boundaries. Test agents individually and as coordinated systems. Use instrumentation to learn from real usage and continuously improve your multi-agent architecture.
This experiment is written for Astreus v0.5.37. Please ensure you are using a compatible version.