# Orchestrator Example - Complete Guide

Welcome! This directory contains a complete **orchestrator pattern example** demonstrating how a planner/orchestrator can delegate work to multiple specialized teams.

## 📚 Documentation Index

Start here based on your needs:

### 🚀 Quick Start (5 minutes)
**File**: [`QUICKSTART_ORCHESTRATOR.md`](QUICKSTART_ORCHESTRATOR.md)

Perfect for: Getting up and running fast
- Installation steps
- Basic validation
- Running your first orchestrator
- Common troubleshooting

### 📖 Complete Guide
**File**: [`README_ORCHESTRATOR.md`](README_ORCHESTRATOR.md)

Perfect for: Understanding the full system
- Detailed architecture
- How each component works
- Customization options
- Advanced usage patterns

### 🔄 Flow Diagrams
**File**: [`ORCHESTRATOR_FLOW.md`](ORCHESTRATOR_FLOW.md)

Perfect for: Visual learners
- System architecture diagrams
- Message flow examples
- Execution timeline
- Scaling patterns

## 📁 Files in This Example

### Core Implementation
- **`orchestrator_two_teams.py`** - Main example script (620 lines)
  - Project Manager orchestrator
  - Research Team (3 agents)
  - Development Team (3 agents)
  - Complete working example

### Validation & Testing
- **`validate_orchestrator.py`** - Structure validation (no API key needed)
  - Tests imports
  - Validates agent registration
  - Verifies workspace hierarchy
  - Quick sanity check

### Documentation
- **`QUICKSTART_ORCHESTRATOR.md`** - Quick start guide
- **`README_ORCHESTRATOR.md`** - Complete documentation
- **`ORCHESTRATOR_FLOW.md`** - Flow diagrams and patterns
- **`INDEX_ORCHESTRATOR.md`** - This file

## 🎯 What This Example Demonstrates

### Architecture
```
USER
  │
  └─ Project Manager (Orchestrator)
      │
      ├─ Research Team
      │   ├─ Research Lead
      │   ├─ Data Analyst
      │   └─ Report Writer
      │
      └─ Development Team
          ├─ Tech Lead
          ├─ Backend Dev
          └─ Frontend Dev
```

### Key Features
- ✅ **Hierarchical Workspaces**: 1 root + 2 child workspaces
- ✅ **7 Agents Total**: 1 orchestrator + 2 teams of 3
- ✅ **Cross-Workspace Communication**: Parent ↔ Child messaging
- ✅ **Independent Agent Memory**: Each workspace has isolated agents
- ✅ **Real-Time Display**: Watch agents collaborate live
- ✅ **Production-Ready**: Error handling, limits, validation

## 🏃 Getting Started

### Option 1: Quick Start (Recommended for beginners)
```bash
# 1. Read the quick start guide
cat QUICKSTART_ORCHESTRATOR.md

# 2. Install dependencies
pip install synqed anthropic python-dotenv

# 3. Create .env file
echo 'ANTHROPIC_API_KEY=your-key' > .env

# 4. Validate structure (no API calls)
python validate_orchestrator.py

# 5. Run full example
python orchestrator_two_teams.py
```

### Option 2: Deep Dive (For understanding internals)
```bash
# 1. Read architecture overview
cat README_ORCHESTRATOR.md

# 2. Study flow diagrams
cat ORCHESTRATOR_FLOW.md

# 3. Read the source code
less orchestrator_two_teams.py

# 4. Customize and experiment
```

## 💡 Use Cases

This pattern is perfect for:

### 1. **Software Development Projects**
- Project manager coordinates multiple development teams
- Research, design, development, QA teams work in parallel
- Each team has specialized expertise

### 2. **Research & Analysis**
- Orchestrator delegates to domain experts
- Data collection, analysis, and reporting teams
- Results synthesized into comprehensive report

### 3. **Content Creation**
- Editor coordinates writers, researchers, designers
- Parallel work on different content aspects
- Final assembly and quality review

### 4. **Business Operations**
- Manager delegates to specialized departments
- Sales, marketing, operations, finance teams
- Cross-functional coordination

### 5. **Event Planning**
- Event coordinator manages multiple committees
- Venue, catering, entertainment, marketing teams
- Synchronized timeline and deliverables

## 🔑 Key Concepts

### 1. Workspace Hierarchy
Workspaces are **logical routing domains** that contain agents and can be nested:

```python
# Root workspace
root_workspace = await workspace_manager.create_workspace(
    task_tree_node=root_node,
    parent_workspace_id=None
)

# Child workspace
team_workspace = await workspace_manager.create_workspace(
    task_tree_node=team_node,
    parent_workspace_id=root_workspace.workspace_id
)
```

### 2. Agent Registry
The **AgentRuntimeRegistry** stores agent prototypes (templates):

```python
# Register prototype
AgentRuntimeRegistry.register("Research Lead", research_lead_agent)

# Each workspace gets independent cloned instances
workspace1 = create_workspace(...)  # Gets Research Lead clone #1
workspace2 = create_workspace(...)  # Gets Research Lead clone #2
```

### 3. Message Routing
Messages automatically route across workspace boundaries:

```python
# Send from root to child workspace
await root_workspace.route_message(
    sender="Project Manager",
    recipient="Research Lead",  # In child workspace
    content="Do research...",
    manager=workspace_manager
)
```

### 4. Result Aggregation
Child workspaces return results marked with `[subteam_result]`:

```python
# Execution engine automatically sends when child completes
await parent_workspace.route_message(
    sender="Research Lead",
    recipient="Project Manager",
    content="[subteam_result] Research complete: ...",
)
```

