# Tavus API Error Catalog

## Analysis Metadata
- **Analysis Date**: 2025-09-30
- **Source Files**: 2 error logs, 1 schema file, 3 test calls, 3 session files
- **Total Errors Analyzed**: 3 unique error scenarios
- **Success Rate**: 66.67% (6 success / 9 total responses)

---

## Error Types

### 1. Payment Required (402) - Out of Conversational Credits

**Error Code**: `out_of_conversational_credits`

**HTTP Status**: 402 Payment Required

**Endpoint**: `POST /v2/conversations`

**Frequency**: 2 occurrences

**Description**: This error occurs when the account has exhausted its conversational credits allocation.

#### Response Structure
```json
{
  "error": "out_of_conversational_credits",
  "message": "You have run out of conversational credits. Please upgrade your plan.",
  "status_code": 402
}
```

#### Response Headers
```json
{
  "content-type": "application/json",
  "x-request-id": "req_error_12345"
}
```

#### Timing Characteristics
- **Duration**: 850ms (consistent across both occurrences)
- **Observation**: Error responses are faster than typical success responses (~1250ms)

#### Request Context (from errors)
Both error occurrences had identical request parameters:
```json
{
  "replica_id": "r92debe21318",
  "persona_id": "p9c7988840cc"
}
```

#### Example Occurrences
1. **Timestamp**: 2025-08-14T15:02:20.436Z
   - **Session ID**: 1a0c9831-ef59-42f5-a43f-30c5a3ff27db
   - **Request ID**: req_error_12345

2. **Timestamp**: 2025-08-14T15:05:53.674Z
   - **Session ID**: 62485973-df74-4e37-ba0b-3f3569f8413f
   - **Request ID**: req_error_12345

#### Impact & Handling
- **User Impact**: High - blocks conversation creation entirely
- **Retry Logic**: Should NOT retry automatically (permanent failure until credits restored)
- **User Action Required**: Upgrade plan or purchase additional credits
- **Client Handling**: Display clear message about credit exhaustion with upgrade path

---

### 2. Internal Server Error (500) - JSON Parsing Failure

**Error Type**: Internal Server Error

**HTTP Status**: 500 Internal Server Error

**Endpoint**: `POST /api/conversations/:id/end` (Proxy endpoint)

**Frequency**: 1 occurrence

**Description**: Server-side error when attempting to end a conversation, caused by malformed JSON response from upstream service.

#### Response Structure
```json
{
  "error": "Failed to end conversation",
  "details": "Unexpected end of JSON input"
}
```

#### Response Headers
```json
{
  "access-control-allow-credentials": "true",
  "access-control-allow-headers": "Content-Type, Authorization",
  "access-control-allow-methods": "GET, POST, OPTIONS",
  "access-control-allow-origin": "https://buzztrail.ai",
  "cache-control": "public, max-age=0, must-revalidate",
  "content-type": "application/json; charset=utf-8",
  "server": "Vercel",
  "x-vercel-cache": "MISS",
  "x-vercel-id": "cdg1::iad1::st57p-1755873504681-77796469a3bd"
}
```

#### Timing Characteristics
- **Duration**: 1978ms
- **Context**: Significantly slower than successful end conversation calls (450ms)

#### Request Context
```json
{
  "method": "POST",
  "url": "https://buzztrail-proxy.vercel.app/api/conversations/c633d9e801a4d455/end",
  "body": null
}
```

#### Example Occurrence
- **Timestamp**: 2025-08-22T14:38:26.610Z
- **Test ID**: 07792a37-3e24-4f24-9529-5deca4c149d5
- **Conversation ID**: c633d9e801a4d455
- **Context**: Test call immediately after successful conversation creation

#### Root Cause Analysis
- **Immediate Cause**: JSON parsing error suggests malformed response from upstream Tavus API
- **Possible Causes**:
  - Incomplete/truncated response from Tavus API
  - Network interruption during response transmission
  - Upstream API returned non-JSON content
  - Timeout resulted in partial response

#### Impact & Handling
- **User Impact**: Medium - conversation may still be active despite error
- **Retry Logic**: MAY retry with exponential backoff (transient error)
- **Fallback**: Attempt conversation status check before retry
- **Client Handling**:
  - Display generic "service unavailable" message
  - Log detailed error for debugging
  - Consider conversation in unknown state

---

## Error Response Patterns

### Common Error Response Structure

#### Direct Tavus API Errors
```json
{
  "error": "error_code_string",
  "message": "Human-readable error message",
  "status_code": 402  // HTTP status code repeated in body
}
```

