# Agent Collaboration Guide

## Overview

**Synqed** enables TRUE multi-agent collaboration, not just task delegation. When you enable collaboration, agents actually interact with each other, provide feedback, and refine their work based on peer input.

## The Difference: Delegation vs. Collaboration

### ❌ Traditional Delegation (Without Collaboration)
```
Task → Agent 1 works independently → Result 1
     → Agent 2 works independently → Result 2
     → Agent 3 works independently → Result 3
→ Results combined
```

**Problems:**
- Agents work in isolation
- No cross-pollination of ideas
- Potential conflicts or gaps between results
- No peer review or feedback

### ✅ True Collaboration (With Collaboration Enabled)
```
Task → All agents see the full context
     → Each agent proposes their approach
     → Agents review and provide feedback to each other
     → Agents refine their work based on peer input
     → Integrated, cohesive solution
```

**Benefits:**
- Agents build on each other's ideas
- Peer review and quality improvement
- Better integration between components
- Synergistic solutions that leverage multiple perspectives

## How It Works

When you enable collaboration in `OrchestratedWorkspace`, the execution follows a structured collaborative protocol:

### Phase 1: Collaborative Kickoff
All agents receive an introduction that includes:
- The overall task
- Team assignments
- How they'll work together
- The collaboration protocol

### Phase 2: Initial Proposals
Each agent:
- Sees what other agents are working on
- Understands the full context
- Proposes their initial approach
- Explains their plan and key ideas

### Phase 3: Peer Feedback & Discussion
Each agent:
- Reviews other agents' proposals
- Identifies opportunities for synergy
- Provides constructive feedback
- Shares insights that could help others
- Suggests integration points

### Phase 4: Refinement & Integration
Each agent:
- Receives feedback from all peers
- Refines their approach based on insights
- Ensures integration with team's work
- Produces final, polished result

## Code Example

### Basic Setup

```python
import synqed

# Create orchestrator
orchestrator = synqed.Orchestrator(
    provider=synqed.LLMProvider.OPENAI,
    api_key=api_key,
    model="gpt-4o",
)

# Create orchestrated workspace WITH collaboration
orchestrated = synqed.OrchestratedWorkspace(
    orchestrator=orchestrator,
    enable_agent_discussion=True,  # 🔑 This enables true collaboration!
)

# Register your agents
orchestrated.register_agent(research_agent)
orchestrated.register_agent(design_agent)
orchestrated.register_agent(development_agent)

# Execute task - agents will collaborate!
result = await orchestrated.execute_task(
    "Design a new feature with research, design, and implementation"
)
```

### Without Collaboration (Parallel Execution)

```python
# Create workspace WITHOUT collaboration
orchestrated = synqed.OrchestratedWorkspace(
    orchestrator=orchestrator,
    enable_agent_discussion=False,  # Agents work independently
)
```

## Configuration Options

### OrchestratedWorkspace Parameters

```python
orchestrated = synqed.OrchestratedWorkspace(
    orchestrator=orchestrator,
    
    # Enable/disable agent discussion and feedback
    enable_agent_discussion=True,
    
    # Whether to persist workspace state to disk
    workspace_persistence=False,
    
    # Maximum subtasks to run in parallel
    max_parallel_subtasks=3,
    
    # Optional: Callback for real-time message streaming
    message_callback=my_callback_function,
)
```

## Real-Time Message Streaming 🔴 LIVE

Want to see agents collaborate **as it happens**? Use the `message_callback` parameter!

### Basic Real-Time Display

```python
def display_message(msg):
    """Called for each message in real-time."""
    print(f"{msg['sender_name']}: {msg['content'][:100]}...")

orchestrated = synqed.OrchestratedWorkspace(
    orchestrator=orchestrator,
    enable_agent_discussion=True,
    message_callback=display_message,  # Stream messages live!
)

# Now when you execute, you'll see messages as they happen!
result = await orchestrated.execute_task(task)
```

### Advanced Real-Time Display with Phase Tracking

