# LiveKit Agent Implementation Guide

## Overview

This document describes the proper LiveKit Agents SDK implementation for the KAORI Voice Assistant, following the latest LiveKit documentation patterns from September 2025.

## Architecture

### 1. KAORIVoiceAgent Class

The `KAORIVoiceAgent` class extends the LiveKit `Agent` class and implements the core voice assistant functionality:

```python
class KAORIVoiceAgent(Agent):
    def __init__(self, user_context: Dict[str, Any] = None):
        super().__init__(
            instructions="You are KAORI, a helpful productivity assistant...",
            stt=deepgram.STT(model="nova-2", language="multi"),
            llm=openai.LLM(model="gpt-4o-mini", timeout=30),
            tts=elevenlabs.TTS(
                api_key=os.getenv("ELEVENLABS_TTS_API_KEY"),
                voice_id="21m00Tcm4TlvDq8ikWAM",
                model="eleven_monolingual_v1"
            ),
            allow_interruptions=True,
            min_endpointing_delay=0.5,
            max_endpointing_delay=5.0,
        )
```

**Key Features:**
- **STT**: Deepgram Nova-2 for multi-language speech recognition
- **LLM**: OpenAI GPT-4o-mini for intelligent responses
- **TTS**: ElevenLabs with professional female voice (Rachel)
- **Turn Detection**: Built-in LiveKit turn detection
- **Interruptions**: Allows user to interrupt the agent

### 2. LiveKitVoiceService Class

The `LiveKitVoiceService` class manages voice sessions and provides REST API compatibility:

```python
class LiveKitVoiceService:
    def __init__(self):
        self.sessions: Dict[str, VoiceSessionData] = {}
        self.rooms: Dict[str, str] = {}
        self.agent_sessions: Dict[str, AgentSession] = {}
        self.event_queues: Dict[str, asyncio.Queue] = {}
```

**Key Methods:**
- `start_voice_session()`: Creates a new voice session
- `add_audio_chunk()`: Processes audio input (for compatibility)
- `stream_voice_events()`: Streams real-time events via SSE
- `end_voice_session()`: Cleans up session resources
- `health_check()`: Service health monitoring

### 3. LiveKit Agent Entrypoint

The `entrypoint` function follows the standard LiveKit pattern:

```python
async def entrypoint(ctx: JobContext):
    """LiveKit agent entrypoint function"""
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    participant = await ctx.wait_for_participant()
    
    # Create agent session with proper configuration
    session = AgentSession(
        vad=silero.VAD.load(),
        min_endpointing_delay=0.5,
        max_endpointing_delay=5.0,
    )
    
    # Create and start KAORI agent
    agent = KAORIVoiceAgent()
    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
        ),
        room_output_options=RoomOutputOptions(
            audio_enabled=True,
            audio_sample_rate=24000,
            audio_num_channels=1,
            transcription_enabled=True,
        ),
    )
```

## Running the Agent

### 1. Standalone Agent Runner

Use the `run_livekit_agent.py` script to run the agent as a standalone service:

```bash
cd backend
python run_livekit_agent.py
```

### 2. FastAPI Integration

The agent can also be integrated with FastAPI for REST API compatibility:

```bash
cd backend
python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```

## Configuration

### Environment Variables

Required environment variables:

```bash
# LiveKit Configuration
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret

# AI Service Configuration
OPENAI_API_KEY=your-openai-key
ELEVENLABS_TTS_API_KEY=your-elevenlabs-key

# Optional: Test Mode
TEST_MODE=false
```

### Voice Configuration

The agent supports multiple ElevenLabs voices:

