# ElevenLabs Integration Guide

This guide explains how to set up and test the ElevenLabs integration for the AI Learning Platform chatbot platform.

## Overview

The application integrates with ElevenLabs to provide AI-powered voice conversations. Each bot in the system has an ElevenLabs agent ID that enables real-time voice interactions.

## Architecture

### Backend Components

1. **ElevenLabsService** (`backend/src/services/elevenLabsService.ts`)
   - Manages API key configuration
   - Gets signed URLs for WebSocket connections
   - Validates agent IDs
   - Handles conversation tokens

2. **WebSocketService** (`backend/src/services/websocketService.ts`)
   - Manages WebSocket connections
   - Initializes conversations with ElevenLabs
   - Proxies messages between frontend and ElevenLabs

3. **ElevenLabsController** (`backend/src/controllers/elevenLabsController.ts`)
   - REST API endpoints for ElevenLabs operations
   - Configuration management
   - Agent validation

### Frontend Components

1. **ElevenLabsChat** (`frontend/src/components/ElevenLabsChat.vue`)
   - Main chat interface
   - Connects to backend WebSocket
   - Establishes direct connection to ElevenLabs
   - Handles real-time messaging

2. **ChatView** (`frontend/src/views/ChatView.vue`)
   - Chat page layout
   - Bot information display
   - Connection status management

## Setup Instructions

### 1. Environment Configuration

Set up your environment variables:

```bash
# Backend (.env)
VITE_API_URL=http://localhost:3000

# Frontend (.env)
VITE_API_URL=http://localhost:3000
```

> **📝 Nota**: La API Key de ElevenLabs se configura desde el panel de administración del frontend, no desde variables de entorno.

### 2. Database Setup

Run the database migrations and seed the database:

```bash
# Navigate to backend directory
cd backend

# Install dependencies
npm install

# Run database migrations
npm run prisma:migrate

# Seed the database with test data
npm run prisma:seed
```

### 3. ElevenLabs Configuration

1. **Get an ElevenLabs API Key**:
   - Sign up at [ElevenLabs](https://elevenlabs.io)
   - Go to your profile settings
   - Copy your API key

2. **Configure the API Key**:
   - Log in to the admin panel in the frontend
   - Navigate to ElevenLabs configuration section
   - Add your API key through the web interface
   - The key will be stored securely in the database

3. **Create Agents in ElevenLabs**:
   - Create agents in your ElevenLabs dashboard
   - Note down the agent IDs
   - Update the bot records in the database with the correct agent IDs

### 4. Start the Application

```bash
# Start backend
cd backend
npm run dev

# Start frontend (in another terminal)
cd frontend
npm run dev
```

## Testing the Integration

### 1. Test Accounts

After running the seed script, you can use these test accounts:

- **Admin**: `admin@example.com` / `K9#mX7$vL2@n`
- **Teacher**: `teacher@example.com` / `P3&wQ8!bR5%t`
- **Student**: `student@example.com` / `M6@fN9#kY2&z`

### 2. Test Bots

The seed script creates these test bots:

- **English Tutor Sarah** (A1) - `test-agent-sarah-001`
- **Business English Mike** (B1) - `test-agent-mike-002`
- **Travel Guide Emma** (A2) - `test-agent-emma-003`
- **Academic Writing Professor** (C1) - `test-agent-professor-004`

### 3. Testing Flow

1. **Login as Student**:
   - Go to `http://localhost:5173/login`
   - Use `student@example.com` / `M6@fN9#kY2&z`

2. **Access Chat**:
   - Go to the Bots page
   - Click on any bot to start chatting
   - The chat will connect to ElevenLabs automatically

3. **Monitor Connections**:
   - Check the browser console for connection logs
   - Use the debug panel (in development mode) to see connection status

### 4. Development Mode Features

In development mode, you'll see:
- Debug information panel
- Connection status indicators
- Manual reconnect buttons
- ElevenLabs connection status

## API Endpoints

### ElevenLabs Configuration (Admin Only)

- `GET /api/elevenlabs/config` - Get current configuration
- `PUT /api/elevenlabs/config` - Update API key
- `GET /api/elevenlabs/config/test` - Test API key

### Agent Management (Admin/Teacher)

- `GET /api/elevenlabs/agent/:agentId/validate` - Validate agent ID

### Conversation Endpoints (Authenticated Users)

- `GET /api/elevenlabs/agent/:agentId/signed-url` - Get signed URL for agent
- `GET /api/elevenlabs/agent/:agentId/conversation-token` - Get conversation token
- `GET /api/elevenlabs/bot/:botName/signed-url` - Get signed URL by bot name
- `GET /api/elevenlabs/bot/:botName/conversation-token` - Get conversation token by bot name

## WebSocket Protocol

### Connection Flow

1. **Frontend connects to backend WebSocket** (`ws://localhost:3000/ws`)
2. **Frontend sends initialization message**:
   ```json
   {
     "type": "init_conversation",
     "botName": "English Tutor Sarah",
     "userId": "user-id"
   }
   ```
3. **Backend validates access and gets signed URL**
4. **Backend responds with ElevenLabs ready message**:
   ```json
   {
     "type": "elevenlabs_ready",
     "signedUrl": "wss://api.elevenlabs.io/...",
     "agentId": "test-agent-sarah-001",
     "botName": "English Tutor Sarah"
   }
   ```
5. **Frontend connects directly to ElevenLabs** using the signed URL

### Message Flow

1. **User sends message** → Frontend → ElevenLabs WebSocket
2. **ElevenLabs responds** → Frontend → Display in chat
3. **Typing indicators** are handled by both connections

## Troubleshooting

### Common Issues

1. **"No API key configured"**
   - Log in to the admin panel in the frontend
   - Navigate to ElevenLabs configuration
   - Add your API key through the web interface

2. **"Bot not found or access denied"**
   - Ensure the bot exists in the database
   - Check that the user has access to the bot
   - Verify the bot is active

3. **"Failed to connect to ElevenLabs"**
   - Check your internet connection
   - Verify the API key is valid
   - Ensure the agent ID exists in ElevenLabs

4. **"Invalid agent ID"**
   - Create the agent in ElevenLabs dashboard
   - Update the bot record with the correct agent ID

### Debug Information

In development mode, check:
- Browser console for detailed logs
- Debug panel in chat interface
- Backend logs for WebSocket and API calls

### Logs to Monitor

- Backend: WebSocket connections, ElevenLabs API calls
- Frontend: Connection status, message flow
- ElevenLabs: Agent responses, audio processing

## Production Considerations

1. **API Key Security**: Store API keys securely, never in client-side code
2. **Rate Limiting**: Implement rate limiting for ElevenLabs API calls
3. **Error Handling**: Graceful fallbacks for API failures
4. **Monitoring**: Track usage and performance metrics
5. **CORS**: Configure CORS properly for WebSocket connections

## Next Steps

1. **Voice Integration**: Add audio playback for ElevenLabs responses
2. **Conversation History**: Store and retrieve chat transcripts
3. **Analytics**: Track conversation quality and learning progress
4. **Multi-language**: Support for different languages and accents
5. **Advanced Features**: Voice input, real-time translation, etc. 