# Multi-Agent Architecture Guide

This guide covers the multi-agent system architecture for autonomous content generation and task orchestration.

## Overview

The platform uses a multi-agent architecture where specialized agents collaborate to accomplish complex tasks. This enables:

- **Autonomous Operation**: Agents work independently with minimal supervision
- **Specialization**: Each agent excels at specific tasks
- **Collaboration**: Agents coordinate through workflows
- **Scalability**: Add new agents without changing existing code
- **Reliability**: Built-in error handling and recovery

## Architecture Components

```
┌─────────────────────────────────────────────────────────────────┐
│                    Multi-Agent System                            │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │ ContentAgent │  │ SessionAgent │  │AnalyticsAgent│  ...     │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘          │
│         │                 │                 │                   │
│         └────────────────┬┴─────────────────┘                   │
│                          │                                      │
│               ┌──────────▼──────────┐                          │
│               │  Agent Coordinator  │                          │
│               └──────────┬──────────┘                          │
│                          │                                      │
│               ┌──────────▼──────────┐                          │
│               │   Workflow Engine   │                          │
│               └──────────┬──────────┘                          │
│                          │                                      │
│               ┌──────────▼──────────┐                          │
│               │   Agent Executor    │                          │
│               └─────────────────────┘                          │
└─────────────────────────────────────────────────────────────────┘
```

## Core Agents

### System Agents

| Agent | Capabilities | Purpose |
|-------|--------------|---------|
| `ContentAgent` | content-creation, content-discovery, content-organization | Generate and manage content |
| `SessionAgent` | session-management, progress-tracking | Manage user sessions |
| `AnalyticsAgent` | analytics, user-analysis | Analyze user behavior |
| `RecommendationAgent` | recommendation-engine, learning-path-design | Personalize content |
| `QualityAgent` | quality-assurance, validation, verification | Ensure content quality |
| `VersionControlAgent` | version-control | Manage content versions |
| `ErrorHandlingAgent` | error-handling | Handle failures gracefully |

### Domain Agents

| Agent | Role | Expertise |
|-------|------|-----------|
| `Librarian` | Knowledge discovery | Cataloging, information retrieval |
| `Curator` | Content curation | Selection, organization |
| `Scholar` | Research | Academic analysis, citations |
| `SocraticCoach` | Teaching | Dialogue, questioning |
| `PersonaEngine` | Character creation | Voice, personality |
| `SafetyModerator` | Content safety | Filtering, moderation |
| `Narrator` | Storytelling | Narrative, pacing |

### Academic Research Agents

| Agent | Specialization |
|-------|---------------|
| `Historian` | Historical analysis |
| `Theologian` | Religious studies |
| `Philosopher` | Philosophical inquiry |
| `Linguist` | Language analysis |
| `Indologist` | Hindu/Buddhist traditions |
| `IslamicStudies` | Islamic traditions |
| `Sinologist` | Chinese traditions |
| `Classicist` | Greek/Roman traditions |
| `Mysticism` | Mystical traditions |

## Agent Configuration

### Basic Agent Structure

```typescript
interface AgentConfig {
  name: string;
  capabilities: string[];
  autonomyLevel: 'full' | 'supervised' | 'restricted';
  status: 'ready' | 'busy' | 'error' | 'offline';
  taskQueue: Task[];
  completedTasks: Task[];
  metrics: {
    tasksCompleted: number;
    successRate: number;
    averageResponseTime: number;
  };
}
```

### Domain Agent Structure

```typescript
interface DomainAgent {
  id: string;
  role: AgentRole;
  name: string;
  description: string;
  capabilities: string[];
  toolAccess: AgentToolAccess[];
  personality: {
    tone: string;      // 'helpful', 'scholarly', 'warm'
    style: string;     // 'precise', 'conversational', 'narrative'
    expertise: string[];
  };
  status: 'idle' | 'busy' | 'error';
  metrics: AgentMetrics;
}
```

### Tool Access Configuration

