# BuzzTrail Proxy Server

Vercel serverless function proxy for Tavus Conversational Video Interface (CVI) API.

This proxy server provides centralized access to the Tavus API with built-in credit optimization, timeout enforcement, and enhanced parameter support.

## 🎯 Purpose

- **Credit Optimization**: Automatic timeout enforcement to minimize credit consumption
- **Centralized Access**: Single point of control for all Tavus API calls
- **Enhanced Features**: Support for advanced Tavus API parameters
- **Environment Isolation**: Separate configurations for development, staging, and production
- **Backward Compatibility**: Maintains support for legacy API patterns

## 🚀 Key Features

### Credit Optimization (Added 2025-09-30)

**Aggressive Timeout Defaults**:
- `max_call_duration`: 180s (3 minutes) - down from 3600s
- `participant_left_timeout`: 10s - cleanup when participant leaves
- `participant_absent_timeout`: 30s - cleanup when no one joins

**Expected Impact**:
- 40-60% reduction in monthly credit consumption
- <40s cleanup time for abandoned conversations
- 100% timeout coverage on all conversations

### Dynamic Conversation Naming

Automatically generates descriptive conversation names:
```
Format: "{PersonaName} - {Context} - {Timestamp}"
Example: "BuzzTrail Researcher - Product Demo - 2025-09-30 18:15"
```

No more hardcoded conversation names!

### Enhanced API Parameters

Full support for advanced Tavus features:
- `conversational_context` - Provide conversation background
- `custom_greeting` - Personalized intro messages
- `callback_url` - Webhook notifications for events
- `language` - Multi-language support
- `enable_video` - Audio-only mode for additional savings

## 📡 API Endpoints

### POST /api/conversations/create

Create a new Tavus conversation with automatic credit optimization.

**Request Format (New - Recommended)**:
```json
{
  "persona_id": "p527c5d8b826",
  "replica_id": "rca8a38779a8",
  "conversational_context": "Product demo for enterprise customer",
  "custom_greeting": "Hello! I'm here to show you our platform.",
  "properties": {
    "language": "en",
    "max_call_duration": 180
  }
}
```

**Request Format (Legacy - Still Supported)**:
```json
{
  "personaKey": "buzztrail-researcher",
  "conversation_duration_seconds": 180
}
```

**Response**:
```json
{
  "conversation_id": "conv_abc123",
  "conversation_url": "https://tavus.daily.co/...",
  "status": "active"
}
```

**Timeout Behavior**:
- All timeout parameters are **automatically enforced**
- Client can override defaults by providing values in `properties`
- Values are validated against Tavus API limits (max=3600s, left/absent=300s)

### POST /api/conversations/:id/end

End a conversation gracefully.

## 🔧 Configuration

### Environment Variables

**Required**:
- `TAVUS_API_KEY` - Your Tavus API key

**Optional**:
- `TESTING_MODE` - Set to `fake-only` to use fake Tavus server
- `FAKE_SERVER_URL` - URL for fake server (default: http://localhost:3001)
- `REAL_SERVER_URL` - Real Tavus API URL (default: https://tavusapi.com)

**Timeout Overrides** (optional):
- `TAVUS_MAX_CALL_DURATION` - Override max duration (0-3600)
- `TAVUS_PARTICIPANT_LEFT_TIMEOUT` - Override left timeout (0-300)
- `TAVUS_PARTICIPANT_ABSENT_TIMEOUT` - Override absent timeout (0-300)

### Testing Modes

1. **Production Mode** (default):
   - Uses real Tavus API
   - Full credit consumption
   - `TESTING_MODE` not set or set to `production`

2. **Fake Server Mode**:
   - Uses local fake Tavus server
   - No credit consumption
   - `TESTING_MODE=fake-only`

## 📦 Deployment

### Vercel Deployment

```bash
# Build
pnpm exec nx build proxy-server

# Deploy
vercel deploy apps/proxy-server
```

### Environment Setup

Add to Vercel environment variables:
```
TAVUS_API_KEY=your-production-key
TESTING_MODE=production
```

## 🏗️ Architecture

### Timeout Enforcement Flow

```
Client Request
    ↓
Extract Parameters (persona_id, replica_id, properties, etc.)
    ↓
Merge with Recording Defaults (from recording-config.js)
    ↓
Enforce Timeout Defaults (enforceTimeouts function)
    ↓
Validate Against API Limits (validateTimeouts function)
    ↓
Generate Dynamic Name (generateConversationName function)
    ↓
Build Tavus Request
    ↓
Call Tavus API
```

### Key Functions

**`enforceTimeouts(properties)`**
- Ensures all conversations have timeout parameters
- Applies defaults: max=180s, left=10s, absent=30s
- Preserves client overrides if provided

**`validateTimeouts(properties)`**
- Validates against Tavus API limits
- Throws error if values out of range
- Limits: max ≤ 3600s, left/absent ≤ 300s

**`generateConversationName(personaId, replicaId, personaName, context)`**
- Creates descriptive names with timestamp
- Format: "{PersonaName} - {Context} - {YYYY-MM-DD HH:mm}"
- Eliminates hardcoded names

**`mergeConversationDefaults(properties, personaId)`**
- Merges client properties with smart defaults
- Includes recording configuration
- Persona-specific settings

## 📚 Related Documentation

- [VALIDATION-SUMMARY.md](../../VALIDATION-SUMMARY.md) - Implementation validation
- [BUILD-TEST-SUMMARY.md](../../BUILD-TEST-SUMMARY.md) - Build and test results
- [Tavus API Docs](https://docs.tavus.io)

## 🔍 Monitoring

### Credit Usage Tracking

Monitor in Tavus dashboard:
- Conversation durations
- Timeout trigger frequency
- Credit consumption trends

### Key Metrics

- **Average conversation duration**: Should be ≤ 180s
- **Cleanup time**: Should be < 40s for abandoned calls
- **Credit reduction**: Target 40-60% decrease

## 🛠️ Development

### Local Development

```bash
# Start fake Tavus server
pnpm nx serve fake-tavus-server

# In another terminal, set environment
export TESTING_MODE=fake-only
export FAKE_SERVER_URL=http://localhost:3001
export TAVUS_API_KEY=test-key

# Run proxy locally
vercel dev
```

### Testing

```bash
# Create conversation
curl -X POST http://localhost:3000/api/conversations/create \
  -H "Content-Type: application/json" \
  -d '{
    "persona_id": "p527c5d8b826",
    "replica_id": "rca8a38779a8"
  }'
```

## 📊 Credit Optimization Results

**Before** (2025-09-29):
- Max duration: 3600s (1 hour)
- No timeout enforcement
- Hardcoded conversation names

**After** (2025-09-30):
- Max duration: 180s (3 minutes) ✅
- 100% timeout enforcement ✅
- Dynamic conversation naming ✅
- Expected savings: 40-60% ✅

## 🔗 Dependencies

- `axios` - HTTP client for Tavus API calls
- `./recording-config.js` - Recording configuration utilities

## 📄 License

Private - BuzzTrail AI

## 📞 Support

For issues or questions:
- Check logs in Vercel dashboard
- Review VALIDATION-SUMMARY.md
- Contact: team@buzztrail.ai

---

**Last Updated**: 2025-09-30
**Epic**: optimize-tavus-credit-usage
**Status**: Production Ready ✅
