# 🎨 Visual Reference Guide

**Quick visual guide to understanding Synqed concepts**

---

## 🏗️ Architecture Overview

```
┌──────────────────────────────────────────────────────────────┐
│                         YOUR APPLICATION                      │
└────────────────────┬─────────────────────────────────────────┘
                     │
                     ▼
      ┌──────────────────────────────┐
      │   OrchestratedWorkspace       │  ← Coordination layer
      │  (enable_agent_discussion)    │
      └────────────┬─────────────────┘
                   │
                   ▼
         ┌─────────────────┐
         │  Orchestrator    │  ← AI planner (GPT-4o)
         │  (LLM-powered)   │
         └────────┬─────────┘
                  │
        ┌─────────┴─────────┐
        │                   │
        ▼                   ▼
   ┌────────┐         ┌────────┐
   │ Agent  │ A2A     │ Agent  │  ← Specialized workers
   │   1    │◄───────►│   2    │
   └────────┘         └────────┘
        │                   │
        ▼                   ▼
   ┌────────┐         ┌────────┐
   │ Server │         │ Server │  ← HTTP endpoints
   │ :8001  │         │ :8002  │
   └────────┘         └────────┘
```

---

## 🔄 Message Flow

```
1. User submits task
   │
   ▼
2. Workspace receives task
   │
   ▼
3. Orchestrator analyzes (uses LLM)
   │
   ├─ Understands requirements
   ├─ Breaks into subtasks
   └─ Selects best agents
   │
   ▼
4. Agent Discovery (A2A Protocol)
   │
   GET /.well-known/agent-card.json
   │
   ├─► Agent 1: Returns capabilities
   ├─► Agent 2: Returns capabilities
   └─► Agent 3: Returns capabilities
   │
   ▼
5. Task Delegation
   │
   POST / with task payload
   │
   ├─► Agent 1: Task A ──┐
   ├─► Agent 2: Task B ──┤ (parallel)
   └─► Agent 3: Task C ──┘
   │
   ▼
6. Agents Execute
   │
   ├─ Agent 1: Calls LLM, returns result
   ├─ Agent 2: Calls LLM, returns result
   └─ Agent 3: Calls LLM, returns result
   │
   ▼
7. Result Collection
   │
   ├─ Result A ──┐
   ├─ Result B ──┤ Orchestrator collects
   └─ Result C ──┘
   │
   ▼
8. Synthesis (Orchestrator uses LLM)
   │
   └─ Combines all results into coherent answer
   │
   ▼
9. Return to user
```

---

## 🎯 Execution Patterns

### Sequential (Dependencies)

```
Task: "Research topic, then write article about it"

Agent A          Agent B
(Research)       (Writer)
   │                
   ├──── runs ─────┐
   │               │
   ▼               │
 Result A          │
   │               │
   └──── waits ────┤
                   │
                   ├──── runs ────┐
                   │               │
                   ▼               │
                 Result B          │
                   │               │
                   └───────────────┘

Execution Order: [[Agent A], [Agent B]]
Time: Sequential (slower, but necessary)
```

### Parallel (No Dependencies)

```
Task: "Analyze data AND create report template"

Agent A          Agent B
(Analyst)        (Designer)
   │                │
   ├──── runs ──────┤
   │                │
   ▼                ▼
 Result A        Result B
   │                │
   └────── both ────┘

Execution Order: [[Agent A, Agent B]]
Time: Parallel (faster!)
```

### Mixed (Complex Dependencies)

```
Task: "Research, then create content and quote in parallel, then admin"

   Agent A
  (Research)
      │
      ▼
   Result A
      │
   ┌──┴──┐
   │     │
   ▼     ▼
Agent B  Agent C    ← Parallel
(Content)(Deal)
   │     │
   ▼     ▼
   └──┬──┘
      │
      ▼
   Agent D
   (Admin)

Execution Order: [[A], [B, C], [D]]
Stages: 3 (optimal speed)
```

---

## 🧩 Component Relationships

```
┌─────────────────────────────────────────────────────────┐
│                        Agent                             │
│                                                          │
│  ┌────────────┐  ┌──────────────┐  ┌────────────────┐  │
│  │    Name    │  │ Description  │  │    Skills      │  │
│  │            │  │              │  │  [{...}, {...}]│  │
│  │ "MyAgent"  │  │ "What it     │  │                │  │
│  │            │  │  does"       │  │  - skill_id    │  │
│  │            │  │              │  │  - name        │  │
│  └────────────┘  └──────────────┘  │  - description │  │
│                                     │  - tags[]      │  │
│                                     └────────────────┘  │
│                                                          │
│  ┌──────────────────────────────────────────────────┐  │
│  │              Executor Function                    │  │
│  │                                                   │  │
│  │  async def executor(context):                    │  │
│  │      user_input = context.get_user_input()       │  │
│  │      # Do something smart                        │  │
│  │      return result                               │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
              ┌────────────────────────┐
              │    AgentServer          │
              │    (port: 8001)         │
              └────────────────────────┘
                           │
                           ▼
              ┌────────────────────────┐
              │  HTTP Endpoints:        │
              │                         │
              │  GET /.well-known/      │
              │      agent-card.json    │
              │                         │
              │  POST /                 │
              │      (task delegation)  │
              └────────────────────────┘
```