```typescript
interface AgentToolAccess {
  toolName: ToolCapability;
  permissions: string[];
  rateLimit?: {
    calls: number;
    period: 'minute' | 'hour' | 'day';
  };
}

type ToolCapability =
  | 'search'      // Knowledge search
  | 'kg_query'    // Knowledge graph queries
  | 'calc'        // Calculations
  | 'tts'         // Text-to-speech
  | 'stt'         // Speech-to-text
  | 'scheduler';  // Task scheduling
```

## Workflow System

### Workflow Definition

```typescript
interface Workflow {
  name: string;
  steps: WorkflowStep[];
  status: 'pending' | 'running' | 'completed' | 'failed';
  startTime: number;
  endTime?: number;
  duration?: number;
  results: StepResult[];
}

interface WorkflowStep {
  name: string;
  capabilities: string[];  // Required agent capabilities
  action: string;
  params?: Record<string, unknown>;
  timeout?: number;
  retries?: number;
}
```

### Creating a Workflow

```typescript
const meditationWorkflow: WorkflowStep[] = [
  {
    name: 'plan-structure',
    capabilities: ['content-creation'],
    action: 'plan_meditation_structure',
    params: { tradition: 'buddhist', duration: 600 }
  },
  {
    name: 'write-script',
    capabilities: ['content-creation'],
    action: 'generate_script_content',
    params: { includeAudioTags: true }
  },
  {
    name: 'validate-tradition',
    capabilities: ['quality-assurance', 'validation'],
    action: 'validate_tradition_accuracy',
    params: { minScore: 0.85 }
  },
  {
    name: 'quality-review',
    capabilities: ['quality-assurance'],
    action: 'review_content_quality',
    params: { checkReadability: true }
  }
];

const result = await system.executeWorkflow('meditation-generation', meditationWorkflow);
```

### Workflow Execution

```typescript
class MultiAgentSystem {
  async executeWorkflow(name: string, steps: WorkflowStep[]): Promise<Workflow> {
    const workflow: Workflow = {
      name,
      steps,
      status: 'running',
      startTime: Date.now(),
      results: []
    };

    for (const step of steps) {
      // Select best agent for this step
      const agent = this.selectAgent(step.capabilities);

      if (!agent) {
        throw new Error(`No agent available for: ${step.name}`);
      }

      // Execute step with selected agent
      const result = await this.executeStep(agent, step);
      workflow.results.push(result);

      if (!result.success) {
        workflow.status = 'failed';
        break;
      }
    }

    workflow.status = workflow.status === 'running' ? 'completed' : workflow.status;
    workflow.endTime = Date.now();
    workflow.duration = workflow.endTime - workflow.startTime;

    return workflow;
  }
}
```

## Agent Coordination

### Agent Selection

```typescript
class AgentCoordinator {
  selectAgent(requiredCapabilities: string[]): AgentConfig | null {
    // Find agent with all required capabilities
    for (const [name, agent] of this.agents) {
      if (this.hasCapabilities(agent, requiredCapabilities)) {
        if (agent.status === 'ready') {
          return agent;
        }
      }
    }

    return null;
  }

  private hasCapabilities(agent: AgentConfig, required: string[]): boolean {
    return required.every(cap => agent.capabilities.includes(cap));
  }
}
```

### Load Balancing

```typescript
class AgentCoordinator {
  selectBestAgent(capabilities: string[]): AgentConfig | null {
    const candidates = this.findAgentsWithCapabilities(capabilities);

    if (candidates.length === 0) return null;

    // Sort by availability and performance
    candidates.sort((a, b) => {
      // Prefer ready agents
      if (a.status !== b.status) {
        return a.status === 'ready' ? -1 : 1;
      }

      // Then by success rate
      if (a.metrics.successRate !== b.metrics.successRate) {
        return b.metrics.successRate - a.metrics.successRate;
      }

      // Then by response time
      return a.metrics.averageResponseTime - b.metrics.averageResponseTime;
    });

    return candidates[0];
  }
}
```

### Task Distribution