## 📊 Performance & Cost

### Typical Execution
- **Duration**: 15-30 seconds
- **Messages**: ~30 total across all workspaces
- **Tokens**: ~6,000 output tokens
- **Cost**: ~$0.03 per run (Claude Sonnet 4.5)

### Optimization
- Use Claude Haiku for 3x faster, 10x cheaper
- Reduce `max_agent_turns` for simpler tasks
- Cache agent responses for repeated patterns
- Batch similar requests together

## 🎓 Learning Path

### Beginner
1. ✅ Read `QUICKSTART_ORCHESTRATOR.md`
2. ✅ Run `validate_orchestrator.py`
3. ✅ Run `orchestrator_two_teams.py` with example task
4. ✅ Modify the task and re-run

### Intermediate
1. ✅ Read `README_ORCHESTRATOR.md` completely
2. ✅ Study `ORCHESTRATOR_FLOW.md` diagrams
3. ✅ Modify agent logic functions
4. ✅ Add a new agent to existing team
5. ✅ Change execution parameters

### Advanced
1. ✅ Read the full source code
2. ✅ Add a third team (e.g., QA Team)
3. ✅ Implement deeper nesting (sub-sub-teams)
4. ✅ Add dynamic subteam creation
5. ✅ Build custom message display/UI
6. ✅ Implement state persistence

## 🔧 Customization Examples

### Add a Third Team
```python
# 1. Create agent logic functions
async def qa_lead_logic(context): ...
async def tester_logic(context): ...
async def reviewer_logic(context): ...

# 2. Register agents
AgentRuntimeRegistry.register("QA Lead", qa_lead)
AgentRuntimeRegistry.register("Tester", tester)
AgentRuntimeRegistry.register("Reviewer", reviewer)

# 3. Add to task tree
root_task_node.children.append(
    TaskTreeNode(
        id="qa-team",
        description="Quality assurance tasks",
        required_agents=["QA Lead", "Tester", "Reviewer"],
    )
)

# 4. Create workspace
qa_workspace = await workspace_manager.create_workspace(
    task_tree_node=qa_team_node,
    parent_workspace_id=root_workspace.workspace_id
)
```

### Change Team Size
```python
# Instead of 3 agents per team, use 2 or 4
TaskTreeNode(
    id="research-team",
    required_agents=["Research Lead", "Analyst"],  # Only 2 agents
    ...
)
```

### Modify Agent Behavior
```python
# In agent logic function
system_prompt = (
    "You are a Research Lead. "
    "NEW INSTRUCTION: Always provide citations for claims. "
    "NEW INSTRUCTION: Limit responses to 100 words. "
    ...
)
```

## 🐛 Debugging

### Enable Detailed Logging
```python
import logging
logging.basicConfig(level=logging.DEBUG)
```

### View Workspace Transcripts
```python
# After execution
transcript = workspace.router.get_transcript()
for entry in transcript:
    print(json.dumps(entry, indent=2))
```

### Check Agent Memory
```python
agent = workspace.agents["Research Lead"]
messages = agent.memory.get_messages()
print(f"Agent has {len(messages)} messages in memory")
```

### Inspect Workspace Hierarchy
```python
print(f"Root: {root_workspace.workspace_id}")
print(f"Children: {root_workspace.children}")
print(f"Agents: {list(root_workspace.agents.keys())}")
```

## 🚨 Common Issues

### Task Doesn't Complete
**Symptom**: "Task incomplete (no message sent to USER)"

**Solutions**:
1. Increase `max_agent_turns`
2. Simplify the task
3. Check agent logic for infinite loops
4. Review transcripts to find where it stopped

### API Rate Limits
**Symptom**: "RateLimitError" from Anthropic

**Solutions**:
1. Add delays between requests
2. Use lower tier (Haiku)
3. Reduce concurrent workspaces
4. Implement retry logic

### Memory Issues
**Symptom**: Agents lose context or repeat themselves

**Solutions**:
1. Check agent memory implementation
2. Verify transcript building logic
3. Ensure agents include conversation context
4. Debug with smaller message history

## 📚 Related Resources

### Other Examples
- `two_agents_collaborating.py` - Simple collaboration
- `client.py` - Single-agent pattern

### Synqed Documentation
- Core concepts: Agent, Workspace, Router
- Advanced patterns: Dynamic subteams, state persistence
- API reference: Full method documentation

### External Resources
- Anthropic API documentation
- Multi-agent system design patterns
- LangChain orchestration patterns

## 🎯 Next Steps

After mastering this example:

1. **Scale Up**: Add more teams and agents
2. **Go Deeper**: Implement nested sub-sub-teams
3. **Add Features**: Persistent state, web UI, monitoring
4. **Optimize**: Caching, batching, parallel execution
5. **Productionize**: Error recovery, rate limiting, logging

## 💬 Support

### Getting Help
- Read the documentation files in this directory
- Check error messages and logs
- Review transcripts to understand agent behavior
- Enable debug logging for detailed information

### Contributing
- Report issues with examples
- Suggest improvements
- Share your custom patterns
- Contribute new examples

## 📝 Summary

This orchestrator example provides:
- ✅ Complete working implementation
- ✅ Comprehensive documentation
- ✅ Validation tools
- ✅ Clear learning path
- ✅ Production-ready patterns

**You now have everything you need to build sophisticated multi-agent orchestrator systems!**

---

**Start here**: [`QUICKSTART_ORCHESTRATOR.md`](QUICKSTART_ORCHESTRATOR.md)

**Questions?** Review the documentation or open an issue.

**Ready to build?** Let's go! 🚀

