# Orchestrator Quick Start Guide

Get up and running with the orchestrator pattern in 5 minutes!

## What You'll Build

A **Project Manager** orchestrating **two specialized teams**:

1. **Research Team** (3 agents): Market research and analysis
2. **Development Team** (3 agents): Technical implementation

**Total**: 7 agents across 3 workspaces working together on a project.

## Prerequisites

- Python 3.9+
- Anthropic API key ([get one here](https://console.anthropic.com/))

## Installation

```bash
# 1. Install synqed and dependencies
pip install synqed anthropic python-dotenv

# 2. Navigate to examples directory
cd synqed-python/examples/intro

# 3. Create .env file with your API key
echo 'ANTHROPIC_API_KEY=your-key-here' > .env
```

## Quick Test (No API Key Required)

Test the structure without running LLMs:

```bash
python validate_orchestrator.py
```

Expected output:
```
✅ All imports successful
✅ All 7 agent logic functions imported successfully
✅ Root workspace created
✅ Research Team created
✅ Development Team created
✅ VALIDATION SUCCESSFUL!
```

## Full Run (API Key Required)

Run the complete orchestrator demo:

```bash
python orchestrator_two_teams.py
```

Expected output:
```
Multi-Team Orchestrator Demo
1 Project Manager → 2 Teams (Research + Development)

✅ Registered 7 agents
✅ Created root workspace
✅ Created Research Team workspace
✅ Created Development Team workspace

📋 Task: Build a social media analytics dashboard...

EXECUTION LOG (Real-time messages)
────────────────────────────────────────────
Project Manager → Research Lead: Research competitors...
Research Lead → Data Analyst: Analyze data...
Tech Lead → Backend Dev: Design APIs...
...
✅ Status: Task completed successfully!
```

## Understanding the Output

### Real-Time Display

Watch agents collaborate in real-time:
```
🔵 Project Manager → Research Lead
   "Please research competitors and user needs..."

🔵 Research Lead → Data Analyst
   "Analyze competitor features..."

🔵 Data Analyst → Research Lead
   "Analysis complete: Found 5 key competitors..."
```

### Final Summary

At the end, you'll see:
```
📊 Workspace Hierarchy:
   Root: ws-xxx (Project Manager)
   ├─ Research Team: ws-yyy (3 agents)
   └─ Development Team: ws-zzz (3 agents)

📈 Message Statistics:
   Root workspace: 8 messages
   Research Team: 12 messages
   Development Team: 10 messages
   Total: 30 messages

✅ Status: Task completed successfully!
```

## Customize the Task

Edit `orchestrator_two_teams.py` around line 620:

```python
task = (
    "Build a social media analytics dashboard. "
    "We need market research on competitors and user needs, "
    "plus a technical implementation plan for both backend and frontend."
)
```

Change to your own project task!

## Adjust Execution Parameters

Modify the execution engine settings around line 610:

```python
execution_engine = WorkspaceExecutionEngine(
    planner=planner,
    workspace_manager=workspace_manager,
    enable_display=True,           # Show real-time messages
    max_agent_turns=25,            # Increase for complex tasks
    max_workspace_depth=3,         # Maximum nesting level
)
```

## Common Issues & Solutions

### ❌ "Missing agent runtimes for roles"

**Problem**: Agent not registered before workspace creation

**Solution**: Ensure all agents are registered:
```python
AgentRuntimeRegistry.register("Agent Name", agent_instance)
```

### ❌ "Task incomplete (no message sent to USER)"

**Problem**: Agents didn't finish within turn limit

**Solution**: Increase `max_agent_turns`:
```python
execution_engine = WorkspaceExecutionEngine(
    max_agent_turns=50,  # Was 25, now 50
    ...
)
```

### ❌ API Rate Limit Errors

**Problem**: Too many requests to Anthropic API

**Solution**: Add delays or use lower tier model:
```python
planner = PlannerLLM(
    provider="anthropic",
    model="claude-3-haiku-20240307",  # Faster, cheaper
    ...
)
```

### ❌ "ANTHROPIC_API_KEY not found"

**Problem**: Environment variable not set

**Solution**: Verify `.env` file exists and has correct format:
```bash
cat .env
# Should show: ANTHROPIC_API_KEY='sk-ant-...'
```

## Next Steps

### 1. Add More Teams

Add a QA Team to the example:

```python
# Create QA agents
qa_lead = synqed.Agent(name="QA Lead", logic=qa_lead_logic, ...)
tester = synqed.Agent(name="Tester", logic=tester_logic, ...)
# ... register and add to task tree
```

### 2. Implement Dynamic Teams

Let agents request subteams on-demand:

```python
# In agent logic
return {
    "action": "request_subteam",
    "reason": "Need specialized security audit team",
    "requesting_agent": "Tech Lead"
}
```

### 3. Add State Persistence

Save workspace state to resume later:

```python
# After execution
transcript = workspace.router.get_transcript()
with open("transcript.json", "w") as f:
    json.dump(transcript, f)
```

### 4. Build Custom Display

Create a web UI to visualize agent interactions:

```python
# In workspace message callback
async def on_message(sender, recipient, content):
    websocket.send({
        "from": sender,
        "to": recipient,
        "message": content
    })

workspace.on_message(on_message)
```

## Learn More

### Documentation
- **Architecture**: See `ORCHESTRATOR_FLOW.md` for detailed flow diagrams
- **Full README**: See `README_ORCHESTRATOR.md` for comprehensive guide
- **Code**: Explore `orchestrator_two_teams.py` for implementation

### Examples
- `two_agents_collaborating.py` - Simple 2-agent example
- `client.py` - Single-agent client pattern

### Key Concepts
- **Workspaces**: Logical routing domains for agent teams
- **Agent Registry**: Prototype pattern for agent instances
- **Hierarchical Execution**: Parent-child workspace relationships
- **Message Routing**: Cross-workspace communication

## Architecture at a Glance

```
┌─────────────────────────────────────────────┐
│              USER                           │
│                ↓                            │
│         Project Manager ←─────────┐        │
│           ↙         ↘              │        │
│   Research Team  Development Team  │        │
│   (3 agents)     (3 agents)        │        │
│           ↓             ↓           │        │
│           └─────────────┴───[results]       │
│                                              │
└─────────────────────────────────────────────┘
```

### Agents

**Root Workspace (1 agent)**:
- Project Manager: Orchestrates and delegates

**Research Team (3 agents)**:
- Research Lead: Coordinates research
- Data Analyst: Gathers and analyzes data
- Report Writer: Creates reports

**Development Team (3 agents)**:
- Tech Lead: Coordinates development
- Backend Dev: Server-side implementation
- Frontend Dev: Client-side implementation

## Cost & Performance

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

### Optimization Tips
1. Use Haiku for faster/cheaper execution
2. Reduce max_agent_turns for simpler tasks
3. Implement caching for repeated patterns
4. Batch similar requests

## Support

### Getting Help
- Check error messages in console output
- Review transcripts with `workspace.router.get_transcript()`
- Enable debug logging: `logging.basicConfig(level=logging.DEBUG)`

### Common Debugging Commands

```python
# View all messages in workspace
transcript = workspace.router.get_transcript()
for entry in transcript:
    print(f"{entry['from']} → {entry['to']}")

# Check agent memory
agent = workspace.agents["Research Lead"]
print(agent.memory.get_messages())

# List all workspaces
print(workspace_manager.list_workspaces())
```

## Summary

You now have:
- ✅ 7-agent orchestrator system
- ✅ Hierarchical workspace structure
- ✅ Real-time execution monitoring
- ✅ Production-ready pattern

**Ready to build something amazing?** 🚀

Start with the example, customize the agents, and scale to your use case!

---

**Questions?** Open an issue or check the documentation in this directory.

