# Dynamic Multi-Agent Router System Documentation

## Overview

This n8n workflow creates a dynamic multi-agent system that intelligently routes user requests to the most appropriate AI agents based on their expertise. The system can select single or multiple agents to work together and provide comprehensive solutions.

## Key Features

### 🚀 **Intelligent Agent Selection**
- Automatically analyzes user requests
- Selects 1-3 most relevant agents
- Considers agent collaboration potential
- Uses keyword matching and semantic analysis

### 🔄 **Dynamic Agent Discovery**
- Reads all agent files from `/home/node/.n8n/agents/`
- Supports hierarchical organization (departments/categories)
- Extracts agent descriptions and keywords
- Caches agent catalog for performance

### 🤝 **Multi-Agent Collaboration**
- Agents work together on complex tasks
- Synthesizes multiple expert perspectives
- Creates unified action plans
- Identifies synergies and conflicts

### ⚡ **Performance Optimized**
- Redis caching for agent catalog
- Efficient file reading strategies
- Parallel agent execution
- Error handling and fallbacks

## System Architecture

### Flow Components

1. **Input Processing**
   - Webhook endpoint: `POST /agent-task`
   - Input validation and sanitization
   - Support for multiple input formats

2. **Agent Discovery**
   - Reads all `.md` files from agent directory
   - Extracts agent metadata (name, department, description, keywords)
   - Caches agent catalog in Redis (1-hour TTL)

3. **Intelligent Routing**
   - Uses Ollama LLM for agent selection
   - Analyzes task requirements
   - Considers agent expertise and collaboration potential

4. **Agent Execution**
   - Loads specific agent knowledge
   - Executes agents in parallel
   - Formats individual responses

5. **Synthesis & Response**
   - Combines expert perspectives
   - Creates unified action plan
   - Provides structured output

## Agent File Structure

Each agent should be a Markdown file with the following structure:

```markdown
---
name: agent-name
description: Brief description of agent's expertise
keywords: keyword1, keyword2, keyword3
color: cyan
tools: Write, Read, MultiEdit, Bash, WebFetch
---

# Agent Name

## Description
Detailed description of the agent's capabilities and expertise.

## System Prompt
You are an expert in [field]...

[Detailed agent instructions and knowledge base]
```

### Required Fields

- **name**: Unique identifier for the agent
- **description**: Brief description used for routing decisions
- **keywords**: Comma-separated keywords for better matching

### Optional Fields

- **color**: UI color for the agent
- **tools**: Available tools for the agent

## API Usage

### Endpoint
```
POST http://your-n8n-instance/webhook/agent-task
```

### Request Format

```json
{
  "task": "I need help building a mobile app for food delivery",
  "context": "We're a startup with 3 developers, 6-week timeline",
  "user_id": "user123"
}
```

### Response Format

```json
{
  "success": true,
  "task": "I need help building a mobile app for food delivery",
  "context": "We're a startup with 3 developers, 6-week timeline",
  "user_id": "user123",
  "agents_consulted": ["mobile-app-builder", "backend-architect", "ui-designer"],
  "synthesized_plan": "# Executive Summary\n...",
  "individual_responses": [
    {
      "agent": "mobile-app-builder",
      "response": "As a mobile app builder..."
    }
  ],
  "timestamp": "2024-01-15T10:30:00.000Z",
  "execution_time": 2500
}
```

## Agent Directory Structure

```
/home/node/.n8n/agents/
├── engineering/
│   ├── ai-engineer.md
│   ├── backend-architect.md
│   ├── frontend-developer.md
│   └── mobile-app-builder.md
├── design/
│   ├── ui-designer.md
│   ├── ux-researcher.md
│   └── visual-storyteller.md
├── marketing/
│   ├── content-creator.md
│   ├── growth-hacker.md
│   └── social-media-manager.md
└── product/
    ├── product-manager.md
    └── user-researcher.md
```

## Configuration

### Environment Variables