- **Rachel** (21m00Tcm4TlvDq8ikWAM): Professional female voice (default)
- **Domi** (AZnzlk1XvdvUeBnXmlld): Confident female voice
- **Bella** (EXAVITQu4vr4xnSDxMaL): Friendly female voice
- **Antoni** (ErXwobaYiN019PkySvjV): Professional male voice
- **Elli** (MF3mGyEYCl7XYWbV9V6O): Young female voice
- **Josh** (TxGEqnHWrfWFTfGW9XjX): Deep male voice
- **Arnold** (VR6AewLTigWG4xSOukaG): Strong male voice
- **Adam** (pNInz6obpgDQGcFmaJgB): Calm male voice
- **Sam** (yoZ06aMxZJJ28mfd3POQ): Friendly male voice

## API Endpoints

### Test Endpoints (No Authentication)

- `POST /test/voice/session/start` - Start a voice session
- `POST /test/voice/session/{session_id}/audio-chunk` - Send audio chunk
- `GET /test/voice/session/{session_id}/stream` - Stream events (SSE)
- `GET /test/voice/session/{session_id}/events-simple` - Get events (non-streaming)
- `GET /test/voice/sessions` - List all sessions
- `GET /test/voice/health` - Health check

### Example Usage

```bash
# Start a voice session
curl -X POST "http://localhost:8000/test/voice/session/start?user_id=test_user&user_name=Test%20User"

# Send audio chunk
echo "test audio data" > test_audio.txt
curl -X POST "http://localhost:8000/test/voice/session/{session_id}/audio-chunk" -F "audio_chunk=@test_audio.txt"

# Stream events
curl -X GET "http://localhost:8000/test/voice/session/{session_id}/stream"
```

## Frontend Integration

The frontend can integrate with the voice service using:

1. **LiveKit Room Connection**: Direct connection to LiveKit rooms
2. **REST API**: For session management and audio chunk sending
3. **Server-Sent Events**: For real-time event streaming

### Frontend Code Example

```typescript
// Connect to LiveKit room
const room = new Room();
await room.connect(livekitUrl, token);

// Send audio chunks via REST API
const formData = new FormData();
formData.append('audio_chunk', audioBlob);
await fetch(`/test/voice/session/${sessionId}/audio-chunk`, {
    method: 'POST',
    body: formData
});

// Stream events via SSE
const eventSource = new EventSource(`/test/voice/session/${sessionId}/stream`);
eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Voice event:', data);
};
```

## Testing

### Unit Tests

Run the integration test script:

```bash
cd backend
python test_livekit_integration.py
```

### Manual Testing

1. Start the FastAPI server
2. Use the test endpoints to create sessions and send audio
3. Monitor the console for logs and events
4. Test the frontend integration

## Troubleshooting

### Common Issues

1. **Import Errors**: Ensure all LiveKit dependencies are installed
2. **API Key Issues**: Verify all environment variables are set
3. **Connection Issues**: Check LiveKit server configuration
4. **Audio Issues**: Verify microphone permissions and audio format

### Debug Mode

Enable debug logging:

```python
import logging
logging.basicConfig(level=logging.DEBUG)
```

### Health Check

Check service health:

```bash
curl -X GET "http://localhost:8000/test/voice/health"
```

## Performance Considerations

1. **Audio Buffer Size**: Adjust based on network conditions
2. **Rate Limiting**: Implement proper rate limiting for API calls
3. **Session Cleanup**: Ensure proper cleanup of expired sessions
4. **Memory Management**: Monitor memory usage for long-running sessions

## Security Considerations

1. **Authentication**: Implement proper JWT authentication for production
2. **API Keys**: Store API keys securely in environment variables
3. **Rate Limiting**: Implement rate limiting to prevent abuse
4. **Input Validation**: Validate all input data

## Future Enhancements

1. **Multi-language Support**: Add support for more languages
2. **Custom Voices**: Allow users to select custom voices
3. **Voice Cloning**: Integrate voice cloning capabilities
4. **Advanced Analytics**: Add detailed usage analytics
5. **Multi-user Support**: Support multiple users in the same room

## Conclusion

This implementation provides a robust, scalable voice assistant using the LiveKit Agents SDK. It follows best practices and provides both standalone and integrated deployment options. The modular design allows for easy customization and extension of functionality.
