# Chat Integration Guide

Learn how to integrate Lilith's AI-powered wisdom chat into your applications
for meaningful conversations with trained AI personas.

## Table of Contents

- [Overview](#overview)
- [Quick Start](#quick-start)
- [AI Personas](#ai-personas)
- [Chat Modes](#chat-modes)
- [Streaming Responses](#streaming-responses)
- [Conversation Management](#conversation-management)
- [Advanced Features](#advanced-features)
- [Error Handling](#error-handling)
- [Best Practices](#best-practices)

## Overview

The Lilith Chat API enables rich conversational experiences with AI personas
trained in various wisdom traditions. Each persona offers unique perspectives
while maintaining consistency, depth, and contextual awareness.

### Key Features

- 🧘 **Multiple AI Personas**: Zen Master, Philosopher, Stoic, Mystic, Teacher
- 💬 **Text & Voice Input**: Support for both text and audio input
- 🔄 **Real-time Streaming**: Server-Sent Events and WebSocket support
- 📚 **Source Citations**: Transparent references to wisdom sources
- 🎯 **Context Awareness**: Maintains conversation history and context
- 🌐 **Multi-language**: Support for multiple languages
- 📱 **Cross-platform**: Works on web, mobile, and desktop

### Chat Flow Overview

```mermaid
graph TD
    A[User Input] --> B{Input Type?}
    B -->|Text| C[Text Processing]
    B -->|Audio| D[Speech Recognition]
    C --> E[AI Persona Processing]
    D --> E
    E --> F{Response Mode?}
    F -->|Streaming| G[Server-Sent Events]
    F -->|Complete| H[JSON Response]
    G --> I[Token Stream]
    I --> J[Citations]
    J --> K[Audio URL]
    H --> L[Complete Response]
    K --> M[Response Complete]
    L --> M
```

## Quick Start

### Basic Chat Request

```bash
curl -X POST "https://api.lilith.app/v1/chat" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "persona": "zen_master",
    "input": {
      "text": "How can I find peace in a chaotic world?"
    },
    "mode": "text",
    "options": {
      "stream": false,
      "cite": true,
      "depth": "practical"
    }
  }'
```

### Simple Integration Examples

#### JavaScript/TypeScript

```javascript
class LilithChat {
  constructor(apiToken, baseURL = 'https://api.lilith.app') {
    this.apiToken = apiToken;
    this.baseURL = baseURL;
  }

  async sendMessage(conversationId, persona, message, options = {}) {
    const response = await fetch(`${this.baseURL}/v1/chat`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${this.apiToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        conversation_id: conversationId,
        persona: persona,
        input: { text: message },
        mode: 'text',
        options: {
          stream: false,
          cite: true,
          depth: 'practical',
          ...options,
        },
      }),
    });

    if (!response.ok) {
      throw new Error(`Chat API error: ${response.status}`);
    }

    return await response.json();
  }

  // Example usage
  async example() {
    try {
      const result = await this.sendMessage(
        null, // New conversation
        'zen_master',
        'What is the nature of mindfulness?'
      );

      console.log('AI Response:', result.text);
      console.log('Conversation ID:', result.conversation_id);
      console.log('Citations:', result.citations);
    } catch (error) {
      console.error('Chat error:', error);
    }
  }
}
```

#### React Component

```jsx
import React, { useState } from 'react';

const ChatInterface = ({ apiToken }) => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [conversationId, setConversationId] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const sendMessage = async () => {
    if (!inputValue.trim()) return;

    const userMessage = { role: 'user', content: inputValue };
    setMessages((prev) => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);

    try {
      const response = await fetch('https://api.lilith.app/v1/chat', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${apiToken}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          conversation_id: conversationId,
          persona: 'zen_master',
          input: { text: inputValue },
          mode: 'text',
          options: { stream: false, cite: true },
        }),
      });

      const result = await response.json();

      if (!conversationId) {
        setConversationId(result.conversation_id);
      }

      const aiMessage = {
        role: 'assistant',
        content: result.text,
        citations: result.citations,
      };

      setMessages((prev) => [...prev, aiMessage]);
    } catch (error) {
      console.error('Chat error:', error);
      // Handle error appropriately
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="chat-interface">
      <div className="messages">
        {messages.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            <div className="content">{msg.content}</div>
            {msg.citations && (
              <div className="citations">
                {msg.citations.map((cite, i) => (
                  <span key={i} className="citation">
                    📚 {cite.source_uri}
                  </span>
                ))}
              </div>
            )}
          </div>
        ))}
        {isLoading && <div className="loading">AI is thinking...</div>}
      </div>

      <div className="input-area">
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
          placeholder="Ask about wisdom, philosophy, mindfulness..."
          disabled={isLoading}
        />
        <button onClick={sendMessage} disabled={isLoading}>
          Send
        </button>
      </div>
    </div>
  );
};
```

#### Android/Kotlin

```kotlin
class LilithChatClient(
    private val apiToken: String,
    private val baseUrl: String = "https://api.lilith.app"
) {
    private val client = OkHttpClient()
    private val gson = Gson()

    suspend fun sendMessage(
        conversationId: String?,
        persona: String,
        message: String,
        options: ChatOptions = ChatOptions()
    ): ChatResponse = withContext(Dispatchers.IO) {
        val request = ChatRequest(
            conversationId = conversationId,
            persona = persona,
            input = ChatInput(text = message),
            mode = "text",
            options = options
        )

        val json = gson.toJson(request)
        val body = json.toRequestBody("application/json".toMediaType())

        val httpRequest = Request.Builder()
            .url("$baseUrl/v1/chat")
            .addHeader("Authorization", "Bearer $apiToken")
            .post(body)
            .build()

        val response = client.newCall(httpRequest).execute()

        if (!response.isSuccessful) {
            throw Exception("Chat API error: ${response.code}")
        }

        gson.fromJson(response.body?.string(), ChatResponse::class.java)
    }
}

// Data classes
data class ChatRequest(
    @SerializedName("conversation_id") val conversationId: String?,
    val persona: String,
    val input: ChatInput,
    val mode: String,
    val options: ChatOptions
)

data class ChatInput(
    val text: String? = null,
    val audio: String? = null
)

data class ChatOptions(
    val stream: Boolean = false,
    val cite: Boolean = true,
    val depth: String = "practical"
)

data class ChatResponse(
    @SerializedName("message_id") val messageId: String,
    @SerializedName("conversation_id") val conversationId: String,
    val text: String?,
    val citations: List<Citation>?,
    @SerializedName("audio_url") val audioUrl: String?
)
```

#### iOS/Swift

```swift
class LilithChatClient: ObservableObject {
    private let apiToken: String
    private let baseURL = "https://api.lilith.app"

    @Published var messages: [ChatMessage] = []
    @Published var isLoading = false

    init(apiToken: String) {
        self.apiToken = apiToken
    }

    func sendMessage(
        conversationId: String? = nil,
        persona: String = "zen_master",
        text: String,
        options: ChatOptions = ChatOptions()
    ) async throws -> ChatResponse {
        let url = URL(string: "\(baseURL)/v1/chat")!

        let requestBody: [String: Any] = [
            "conversation_id": conversationId as Any,
            "persona": persona,
            "input": ["text": text],
            "mode": "text",
            "options": [
                "stream": options.stream,
                "cite": options.cite,
                "depth": options.depth
            ]
        ]

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("Bearer \(apiToken)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)

        let (data, response) = try await URLSession.shared.data(for: request)

        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw ChatError.requestFailed
        }

        return try JSONDecoder().decode(ChatResponse.self, from: data)
    }
}

struct ChatOptions {
    let stream: Bool
    let cite: Bool
    let depth: String

    init(stream: Bool = false, cite: Bool = true, depth: String = "practical") {
        self.stream = stream
        self.cite = cite
        self.depth = depth
    }
}

struct ChatMessage: Identifiable, Codable {
    let id = UUID()
    let role: String // "user" or "assistant"
    let content: String
    let citations: [Citation]?
    let timestamp: Date

    init(role: String, content: String, citations: [Citation]? = nil) {
        self.role = role
        self.content = content
        self.citations = citations
        self.timestamp = Date()
    }
}
```

## AI Personas

The Lilith platform offers several AI personas, each trained in specific wisdom
traditions and approaches:

### Available Personas

#### zen_master

**Philosophy**: Buddhist and Zen traditions **Approach**: Mindful,
present-moment focused, emphasizes simplicity **Best for**: Meditation guidance,
mindfulness practices, inner peace

```javascript
const response = await chat.sendMessage(
  null,
  'zen_master',
  'How do I let go of attachment to outcomes?'
);
// Response focuses on Buddhist teachings about non-attachment
```

#### philosopher

**Philosophy**: Western philosophical traditions (Socratic, Platonic, etc.)
**Approach**: Analytical, questioning, rational exploration **Best for**:
Ethical dilemmas, logical reasoning, concept exploration

```javascript
const response = await chat.sendMessage(
  null,
  'philosopher',
  'What is the relationship between knowledge and wisdom?'
);
// Response explores epistemological concepts and philosophical distinctions
```

#### stoic

**Philosophy**: Stoic philosophy (Marcus Aurelius, Epictetus, Seneca)
**Approach**: Practical wisdom, emotional resilience, virtue ethics **Best
for**: Emotional regulation, practical life advice, resilience building

```javascript
const response = await chat.sendMessage(
  null,
  'stoic',
  'How do I deal with criticism from others?'
);
// Response focuses on Stoic principles of emotional control and virtue
```

#### mystic

**Philosophy**: Mystical and esoteric traditions across cultures **Approach**:
Intuitive, symbolic, transcendent experiences **Best for**: Spiritual
exploration, meaning-making, transcendent experiences

```javascript
const response = await chat.sendMessage(
  null,
  'mystic',
  'What is the nature of consciousness?'
);
// Response explores mystical and spiritual perspectives on consciousness
```

#### teacher

**Philosophy**: Pedagogical approach across traditions **Approach**:
Educational, structured, step-by-step guidance **Best for**: Learning new
concepts, skill development, structured guidance

```javascript
const response = await chat.sendMessage(
  null,
  'teacher',
  'Can you teach me the basics of meditation?'
);
// Response provides structured, educational content with clear steps
```

### Persona Selection Strategy

Choose personas based on your use case:

```javascript
function selectPersona(userIntent, context) {
  const intentMap = {
    meditation: 'zen_master',
    mindfulness: 'zen_master',
    ethical_dilemma: 'philosopher',
    emotional_challenge: 'stoic',
    spiritual_question: 'mystic',
    learning: 'teacher',
    practical_advice: 'stoic',
    philosophical_inquiry: 'philosopher',
  };

  return intentMap[userIntent] || 'zen_master'; // Default fallback
}

// Usage
const persona = selectPersona('emotional_challenge');
const response = await chat.sendMessage(conversationId, persona, userMessage);
```

## Chat Modes

The API supports two chat modes for different interaction types:

### Text Mode

For text-based conversations:

```javascript
const textChat = {
  persona: 'zen_master',
  input: { text: 'What is the essence of mindfulness?' },
  mode: 'text',
  options: {
    cite: true,
    depth: 'practical',
    stream: false,
  },
};
```

### Voice Mode

For voice-enabled interactions with audio synthesis:

```javascript
const voiceChat = {
  persona: 'zen_master',
  input: { text: 'Guide me through a breathing exercise' },
  mode: 'voice',
  options: {
    cite: false, // Usually disabled for voice
    depth: 'practical',
    stream: true,
    voice_settings: {
      voice_id: 'calm_female_01',
      speed: 0.9,
      pitch: 0.0,
    },
  },
};
```

### Audio Input

Send audio input for voice-to-voice interactions:

```javascript
// Convert audio file to base64
const audioBase64 = await convertAudioToBase64(audioFile);

const audioChat = {
  persona: 'zen_master',
  input: { audio: audioBase64 },
  mode: 'voice',
  options: {
    cite: false,
    stream: true,
  },
};
```

## Streaming Responses

For real-time conversational experiences, use streaming responses:

### Server-Sent Events (SSE)

```javascript
class StreamingChat {
  constructor(apiToken) {
    this.apiToken = apiToken;
  }

  async startStreamingChat(
    persona,
    message,
    onToken,
    onCitations,
    onComplete,
    onError
  ) {
    const response = await fetch('https://api.lilith.app/v1/chat', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${this.apiToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        persona: persona,
        input: { text: message },
        mode: 'text',
        options: { stream: true, cite: true },
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6));
              this.handleStreamEvent(
                data,
                onToken,
                onCitations,
                onComplete,
                onError
              );
            } catch (e) {
              // Skip invalid JSON
            }
          }
        }
      }
    } finally {
      reader.releaseLock();
    }
  }

  handleStreamEvent(event, onToken, onCitations, onComplete, onError) {
    switch (event.event) {
      case 'token':
        onToken(event.data.text);
        break;
      case 'citations':
        onCitations(event.data);
        break;
      case 'done':
        onComplete(event.data.message_id);
        break;
      case 'error':
        onError(event.data);
        break;
    }
  }
}

// Usage example
const streamChat = new StreamingChat(apiToken);

let fullResponse = '';

await streamChat.startStreamingChat(
  'zen_master',
  'What is the path to inner peace?',

  // On token received
  (token) => {
    fullResponse += token;
    updateUI(fullResponse);
  },

  // On citations received
  (citations) => {
    displayCitations(citations);
  },

  // On completion
  (messageId) => {
    console.log('Chat completed:', messageId);
    finalizeMessage(messageId, fullResponse);
  },

  // On error
  (error) => {
    console.error('Streaming error:', error);
    showError(error.message);
  }
);
```

### WebSocket Integration

For bidirectional real-time communication:

```javascript
class WebSocketChat {
  constructor(apiToken) {
    this.apiToken = apiToken;
    this.ws = null;
    this.messageHandlers = new Map();
  }

  connect() {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket('wss://api.lilith.app/ws');

      this.ws.onopen = () => {
        // Authenticate
        this.ws.send(
          JSON.stringify({
            type: 'auth',
            token: this.apiToken,
          })
        );
        resolve();
      };

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.handleMessage(message);
      };

      this.ws.onerror = (error) => {
        reject(error);
      };

      this.ws.onclose = () => {
        console.log('WebSocket connection closed');
      };
    });
  }

  sendChatMessage(persona, text, options = {}) {
    const messageId = this.generateMessageId();

    this.ws.send(
      JSON.stringify({
        type: 'chat',
        message_id: messageId,
        data: {
          persona: persona,
          input: { text: text },
          mode: 'text',
          options: { stream: true, cite: true, ...options },
        },
      })
    );

    return messageId;
  }

  onChatResponse(messageId, callback) {
    this.messageHandlers.set(messageId, callback);
  }

  handleMessage(message) {
    if (message.type === 'chat_response') {
      const handler = this.messageHandlers.get(message.message_id);
      if (handler) {
        handler(message);
      }
    }
  }

  generateMessageId() {
    return 'msg_' + Math.random().toString(36).substr(2, 9);
  }

  disconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}

// Usage
const wsChat = new WebSocketChat(apiToken);

await wsChat.connect();

const messageId = wsChat.sendChatMessage('zen_master', 'What is mindfulness?');

wsChat.onChatResponse(messageId, (response) => {
  switch (response.event) {
    case 'token':
      appendToChat(response.data.text);
      break;
    case 'citations':
      showCitations(response.data);
      break;
    case 'done':
      finalizeChatMessage();
      break;
  }
});
```

## Conversation Management

### Starting New Conversations

```javascript
// Start a new conversation (conversation_id = null)
const newChat = await chat.sendMessage(
  null, // New conversation
  'zen_master',
  'Hello, I would like to learn about meditation.'
);

console.log('New conversation ID:', newChat.conversation_id);
```

### Continuing Conversations

```javascript
// Continue existing conversation
const followUp = await chat.sendMessage(
  newChat.conversation_id, // Use existing conversation ID
  'zen_master',
  'Can you guide me through a basic breathing exercise?'
);
```

### Conversation Context Management

```javascript
class ConversationManager {
  constructor() {
    this.conversations = new Map();
  }

  createConversation(userId, persona) {
    const conversationId = this.generateConversationId();

    this.conversations.set(conversationId, {
      id: conversationId,
      userId: userId,
      persona: persona,
      messages: [],
      created: new Date(),
      lastActivity: new Date(),
      context: {
        topics: [],
        mood: null,
        preferences: {},
      },
    });

    return conversationId;
  }

  addMessage(conversationId, message) {
    const conversation = this.conversations.get(conversationId);
    if (conversation) {
      conversation.messages.push({
        ...message,
        timestamp: new Date(),
      });
      conversation.lastActivity = new Date();

      // Update context
      this.updateContext(conversation, message);
    }
  }

  updateContext(conversation, message) {
    // Extract topics, mood, preferences from message
    if (message.role === 'user') {
      conversation.context.topics = this.extractTopics(message.content);
    }
  }

  getConversationContext(conversationId) {
    const conversation = this.conversations.get(conversationId);
    return conversation ? conversation.context : null;
  }

  cleanupOldConversations(maxAge = 7 * 24 * 60 * 60 * 1000) {
    // 7 days
    const cutoff = new Date(Date.now() - maxAge);

    for (const [id, conversation] of this.conversations.entries()) {
      if (conversation.lastActivity < cutoff) {
        this.conversations.delete(id);
      }
    }
  }

  generateConversationId() {
    return 'conv_' + Math.random().toString(36).substr(2, 9);
  }

  extractTopics(text) {
    // Simple topic extraction (in production, use NLP libraries)
    const topics = [];
    const topicKeywords = {
      meditation: ['meditat', 'mindful', 'breath', 'awareness'],
      philosophy: ['wisdom', 'truth', 'meaning', 'ethics'],
      stoicism: ['stoic', 'virtue', 'discipline', 'resilience'],
      emotions: ['feel', 'emotion', 'anxious', 'sad', 'happy'],
    };

    const lowerText = text.toLowerCase();

    for (const [topic, keywords] of Object.entries(topicKeywords)) {
      if (keywords.some((keyword) => lowerText.includes(keyword))) {
        topics.push(topic);
      }
    }

    return topics;
  }
}
```

### Conversation Persistence

```javascript
class ConversationPersistence {
  constructor(storage = localStorage) {
    this.storage = storage;
    this.storageKey = 'lilith_conversations';
  }

  saveConversation(conversation) {
    const conversations = this.loadAllConversations();
    conversations[conversation.id] = {
      ...conversation,
      lastSaved: new Date().toISOString(),
    };

    this.storage.setItem(this.storageKey, JSON.stringify(conversations));
  }

  loadConversation(conversationId) {
    const conversations = this.loadAllConversations();
    return conversations[conversationId] || null;
  }

  loadAllConversations() {
    const stored = this.storage.getItem(this.storageKey);
    return stored ? JSON.parse(stored) : {};
  }

  deleteConversation(conversationId) {
    const conversations = this.loadAllConversations();
    delete conversations[conversationId];
    this.storage.setItem(this.storageKey, JSON.stringify(conversations));
  }

  // Auto-save functionality
  enableAutoSave(conversationManager, intervalMs = 30000) {
    setInterval(() => {
      for (const [
        id,
        conversation,
      ] of conversationManager.conversations.entries()) {
        this.saveConversation(conversation);
      }
    }, intervalMs);
  }
}
```

## Advanced Features

### Response Customization

#### Depth Control

```javascript
// Practical responses (default)
const practicalResponse = await chat.sendMessage(
  null,
  'stoic',
  'How do I handle workplace stress?',
  { depth: 'practical' }
);

// Scholarly responses with more depth and references
const scholarlyResponse = await chat.sendMessage(
  null,
  'stoic',
  'How do I handle workplace stress?',
  { depth: 'scholarly' }
);
```

#### Citation Control

```javascript
// Enable citations (recommended for educational use)
const withCitations = await chat.sendMessage(
  null,
  'philosopher',
  'What is the trolley problem?',
  { cite: true }
);

// Disable citations for casual conversation
const withoutCitations = await chat.sendMessage(
  null,
  'zen_master',
  'I feel peaceful today',
  { cite: false }
);
```

### Multi-turn Conversations with Context

```javascript
class ContextualChat {
  constructor(apiToken) {
    this.chat = new LilithChat(apiToken);
    this.conversationId = null;
    this.context = {
      topics: new Set(),
      userPreferences: {},
      conversationGoal: null,
    };
  }

  async sendContextualMessage(persona, message, userContext = {}) {
    // Update context
    this.updateContext(message, userContext);

    // Send message with context
    const response = await this.chat.sendMessage(
      this.conversationId,
      persona,
      message,
      {
        depth: this.determineDepth(),
        cite: this.shouldIncludeCitations(),
        context: this.getContextSummary(),
      }
    );

    if (!this.conversationId) {
      this.conversationId = response.conversation_id;
    }

    // Update context based on response
    this.updateContextFromResponse(response);

    return response;
  }

  updateContext(message, userContext) {
    // Extract topics
    const topics = this.extractTopics(message);
    topics.forEach((topic) => this.context.topics.add(topic));

    // Update preferences
    Object.assign(this.context.userPreferences, userContext);
  }

  determineDepth() {
    // Use scholarly depth for philosophy and complex topics
    const scholarlyTopics = ['philosophy', 'ethics', 'consciousness'];
    return Array.from(this.context.topics).some((topic) =>
      scholarlyTopics.includes(topic)
    )
      ? 'scholarly'
      : 'practical';
  }

  shouldIncludeCitations() {
    // Include citations for educational contexts
    return (
      this.context.conversationGoal === 'learning' ||
      this.context.userPreferences.includeCitations !== false
    );
  }

  getContextSummary() {
    return {
      topics: Array.from(this.context.topics),
      goal: this.context.conversationGoal,
      preferences: this.context.userPreferences,
    };
  }

  extractTopics(text) {
    // Enhanced topic extraction
    const topicPatterns = {
      meditation: /meditat|mindful|breath|awareness|present/i,
      philosophy: /wisdom|truth|meaning|ethics|moral/i,
      stoicism: /stoic|virtue|discipline|resilience|control/i,
      emotions: /feel|emotion|anxious|sad|happy|stress/i,
      relationships: /relation|friend|family|love|conflict/i,
      work: /work|job|career|colleague|boss|stress/i,
    };

    const topics = [];
    for (const [topic, pattern] of Object.entries(topicPatterns)) {
      if (pattern.test(text)) {
        topics.push(topic);
      }
    }

    return topics;
  }

  updateContextFromResponse(response) {
    // Analyze AI response to understand conversation direction
    if (response.citations && response.citations.length > 0) {
      this.context.conversationGoal = 'learning';
    }

    // Extract any user preferences mentioned in the response
    // This could be enhanced with NLP analysis
  }
}
```

### Voice Integration

```javascript
class VoiceChat {
  constructor(apiToken) {
    this.chat = new LilithChat(apiToken);
    this.recognition = null;
    this.synthesis = window.speechSynthesis;
    this.isListening = false;
  }

  // Initialize speech recognition
  initializeSpeechRecognition() {
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
      const SpeechRecognition =
        window.SpeechRecognition || window.webkitSpeechRecognition;
      this.recognition = new SpeechRecognition();

      this.recognition.continuous = false;
      this.recognition.interimResults = false;
      this.recognition.lang = 'en-US';

      this.recognition.onresult = (event) => {
        const transcript = event.results[0][0].transcript;
        this.handleVoiceInput(transcript);
      };

      this.recognition.onerror = (event) => {
        console.error('Speech recognition error:', event.error);
        this.isListening = false;
      };

      this.recognition.onend = () => {
        this.isListening = false;
      };
    }
  }

  startListening() {
    if (this.recognition && !this.isListening) {
      this.isListening = true;
      this.recognition.start();
    }
  }

  stopListening() {
    if (this.recognition && this.isListening) {
      this.recognition.stop();
      this.isListening = false;
    }
  }

  async handleVoiceInput(transcript) {
    console.log('Voice input:', transcript);

    try {
      const response = await this.chat.sendMessage(
        null,
        'zen_master',
        transcript,
        {
          mode: 'voice',
          stream: false,
          cite: false,
        }
      );

      // Speak the response
      if (response.audio_url) {
        this.playAudio(response.audio_url);
      } else if (response.text) {
        this.speakText(response.text);
      }
    } catch (error) {
      console.error('Voice chat error:', error);
      this.speakText(
        'I apologize, but I encountered an error processing your request.'
      );
    }
  }

  speakText(text) {
    // Use browser speech synthesis as fallback
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.rate = 0.9;
    utterance.pitch = 1.0;
    utterance.voice =
      this.synthesis
        .getVoices()
        .find(
          (voice) => voice.name.includes('Female') && voice.lang.includes('en')
        ) || this.synthesis.getVoices()[0];

    this.synthesis.speak(utterance);
  }

  async playAudio(audioUrl) {
    try {
      const audio = new Audio(audioUrl);
      await audio.play();
    } catch (error) {
      console.error('Audio playback error:', error);
    }
  }
}

// Usage
const voiceChat = new VoiceChat(apiToken);
voiceChat.initializeSpeechRecognition();

// Start voice interaction
document.getElementById('voiceButton').addEventListener('click', () => {
  if (voiceChat.isListening) {
    voiceChat.stopListening();
  } else {
    voiceChat.startListening();
  }
});
```

## Error Handling

### Comprehensive Error Handling

```javascript
class ChatErrorHandler {
  constructor(chat, options = {}) {
    this.chat = chat;
    this.retryAttempts = options.retryAttempts || 3;
    this.retryDelay = options.retryDelay || 1000;
    this.onError = options.onError || console.error;
    this.onRetry = options.onRetry || console.log;
  }

  async sendMessageWithRetry(
    conversationId,
    persona,
    message,
    options = {},
    attempt = 1
  ) {
    try {
      return await this.chat.sendMessage(
        conversationId,
        persona,
        message,
        options
      );
    } catch (error) {
      return await this.handleError(error, {
        conversationId,
        persona,
        message,
        options,
        attempt,
      });
    }
  }

  async handleError(error, context) {
    const { conversationId, persona, message, options, attempt } = context;

    // Parse error response
    let errorData;
    try {
      errorData =
        typeof error.response === 'string'
          ? JSON.parse(error.response)
          : error.response;
    } catch {
      errorData = { code: 'UNKNOWN_ERROR', message: error.message };
    }

    switch (errorData.code) {
      case 'RATE_LIMIT_EXCEEDED':
        return this.handleRateLimit(errorData, context);

      case 'INVALID_TOKEN':
      case 'TOKEN_EXPIRED':
        return this.handleAuthError(errorData, context);

      case 'VALIDATION_ERROR':
        return this.handleValidationError(errorData, context);

      case 'CONTENT_TOO_LARGE':
        return this.handleContentTooLarge(errorData, context);

      case 'SERVICE_UNAVAILABLE':
      case 'INTERNAL_SERVER_ERROR':
        return this.handleServerError(errorData, context);

      default:
        return this.handleUnknownError(errorData, context);
    }
  }

  async handleRateLimit(error, context) {
    const retryAfter = error.details?.reset_time
      ? new Date(error.details.reset_time).getTime() - Date.now()
      : 60000; // Default 1 minute

    this.onError('Rate limit exceeded', { retryAfter, error });

    if (context.attempt <= this.retryAttempts) {
      this.onRetry(
        `Retrying after ${retryAfter}ms (attempt ${context.attempt})`
      );

      await this.delay(retryAfter);
      return this.sendMessageWithRetry(
        context.conversationId,
        context.persona,
        context.message,
        context.options,
        context.attempt + 1
      );
    }

    throw new Error(`Rate limit exceeded. ${error.message}`);
  }

  async handleAuthError(error, context) {
    this.onError('Authentication error', { error });

    // Attempt token refresh
    try {
      await this.chat.authManager.refreshToken();

      if (context.attempt <= this.retryAttempts) {
        this.onRetry(
          `Retrying with refreshed token (attempt ${context.attempt})`
        );
        return this.sendMessageWithRetry(
          context.conversationId,
          context.persona,
          context.message,
          context.options,
          context.attempt + 1
        );
      }
    } catch (refreshError) {
      // Refresh failed, require re-authentication
      throw new Error('Authentication required. Please log in again.');
    }

    throw new Error(`Authentication failed: ${error.message}`);
  }

  async handleValidationError(error, context) {
    this.onError('Validation error', { error });

    // Attempt to fix common validation errors
    const fixedOptions = this.fixValidationIssues(context.options, error);

    if (fixedOptions && context.attempt <= this.retryAttempts) {
      this.onRetry(
        `Retrying with corrected parameters (attempt ${context.attempt})`
      );
      return this.sendMessageWithRetry(
        context.conversationId,
        context.persona,
        context.message,
        fixedOptions,
        context.attempt + 1
      );
    }

    throw new Error(`Validation error: ${error.message}`);
  }

  async handleContentTooLarge(error, context) {
    this.onError('Content too large', { error });

    // Attempt to truncate message
    if (
      context.message.length > 1000 &&
      context.attempt <= this.retryAttempts
    ) {
      const truncatedMessage = context.message.substring(0, 1000) + '...';

      this.onRetry(
        `Retrying with truncated message (attempt ${context.attempt})`
      );
      return this.sendMessageWithRetry(
        context.conversationId,
        context.persona,
        truncatedMessage,
        context.options,
        context.attempt + 1
      );
    }

    throw new Error(`Message too large: ${error.message}`);
  }

  async handleServerError(error, context) {
    this.onError('Server error', { error });

    if (context.attempt <= this.retryAttempts) {
      const delay = this.retryDelay * Math.pow(2, context.attempt - 1); // Exponential backoff

      this.onRetry(
        `Retrying after server error in ${delay}ms (attempt ${context.attempt})`
      );
      await this.delay(delay);

      return this.sendMessageWithRetry(
        context.conversationId,
        context.persona,
        context.message,
        context.options,
        context.attempt + 1
      );
    }

    throw new Error(
      `Server error: ${error.message}. Trace ID: ${error.trace_id}`
    );
  }

  async handleUnknownError(error, context) {
    this.onError('Unknown error', { error });

    if (context.attempt <= this.retryAttempts) {
      this.onRetry(`Retrying unknown error (attempt ${context.attempt})`);
      await this.delay(this.retryDelay);

      return this.sendMessageWithRetry(
        context.conversationId,
        context.persona,
        context.message,
        context.options,
        context.attempt + 1
      );
    }

    throw new Error(`Unknown error: ${error.message}`);
  }

  fixValidationIssues(options, error) {
    if (!error.details?.field) return null;

    const fixes = {
      persona: () => ({ ...options, persona: 'zen_master' }),
      depth: () => ({ ...options, depth: 'practical' }),
      mode: () => ({ ...options, mode: 'text' }),
    };

    const fix = fixes[error.details.field];
    return fix ? fix() : null;
  }

  delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}

// Usage
const errorHandler = new ChatErrorHandler(chat, {
  retryAttempts: 3,
  retryDelay: 1000,
  onError: (message, details) => {
    console.error(`Chat error: ${message}`, details);
    showUserNotification(`Error: ${message}`);
  },
  onRetry: (message) => {
    console.log(`Chat retry: ${message}`);
    showUserNotification(`Retrying: ${message}`, 'info');
  },
});

// Use error handler for all chat requests
try {
  const response = await errorHandler.sendMessageWithRetry(
    conversationId,
    'zen_master',
    userMessage
  );
  handleChatResponse(response);
} catch (error) {
  handleFinalError(error);
}
```

## Best Practices

### Performance Optimization

#### Request Batching

```javascript
class BatchedChatClient {
  constructor(apiToken, batchSize = 5, batchDelay = 100) {
    this.chat = new LilithChat(apiToken);
    this.batchSize = batchSize;
    this.batchDelay = batchDelay;
    this.requestQueue = [];
    this.processing = false;
  }

  async sendMessage(conversationId, persona, message, options = {}) {
    return new Promise((resolve, reject) => {
      this.requestQueue.push({
        conversationId,
        persona,
        message,
        options,
        resolve,
        reject,
      });

      this.processBatch();
    });
  }

  async processBatch() {
    if (this.processing || this.requestQueue.length === 0) return;

    this.processing = true;

    while (this.requestQueue.length > 0) {
      const batch = this.requestQueue.splice(0, this.batchSize);

      // Process batch in parallel
      const promises = batch.map(async (request) => {
        try {
          const response = await this.chat.sendMessage(
            request.conversationId,
            request.persona,
            request.message,
            request.options
          );
          request.resolve(response);
        } catch (error) {
          request.reject(error);
        }
      });

      await Promise.all(promises);

      // Small delay between batches
      if (this.requestQueue.length > 0) {
        await this.delay(this.batchDelay);
      }
    }

    this.processing = false;
  }

  delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}
```

#### Response Caching

```javascript
class CachedChatClient {
  constructor(apiToken, cacheOptions = {}) {
    this.chat = new LilithChat(apiToken);
    this.cache = new Map();
    this.maxCacheSize = cacheOptions.maxSize || 100;
    this.cacheTimeout = cacheOptions.timeout || 5 * 60 * 1000; // 5 minutes
  }

  async sendMessage(conversationId, persona, message, options = {}) {
    const cacheKey = this.generateCacheKey(persona, message, options);
    const cached = this.cache.get(cacheKey);

    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      return { ...cached.response, cached: true };
    }

    const response = await this.chat.sendMessage(
      conversationId,
      persona,
      message,
      options
    );

    // Cache non-conversational responses
    if (!conversationId && !options.stream) {
      this.setCacheEntry(cacheKey, response);
    }

    return response;
  }

  generateCacheKey(persona, message, options) {
    const keyData = {
      persona,
      message: message.toLowerCase().trim(),
      depth: options.depth || 'practical',
      cite: options.cite !== false,
    };

    return JSON.stringify(keyData);
  }

  setCacheEntry(key, response) {
    // Remove oldest entries if cache is full
    if (this.cache.size >= this.maxCacheSize) {
      const oldestKey = this.cache.keys().next().value;
      this.cache.delete(oldestKey);
    }

    this.cache.set(key, {
      response: { ...response },
      timestamp: Date.now(),
    });
  }

  clearCache() {
    this.cache.clear();
  }
}
```

### User Experience Guidelines

#### Progressive Enhancement

```javascript
class ProgressiveChat {
  constructor(apiToken) {
    this.chat = new LilithChat(apiToken);
    this.hasStreamingSupport = this.detectStreamingSupport();
  }

  detectStreamingSupport() {
    return (
      typeof EventSource !== 'undefined' &&
      typeof ReadableStream !== 'undefined'
    );
  }

  async sendMessage(conversationId, persona, message, onProgress) {
    if (this.hasStreamingSupport) {
      return this.sendStreamingMessage(
        conversationId,
        persona,
        message,
        onProgress
      );
    } else {
      return this.sendPollingMessage(
        conversationId,
        persona,
        message,
        onProgress
      );
    }
  }

  async sendStreamingMessage(conversationId, persona, message, onProgress) {
    // Use streaming for real-time updates
    const streamChat = new StreamingChat(this.chat.apiToken);

    let fullResponse = '';

    await streamChat.startStreamingChat(
      persona,
      message,
      (token) => {
        fullResponse += token;
        onProgress({ type: 'token', data: token, fullText: fullResponse });
      },
      (citations) => {
        onProgress({ type: 'citations', data: citations });
      },
      (messageId) => {
        onProgress({ type: 'complete', messageId, fullText: fullResponse });
      },
      (error) => {
        onProgress({ type: 'error', error });
      }
    );
  }

  async sendPollingMessage(conversationId, persona, message, onProgress) {
    // Fallback to polling for older browsers
    onProgress({ type: 'start' });

    try {
      const response = await this.chat.sendMessage(
        conversationId,
        persona,
        message,
        {
          stream: false,
        }
      );

      // Simulate streaming for consistent UX
      await this.simulateStreaming(response.text, onProgress);

      onProgress({
        type: 'complete',
        messageId: response.message_id,
        fullText: response.text,
        citations: response.citations,
      });

      return response;
    } catch (error) {
      onProgress({ type: 'error', error });
      throw error;
    }
  }

  async simulateStreaming(text, onProgress, delayMs = 30) {
    const words = text.split(' ');
    let current = '';

    for (const word of words) {
      current += (current ? ' ' : '') + word;
      onProgress({ type: 'token', data: word, fullText: current });
      await this.delay(delayMs);
    }
  }

  delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}
```

#### Accessibility Features

```javascript
class AccessibleChat {
  constructor(apiToken, options = {}) {
    this.chat = new LilithChat(apiToken);
    this.announceResponses = options.announceResponses !== false;
    this.highContrastMode = options.highContrastMode || false;
    this.largeText = options.largeText || false;
  }

  async sendMessage(conversationId, persona, message, onResponse) {
    // Announce that processing is starting
    if (this.announceResponses) {
      this.announceToScreenReader('Processing your message...');
    }

    try {
      const response = await this.chat.sendMessage(
        conversationId,
        persona,
        message
      );

      // Announce completion
      if (this.announceResponses) {
        this.announceToScreenReader('Response received');
      }

      onResponse(response);
      return response;
    } catch (error) {
      if (this.announceResponses) {
        this.announceToScreenReader('Error occurred while processing message');
      }
      throw error;
    }
  }

  announceToScreenReader(message) {
    const announcement = document.createElement('div');
    announcement.setAttribute('aria-live', 'polite');
    announcement.setAttribute('aria-atomic', 'true');
    announcement.className = 'sr-only';
    announcement.textContent = message;

    document.body.appendChild(announcement);

    setTimeout(() => {
      document.body.removeChild(announcement);
    }, 1000);
  }

  formatMessageForAccessibility(message, citations) {
    let formatted = message;

    if (citations && citations.length > 0) {
      formatted += '\n\nSources: ';
      formatted += citations.map((cite) => cite.source_uri).join(', ');
    }

    return formatted;
  }
}
```

### Security Considerations

#### Input Sanitization

```javascript
class SecureChat {
  constructor(apiToken) {
    this.chat = new LilithChat(apiToken);
  }

  async sendMessage(conversationId, persona, message, options = {}) {
    // Sanitize input
    const sanitizedMessage = this.sanitizeInput(message);
    const sanitizedPersona = this.validatePersona(persona);

    // Validate message length
    if (sanitizedMessage.length > 2000) {
      throw new Error('Message too long. Maximum 2000 characters allowed.');
    }

    if (sanitizedMessage.trim().length === 0) {
      throw new Error('Message cannot be empty.');
    }

    return this.chat.sendMessage(
      conversationId,
      sanitizedPersona,
      sanitizedMessage,
      options
    );
  }

  sanitizeInput(input) {
    // Remove potential XSS vectors
    return input
      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
      .replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '')
      .replace(/javascript:/gi, '')
      .replace(/on\w+\s*=/gi, '')
      .trim();
  }

  validatePersona(persona) {
    const validPersonas = [
      'zen_master',
      'philosopher',
      'stoic',
      'mystic',
      'teacher',
    ];

    if (!validPersonas.includes(persona)) {
      console.warn(`Invalid persona: ${persona}. Falling back to zen_master.`);
      return 'zen_master';
    }

    return persona;
  }
}
```

---

## Quick Reference

### Chat Request Format

```javascript
{
  conversation_id: "conv_123" | null,  // null for new conversation
  persona: "zen_master" | "philosopher" | "stoic" | "mystic" | "teacher",
  input: {
    text: "Your message here",      // For text input
    audio: "base64_encoded_audio"   // For audio input
  },
  mode: "text" | "voice",
  options: {
    stream: true | false,          // Enable streaming responses
    cite: true | false,            // Include source citations
    depth: "practical" | "scholarly", // Response complexity
    language: "en"                 // ISO 639-1 language code
  }
}
```

### Response Format

```javascript
{
  message_id: "msg_456",
  conversation_id: "conv_123",
  text: "AI response text...",
  citations: [
    {
      source_uri: "source_identifier",
      span: { start: 0, end: 50 },
      confidence: 0.95,
      license: "CC-BY-SA-4.0"
    }
  ],
  audio_url: "https://cdn.lilith.app/audio/msg_456.opus"
}
```

### Streaming Events

| Event       | Description          | Data Format                       |
| ----------- | -------------------- | --------------------------------- |
| `token`     | Text token generated | `{ text: "word" }`                |
| `citations` | Source citations     | `{ citations: [...] }`            |
| `audio`     | Audio URL available  | `{ audio_url: "..." }`            |
| `done`      | Response complete    | `{ message_id: "..." }`           |
| `error`     | Error occurred       | `{ code: "...", message: "..." }` |

### Persona Characteristics

| Persona         | Philosophy           | Best For                     | Tone                    |
| --------------- | -------------------- | ---------------------------- | ----------------------- |
| **zen_master**  | Buddhist/Zen         | Meditation, mindfulness      | Calm, present-focused   |
| **philosopher** | Western philosophy   | Ethics, reasoning            | Analytical, questioning |
| **stoic**       | Stoic philosophy     | Resilience, practical wisdom | Rational, disciplined   |
| **mystic**      | Mystical traditions  | Spirituality, transcendence  | Intuitive, symbolic     |
| **teacher**     | Pedagogical approach | Learning, skill development  | Structured, educational |

For more advanced chat features, see our
[WebSocket Integration Guide](./websocket-integration.md) and
[Voice Integration Guide](./voice-integration.md).
