# Railway Deployment Guide - Voice Agent LiveKit

This guide covers deploying the voice agent to Railway for production use.

## Prerequisites

- Railway account (https://railway.app/)
- Railway CLI installed: `npm install -g @railway/cli`
- All required API keys (see Environment Variables section)

## Deployment Steps

### 1. Login to Railway

```bash
railway login
```

### 2. Initialize Railway Project

From the `apps/voice-agent-livekit` directory:

```bash
cd apps/voice-agent-livekit
railway init
```

Select or create a new project when prompted.

### 3. Link to Railway Service

**Important:** After initializing the project, you must link to a service before setting variables or deploying:

```bash
railway service
```

This will prompt you to select or create a service. Railway needs this link to know which service to configure.

### 4. Configure Environment Variables

Set all required environment variables in Railway:

```bash
# LiveKit Cloud credentials
railway variables set LIVEKIT_URL=wss://your-project.livekit.cloud
railway variables set LIVEKIT_API_KEY=your-api-key
railway variables set LIVEKIT_API_SECRET=your-api-secret

# Voice service API keys
railway variables set DEEPGRAM_API_KEY=your-deepgram-key
railway variables set OPENAI_API_KEY=your-openai-key

# Supabase Configuration (for slide control)
railway variables set SUPABASE_URL=https://your-project-ref.supabase.co
railway variables set SUPABASE_SERVICE_KEY=your-supabase-service-role-key

# Optional: Agent configuration
railway variables set AGENT_LOG_LEVEL=INFO
railway variables set AGENT_TTS_MODEL="cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"
railway variables set AGENT_STT_MODEL=base
railway variables set AGENT_LLM_MODEL=gpt-4o-mini
```

### 5. Deploy to Railway

```bash
railway up
```

This will:
- Build the Python environment using nixpacks
- Install dependencies with uv
- Start the LiveKit agent worker

### 6. Monitor Deployment

Check deployment status:

```bash
railway status
```

View logs:

```bash
railway logs
```

## Environment Variables

### Required Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `LIVEKIT_URL` | LiveKit server WebSocket URL | `wss://your-project.livekit.cloud` |
| `LIVEKIT_API_KEY` | LiveKit API key | `APIxxxxxxxxx` |
| `LIVEKIT_API_SECRET` | LiveKit API secret | `xxxxxxxxxxxxxxx` |
| `DEEPGRAM_API_KEY` | Deepgram API key for STT | `xxxxxxxxxxxxxxx` |
| `OPENAI_API_KEY` | OpenAI API key for LLM | `sk-xxxxxxxxxx` |
| `SUPABASE_URL` | Supabase project URL | `https://xxx.supabase.co` |
| `SUPABASE_SERVICE_KEY` | Supabase service role key | `eyJxxxxxxxxxxxx` |

### Optional Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `LIVEKIT_ROOM_NAME` | auto-generated | Specific room name to join |
| `AGENT_INITIAL_GREETING` | (see config.py) | Custom greeting message |
| `AGENT_TTS_MODEL` | `cartesia/sonic-2:...` | TTS model to use |
| `AGENT_STT_MODEL` | `base` | Deepgram STT model |
| `AGENT_LLM_MODEL` | `gpt-4o-mini` | OpenAI LLM model |
| `AGENT_LOG_LEVEL` | `INFO` | Logging level (DEBUG/INFO/WARNING/ERROR) |

## Architecture

### LiveKit Agent Worker

The voice agent runs as a **LiveKit Agent Worker** that:

1. Connects to LiveKit Cloud using the provided credentials
2. Listens for room creation events (job dispatches)
3. Joins rooms automatically when users connect
4. Handles voice conversations using:
   - **Cartesia TTS** (via LiveKit Inference - FREE)
   - **Deepgram STT** (base model - $0.0043/min)
   - **OpenAI GPT-4o-mini** (fast & cost-effective)
5. Integrates with Supabase for slide control commands

### How It Works

```
User creates room → LiveKit dispatches job → Agent joins room
                                              ↓
                         User speaks → STT (Deepgram) → LLM (OpenAI)
                                              ↓
                         Agent speaks ← TTS (Cartesia) ← Response
                                              ↓
                         Slide commands → Supabase Realtime → Frontend
```

## Cost Estimation

Based on POC validation:

- **TTS (Cartesia via LiveKit)**: FREE (included in LiveKit)
- **STT (Deepgram base)**: ~$0.026 per 5-minute session
- **LLM (GPT-4o-mini)**: ~$0.083 per session
- **Total**: ~$0.109 per 5-minute session

**83% cheaper than original estimate!** ($0.109 vs $0.66)

## Monitoring

### Health Check

The agent automatically registers with LiveKit as a worker. Check worker status in:
- LiveKit Cloud Dashboard: https://cloud.livekit.io/projects/your-project/agents
- Railway logs: `railway logs`

### Debugging

Enable debug logging:

```bash
railway variables set AGENT_LOG_LEVEL=DEBUG
railway up
```

Common issues:

**Agent doesn't connect:**
- Verify LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET are correct
- Check Railway logs for connection errors
- Ensure LiveKit Cloud project is active

**Agent doesn't respond:**
- Verify DEEPGRAM_API_KEY and OPENAI_API_KEY are valid
- Check API key billing/credits
- Enable DEBUG logging to see STT/LLM requests

**Slide commands don't work:**
- Verify SUPABASE_URL and SUPABASE_SERVICE_KEY
- Check Supabase project is active
- Ensure frontend is subscribed to correct channel

## Scaling

Railway automatically handles:
- **Restarts**: Agent restarts on failure (max 10 retries)
- **Resource allocation**: Auto-scales based on usage
- **Zero-downtime deploys**: New version deployed alongside old

For high-traffic scenarios:
1. Increase Railway service replicas
2. LiveKit automatically load-balances across workers
3. Monitor costs with higher usage

## Rollback

If deployment has issues:

```bash
# View deployments
railway status

# Rollback to previous deployment
railway rollback <deployment-id>
```

## Local Testing Before Deploy

Test the agent locally first:

```bash
# Load environment variables
set -a && source .env && set +a

# Run agent locally
uv run python -m livekit.agents.cli start voice_agent_livekit.agent:entrypoint

# In another terminal, test with LiveKit Sandbox
# https://cloud.livekit.io/projects/your-project/sandbox
```

## Production Checklist

Before deploying to production:

- [ ] All environment variables configured in Railway
- [ ] LiveKit Cloud project configured and active
- [ ] API keys have sufficient credits/billing enabled
- [ ] Supabase project configured with realtime channels
- [ ] Local testing successful
- [ ] Deployment tested in staging environment
- [ ] Monitoring and logging configured
- [ ] Error alerting set up (Railway Slack/Discord integration)

## Support

- **LiveKit Docs**: https://docs.livekit.io/agents/overview/
- **Railway Docs**: https://docs.railway.app/
- **Project Issues**: https://github.com/BuzzTrail/video-extension/issues
