# Dynamic Multi-Agent Router System - Complete Setup Guide

## 🚀 Overview

This guide will help you set up the Dynamic Multi-Agent Router System in n8n. The system intelligently routes user requests to the most appropriate AI agents based on their expertise and can have multiple agents collaborate on complex tasks.

## 📋 Prerequisites

- Docker and Docker Compose installed
- Agent files in the correct directory structure (optional - system has built-in agents)

## 🛠️ Quick Setup (Recommended)

### Option 1: Automated Setup

**For Windows:**
```cmd
setup_agent_system.bat
```

**For Linux/Mac:**
```bash
chmod +x setup_agent_system.sh
./setup_agent_system.sh
```

### Option 2: Manual Setup

1. **Start the services:**
   ```bash
   docker-compose up -d
   ```

2. **Wait for services to be ready:**
   ```bash
   # Check n8n
   curl http://localhost:5678
   
   # Check Ollama
   curl http://localhost:11434/api/tags
   ```

3. **Pull the required model:**
   ```bash
   docker exec ollama-server ollama pull llama3.1
   ```

## 📥 Import the Workflow

1. **Access n8n Interface:**
   - Open your browser and go to `http://localhost:5678`
   - Login with: **admin** / **admin123**

2. **Import the Workflow:**
   - Click the "+" button to create a new workflow
   - Click the three dots menu (⋮) in the top-right corner
   - Select "Import from File"
   - Choose one of these workflows:
     - `n8n_agent_system_flow_simple.json` (No Ollama required - start here)
     - `n8n_agent_system_flow_corrected.json` (Full system with Ollama)

3. **Activate the Workflow:**
   - Toggle the switch in the top-right corner to "Active" (green)
   - Make sure it shows "Active" status

## 🤖 Built-in Agents

The system comes with 6 pre-configured agents:

- **mobile-app-builder** (engineering) - Mobile app development
- **ui-designer** (design) - User interface design  
- **backend-architect** (engineering) - Backend architecture
- **frontend-developer** (engineering) - Frontend development
- **content-creator** (marketing) - Content creation
- **growth-hacker** (marketing) - Growth strategies

### Optional: Custom Agent Files

If you want to add custom agents, place them in `./agents/` directory:

```
./agents/
├── engineering/
│   ├── ai-engineer.md
│   └── devops-automator.md
├── design/
│   ├── ux-researcher.md
│   └── visual-storyteller.md
└── marketing/
    ├── social-media-manager.md
    └── seo-specialist.md
```

**Agent file format:**
```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]
```

## 🧪 Test the System

1. **Basic functionality test:**
   ```bash
   curl -X POST http://localhost:5678/webhook/agent-task \
     -H "Content-Type: application/json" \
     -d '{"task": "Build a mobile app"}'
   ```

2. **Full agent system test:**
   ```bash
   curl -X POST http://localhost:5678/webhook/agent-task \
     -H "Content-Type: application/json" \
     -d '{
       "task": "I need help building a mobile app for food delivery",
       "context": "We are a startup with 3 developers, 6-week timeline"
     }'
   ```

3. **Test with Postman:**
   - Method: POST
   - URL: `http://localhost:5678/webhook/agent-task`
   - Headers: `Content-Type: application/json`
   - Body (raw JSON):
     ```json
     {
       "task": "Design a beautiful user interface for our app",
       "context": "Target audience: young professionals, modern aesthetic"
     }
     ```

## 🔧 Configuration Options

### Workflow Variants

1. **Sequential Execution** (`n8n_agent_system_flow_dynamic_router.json`):
   - Agents execute one after another
   - Lower resource usage
   - Slower overall response time

2. **Parallel Execution** (`n8n_agent_system_flow_parallel_agents.json`):
   - Agents execute simultaneously
   - Higher resource usage
   - Faster overall response time
   - **Recommended for production**

### Agent Selection Parameters

You can modify the agent selection prompt in the "Select Agents" node to:
- Change the maximum number of agents (default: 1-3)
- Adjust selection criteria
- Modify collaboration logic

### Caching Configuration

- **Cache TTL**: 3600 seconds (1 hour) - modify in "Cache Agents" node
- **Cache Key**: "agent-catalog" - modify in Redis nodes
- **Cache Strategy**: Agents are cached after first read

## 📊 Monitoring and Debugging

### Key Metrics to Monitor

1. **Response Times:**
   - Total execution time
   - Agent selection time
   - Individual agent response times

2. **Success Rates:**
   - Webhook availability
   - Agent selection accuracy
   - Response generation success

3. **Resource Usage:**
   - Redis cache hit/miss rates
   - Ollama model performance
   - Memory usage

### Debug Mode

Enable debug logging by setting:
```bash
N8N_LOG_LEVEL=debug
```

### Common Issues and Solutions

1. **"Webhook not registered" error:**
   - Ensure workflow is active (green toggle)
   - Check webhook path is correct: `/webhook/agent-task`

2. **"No suitable agents found" error:**
   - Verify agent files exist in `/home/node/.n8n/agents/`
   - Check agent file format (frontmatter required)
   - Review agent descriptions and keywords

3. **Slow response times:**
   - Check Redis connectivity
   - Verify Ollama is running and responsive
   - Consider using parallel execution workflow

4. **Agent selection issues:**
   - Review agent descriptions for clarity
   - Check keyword matching in agent files
   - Test with different task phrasings

## 🚀 Production Deployment

### 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
      - REDIS_PORT=6379
      - N8N_LOG_LEVEL=info
    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:
```

### Security Considerations

1. **Input Validation:**
   - All inputs are validated and sanitized
   - File access restricted to agent directory only

2. **Error Handling:**
   - No sensitive information in error responses
   - Comprehensive error logging

3. **Rate Limiting:**
   - Consider implementing rate limiting for production
   - Monitor for abuse patterns

## 📈 Performance Optimization

### Caching Strategy

- Agent catalog cached in Redis (1-hour TTL)
- Reduces file system reads
- Improves response times significantly

### 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

## 🔄 Maintenance

### Regular Tasks

1. **Update Agent Knowledge:**
   - Keep agent files current
   - Add new agents as needed
   - Remove outdated agents

2. **Monitor Performance:**
   - Track response times
   - Monitor error rates
   - Check cache performance

3. **Test Agent Selection:**
   - Verify selection accuracy
   - Test with new request types
   - Validate agent collaboration

### Backup Strategy

1. **Workflow Backup:**
   - Export workflow regularly
   - Version control workflow files
   - Test backup restoration

2. **Agent Files Backup:**
   - Backup agent directory
   - Version control agent files
   - Document agent changes

## 📞 Support

### Troubleshooting Checklist

1. ✅ n8n is running and accessible
2. ✅ Workflow is active (green toggle)
3. ✅ Ollama is running with llama3.1 model
4. ✅ Redis is running and accessible
5. ✅ Agent files exist in correct directory
6. ✅ Agent files have proper frontmatter format
7. ✅ Environment variables are set correctly

### Getting Help

1. Check n8n execution logs
2. Run the test script for diagnostics
3. Verify all dependencies are running
4. Review workflow node configurations
5. Test with simple requests first

---

*This system is designed to be flexible, scalable, and easy to maintain. Regular updates and monitoring will ensure optimal performance.*