```typescript
class AgentCoordinator {
  async distributeTask(task: AgentTask): Promise<void> {
    const agent = this.selectBestAgent(task.requiredCapabilities);

    if (!agent) {
      await this.queueTask(task);
      return;
    }

    agent.status = 'busy';
    agent.taskQueue.push(task);

    try {
      const result = await this.executor.execute(agent, task);
      task.result = result;
      task.status = 'completed';
      agent.completedTasks.push(task);
      agent.metrics.tasksCompleted++;
    } catch (error) {
      task.status = 'failed';
      task.error = error.message;
    } finally {
      agent.status = 'ready';
    }
  }
}
```

## Agent Executor

### Task Execution

```typescript
class AgentExecutor {
  private orchestrator: LLMOrchestrator | null = null;

  setOrchestrator(orchestrator: LLMOrchestrator): void {
    this.orchestrator = orchestrator;
  }

  async execute(agent: DomainAgent, task: AgentTask): Promise<TaskExecutionResult> {
    if (!this.orchestrator) {
      return this.simulateExecution(agent, task);
    }

    const prompt = this.buildPrompt(agent, task);
    const response = await this.orchestrator.complete({
      system_prompt: this.buildSystemPrompt(agent),
      user_prompt: prompt,
      temperature: this.getTemperature(task.type)
    });

    return this.parseResponse(response, task);
  }

  private buildSystemPrompt(agent: DomainAgent): string {
    return `You are ${agent.name}, a ${agent.description}.

Your expertise includes: ${agent.personality.expertise.join(', ')}.
Your communication style is ${agent.personality.style} with a ${agent.personality.tone} tone.

Available tools: ${agent.toolAccess.map(t => t.toolName).join(', ')}.`;
  }
}
```

### Tool Execution

```typescript
class AgentExecutor {
  async executeTool(
    agent: DomainAgent,
    tool: ToolCapability,
    params: Record<string, unknown>
  ): Promise<ToolExecutionResult> {
    // Check permissions
    const access = agent.toolAccess.find(t => t.toolName === tool);
    if (!access) {
      throw new Error(`Agent ${agent.name} does not have access to ${tool}`);
    }

    // Check rate limit
    if (access.rateLimit && this.isRateLimited(agent.id, tool)) {
      throw new Error(`Rate limit exceeded for ${tool}`);
    }

    // Execute tool
    const startTime = Date.now();
    const result = await this.tools[tool].execute(params);

    // Record execution
    this.recordToolExecution({
      agentId: agent.id,
      toolName: tool,
      input: params,
      output: result,
      success: true,
      duration: Date.now() - startTime,
      timestamp: new Date()
    });

    return result;
  }
}
```

## Content Generation Pipeline

### Meditation Script Pipeline

```typescript
const meditationPipeline = {
  name: 'meditation-script-generation',
  agents: [
    {
      role: 'architect',
      agent: 'ContentAgent',
      task: 'Plan meditation structure',
      output: 'structure'
    },
    {
      role: 'writer',
      agent: 'ContentAgent',
      task: 'Generate script content',
      input: 'structure',
      output: 'draft'
    },
    {
      role: 'tradition_expert',
      agent: 'Scholar',
      task: 'Validate tradition accuracy',
      input: 'draft',
      output: 'validated'
    },
    {
      role: 'reviewer',
      agent: 'QualityAgent',
      task: 'Quality review',
      input: 'validated',
      output: 'final'
    }
  ]
};
```

### Pipeline Execution

```typescript
class ContentPipeline {
  async execute(request: GenerationRequest): Promise<GenerationResult> {
    let context = { request };

    for (const stage of this.stages) {
      const agent = this.coordinator.getAgent(stage.agent);
      const task = this.createTask(stage, context);

      const result = await this.executor.execute(agent, task);

      if (!result.success) {
        return { success: false, error: result.error };
      }

      context[stage.output] = result.data;

      this.emit('stage-complete', { stage: stage.role, result });
    }

    return { success: true, data: context.final };
  }
}
```

## Error Handling

### Retry Strategy

```typescript
class AgentExecutor {
  async executeWithRetry(
    agent: DomainAgent,
    task: AgentTask,
    maxRetries: number = 3
  ): Promise<TaskExecutionResult> {
    let lastError: Error | null = null;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await this.execute(agent, task);
      } catch (error) {
        lastError = error;
        console.warn(`Attempt ${attempt} failed: ${error.message}`);

        if (attempt < maxRetries) {
          await this.delay(Math.pow(2, attempt) * 1000);
        }
      }
    }

    throw lastError;
  }
}
```