---

## 📊 Data Flow in Executor

```
                    ┌─────────────────┐
                    │  Task arrives   │
                    │  at agent       │
                    └────────┬────────┘
                             │
                             ▼
              ┌──────────────────────────────┐
              │  Executor Function Called    │
              │                              │
              │  async def executor(context) │
              └──────────────┬───────────────┘
                             │
                ┌────────────┴────────────┐
                │                         │
                ▼                         ▼
    ┌───────────────────────┐   ┌──────────────────┐
    │  Context Object       │   │  User Input      │
    │                       │   │  "Do this task"  │
    │  - get_user_input()   │   └──────────────────┘
    │  - get_task()         │            │
    │  - get_message()      │            │
    └───────────────────────┘            │
                │                        │
                └────────────┬───────────┘
                             │
                             ▼
                  ┌─────────────────────┐
                  │  Processing Logic   │
                  │                     │
                  │  - Call LLM         │
                  │  - Query DB         │
                  │  - Call API         │
                  │  - Process data     │
                  └──────────┬──────────┘
                             │
                             ▼
                  ┌─────────────────────┐
                  │  Return Result      │
                  │                     │
                  │  return "answer"    │
                  └──────────┬──────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │  Result sent    │
                    │  back to        │
                    │  orchestrator   │
                    └─────────────────┘
```

---

## 🎭 Workspace Lifecycle

```
┌─────────────────────────────────────────────────────────┐
│                    INITIALIZATION                        │
└────────────────────┬────────────────────────────────────┘
                     │
                     ▼
         ┌─────────────────────────┐
         │  Create Orchestrator    │
         │  (LLM configuration)    │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Create Workspace       │
         │  (configure options)    │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Register Agents        │
         │  (make available)       │
         └────────────┬────────────┘
                      │
┌─────────────────────┴────────────────────────────────────┐
│                     EXECUTION                             │
└────────────────────┬─────────────────────────────────────┘
                     │
                     ▼
         ┌─────────────────────────┐
         │  execute_task() called  │
         │  (user submits task)    │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Analysis & Planning    │
         │  (orchestrator thinks)  │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Agent Selection        │
         │  (match skills to task) │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Task Delegation        │
         │  (send work to agents)  │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Parallel Execution     │
         │  (agents work)          │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Result Collection      │
         │  (gather outputs)       │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Synthesis              │
         │  (combine into answer)  │
         └────────────┬────────────┘
                      │
                      ▼
         ┌─────────────────────────┐
         │  Return ExecutionResult │
         │  (success + data)       │
         └────────────┬────────────┘
                      │
┌─────────────────────┴────────────────────────────────────┐
│                      CLEANUP                              │
└────────────────────┬─────────────────────────────────────┘
                     │
                     ▼
         ┌─────────────────────────┐
         │  Stop Agent Servers     │
         │  (free resources)       │
         └─────────────────────────┘
```

---

## 📦 ExecutionResult Structure

```
ExecutionResult
│
├─ success: bool
│  └─ True/False
│
├─ final_result: str
│  └─ "The synthesized answer..."
│
├─ workspace_id: str
│  └─ "workspace_abc123"
│
├─ workspace_messages: List[dict]
│  └─ [
│      {
│        'sender_name': 'ResearchAgent',
│        'content': '...',
│        'message_type': 'task_result',
│        'timestamp': '...',
│        'metadata': {...}
│      },
│      ...
│     ]
│
├─ plan: ExecutionPlan
│  │
│  ├─ subtasks: List[Subtask]
│  │  └─ [
│  │      {
│  │        'subtask_id': 'task_1',
│  │        'description': '...',
│  │        'assigned_agent_name': '...',
│  │        'status': 'completed',
│  │        'order': 1,
│  │        'dependencies': [...]
│  │      },
│  │      ...
│  │     ]
│  │
│  ├─ selected_agents: List[str]
│  │  └─ ['Agent1', 'Agent2', 'Agent3']
│  │
│  ├─ execution_order: List[List[str]]
│  │  └─ [['task_1'], ['task_2', 'task_3'], ['task_4']]
│  │
│  └─ reasoning: str
│     └─ "I broke this into 4 subtasks because..."
│
├─ subtask_results: Dict[str, str]
│  └─ {
│      'task_1': 'Result from task 1...',
│      'task_2': 'Result from task 2...',
│      ...
│     }
│
└─ metadata: dict
   └─ {
       'num_subtasks': 5,
       'num_agents': 3,
       'execution_time': '45.2s',
       ...
      }
```