**Characteristics**:
- `error` field contains machine-readable error code
- `message` field contains user-friendly description
- `status_code` field echoes the HTTP status (at least for 402 errors)
- Content-Type: `application/json`
- Includes `x-request-id` header for tracking

#### Proxy Service Errors
```json
{
  "error": "High-level error description",
  "details": "Technical error details"
}
```

**Characteristics**:
- `error` field contains user-facing message
- `details` field contains technical error information
- Content-Type: `application/json; charset=utf-8`
- Includes Vercel-specific headers (`x-vercel-id`, `x-vercel-cache`)
- CORS headers present (proxy layer adds these)

---

## Error Status Code Distribution

| Status Code | Count | Percentage | Description |
|-------------|-------|------------|-------------|
| 402 | 2 | 22.22% | Payment Required (out of credits) |
| 500 | 1 | 11.11% | Internal Server Error (JSON parsing) |

**Success Rate**: 66.67% (6 successful / 9 total)

---

## Schema-Defined Error Responses

From `/documentation/data/tavus-logs/schemas/conversations-create.json`:

### 401 Unauthorized
```json
{
  "status": 401,
  "description": "Authentication failed",
  "schema": {
    "error": "string",
    "message": "string"
  }
}
```

**Note**: Not observed in actual logs, but defined in schema.

### 402 Payment Required
```json
{
  "status": 402,
  "description": "Out of credits",
  "schema": {
    "error": "string",
    "message": "string",
    "status_code": "number"
  }
}
```

**Note**: Observed 2 times in actual logs, matches schema definition exactly.

---

## Error Handling Recommendations

### For Fake Server Implementation

1. **402 Out of Credits Error**
   - Implement as deterministic error for specific test scenarios
   - Return consistent 850ms response time
   - Include all three fields: `error`, `message`, `status_code`
   - Set `x-request-id` header for consistency

2. **500 Internal Server Error**
   - Implement as rare/random error for robustness testing
   - Simulate JSON parsing failures
   - Include both `error` and `details` fields
   - Return slower response time (~2000ms) to simulate timeout scenarios

3. **401 Authentication Error**
   - Implement based on schema definition (not yet observed in logs)
   - Follow same structure as 402 error but without `status_code` field
   - Test with invalid/missing API keys

### Retry Strategy Recommendations

| Error Type | Retry? | Strategy | Max Retries |
|------------|--------|----------|-------------|
| 402 Payment Required | NO | Permanent failure | 0 |
| 500 Internal Server Error | YES | Exponential backoff | 3 |
| 401 Unauthorized | NO | Permanent failure | 0 |

---

## Correlation Analysis

### Error Timing Patterns
- **402 Errors**: Consistently 850ms response time
- **500 Errors**: 1978ms response time (slower than success)
- **Success Responses**: 100-1250ms for direct API, 450-3898ms for proxy

### Error Correlation with Request Parameters
- **402 Errors**: Both occurred with same `replica_id` and `persona_id`
- No errors observed when additional optional parameters provided
- Suggests credit validation happens early in request lifecycle

### Error Sequence Patterns
- **500 Error Context**: Occurred immediately after successful conversation creation
- Suggests potential state/timing issue with rapid sequential requests
- Conversation ID was valid (created successfully moments before)

---

## Missing Error Scenarios

Based on schema definitions and typical API patterns, these errors are documented but not yet observed:

1. **401 Unauthorized** - Defined in schema but not in logs
2. **400 Bad Request** - Typical for validation errors, not documented
3. **404 Not Found** - Expected for invalid conversation IDs, not observed
4. **429 Rate Limit** - Common for APIs, not documented or observed
5. **503 Service Unavailable** - Expected for downtime, not observed

**Recommendation**: Implement these standard error types in fake server for comprehensive testing.

---

## Error Detection Metrics

### Response Time Anomalies
- Error responses tend to be faster (402) or slower (500) than typical success
- Can use response time as early indicator of potential error
- Useful for client-side timeout configuration

### Header Indicators
- Presence of `x-request-id` indicates direct Tavus API response
- Presence of `x-vercel-id` indicates proxy layer response
- Can help distinguish error source layer

---

## Conclusion

The error catalog reveals:
1. **High success rate** (66.67%) but limited error diversity in logs
2. **Consistent error structure** for payment issues (402)
3. **Transient parsing errors** in proxy layer (500)
4. **Missing coverage** for authentication and validation errors
5. **Clear patterns** for retry vs. permanent failures

The fake server should implement all observed errors plus schema-defined errors for comprehensive testing coverage.