```bash
# Ollama Configuration
OLLAMA_BASE_URL=http://ollama:11434
OLLAMA_MODEL=llama3.1

# Redis Configuration (for caching)
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=your_password

# Agent Directory
AGENT_DIRECTORY=/home/node/.n8n/agents
```

### Docker Compose Example

```yaml
version: '3.8'
services:
  n8n:
    image: n8nio/n8n
    ports:
      - "5678:5678"
    environment:
      - OLLAMA_BASE_URL=http://ollama:11434
      - REDIS_HOST=redis
    volumes:
      - ./n8n_data:/home/node/.n8n
      - ./agents:/home/node/.n8n/agents
    depends_on:
      - ollama
      - redis

  ollama:
    image: ollama/ollama
    ports:
      - "11434:11434"
    volumes:
      - ollama_data:/root/.ollama

  redis:
    image: redis:alpine
    ports:
      - "6379:6379"
    command: redis-server --requirepass your_password

volumes:
  ollama_data:
```

## Error Handling

### Common Error Responses

1. **Invalid Input**
```json
{
  "success": false,
  "error": "Invalid input: Task is required",
  "suggestion": "Please provide a task or message in your request."
}
```

2. **No Agents Found**
```json
{
  "success": false,
  "error": "No suitable agents found for this task",
  "available_agents": [...],
  "suggestion": "Please rephrase your request or provide more context."
}
```

3. **Agent File Not Found**
- System will skip missing agents
- Continue with available agents
- Log warnings for missing files

## Performance Optimization

### Caching Strategy
- Agent catalog cached in Redis (1-hour TTL)
- Reduces file system reads
- Improves response times

### Parallel Processing
- Multiple agents execute simultaneously
- Faster overall response time
- Better resource utilization

### Error Recovery
- Graceful handling of missing agents
- Fallback to available agents
- Comprehensive error reporting

## Monitoring & Logging

### Key Metrics
- Response time per request
- Agent selection accuracy
- Cache hit/miss rates
- Error rates by type

### Logging
- Request/response logging
- Agent execution times
- Error tracking
- Performance metrics

## Best Practices

### Agent Development
1. **Clear Descriptions**: Write concise, keyword-rich descriptions
2. **Comprehensive Knowledge**: Include detailed expertise in agent files
3. **Keyword Optimization**: Use relevant keywords for better matching
4. **Collaboration Focus**: Design agents to work well together

### System Maintenance
1. **Regular Updates**: Keep agent knowledge bases current
2. **Performance Monitoring**: Track response times and errors
3. **Cache Management**: Monitor Redis cache performance
4. **Agent Testing**: Regularly test agent selection accuracy

### Request Optimization
1. **Clear Tasks**: Provide specific, well-defined tasks
2. **Rich Context**: Include relevant background information
3. **User Identification**: Use consistent user IDs for tracking

## Troubleshooting

### Common Issues

1. **Slow Response Times**
   - Check Redis connectivity
   - Verify agent file accessibility
   - Monitor Ollama performance

2. **Incorrect Agent Selection**
   - Review agent descriptions
   - Check keyword matching
   - Test with different task phrasings

3. **Missing Agents**
   - Verify file paths and permissions
   - Check agent file format
   - Review error logs

### Debug Mode

Enable debug logging by setting:
```bash
N8N_LOG_LEVEL=debug
```

## Security Considerations

1. **Input Validation**: All inputs are validated and sanitized
2. **File Access**: Restricted to agent directory only
3. **Error Handling**: No sensitive information in error responses
4. **Rate Limiting**: Consider implementing rate limiting for production

## Future Enhancements

1. **Agent Learning**: Track successful agent combinations
2. **Dynamic Keywords**: Auto-extract keywords from agent content
3. **Performance Analytics**: Detailed performance dashboards
4. **Agent Versioning**: Support for agent version management
5. **Custom Models**: Support for different LLM models per agent

## Support

For issues or questions:
1. Check the error logs
2. Verify configuration settings
3. Test with simple requests first
4. Review agent file formats

---

*This system is designed to be flexible, scalable, and easy to maintain. Regular updates and monitoring will ensure optimal performance.*
