Building Graph Sub-Agents in Astreus

Combining Graph workflows with Sub-Agent coordination enables hierarchical task distribution in Astreus. This pattern lets you create specialized agents with distinct capabilities and coordinate them through a main agent within graph workflows.

## Installation and Setup

You can clone the complete example repository or install just the package:

```bash
# Clone complete example
git clone https://github.com/astreus-ai/graph-sub-agents
cd graph-sub-agents
npm install

# Or install package only
npm install @astreus-ai/astreus
```

Configure your environment with the required API keys:

```
OPENAI_API_KEY=sk-your-openai-api-key-here
ANTHROPIC_API_KEY=your-anthropic-api-key-here
DB_URL=sqlite://./astreus.db
```

## Creating Specialized Sub-Agents

The framework enables creating specialized agents with different roles. Each agent specifies its `systemPrompt` to define its specialized behavior.

```typescript
// Research specialist with knowledge base and memory
const researchSpecialist = await Agent.create({
name: 'ResearchSpecialist',
model: 'gpt-4o',
systemPrompt: 'You are an expert researcher. Gather comprehensive information and cite sources.',
knowledge: true,
memory: true
});

// Data analyst with tool usage capabilities
const dataAnalyst = await Agent.create({
name: 'DataAnalyst',
model: 'gpt-4o',
systemPrompt: 'You analyze data and extract actionable insights.'
});

// Register analysis tools via plugin system
await dataAnalyst.registerPlugin({
name: 'analytics',
version: '1.0.0',
description: 'Data analysis tools',
tools: [analysisTool]
});

// Content writer with vision capabilities
const contentWriter = await Agent.create({
name: 'ContentWriter',
model: 'claude-3-5-sonnet',
systemPrompt: 'You transform information into compelling narratives.',
vision: true
});
```

Three specialized agents are created: ResearchSpecialist uses GPT-4o with knowledge base and memory for information gathering, DataAnalyst is configured with GPT-4o and tool usage for analytical tasks, and ContentWriter employs Claude 3.5 Sonnet with vision capabilities for content generation.

## Setting Up the Coordinator Agent

The main coordinator delegates tasks to appropriate specialists through the sub-agents configuration parameter:

```typescript
const coordinator = await Agent.create({
name: 'Coordinator',
model: 'gpt-4o',
systemPrompt: `You coordinate complex projects using specialized sub-agents.
Delegate tasks to the appropriate specialist based on task requirements.`,
subAgents: [researchSpecialist, dataAnalyst, contentWriter]
});
```

The coordinator's system prompt defines its role in managing the team. It understands which specialists are available and routes tasks accordingly.

## Creating a Sub-Agent Aware Graph

The graph is created with sub-agent coordination awareness enabled:

```typescript
const graph = new Graph({
name: 'Coordinator Graph'
}, coordinator);
```

The `subAgentAware: true` flag enables sub-agent coordination awareness, while `maxConcurrency: 2` controls parallel execution limits. The default agent is set to the coordinator instance.

## Configuring Task Nodes

Task nodes leverage sub-agents through specific parameters:

```typescript
// Market research task with auto-delegation
const marketResearch = graph.addTaskNode({
name: 'market-research',
prompt: 'Research market trends for {{topic}}',
useSubAgents: true,
subAgentDelegation: 'auto'
});

// Data analysis with parallel coordination
const dataAnalysis = graph.addTaskNode({
name: 'data-analysis',
prompt: 'Analyze research findings',
dependencies: [marketResearch],
useSubAgents: true,
subAgentDelegation: 'auto',
subAgentCoordination: 'parallel'
});

// Report generation
const report = graph.addTaskNode({
name: 'report',
prompt: 'Generate executive report',
dependencies: [dataAnalysis],
useSubAgents: true,
subAgentDelegation: 'auto'
});
```

Key parameters include: `useSubAgents: true` activates sub-agent delegation, `subAgentDelegation: 'auto'` enables automatic specialist selection, `subAgentCoordination: 'parallel'` allows parallel execution mode, and `dependencies: [taskId]` establishes execution order.

## Workflow Execution Flow

The workflow follows a clear execution pattern:

```
Market Research (auto-delegated to ResearchSpecialist)
↓
Data Analysis (parallel processing with DataAnalyst)
↓
Executive Report Generation (ContentWriter)
```