```python
class CollaborationDisplay:
    def __init__(self):
        self.current_phase = None
        self.phase_names = {
            'broadcast': '🤝 KICKOFF',
            'proposal': '📝 PROPOSALS',
            'feedback': '💬 DISCUSSION',
            'refinement': '✨ REFINEMENT',
        }
    
    def display_message(self, msg):
        """Display messages with phase detection."""
        sender = msg.get('sender_name', 'Unknown')
        content = msg.get('content', '')
        msg_type = msg.get('message_type', 'unknown')
        
        # Detect phase changes
        if 'INITIAL PROPOSAL PHASE' in content:
            print("\n📝 PROPOSALS PHASE\n")
        elif 'COLLABORATIVE FEEDBACK PHASE' in content:
            print("\n💬 DISCUSSION PHASE\n")
        elif 'REFINEMENT PHASE' in content:
            print("\n✨ REFINEMENT PHASE\n")
        
        # Show agent messages
        if msg_type == 'agent':
            print(f"{sender}: {content}\n")

display = CollaborationDisplay()

orchestrated = synqed.OrchestratedWorkspace(
    orchestrator=orchestrator,
    enable_agent_discussion=True,
    message_callback=display.display_message,
)

# Watch the collaboration unfold live!
result = await orchestrated.execute_task(task)
```

### What You'll See

**Without real-time streaming:**
```
🎬 Starting task...
[... waiting ...]
✅ Task complete!
```

**With real-time streaming:**
```
🎬 Starting task...

📝 PROPOSALS PHASE

Researcher: I'll analyze user behavior patterns and research...
Designer: I'm thinking of a clean, minimalist interface with...
Developer: For the backend, I propose using a microservices...

💬 DISCUSSION PHASE

Researcher: @Designer your UI mockup is great! My data shows users prefer...
Designer: @Developer can we add push notifications for the feature?
Developer: @Researcher your insights about offline sync are valuable...

✨ REFINEMENT PHASE

Researcher: Incorporating the design feedback, here's my refined analysis...
Designer: Based on technical constraints, I've adjusted the UI to...
Developer: Integrated both research and design insights into the architecture...

✅ Task complete!
```

### Message Structure

Each message passed to your callback contains:

```python
{
    "message_id": "uuid",
    "timestamp": "2025-11-17T10:30:00",
    "sender_id": "agent_id",
    "sender_name": "AgentName",
    "message_type": "agent",  # or "system", "status", etc.
    "content": "The actual message content",
    "metadata": {}
}
```

## Collaboration Artifacts

During collaboration, the workspace creates several artifacts:

### 1. Initial Proposals
Each agent's initial approach is stored as:
```python
# Artifact details
name: f"proposal_{agent_name}.txt"
artifact_type: "proposal"
content: agent's initial proposal
```

### 2. Peer Feedback
Feedback from each agent is stored as:
```python
# Artifact details
name: f"feedback_{agent_name}.txt"
artifact_type: "feedback"
content: agent's feedback on peer proposals
metadata: {"phase": "discussion"}
```

### 3. Final Results
Refined results are stored as:
```python
# Artifact details
name: f"result_{subtask_id}.txt"
artifact_type: "result"
content: agent's final refined result
metadata: {"subtask_id": subtask_id, "collaborative": True}
```

## Accessing Collaboration Data

### Viewing All Messages

```python
result = await orchestrated.execute_task(task)

# See all workspace interactions
for msg in result.workspace_messages:
    print(f"{msg['sender_name']}: {msg['content']}")
```

### Analyzing Collaboration Phases

```python
# Filter messages by phase
proposals = [msg for msg in result.workspace_messages 
             if 'INITIAL PROPOSAL' in msg.get('content', '')]

feedback = [msg for msg in result.workspace_messages 
            if 'FEEDBACK PHASE' in msg.get('content', '')]

refined = [msg for msg in result.workspace_messages 
           if 'REFINEMENT PHASE' in msg.get('content', '')]
```

### Accessing Artifacts

```python
# Access workspace artifacts
workspace = result.workspace_metadata['workspace']

# Get all feedback artifacts
feedback_artifacts = workspace.get_artifacts(artifact_type="feedback")

for artifact in feedback_artifacts:
    print(f"Feedback from {artifact.created_by}:")
    print(artifact.content)
```

## Best Practices

### 1. Choose the Right Agents
Select agents with complementary skills that can provide valuable feedback to each other.

```python
# ✅ Good: Complementary skills
research_agent    # Gathers information
design_agent      # Creates user experience
development_agent # Implements solution

# ❌ Less Useful: Identical skills
writer_agent_1
writer_agent_2
writer_agent_3
```

