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