Each task is automatically routed to the most appropriate specialist. The coordinator analyzes the task requirements and delegates accordingly.

## Running the Example

Execute the workflow with simple commands:

```bash
# Pre-cloned repository
npm run dev

# Custom setup
npx tsx index.ts
```

Results are aggregated and returned with success/failure status, completed node count, execution duration, individual task results, and final consolidated output.

## Understanding Result Structure

The graph execution returns comprehensive results:

```typescript
const result = await graph.run({
topic: 'AI market trends'
});

// Access results
console.log('Success:', result.success);
console.log('Completed nodes:', result.completedNodes);
console.log('Duration:', result.duration, 'ms');
console.log('Final output:', result.output);

// Individual task results
console.log('Research:', result.taskResults['market-research']);
console.log('Analysis:', result.taskResults['data-analysis']);
console.log('Report:', result.taskResults['report']);
```

The result object provides detailed information about the entire workflow execution, including individual task outputs and overall metrics.

## Delegation Strategies

Astreus supports different delegation strategies:

```typescript
// Auto delegation - coordinator decides which specialist to use
graph.addTaskNode({
name: 'deep-research',
prompt: 'Conduct deep research on {{topic}}',
useSubAgents: true,
subAgentDelegation: 'auto'
});

// Sequential delegation - tasks are delegated one at a time
graph.addTaskNode({
name: 'step-by-step',
prompt: 'Process this step by step',
useSubAgents: true,
subAgentDelegation: 'sequential'
});

// Manual delegation - you control the flow explicitly
graph.addTaskNode({
name: 'manual-task',
prompt: 'Handle this with manual control',
useSubAgents: true,
subAgentDelegation: 'manual'
});
```

Auto-delegation lets the coordinator choose the specialist. Sequential processes tasks one at a time. Manual gives you explicit control over the delegation flow.

## Parallel Execution Benefits

Leverage parallel coordination for independent tasks:

```typescript
// Research phase
const research = graph.addTaskNode({
name: 'research',
prompt: 'Research {{topic}}',
useSubAgents: true
});

// Parallel analysis tasks
const technicalAnalysis = graph.addTaskNode({
name: 'technical-analysis',
prompt: 'Technical analysis',
dependencies: [research],
useSubAgents: true,
subAgentCoordination: 'parallel'
});

const marketAnalysis = graph.addTaskNode({
name: 'market-analysis',
prompt: 'Market analysis',
dependencies: [research],
useSubAgents: true,
subAgentCoordination: 'parallel'
});

// Synthesis
graph.addTaskNode({
name: 'synthesis',
prompt: 'Synthesize findings',
dependencies: [technicalAnalysis, marketAnalysis],
useSubAgents: true
});
```

Parallel coordination allows multiple specialists to work simultaneously on independent tasks, significantly reducing overall execution time.

## Monitoring and Debugging

Track delegation and execution events:

```typescript
const graph = new Graph({
name: 'Coordinator Graph'
}, coordinator);
```

These hooks provide visibility into which specialist handles each node, execution times, and outputs. Essential for debugging and optimization.

## Best Practices

Keep specialist roles clearly defined without overlap. Each should excel in one focused area. Match specialists to workflow stages naturally.

Use appropriate models for each specialist. Powerful reasoning models for analysis, creative models for writing, fast models for routine tasks. Balance quality and cost.

Implement comprehensive monitoring to track specialist usage, execution times, and resource consumption. This data is invaluable for optimization.

Start with auto-delegation and move to explicit delegation only when you need precise control. The coordinator is often better at routing than manual assignments.

## When to Use This Pattern

This architecture excels for complex multi-stage workflows where different stages need genuinely different skills. Content production, market research, and data analysis pipelines are ideal use cases.

The pattern also shines when you need high-quality outputs and can accept the complexity trade-off. Specialization improves results but adds architectural overhead.

Avoid this pattern for simple tasks or when latency is critical. The delegation overhead isn't worth it for single-step operations or time-sensitive workflows.

## Resources

Complete example repository: [astreus-ai/graph-sub-agents](https://github.com/astreus-ai/graph-sub-agents)

Official documentation: [astreus.org/docs](https://astreus.org/docs)

This pattern combines the orchestration power of graphs with the specialized expertise of multiple agents, creating sophisticated AI systems that can tackle complex, multi-faceted tasks efficiently.

This experiment is written for Astreus v0.5.37. Please ensure you are using a compatible version.