### 2. Craft Clear Task Descriptions
Be specific about what you want agents to accomplish together.

```python
# ✅ Good: Clear collaborative task
task = """Design a new mobile app feature for habit tracking. 
Research user needs, create UX design, and propose technical implementation. 
Each team member should contribute their expertise and integrate their work."""

# ❌ Vague: Unclear expectations
task = "Make something cool"
```

### 3. Use Appropriate Task Complexity
Collaboration works best for tasks that benefit from multiple perspectives.

```python
# ✅ Good: Complex, multi-faceted task
"Design and implement a payment system with security, UX, and backend considerations"

# ❌ Not Ideal: Simple, single-perspective task
"Write a hello world function"
```

### 4. Review Collaboration Outcomes
Examine the feedback exchanges to improve future collaborations.

```python
# Analyze the quality of collaboration
feedback_count = len([m for m in result.workspace_messages 
                     if 'feedback' in m.get('metadata', {})])
print(f"Agents exchanged {feedback_count} feedback messages")
```

## Performance Considerations

### Collaboration is Slower
- **Without collaboration**: Agents work in parallel → faster
- **With collaboration**: Agents work sequentially through phases → slower but higher quality

### Token Usage
Collaboration uses more LLM tokens because:
- Each agent receives full context (other agents' proposals)
- Feedback round requires additional prompts
- Refinement round incorporates all feedback

**Estimate**: Collaborative execution uses 2-3x more tokens than independent execution

### When to Use Collaboration

✅ **Use collaboration when:**
- Task requires integration of multiple perspectives
- Quality and synergy matter more than speed
- Agents have complementary expertise
- Cross-functional coordination is important

❌ **Skip collaboration when:**
- Tasks are truly independent
- Speed is critical
- Agents have identical skills
- Simple tasks with clear answers

## Examples

### Example 1: Product Development Team
```python
# Research, Design, and Development collaboration
orchestrated.register_agent(market_researcher)
orchestrated.register_agent(ux_designer)
orchestrated.register_agent(backend_developer)

result = await orchestrated.execute_task(
    "Design and plan a new user onboarding flow"
)
```

### Example 2: Creative Writing Team
```python
# Story, Character, and Dialogue collaboration
orchestrated.register_agent(plot_writer)
orchestrated.register_agent(character_developer)
orchestrated.register_agent(dialogue_specialist)

result = await orchestrated.execute_task(
    "Create a compelling scene for our story"
)
```

### Example 3: Data Analysis Team
```python
# Data collection, Analysis, and Visualization
orchestrated.register_agent(data_collector)
orchestrated.register_agent(statistician)
orchestrated.register_agent(visualization_expert)

result = await orchestrated.execute_task(
    "Analyze sales trends and create insights dashboard"
)
```

## Troubleshooting

### Issue: Agents not providing useful feedback
**Solution**: Ensure agents have distinct skills and perspectives. Similar agents provide redundant feedback.

### Issue: Collaboration taking too long
**Solution**: 
- Reduce number of agents
- Use smaller language models for feedback phase
- Consider disabling collaboration for time-sensitive tasks

### Issue: Feedback not being incorporated
**Solution**: Check that refinement prompts are clear about incorporating feedback. Review agent system prompts.

### Issue: Workspace messages not showing collaboration
**Solution**: Verify `enable_agent_discussion=True` is set. Check logs for any errors during execution.

## Advanced: Custom Collaboration Protocols

While the default 3-phase protocol works for most cases, you can customize it:

```python
# Coming soon: Custom collaboration protocols
orchestrated = synqed.OrchestratedWorkspace(
    orchestrator=orchestrator,
    enable_agent_discussion=True,
    collaboration_protocol="iterative",  # multiple rounds
    max_discussion_rounds=3,
)
```

## Conclusion

True agent collaboration in Synqed enables agents to work as a team, not just as parallel workers. By enabling `enable_agent_discussion=True`, you unlock:

- 🤝 Peer feedback and review
- 💡 Cross-pollination of ideas
- 🔄 Iterative refinement
- 🎯 Integrated, cohesive solutions
- ✨ Emergent insights from agent interactions

This transforms multi-agent systems from parallel execution to true teamwork!