---

## 🔑 Key Patterns

### 1. Executor Factory Pattern

```python
async def create_agent_executor(system_prompt, temperature=0.7):
    """Factory to create executors with different configs"""
    
    async def executor(context):
        user_input = context.get_user_input()
        
        # Configure LLM with system prompt
        response = await llm.create(
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_input}
            ],
            temperature=temperature
        )
        
        return response.content
    
    return executor

# Create multiple agents with different behaviors
research_agent = Agent(
    executor=await create_agent_executor(
        "You are a researcher...",
        temperature=0.3  # Focused
    )
)

creative_agent = Agent(
    executor=await create_agent_executor(
        "You are a creative writer...",
        temperature=0.9  # Creative
    )
)
```

### 2. Background Server Pattern

```python
# Start multiple servers without blocking
servers = []

for agent in agents:
    server = AgentServer(agent, port=get_next_port())
    await server.start_background()  # Non-blocking!
    servers.append(server)

# All servers now running in background
# Do your work...

# Clean up when done
for server in servers:
    await server.stop()
```

### 3. Message Callback Pattern

```python
def create_message_callback():
    """Factory for custom message handling"""
    
    def callback(msg_dict):
        sender = msg_dict['sender_name']
        content = msg_dict['content']
        msg_type = msg_dict['message_type']
        
        # Custom handling based on type
        if msg_type == 'task_assignment':
            log_task_assignment(sender, content)
        elif msg_type == 'task_result':
            log_completion(sender, content)
        
        # Display
        print(f"{sender}: {content}")
    
    return callback

workspace = OrchestratedWorkspace(
    orchestrator=orchestrator,
    message_callback=create_message_callback()
)
```

---

## 🎨 Color Codes for Display

```python
# ANSI color codes for terminal output

COLORS = {
    'BLUE': '\033[94m',      # Orchestrator
    'GREEN': '\033[92m',     # Research agents
    'YELLOW': '\033[93m',    # Content agents
    'MAGENTA': '\033[95m',   # Admin agents
    'CYAN': '\033[96m',      # Pipeline agents
    'RED': '\033[91m',       # Deal agents
    'GRAY': '\033[90m',      # System messages
    'RESET': '\033[0m'       # Reset to default
}

# Usage
print(f"{COLORS['GREEN']}ResearchAgent:{COLORS['RESET']} Found data...")
```

---

## 🧪 Testing Pattern

```
Development Flow:
┌─────────────────────────────────────────────┐
│                                             │
│  1. Create agent                            │
│     ↓                                       │
│  2. Test executor in isolation              │
│     ↓                                       │
│  3. Start server, test with client          │
│     ↓                                       │
│  4. Add to workspace                        │
│     ↓                                       │
│  5. Test multi-agent collaboration          │
│     ↓                                       │
│  6. Add error handling                      │
│     ↓                                       │
│  7. Add logging/monitoring                  │
│     ↓                                       │
│  8. Deploy to production                    │
│                                             │
└─────────────────────────────────────────────┘
```

---

## 📏 Best Practices Checklist

**Agent Design:**
- [ ] Clear, specific name
- [ ] Detailed description
- [ ] Well-defined skills with tags
- [ ] Focused responsibility (not too broad)
- [ ] Appropriate system prompt
- [ ] Right temperature for task type

**Error Handling:**
- [ ] Try-except in executors
- [ ] Validate inputs
- [ ] Timeout protection
- [ ] Meaningful error messages
- [ ] Graceful degradation

**Resource Management:**
- [ ] Start servers in background
- [ ] Track server instances
- [ ] Clean up on exit
- [ ] Use try-finally for cleanup
- [ ] Free ports properly

**Performance:**
- [ ] Use appropriate models (4o vs 4o-mini)
- [ ] Enable parallel execution
- [ ] Minimize dependencies
- [ ] Cache when possible
- [ ] Monitor execution time

**Observability:**
- [ ] Implement message callbacks
- [ ] Add logging
- [ ] Track metrics
- [ ] Display progress
- [ ] Save important data

---

## 🎓 Quick Reference Summary

| Component | Purpose | Key Method |
|-----------|---------|------------|
| Agent | AI worker | `synqed.Agent()` |
| AgentServer | HTTP endpoint | `.start_background()` |
| Orchestrator | AI coordinator | `.orchestrate()` |
| OrchestratedWorkspace | Collaboration space | `.execute_task()` |
| Executor | Agent's logic | `async def executor(context)` |
| Context | Task information | `.get_user_input()` |
| ExecutionResult | Output | `.success`, `.final_result` |

---

**Use this guide as a quick visual reference while coding!**

Keep it open in a separate window alongside the comprehensive guide.

🚀 Happy building!

