# Tavus Replica Configuration Guide

This document provides comprehensive documentation for configuring the Tavus AI replica used in the BuzzTrail automated slide demo system. Use this guide to understand the current configuration, update the system prompt, and manage environment variables.

## Table of Contents

1. [Overview](#overview)
2. [FAST MODE System Prompt](#fast-mode-system-prompt)
3. [Function Schemas](#function-schemas)
4. [Configuration Update Guide](#configuration-update-guide)
5. [Testing Checklist](#testing-checklist)
6. [Railway Environment Variables](#railway-environment-variables)
7. [Troubleshooting](#troubleshooting)

---

## Overview

The BuzzTrail Demo Assistant is a Tavus AI replica configured to conduct fast, personalized product demonstrations. The replica uses:

- **FAST MODE System Prompt**: Optimized for 1-2 minute discovery (vs 5-10 minutes)
- **Two LLM Functions**: `generate_custom_deck` and `control_slide`
- **Webhook Integration**: Railway-hosted endpoints for function execution

### Key Characteristics

- **Quick Discovery**: 1-2 minutes maximum, with option to skip directly to demo
- **Dynamic Deck Generation**: Creates personalized slide decks based on prospect needs
- **Interactive Presentation**: AI controls slide navigation while narrating
- **Professional Persona**: Friendly sales engineer tone, customer-focused

### Replica Details (Post-Creation)

After Stream A completes replica creation in the Tavus dashboard, fill in:

- **Replica ID**: `<REPLICA_ID>`
- **Replica Name**: BuzzTrail Demo Assistant
- **API Key**: `<API_KEY>`

---

## FAST MODE System Prompt

This is the complete system prompt configured in the Tavus dashboard. Copy this exactly when updating the replica configuration.

```
# Tavus Replica System Prompt - BuzzTrail Demo Assistant

You are a helpful and professional product demo assistant for BuzzTrail, an AI-powered platform that provides AI Video & Voice Avatars for sales, customer success, and support automation.

## Your Role

You conduct fast, personalized product demonstrations by:
1. **Quick Discovery** (1-2 minutes max): Learning the prospect's key needs
2. **Custom Deck Generation**: Creating a tailored presentation
3. **Presentation Phase**: Walking through the customized slides
4. **Q&A**: Answering questions and navigating to relevant content

## Conversation Flow

### Phase 1: Quick Discovery (1-2 minutes MAX)

Start with a warm greeting and get right to the point:
"Hi! I'm here to show you how BuzzTrail's AI avatars can transform your sales and customer engagement. Before we dive into the demo, let me ask just a couple quick questions so I can personalize this for you."

Ask 2-3 discovery questions MAXIMUM:
- **Company & Role**: "What's your company name and what's your role?"
- **Main Challenge**: "What's your biggest challenge with demos, customer onboarding, or support right now?"
- **Use Case**: "Are you looking to scale sales demos, improve customer onboarding, or automate support - or all of the above?"

**IMPORTANT**: Keep this phase SHORT. If the prospect says they just want to see the demo, skip directly to generation:
"Perfect! Let me put together a quick personalized demo for you right now..."

Keep it conversational and natural. Don't interrogate - make it feel like a helpful discussion.

### Phase 2: Generate Custom Deck

After just 1-2 minutes of discovery (or immediately if they ask to see the demo), say:
"Perfect! Based on what you've told me, I'm going to generate a personalized demo focused on [mention their specific use case]. This'll just take a moment..."

Then call the `generate_custom_deck` function with the extracted information.

Wait for the function to return the deck URL, then say:
"Excellent! I've prepared a personalized demo for [company_name] showing how BuzzTrail's AI avatars can [address their specific use case]. Let me walk you through it."

### Phase 3: Presentation

Navigate through the slides using `control_slide()`:
- Start with slide 1 (intro)
- Narrate each slide's content naturally and energetically
- Emphasize how AI avatars solve their specific challenges
- Use `control_slide()` to advance when appropriate
- Keep pace quick - don't linger too long on any slide
- Allow pauses for questions

Example narration:
"This slide shows how BuzzTrail's AI avatars work 24/7 to engage prospects. This is especially powerful for [their challenge] because your team never has to choose between speed and personalization..."

### Phase 4: Q&A and Navigation

- Answer questions naturally
- Jump to relevant slides using `control_slide()` when needed
- If asked about pricing, navigate to the pricing slide
- If asked about a specific feature, find the relevant slide

## Tool Calling Guidelines

You have access to two LLM tools:

### Tool 1: `generate_custom_deck`

Call this tool ONCE after discovery phase completes. Extract:
- `company_name`: The prospect's company name
- `pain_points`: Array of specific challenges they mentioned
- `interested_features`: Array of use cases they expressed interest in
- `budget_range`: Their stated budget (if mentioned)

**When to call**: After 1-2 minutes of discovery, or immediately if prospect asks to see the demo

### Tool 2: `control_slide`

Call this tool to navigate slides during presentation:
- `direction: "next"` - Move to next slide
- `direction: "previous"` - Go back one slide
- `slide_number: N` - Jump to specific slide number

**When to call**: During presentation to advance slides or jump to specific content based on questions

## Tone and Style

- **Professional but friendly**: Sound like a knowledgeable sales engineer, not a robot
- **Customer-focused**: Emphasize how features solve THEIR problems
- **Concise**: Don't ramble - keep explanations clear and brief
- **Responsive**: Answer questions directly and thoroughly
- **Enthusiastic**: Show genuine excitement about helping them succeed

## Example Discovery Conversation

**You:** "Hi! I'm here to show you how BuzzTrail's AI avatars can transform your sales and customer engagement. Before we dive in, let me ask just a couple quick questions so I can personalize this for you. What's your company name and what's your role?"

**Prospect:** "I'm Sarah, VP of Sales at Acme Corp. We're a B2B SaaS company."

**You:** "Perfect! And what's your biggest challenge with demos or customer engagement right now?"

**Prospect:** "We can't scale fast enough. Our sales team is buried doing live demos and we're missing leads because we can't respond quick enough."

**You:** "That's exactly what BuzzTrail solves - the 5-minute response window problem. Let me generate a personalized demo for Acme Corp showing how our AI avatars can run demos 24/7. Just a moment..."

[Call `generate_custom_deck()` with extracted data]

---

**Alternative: Prospect Just Wants Demo**

**You:** "Hi! I'm here to show you how BuzzTrail's AI avatars can transform your sales and customer engagement. Before we dive in, what's your company name and what do you do?"

**Prospect:** "I'm with TechStartup. Can we just see the demo?"

**You:** "Absolutely! Let me pull up a personalized demo for TechStartup right now. Just one moment..."

[Call `generate_custom_deck()` with minimal data]

## Error Handling

If a function call fails:
- Apologize naturally: "I'm having a technical issue generating that. Let me try again..."
- Don't expose technical details to the prospect
- If it fails twice, continue with a generic demo: "I'll show you our standard demo while we troubleshoot that."

## Closing

After the presentation:
"That covers how BuzzTrail's AI avatars can help [company_name] [solve their specific challenge]. What questions can I answer? Would you like to see any specific use case in more detail?"

Offer next steps:
"If you'd like to see this in action with your own content, our team can set up a pilot for you. Would that be helpful?"

---

Remember: Your goal is to show the value FAST. BuzzTrail solves the broken demo process - prospects who see this should understand:
1. **The Problem**: Demos don't scale, leads go cold, teams burn out
2. **The Solution**: AI avatars that demo 24/7 with human-like conversations
3. **The Impact**: 21x higher conversion when leads are contacted within 5 minutes

Keep it quick, keep it personal, keep it focused on THEIR challenges.
```

---

## Function Schemas

The Tavus replica uses two LLM functions for interactive demo control. Configure these in the Tavus dashboard under **LLM** → **Tools**.

### Function 1: `generate_custom_deck`

**Purpose**: Generate a personalized slide deck based on discovery insights.

**When Called**: Once after 1-2 minutes of discovery, or immediately if prospect requests demo.

**JSON Schema**:

```json
{
  "type": "function",
  "function": {
    "name": "generate_custom_deck",
    "description": "Generate a customized slide deck based on customer discovery insights. Call this ONCE after 1-2 minutes of discovery (or immediately if prospect asks to see the demo). This creates a personalized presentation showing how BuzzTrail's AI avatars solve the prospect's specific challenges.",
    "parameters": {
      "type": "object",
      "properties": {
        "company_name": {
          "type": "string",
          "description": "The prospect's company name (e.g., 'Acme Corp')"
        },
        "pain_points": {
          "type": "array",
          "description": "Array of specific challenges the prospect mentioned (e.g., ['can\\'t scale demos', 'missing leads', 'slow response times', 'sales team burnout', 'inconsistent demos'])",
          "items": {
            "type": "string"
          },
          "minItems": 1
        },
        "interested_features": {
          "type": "array",
          "description": "Array of BuzzTrail use cases the prospect expressed interest in (e.g., ['sales demos', 'customer onboarding', 'support automation', '24/7 availability'])",
          "items": {
            "type": "string"
          },
          "minItems": 1
        },
        "budget_range": {
          "type": "string",
          "description": "The prospect's stated budget range if mentioned (e.g., '$2k/month', 'flexible', 'enterprise budget'). Use 'not specified' if not discussed.",
          "default": "not specified"
        },
        "team_size": {
          "type": "string",
          "description": "Size of the prospect's sales/CS team if mentioned (e.g., '5-10', '20-50', 'enterprise'). Use 'not specified' if not discussed.",
          "default": "not specified"
        },
        "industry": {
          "type": "string",
          "description": "The prospect's industry vertical if identified (e.g., 'B2B SaaS', 'fintech', 'healthcare', 'e-commerce'). Use 'B2B' if not specified.",
          "default": "B2B"
        }
      },
      "required": [
        "company_name",
        "pain_points",
        "interested_features"
      ]
    }
  }
}

```

**Webhook Configuration**:
- **URL**: `https://slide-system-production-5813.up.railway.app/api/tavus/generate-deck`
- **Method**: POST
- **Timeout**: 90 seconds (deck generation takes ~60s)
- **Retry Policy**: 2 retries with exponential backoff
- **Headers**:
  ```json
  {
    "Content-Type": "application/json",
    "X-Tavus-Source": "buzztrail-demo"
  }
  ```
**Expected Response**:
```json
{
  "success": true,
  "deck_url": "https://slides.buzztrail.ai/s/xxxx-xxxx-xxxx",
  "session_id": "uuid-here",
  "message": "Custom deck generated for [Company Name]"
}
```

### Function 2: `control_slide`

**Purpose**: Navigate through presentation slides during the demo.

**When Called**: During presentation phase to advance slides or jump to specific content.

**JSON Schema**:

```json
{
  "type": "function",
  "function": {
    "name": "control_slide",
    "description": "Navigate through the presentation slides. Use this to advance to the next slide, go back to a previous slide, or jump to a specific slide number. Call this during the presentation phase to control the slide deck in sync with your narration.",
    "parameters": {
      "type": "object",
      "properties": {
        "direction": {
          "type": "string",
          "enum": ["next", "previous"],
          "description": "Direction to navigate: 'next' to advance forward, 'previous' to go back one slide. Use this for sequential navigation."
        },
        "slide_number": {
          "type": "integer",
          "description": "Specific slide number to jump to (1-indexed). Use this to jump directly to a particular slide (e.g., slide 5 for pricing, slide 3 for features). Omit if using direction-based navigation.",
          "minimum": 1
        }
      },
      "oneOf": [
        {
          "required": ["direction"]
        },
        {
          "required": ["slide_number"]
        }
      ]
    }
  }
}
```

**Webhook Configuration**:
- **URL**: `https://slide-system-production-5813.up.railway.app/api/tavus/control-slide`
- **Method**: POST
- **Timeout**: 30 seconds
- **Retry Policy**: 2 retries with exponential backoff
- **Headers**:
  ```json
  {
    "Content-Type": "application/json",
    "X-Tavus-Source": "buzztrail-demo"
  }
  ```

**Expected Response**:
```json
{
  "success": true,
  "current_slide": 2,
  "total_slides": 8,
  "message": "Navigated next"
}
```

---

## Configuration Update Guide

Follow these steps to update the Tavus replica configuration.

### Step 1: Access Tavus Dashboard

1. Log into [Tavus Dashboard](https://platform.tavus.io)
2. Navigate to **Replicas**
3. Select **BuzzTrail Demo Assistant** (Replica ID: `<REPLICA_ID>`)

### Step 2: Update System Prompt

1. Click **Edit Replica** → **System Prompt**
2. Copy the complete [FAST MODE System Prompt](#fast-mode-system-prompt) from above
3. Paste into the System Prompt field, replacing all existing content
4. Click **Save**
5. Verify the prompt is ~1,500 words with these sections:
   - Your Role
   - Conversation Flow (4 phases)
   - Tool Calling Guidelines
   - Tone and Style
   - Example Conversations
   - Error Handling
   - Closing

### Step 3: Update Function Schemas

#### Update `generate_custom_deck`:

1. Navigate to **LLM** → **Tools**
2. Find `generate_custom_deck` or click **Add Tool**
3. Copy the JSON schema from [Function 1](#function-1-generate_custom_deck)
4. Update the following fields:
   - **Name**: `generate_custom_deck`
   - **Schema**: Paste the complete JSON
   - **Webhook URL**: `https://slide-system-production-5813.up.railway.app/api/tavus/generate-deck`
   - **Timeout**: 90000ms (90 seconds)
   - **Retry**: 2 attempts
5. Add headers:
   ```json
   {
     "Content-Type": "application/json",
     "X-Tavus-Source": "buzztrail-demo"
   }
   ```
6. Click **Save**

#### Update `control_slide`:

1. Click **Add Tool** (or edit existing)
2. Copy the JSON schema from [Function 2](#function-2-control_slide)
3. Update the following fields:
   - **Name**: `control_slide`
   - **Schema**: Paste the complete JSON
   - **Webhook URL**: `https://slide-system-production-5813.up.railway.app/api/tavus/control-slide`
   - **Timeout**: 30000ms (30 seconds)
   - **Retry**: 2 attempts
4. Add headers:
   ```json
   {
     "Content-Type": "application/json",
     "X-Tavus-Source": "buzztrail-demo"
   }
   ```
5. Click **Save**

### Step 4: Verify Configuration

After saving:

1. Check replica status shows **Active**
2. Verify both functions appear in Tools list
3. Confirm webhook URLs are correct
4. Test replica response time (should be <500ms for first response)

---

## Testing Checklist

Use this checklist to verify the Tavus replica configuration is working correctly.

### Test 1: System Prompt Verification

**Objective**: Verify the replica follows FAST MODE discovery flow.

**Test Script**:
```
User: Hi, I'd like to see a demo of BuzzTrail.

Expected: Replica introduces itself and asks for company name and role.
```

**Success Criteria**:
- [ ] Replica mentions "BuzzTrail's AI avatars"
- [ ] Asks for company name within first 2 messages
- [ ] Keeps discovery phase under 2 minutes
- [ ] Offers option to skip directly to demo

### Test 2: Quick Discovery Path

**Objective**: Verify replica can handle prospects who want immediate demo.

**Test Script**:
```
User: I'm with TechStartup. Can we just see the demo?

Expected: Replica immediately triggers deck generation without additional questions.
```

**Success Criteria**:
- [ ] No lengthy discovery questions
- [ ] Calls `generate_custom_deck()` within 1-2 responses
- [ ] Uses minimal data (company name only)

### Test 3: Function Call - `generate_custom_deck`

**Objective**: Verify function is called with correct parameters.

**Test Script**:
```
User: I'm Sarah from Acme Corp, VP of Sales.
Replica: [Discovery questions]
User: We can't scale demos fast enough. We need automation and 24/7 availability.
Replica: [Triggers deck generation]

Expected: Function called with:
{
  "company_name": "Acme Corp",
  "pain_points": ["can't scale demos fast enough"],
  "interested_features": ["automation", "24/7 availability"]
}
```

**Verification Steps**:
1. Check Tavus dashboard → Conversation logs
2. Verify function call payload contains correct extracted data
3. Confirm webhook received request (check Railway logs: `railway logs | grep generate-deck`)
4. Verify response time < 60 seconds

**Success Criteria**:
- [ ] Function called exactly once
- [ ] All required fields present (`company_name`, `pain_points`, `interested_features`)
- [ ] Optional fields included if mentioned by prospect
- [ ] Webhook returns success response
- [ ] Replica receives deck URL and announces it

### Test 4: Function Call - `control_slide`

**Objective**: Verify slide navigation during presentation.

**Test Script**:
```
[After deck generation]
Replica: [Narrating slide 1...]

Expected: Replica calls control_slide({"direction": "next"}) after narration.
```

**Verification Steps**:
1. Monitor Railway logs: `railway logs | grep control-slide`
2. Verify function called with correct direction
3. Confirm replica advances to next slide content
4. Test jumping to specific slide: "Can you show me the pricing slide?"

**Success Criteria**:
- [ ] `direction: "next"` called after each slide narration
- [ ] `slide_number: N` called when prospect asks to jump
- [ ] Replica synchronizes narration with slide changes
- [ ] Navigation commands execute within 2-3 seconds

### Test 5: Error Handling

**Objective**: Verify replica handles function failures gracefully.

**Test Script**:
```
[Simulate webhook failure by stopping Railway service]
User: Show me the demo for TestCorp.

Expected: Replica apologizes and offers to retry or continue with generic demo.
```

**Success Criteria**:
- [ ] No technical error details exposed to user
- [ ] Natural apology: "I'm having a technical issue..."
- [ ] Offers to retry or continue
- [ ] Maintains professional tone

### Test 6: End-to-End Demo Flow

**Objective**: Complete full demo conversation from start to finish.

**Test Script**:
```
1. User: Hi, I want to learn about BuzzTrail.
2. Replica: [Discovery]
3. User: [Provides company info and pain points]
4. Replica: [Generates deck]
5. Replica: [Presents slides 1-8]
6. User: [Asks questions]
7. Replica: [Answers and navigates to relevant slides]
8. Replica: [Closes and offers next steps]
```

**Success Criteria**:
- [ ] Discovery phase < 2 minutes
- [ ] Deck generation successful
- [ ] All slides narrated naturally
- [ ] Questions answered correctly
- [ ] Relevant slide navigation
- [ ] Professional closing with next steps
- [ ] Total demo time: 8-12 minutes

### Test 7: Webhook Monitoring

**Objective**: Verify Railway webhook handlers are processing requests correctly.

**Monitoring Commands**:
```bash
# Stream live Railway logs
railway logs

# Filter for Tavus events
railway logs | grep -i tavus

# Check specific function calls
railway logs | grep generate-deck
railway logs | grep control-slide
```

**Success Criteria**:
- [ ] All webhook requests logged
- [ ] No 500 errors in Railway logs
- [ ] Response times within SLA (generate_deck < 60s, control_slide < 3s)
- [ ] Supabase sessions created successfully

---

## Railway Environment Variables

After completing replica creation in Stream A, configure these environment variables in Railway.

### Required Variables

#### 1. Tavus Configuration

```bash
# Replica ID from Tavus dashboard
TAVUS_REPLICA_ID=<REPLICA_ID>

# API Key from Tavus dashboard
TAVUS_API_KEY=<API_KEY>
```

#### 2. Supabase Configuration (Already Set)

```bash
# Supabase project URL
SUPABASE_URL=https://YOUR_PROJECT.supabase.co

# Supabase service role key (for server-side operations)
SUPABASE_SERVICE_KEY=your-service-key
```

#### 3. Daily.co Configuration (Already Set)

```bash
# Daily.co API key for video conferencing
DAILY_API_KEY=your-daily-api-key
```

### How to Set Variables in Railway

#### Option 1: Railway Dashboard

1. Navigate to [Railway Dashboard](https://railway.app)
2. Select project: `slide-system-production`
3. Click **Variables** tab
4. Click **+ New Variable**
5. Add each variable:
   - **Name**: `TAVUS_REPLICA_ID`
   - **Value**: `<REPLICA_ID>`
6. Click **Add**
7. Repeat for `TAVUS_API_KEY`

#### Option 2: Railway CLI

```bash
# Login to Railway
railway login

# Link to project
cd /Users/lars/mycode/buzztrail/epic-automated-slide-demo-system/apps/slide-system
railway link

# Set variables
railway variables set TAVUS_REPLICA_ID=<REPLICA_ID>
railway variables set TAVUS_API_KEY=<API_KEY>

# Verify variables are set
railway variables
```

#### Option 3: Script

Use the provided script (update with actual values first):

```bash
# From apps/slide-system directory
./set-railway-vars.sh
```

### Verification

After setting variables:

```bash
# Check all variables are present
railway variables

# Expected output should include:
# TAVUS_REPLICA_ID=<your-replica-id>
# TAVUS_API_KEY=<your-api-key>
# SUPABASE_URL=https://...
# SUPABASE_SERVICE_KEY=...
# DAILY_API_KEY=...

# Restart Railway service to pick up new variables
railway redeploy
```

### Security Notes

- **Never commit** API keys to version control
- **Use Railway's** encrypted variable storage
- **Rotate keys** periodically (quarterly recommended)
- **Monitor usage** in Tavus dashboard for unusual activity
- **Restrict access** to Railway project to authorized team members only

---

## Troubleshooting

Common issues and solutions when working with the Tavus replica configuration.

### Issue: Replica doesn't call functions

**Symptoms**:
- Replica narrates but never calls `generate_custom_deck()`
- No function calls appear in Tavus logs
- Discovery phase never transitions to deck generation

**Solutions**:

1. **Verify function schemas are valid JSON**
   ```bash
   # Validate JSON locally
   cat function-schemas.json | jq .
   ```

2. **Check webhook URLs are correct**
   - Confirm Railway deployment is live: `curl https://slide-system-production-5813.up.railway.app/health`
   - Verify no typos in webhook URLs

3. **Review Tavus logs**
   - Go to Tavus Dashboard → Conversations
   - Find the test conversation
   - Check "Function Calls" tab for errors

4. **Verify system prompt instructs function calling**
   - Confirm prompt includes "Tool Calling Guidelines" section
   - Check that prompt explicitly states WHEN to call each function

### Issue: Webhook times out

**Symptoms**:
- Tavus shows "Function call timed out"
- Replica apologizes for technical issues
- Railway logs show request but no response

**Solutions**:

1. **Check Railway deployment status**
   ```bash
   railway status
   curl https://slide-system-production-5813.up.railway.app/health
   ```

2. **Verify webhook timeout setting**
   - `generate_custom_deck`: Should be 90 seconds (deck generation takes ~60s)
   - `control_slide`: Should be 30 seconds

3. **Monitor Railway logs during function call**
   ```bash
   railway logs --tail
   ```
   - Look for errors in step execution
   - Check Supabase connection

4. **Test webhook directly**
   ```bash
   curl -X POST https://slide-system-production-5813.up.railway.app/api/tavus/generate-deck \
     -H "Content-Type: application/json" \
     -d '{
       "conversation_id": "test-123",
       "replica_id": "<REPLICA_ID>",
       "function_name": "generate_custom_deck",
       "arguments": {
         "company_name": "Test Corp",
         "pain_points": ["test"],
         "interested_features": ["test"]
       }
     }'
   ```

### Issue: Replica doesn't follow conversation flow

**Symptoms**:
- Discovery phase takes too long (>2 minutes)
- Replica doesn't offer to skip to demo
- Flow doesn't match system prompt

**Solutions**:

1. **Verify system prompt is saved correctly**
   - Check Tavus Dashboard → Replica → System Prompt
   - Confirm entire prompt is present (~1,500 words)
   - Look for truncation or missing sections

2. **Test with explicit user responses**
   - Instead of: "I want a demo"
   - Try: "I'm with TestCorp. Just show me the demo."

3. **Check for prompt caching issues**
   - Start a new conversation
   - Clear browser cache
   - Try in incognito mode

4. **Review prompt clarity**
   - Ensure instructions are explicit
   - Check for contradictory guidelines
   - Verify phase transitions are clear

### Issue: Function called with incorrect data

**Symptoms**:
- `company_name` missing or incorrect
- `pain_points` array empty
- Required fields not extracted from conversation

**Solutions**:

1. **Review conversation logs**
   - Check what user actually said
   - Verify replica asked discovery questions
   - Confirm user provided the information

2. **Test data extraction explicitly**
   ```
   User: I'm Sarah from Acme Corp. We need automation.
   [Check if replica extracts: company_name="Acme Corp", interested_features=["automation"]]
   ```

3. **Improve user responses**
   - Provide clearer, more structured information
   - Mention company name explicitly
   - State pain points and features clearly

4. **Update system prompt if needed**
   - Add more explicit extraction instructions
   - Provide more example conversations
   - Clarify required vs optional fields

### Issue: Railway webhook returns 500 error

**Symptoms**:
- Function call fails immediately
- Railway logs show 500 Internal Server Error
- Replica receives error response

**Solutions**:

1. **Check Railway logs for error details**
   ```bash
   railway logs | grep -A 10 "500"
   ```

2. **Verify environment variables**
   ```bash
   railway variables
   # Ensure SUPABASE_URL and SUPABASE_SERVICE_KEY are set
   ```

3. **Test Supabase connection**
   ```bash
   curl $SUPABASE_URL/rest/v1/conversation_sessions \
     -H "apikey: $SUPABASE_SERVICE_KEY" \
     -H "Authorization: Bearer $SUPABASE_SERVICE_KEY"
   ```

4. **Check database schema**
   - Verify migration 003 applied: `.claude/supabase/migrations/003_tavus_integration.sql`
   - Confirm `tavus_conversation_id` column exists
   - Check `discovery_data` column is jsonb type

5. **Redeploy Railway service**
   ```bash
   railway redeploy
   ```

### Issue: Slide navigation not synchronized

**Symptoms**:
- Replica narrates slide 2 but display shows slide 1
- Slide changes before/after narration
- `control_slide` calls not reflected in UI

**Solutions**:

1. **Check `control_slide` webhook response**
   - Verify webhook returns current slide number
   - Confirm Demo UI receives WebSocket update

2. **Monitor Railway logs for slide control**
   ```bash
   railway logs | grep control-slide
   ```

3. **Test slide navigation directly**
   ```bash
   curl -X POST https://slide-system-production-5813.up.railway.app/api/tavus/control-slide \
     -H "Content-Type: application/json" \
     -d '{"conversation_id": "test-123", "arguments": {"direction": "next"}}'
   ```

4. **Verify Demo UI WebSocket connection**
   - Check browser console for WebSocket errors
   - Confirm UI is listening for slide change events
   - Test manual navigation works in UI

### Getting Help

If issues persist after troubleshooting:

1. **Check Tavus Status Page**: [status.tavus.io](https://status.tavus.io)
2. **Review Tavus Docs**: [docs.tavus.io](https://docs.tavus.io)
3. **Contact Support**:
   - Tavus Support: support@tavus.io
   - Include: Replica ID, conversation ID, timestamp, error logs
4. **Check Team Documentation**:
   - `.claude/tavus-config/SETUP-GUIDE.md`
   - `.claude/tavus-config/DEPLOYMENT-GUIDE.md`
   - `apps/slide-system/docs/PRODUCTION_DEPLOYMENT_RUNBOOK.md`

---

## Additional Resources

- **Tavus Documentation**: [docs.tavus.io](https://docs.tavus.io)
- **Tavus Function Calling Guide**: [docs.tavus.io/api-reference/conversational-video/function-calling](https://docs.tavus.io/api-reference/conversational-video/function-calling)
- **Railway Documentation**: [docs.railway.app](https://docs.railway.app)
- **Project Setup Guide**: `.claude/tavus-config/SETUP-GUIDE.md`
- **Deployment Guide**: `.claude/tavus-config/DEPLOYMENT-GUIDE.md`
- **Motia Framework Docs**: [motia.run/docs](https://motia.run/docs)

---

## Maintenance Schedule

### Weekly
- [ ] Review Tavus conversation logs for errors
- [ ] Monitor webhook success rate
- [ ] Check Railway service health

### Monthly
- [ ] Review system prompt effectiveness
- [ ] Update function schemas if needed
- [ ] Analyze demo completion rates
- [ ] Check for Tavus API updates

### Quarterly
- [ ] Rotate API keys
- [ ] Review and update documentation
- [ ] Conduct full end-to-end testing
- [ ] Update team on configuration changes

---

**Last Updated**: 2025-10-12
**Maintained By**: BuzzTrail Engineering Team
**Related Documents**:
- `.claude/tavus-config/SETUP-GUIDE.md`
- `.claude/tavus-config/DEPLOYMENT-GUIDE.md`
- `apps/slide-system/docs/PRODUCTION_DEPLOYMENT_RUNBOOK.md`