### Fallback Agents

```typescript
class AgentCoordinator {
  async executeWithFallback(
    task: AgentTask,
    primaryCapabilities: string[],
    fallbackCapabilities: string[]
  ): Promise<TaskExecutionResult> {
    // Try primary agent
    const primary = this.selectAgent(primaryCapabilities);
    if (primary) {
      try {
        return await this.executor.execute(primary, task);
      } catch {
        console.warn('Primary agent failed, trying fallback');
      }
    }

    // Try fallback agent
    const fallback = this.selectAgent(fallbackCapabilities);
    if (fallback) {
      return await this.executor.execute(fallback, task);
    }

    throw new Error('No agents available for task');
  }
}
```

## Monitoring & Metrics

### Agent Metrics

```typescript
interface AgentMetrics {
  tasksCompleted: number;
  tasksFailed: number;
  successRate: number;
  averageResponseTime: number;
  toolsUsed: number;
  lastActive: Date;
}

class MetricsCollector {
  getAgentMetrics(agentId: string): AgentMetrics {
    const agent = this.registry.getAgent(agentId);
    const tasks = this.getAgentTasks(agentId);

    const completed = tasks.filter(t => t.status === 'completed');
    const failed = tasks.filter(t => t.status === 'failed');

    return {
      tasksCompleted: completed.length,
      tasksFailed: failed.length,
      successRate: completed.length / (completed.length + failed.length),
      averageResponseTime: this.calculateAverageTime(completed),
      toolsUsed: this.countToolUsage(agentId),
      lastActive: agent.lastActive
    };
  }
}
```

### System Health

```typescript
class SystemMonitor {
  getSystemHealth(): SystemHealth {
    const agents = this.registry.getAllAgents();

    return {
      totalAgents: agents.length,
      activeAgents: agents.filter(a => a.status === 'busy').length,
      idleAgents: agents.filter(a => a.status === 'idle').length,
      errorAgents: agents.filter(a => a.status === 'error').length,
      activeWorkflows: this.workflowEngine.getActiveCount(),
      queuedTasks: this.taskQueue.length,
      systemLoad: this.calculateLoad()
    };
  }
}
```

## Best Practices

### 1. Define Clear Capabilities

```typescript
// Good: Specific, composable capabilities
capabilities: ['content-creation', 'meditation-scripts', 'audio-tags']

// Avoid: Vague, overlapping capabilities
capabilities: ['general-purpose', 'anything']
```

### 2. Use Appropriate Autonomy Levels

```typescript
// Full autonomy for low-risk tasks
{ autonomyLevel: 'full', capabilities: ['content-discovery'] }

// Supervised for quality-critical tasks
{ autonomyLevel: 'supervised', capabilities: ['content-publishing'] }

// Restricted for sensitive operations
{ autonomyLevel: 'restricted', capabilities: ['user-data-access'] }
```

### 3. Implement Graceful Degradation

```typescript
async function generateContent(request) {
  try {
    // Try multi-agent pipeline
    return await multiAgentPipeline.execute(request);
  } catch {
    // Fall back to single agent
    return await singleAgentGeneration(request);
  }
}
```

### 4. Monitor Agent Performance

```typescript
// Track metrics for optimization
setInterval(() => {
  const metrics = collector.getAllAgentMetrics();

  for (const [agentId, metric] of metrics) {
    if (metric.successRate < 0.8) {
      console.warn(`Agent ${agentId} success rate low: ${metric.successRate}`);
    }
    if (metric.averageResponseTime > 5000) {
      console.warn(`Agent ${agentId} slow: ${metric.averageResponseTime}ms`);
    }
  }
}, 60000);
```

## Related Resources

- [Custom Agent Development Guide](./custom-agent-development.md)
- [Prompt Engineering for Meditation](./prompt-engineering-meditation.md)
- [Content Generation API](./content-generation-api.md)
