> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixus.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Collaboration

> How agents work together in mixus using sequential chaining and context passing

Agent collaboration in mixus enables you to build sophisticated workflows where multiple agents work together to accomplish complex tasks. The current implementation focuses on **sequential agent chaining** - a proven pattern where agents hand off work to each other in a clear sequence.

## How Agent Collaboration Actually Works

### Sequential Agent Chaining

The primary collaboration pattern in mixus is **micro-agent chaining** - where one agent completes its work and then runs another agent to continue the workflow. This happens through the `findAndRunAgent` tool.

#### Real Implementation

```typescript theme={null}
// Agent A's final step
{
  description: "Run the 'data-analyzer' agent with the research findings",
  requiresVerification: false
}
```

When this step executes, the AI automatically:

1. Recognizes the "Run the X agent" pattern
2. Calls the `findAndRunAgent` tool internally
3. Starts Agent B in a new chat session
4. Passes context through instructions or chat history

#### Context Passing Methods

**Method 1: Instruction-Based Context**

```typescript theme={null}
// Agent A passes specific data to Agent B
"Run the 'report-generator' agent with instructions: 'Create a report using these findings: [data summary]'"
```

**Method 2: Chat History Context**

```typescript theme={null}
// Agent A includes recent chat context
findAndRunAgent({
  agentName: 'report-generator',
  addContext: true // Includes last 5 AI messages from current chat
})
```

**Method 3: Structured Data Passing**

```typescript theme={null}
// Agent A formats data for Agent B
"Run the 'email-sender' agent with this data: {recipients: ['user@example.com'], subject: 'Report Ready', findings: [...]}"
```

### Technical Flow

1. **Agent A Execution**

   * Processes its steps normally
   * Final step contains "Run \[agent name]" instruction
   * AI recognizes pattern and calls `findAndRunAgent` tool

2. **Agent Discovery**

   * System searches for agent by name using Atlas Search
   * Handles multiple matches with user clarification
   * Validates agent exists and user has access

3. **Agent B Initialization**

   * Creates new chat session for Agent B
   * Passes context via instructions or chat history
   * Links execution with `parentExecutionId`

4. **Execution Tracking**
   * Each agent runs in its own chat session
   * Original chat gets confirmation with link to new chat
   * Results can be monitored using `searchChatHistory`

## Practical Examples

### Research → Analysis → Report Chain

```typescript theme={null}
// Agent 1: Research Collector
{
  name: "market-research",
  steps: [
    "Search for industry trends in [topic]",
    "Compile findings into structured format",
    "Run the 'trend-analyzer' agent with the research data"
  ]
}

// Agent 2: Analysis Processor
{
  name: "trend-analyzer",
  steps: [
    "Analyze the research data for patterns",
    "Identify key insights and recommendations",
    "Run the 'report-generator' agent with analysis results"
  ]
}

// Agent 3: Report Creator
{
  name: "report-generator",
  steps: [
    "Create executive summary from analysis",
    "Format findings into professional report",
    "Email report to stakeholders"
  ]
}
```

### KPI Monitoring Chain

```typescript theme={null}
// Agent 1: Data Collector (runs hourly)
{
  name: "hourly-metrics",
  steps: [
    "Collect system metrics from monitoring tools",
    "Store metrics in structured format",
    "Run the 'anomaly-detector' agent if metrics show issues"
  ]
}

// Agent 2: Analysis Agent (conditional)
{
  name: "anomaly-detector",
  steps: [
    "Analyze metrics for anomalies",
    "Determine severity level",
    "Run the 'alert-sender' agent if critical issues found"
  ]
}

// Agent 3: Monitoring Agent (daily)
{
  name: "daily-reporter",
  steps: [
    "Search chat history for hourly-metrics results",
    "Compile daily performance report",
    "Send summary to team leads"
  ]
}
```

## Advanced Patterns

### Multi-User Verification

Different team members can approve different steps in the chain:

```typescript theme={null}
// Agent A: Research (requires marketing approval)
{
  steps: [
    { content: 'Conduct market research', requiresVerification: true },
    {
      content: "Run the 'campaign-creator' agent with findings",
      requiresVerification: false
    }
  ]
}

// Agent B: Campaign Creation (requires legal approval)
{
  steps: [
    { content: 'Create campaign materials', requiresVerification: false },
    { content: 'Review legal compliance', requiresVerification: true },
    {
      content: "Run the 'campaign-launcher' agent",
      requiresVerification: false
    }
  ]
}
```

### Performance Monitoring

Use `searchChatHistory` to build monitoring systems:

```typescript theme={null}
// Monitoring Agent
{
  name: "performance-monitor",
  steps: [
    "Search chat history for 'daily-processor' agent results",
    "Analyze success rates and processing times",
    "Generate performance dashboard",
    "Alert if performance drops below threshold"
  ]
}
```

### Self-Improving Networks

Agents that optimize other agents:

```typescript theme={null}
// Optimization Agent
{
  name: "agent-optimizer",
  steps: [
    "Search chat history for agent execution patterns",
    "Identify bottlenecks and failure points",
    "Recommend agent improvements",
    "Run the 'agent-updater' agent with optimization suggestions"
  ]
}
```

## Key Benefits

### 1. **Reliability**

* Each agent has a focused purpose (1-3 steps)
* Failures are isolated to specific agents
* Easy to retry individual agents without restarting entire workflow

### 2. **Cost Efficiency**

* Smaller context windows per agent
* Reduced token usage compared to monolithic agents
* Pay only for the processing each agent actually needs

### 3. **Maintainability**

* Clear separation of concerns
* Easy to modify individual agents
* Simple to add new agents to existing chains

### 4. **Scalability**

* Agents can be scheduled independently
* Different agents can use different AI models
* Easy to add verification points where needed

## Implementation Guidelines

### 1. **Agent Design**

* Keep agents focused (1-3 steps maximum)
* Use clear, descriptive names for easy discovery
* Include context passing in final steps
* Add verification only where human oversight is needed

### 2. **Context Management**

* Pass minimal necessary context between agents
* Use structured data formats when possible
* Prefer instructions over full chat history for efficiency

### 3. **Error Handling**

* Design agents to handle missing or invalid context gracefully
* Include fallback behaviors for common failure scenarios
* Use verification steps for critical decision points

### 4. **Monitoring**

* Create monitoring agents to track chain performance
* Use `searchChatHistory` to analyze execution patterns
* Set up alerts for failed or stalled chains

## What's Next?

The current sequential chaining model provides a solid foundation for agent collaboration. Future enhancements may include:

* **Parallel execution** - Running multiple agents simultaneously
* **Dynamic routing** - Agents choosing which agent to run next based on results
* **Shared memory** - Persistent context sharing between agent executions
* **Event-driven triggers** - Agents responding to external events automatically

For now, micro-agent chaining offers a powerful, reliable way to build complex automated workflows that are easy to understand, maintain, and scale.

## Related Documentation

* **[Micro-Agent Chaining](micro-agent-chaining)** - Detailed guide to sequential agent workflows
* **[Creating Agents](creating)** - How to build agents for collaboration
* **[Search Chat History](../ai-tools/search-chat-history)** - Monitor and track agent performance
* **[Agent Scheduling](scheduling)** - Automate agent execution timing
