Comprehensive guide to implementing real-time bidirectional communication with the Lilith API using WebSocket connections.
Table of Contents#
- Overview
- Connection Setup
- Authentication
- Message Format
- Chat Integration
- Audio Streaming
- Error Handling
- Reconnection Logic
- Performance Optimization
Overview#
The Lilith WebSocket API provides real-time, bidirectional communication for chat interactions and audio streaming. WebSocket connections offer lower latency and more efficient resource usage compared to HTTP polling or Server-Sent Events.
Connection Details#
- Endpoint:
wss://api.lilith.app/ws - Protocol: WebSocket over TLS (wss://)
- Authentication: JWT tokens via connection headers or initial message
- Message Format: JSON-based protocol
- Supported Features: Chat, audio streaming, real-time notifications
Benefits#
- π Lower Latency: Real-time message delivery
- πͺ Bidirectional: Client and server can initiate communication
- π± Efficient: Single persistent connection
- β‘ Streaming: Real-time token streaming for chat responses
- π Stateful: Maintains conversation context
Connection Setup#
Basic WebSocket Connection#
javascript
class LilithWebSocketClient {
constructor(apiToken, options = {}) {
this.apiToken = apiToken;
this.baseURL = options.baseURL || 'wss://api.lilith.app/ws';
this.ws = null;
this.connectionId = null;
this.messageHandlers = new Map();
this.eventListeners = new Map();
this.reconnectAttempts = 0;
this.maxReconnectAttempts = options.maxReconnectAttempts || 5;
this.reconnectDelay = options.reconnectDelay || 1000;
this.heartbeatInterval = options.heartbeatInterval || 30000;
this.heartbeatTimer = null;
}
async connect() {
return new Promise((resolve, reject) => {
try {
// Create WebSocket connection
this.ws = new WebSocket(this.baseURL);
// Connection opened
this.ws.onopen = () => {
console.log('WebSocket connected');
this.reconnectAttempts = 0;
// Authenticate immediately
this.authenticate()
.then(() => {
this.startHeartbeat();
this.emit('connected');
resolve();
})
.catch(reject);
};
// Message received
this.ws.onmessage = (event) => {
this.handleMessage(event);
};
// Connection closed
this.ws.onclose = (event) => {
console.log('WebSocket closed:', event.code, event.reason);
this.stopHeartbeat();
this.emit('disconnected', { code: event.code, reason: event.reason });
if (!event.wasClean && this.shouldReconnect()) {
this.scheduleReconnect();
}
};
// Connection error
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
this.emit('error', error);
reject(error);
};
} catch (error) {
console.error('Failed to create WebSocket:', error);
reject(error);
}
});
}
async authenticate() {
return new Promise((resolve, reject) => {
const authMessage = {
type: 'auth',
data: {
token: this.apiToken,
},
};
// Set up one-time handler for auth response
const authHandler = (message) => {
if (message.type === 'auth_success') {
this.connectionId = message.data.connection_id;
resolve();
} else if (message.type === 'auth_error') {
reject(new Error(message.data.message));
}
};
this.once('auth_success', authHandler);
this.once('auth_error', authHandler);
this.send(authMessage);
// Timeout after 10 seconds
setTimeout(() => {
this.off('auth_success', authHandler);
this.off('auth_error', authHandler);
reject(new Error('Authentication timeout'));
}, 10000);
});
}
send(message) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
const messageStr = JSON.stringify({
...message,
timestamp: Date.now(),
connection_id: this.connectionId,
});
this.ws.send(messageStr);
return true;
}
console.warn('WebSocket not connected, message not sent:', message);
return false;
}
handleMessage(event) {
try {
const message = JSON.parse(event.data);
// Emit specific event
this.emit(message.type, message);
// Handle message with registered handlers
if (message.request_id && this.messageHandlers.has(message.request_id)) {
const handler = this.messageHandlers.get(message.request_id);
handler(message);
// Clean up one-time handlers
if (
message.type.endsWith('_complete') ||
message.type.endsWith('_error')
) {
this.messageHandlers.delete(message.request_id);
}
}
} catch (error) {
console.error('Error parsing WebSocket message:', error);
}
}
// Event emitter methods
on(event, callback) {
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event).push(callback);
}
once(event, callback) {
const onceWrapper = (...args) => {
callback(...args);
this.off(event, onceWrapper);
};
this.on(event, onceWrapper);
}
off(event, callback) {
if (this.eventListeners.has(event)) {
const listeners = this.eventListeners.get(event);
const index = listeners.indexOf(callback);
if (index > -1) {
listeners.splice(index, 1);
}
}
}
emit(event, ...args) {
if (this.eventListeners.has(event)) {
this.eventListeners.get(event).forEach((callback) => {
try {
callback(...args);
} catch (error) {
console.error(`Error in event listener for ${event}:`, error);
}
});
}
}
// Heartbeat to keep connection alive
startHeartbeat() {
this.heartbeatTimer = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.send({ type: 'ping' });
}
}, this.heartbeatInterval);
}
stopHeartbeat() {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
shouldReconnect() {
return this.reconnectAttempts < this.maxReconnectAttempts;
}
scheduleReconnect() {
const delay = Math.min(
this.reconnectDelay * Math.pow(2, this.reconnectAttempts),
30000
);
console.log(
`Scheduling reconnect in ${delay}ms (attempt ${this.reconnectAttempts + 1})`
);
setTimeout(() => {
this.reconnectAttempts++;
this.connect().catch(() => {
// Reconnection failed, will be retried if attempts remaining
});
}, delay);
}
disconnect() {
this.stopHeartbeat();
if (this.ws) {
this.ws.close(1000, 'Client disconnect');
this.ws = null;
}
this.connectionId = null;
this.messageHandlers.clear();
}
generateRequestId() {
return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
}
Authentication#
Token-based Authentication#
javascript
// Authentication with JWT token
const client = new LilithWebSocketClient('your-jwt-token');
await client.connect();
// Handle authentication events
client.on('auth_success', (message) => {
console.log('Authenticated successfully:', message.data);
});
client.on('auth_error', (message) => {
console.error('Authentication failed:', message.data.message);
});
Connection Headers Authentication (Alternative)#
javascript
class LilithWebSocketClient {
constructor(apiToken, options = {}) {
this.apiToken = apiToken;
this.baseURL = options.baseURL || 'wss://api.lilith.app/ws';
}
async connect() {
return new Promise((resolve, reject) => {
// Some WebSocket implementations support custom headers
const wsOptions = {
headers: {
Authorization: `Bearer ${this.apiToken}`,
'User-Agent': 'LilithClient/1.0.0',
},
};
// For environments that support it (Node.js)
if (typeof WebSocket !== 'function' && typeof require === 'function') {
const WS = require('ws');
this.ws = new WS(this.baseURL, wsOptions);
} else {
// Browser WebSocket (authenticate via message after connection)
this.ws = new WebSocket(this.baseURL);
}
// ... rest of connection setup
});
}
}
Message Format#
Message Structure#
All WebSocket messages follow a consistent JSON format:
json
{
"type": "message_type",
"request_id": "unique_request_identifier",
"data": {
// Message-specific data
},
"timestamp": 1670000000000,
"connection_id": "conn_abc123"
}
Message Types#
| Type | Direction | Description |
|---|---|---|
auth |
Client β Server | Authentication request |
auth_success |
Server β Client | Authentication successful |
auth_error |
Server β Client | Authentication failed |
chat |
Client β Server | Chat message request |
chat_token |
Server β Client | Chat response token |
chat_citations |
Server β Client | Citations for chat response |
chat_complete |
Server β Client | Chat response complete |
chat_error |
Server β Client | Chat request error |
audio_request |
Client β Server | Audio synthesis request |
audio_chunk |
Server β Client | Audio data chunk |
audio_complete |
Server β Client | Audio synthesis complete |
ping |
Client β Server | Heartbeat message |
pong |
Client β Server | Heartbeat response |
Example Messages#
Chat Request#
json
{
"type": "chat",
"request_id": "req_123456789",
"data": {
"conversation_id": "conv_abc123",
"persona": "zen_master",
"input": {
"text": "What is mindfulness?"
},
"mode": "text",
"options": {
"stream": true,
"cite": true,
"depth": "practical"
}
}
}
Chat Token Response#
json
{
"type": "chat_token",
"request_id": "req_123456789",
"data": {
"text": "Mindfulness",
"index": 0
},
"timestamp": 1670000000000
}
Chat Complete Response#
json
{
"type": "chat_complete",
"request_id": "req_123456789",
"data": {
"message_id": "msg_def456",
"conversation_id": "conv_abc123",
"total_tokens": 45,
"processing_time_ms": 1500
},
"timestamp": 1670000000000
}
Chat Integration#
Real-time Chat Implementation#
javascript
class LilithChatWebSocket {
constructor(apiToken) {
this.client = new LilithWebSocketClient(apiToken);
this.activeChats = new Map();
}
async connect() {
await this.client.connect();
// Set up chat event handlers
this.client.on('chat_token', this.handleChatToken.bind(this));
this.client.on('chat_citations', this.handleChatCitations.bind(this));
this.client.on('chat_complete', this.handleChatComplete.bind(this));
this.client.on('chat_error', this.handleChatError.bind(this));
}
async sendMessage(conversationId, persona, message, options = {}) {
const requestId = this.client.generateRequestId();
// Set up response tracking
const chatSession = {
requestId,
conversationId,
fullText: '',
citations: [],
startTime: Date.now(),
onToken: options.onToken,
onCitations: options.onCitations,
onComplete: options.onComplete,
onError: options.onError,
};
this.activeChats.set(requestId, chatSession);
// Send chat request
const success = this.client.send({
type: 'chat',
request_id: requestId,
data: {
conversation_id: conversationId,
persona: persona,
input: { text: message },
mode: 'text',
options: {
stream: true,
cite: true,
depth: 'practical',
...options,
},
},
});
if (!success) {
this.activeChats.delete(requestId);
throw new Error('Failed to send message - WebSocket not connected');
}
return requestId;
}
handleChatToken(message) {
const session = this.activeChats.get(message.request_id);
if (!session) return;
const token = message.data.text;
session.fullText += token;
if (session.onToken) {
session.onToken(token, session.fullText);
}
}
handleChatCitations(message) {
const session = this.activeChats.get(message.request_id);
if (!session) return;
session.citations = message.data.citations;
if (session.onCitations) {
session.onCitations(session.citations);
}
}
handleChatComplete(message) {
const session = this.activeChats.get(message.request_id);
if (!session) return;
const result = {
messageId: message.data.message_id,
conversationId: message.data.conversation_id,
text: session.fullText,
citations: session.citations,
processingTime: Date.now() - session.startTime,
};
if (session.onComplete) {
session.onComplete(result);
}
this.activeChats.delete(message.request_id);
}
handleChatError(message) {
const session = this.activeChats.get(message.request_id);
if (!session) return;
const error = new Error(message.data.message);
error.code = message.data.code;
if (session.onError) {
session.onError(error);
}
this.activeChats.delete(message.request_id);
}
disconnect() {
this.client.disconnect();
this.activeChats.clear();
}
}
// Usage example
const chatWs = new LilithChatWebSocket(apiToken);
await chatWs.connect();
let fullResponse = '';
const requestId = await chatWs.sendMessage(
null, // New conversation
'zen_master',
'How can I find inner peace?',
{
onToken: (token, fullText) => {
fullResponse = fullText;
updateChatUI(fullText);
},
onCitations: (citations) => {
displayCitations(citations);
},
onComplete: (result) => {
console.log('Chat completed:', result);
finalizeChatMessage(result);
},
onError: (error) => {
console.error('Chat error:', error);
showErrorMessage(error.message);
},
}
);
console.log('Chat request sent:', requestId);
Multi-turn Conversation Management#
javascript
class ConversationManager {
constructor(chatWebSocket) {
this.chatWs = chatWebSocket;
this.conversations = new Map();
this.activeRequests = new Set();
}
async startConversation(persona, initialMessage) {
const conversationId = this.generateConversationId();
const conversation = {
id: conversationId,
persona: persona,
messages: [],
created: new Date(),
lastActivity: new Date(),
};
this.conversations.set(conversationId, conversation);
// Send initial message
const response = await this.sendMessage(conversationId, initialMessage);
return { conversationId, response };
}
async sendMessage(conversationId, message) {
const conversation = this.conversations.get(conversationId);
if (!conversation) {
throw new Error('Conversation not found');
}
// Add user message to history
const userMessage = {
role: 'user',
content: message,
timestamp: new Date(),
};
conversation.messages.push(userMessage);
return new Promise((resolve, reject) => {
let fullResponse = '';
let citations = [];
const requestId = this.chatWs.sendMessage(
conversationId,
conversation.persona,
message,
{
onToken: (token, fullText) => {
fullResponse = fullText;
this.onMessageToken(conversationId, token);
},
onCitations: (cites) => {
citations = cites;
},
onComplete: (result) => {
// Add AI message to history
const aiMessage = {
role: 'assistant',
content: fullResponse,
citations: citations,
messageId: result.messageId,
timestamp: new Date(),
};
conversation.messages.push(aiMessage);
conversation.lastActivity = new Date();
this.activeRequests.delete(requestId);
resolve(result);
},
onError: (error) => {
this.activeRequests.delete(requestId);
reject(error);
},
}
);
this.activeRequests.add(requestId);
});
}
getConversation(conversationId) {
return this.conversations.get(conversationId);
}
getConversationHistory(conversationId) {
const conversation = this.conversations.get(conversationId);
return conversation ? conversation.messages : [];
}
deleteConversation(conversationId) {
this.conversations.delete(conversationId);
}
// Override to customize token handling
onMessageToken(conversationId, token) {
// Default: emit event for UI updates
this.emit('conversation_token', { conversationId, token });
}
generateConversationId() {
return 'conv_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
// Event emitter methods (simplified)
on(event, callback) {
if (!this.eventListeners) this.eventListeners = new Map();
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event).push(callback);
}
emit(event, data) {
if (!this.eventListeners) return;
if (this.eventListeners.has(event)) {
this.eventListeners.get(event).forEach((callback) => callback(data));
}
}
}
// Usage
const conversationMgr = new ConversationManager(chatWs);
// Start new conversation
const { conversationId } = await conversationMgr.startConversation(
'zen_master',
'Hello, I would like to learn about meditation.'
);
// Continue conversation
await conversationMgr.sendMessage(
conversationId,
'Can you guide me through a simple breathing exercise?'
);
// Get conversation history
const history = conversationMgr.getConversationHistory(conversationId);
console.log('Conversation history:', history);
Audio Streaming#
Real-time Audio Synthesis#
javascript
class LilithAudioWebSocket {
constructor(apiToken) {
this.client = new LilithWebSocketClient(apiToken);
this.audioContext = null;
this.audioQueue = [];
this.isPlaying = false;
this.currentSource = null;
}
async connect() {
await this.client.connect();
// Initialize audio context
this.audioContext = new (
window.AudioContext || window.webkitAudioContext
)();
// Set up audio event handlers
this.client.on('audio_chunk', this.handleAudioChunk.bind(this));
this.client.on('audio_complete', this.handleAudioComplete.bind(this));
this.client.on('audio_error', this.handleAudioError.bind(this));
}
async synthesizeAndStream(text, voiceId, options = {}) {
const requestId = this.client.generateRequestId();
const success = this.client.send({
type: 'audio_request',
request_id: requestId,
data: {
text: text,
voice_id: voiceId,
format: 'opus',
stream: true,
...options,
},
});
if (!success) {
throw new Error('Failed to send audio request');
}
return requestId;
}
async handleAudioChunk(message) {
try {
// Decode base64 audio chunk
const audioData = this.base64ToArrayBuffer(message.data.chunk);
const audioBuffer = await this.audioContext.decodeAudioData(audioData);
this.audioQueue.push(audioBuffer);
// Start playback if not already playing
if (!this.isPlaying) {
this.startPlayback();
}
} catch (error) {
console.error('Error processing audio chunk:', error);
}
}
startPlayback() {
if (this.audioQueue.length === 0) {
this.isPlaying = false;
return;
}
this.isPlaying = true;
this.playNextBuffer();
}
playNextBuffer() {
if (this.audioQueue.length === 0) {
this.isPlaying = false;
return;
}
const buffer = this.audioQueue.shift();
this.currentSource = this.audioContext.createBufferSource();
this.currentSource.buffer = buffer;
// Add volume control
const gainNode = this.audioContext.createGain();
this.currentSource.connect(gainNode);
gainNode.connect(this.audioContext.destination);
this.currentSource.onended = () => {
this.playNextBuffer();
};
this.currentSource.start();
}
handleAudioComplete(message) {
console.log('Audio synthesis completed:', message.data);
// Continue playing any remaining queued audio
}
handleAudioError(message) {
console.error('Audio synthesis error:', message.data);
this.stopPlayback();
}
stopPlayback() {
if (this.currentSource) {
this.currentSource.stop();
this.currentSource = null;
}
this.isPlaying = false;
this.audioQueue = [];
}
base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
disconnect() {
this.stopPlayback();
if (this.audioContext) {
this.audioContext.close();
this.audioContext = null;
}
this.client.disconnect();
}
}
// Usage example
const audioWs = new LilithAudioWebSocket(apiToken);
await audioWs.connect();
// Synthesize and stream meditation guidance
await audioWs.synthesizeAndStream(
'Take a deep breath in through your nose, hold for three counts, then slowly exhale through your mouth. Feel your body relaxing with each breath.',
'calm_female_01',
{
speed: 0.8,
pitch: -2.0,
}
);
Error Handling#
Comprehensive Error Management#
javascript
class WebSocketErrorHandler {
constructor(client) {
this.client = client;
this.errorCounts = new Map();
this.lastErrors = [];
this.maxErrorHistory = 10;
this.setupErrorHandling();
}
setupErrorHandling() {
this.client.on('error', this.handleConnectionError.bind(this));
this.client.on('auth_error', this.handleAuthError.bind(this));
this.client.on('chat_error', this.handleChatError.bind(this));
this.client.on('audio_error', this.handleAudioError.bind(this));
}
handleConnectionError(error) {
this.logError(
'CONNECTION_ERROR',
error.message || 'WebSocket connection failed'
);
// Implement exponential backoff for reconnection
const errorCount = this.getErrorCount('CONNECTION_ERROR');
if (errorCount < 3) {
// Immediate retry for first few errors
setTimeout(() => this.client.connect(), 1000);
} else if (errorCount < 6) {
// Exponential backoff
const delay = Math.min(1000 * Math.pow(2, errorCount - 3), 30000);
setTimeout(() => this.client.connect(), delay);
} else {
// Give up after too many errors
this.emit('fatal_error', {
code: 'MAX_CONNECTION_RETRIES',
message:
'Unable to establish WebSocket connection after multiple attempts',
});
}
}
handleAuthError(message) {
const error = {
code: message.data.code,
message: message.data.message,
};
this.logError('AUTH_ERROR', error.message, error.code);
switch (error.code) {
case 'INVALID_TOKEN':
case 'TOKEN_EXPIRED':
this.emit('auth_required', error);
break;
case 'INSUFFICIENT_PERMISSIONS':
this.emit('permission_denied', error);
break;
default:
this.emit('auth_failed', error);
}
}
handleChatError(message) {
const error = {
requestId: message.request_id,
code: message.data.code,
message: message.data.message,
};
this.logError('CHAT_ERROR', error.message, error.code);
switch (error.code) {
case 'RATE_LIMIT_EXCEEDED':
this.handleRateLimit(error);
break;
case 'CONTENT_FILTER_VIOLATION':
this.emit('content_filtered', error);
break;
case 'CONVERSATION_NOT_FOUND':
this.emit('conversation_expired', error);
break;
default:
this.emit('chat_error', error);
}
}
handleAudioError(message) {
const error = {
requestId: message.request_id,
code: message.data.code,
message: message.data.message,
};
this.logError('AUDIO_ERROR', error.message, error.code);
switch (error.code) {
case 'UNSUPPORTED_VOICE':
this.emit('voice_unavailable', error);
break;
case 'TEXT_TOO_LONG':
this.emit('text_length_exceeded', error);
break;
default:
this.emit('audio_error', error);
}
}
handleRateLimit(error) {
const retryAfter = error.retryAfter || 60; // seconds
this.emit('rate_limited', {
...error,
retryAfter: retryAfter,
});
// Automatic retry after delay
setTimeout(() => {
this.emit('rate_limit_cleared');
}, retryAfter * 1000);
}
logError(type, message, code = null) {
const errorEntry = {
type: type,
message: message,
code: code,
timestamp: new Date(),
count: this.incrementErrorCount(type),
};
this.lastErrors.unshift(errorEntry);
// Keep only recent errors
if (this.lastErrors.length > this.maxErrorHistory) {
this.lastErrors = this.lastErrors.slice(0, this.maxErrorHistory);
}
console.error(`WebSocket ${type}:`, message, code ? `(${code})` : '');
}
incrementErrorCount(type) {
const current = this.errorCounts.get(type) || 0;
const newCount = current + 1;
this.errorCounts.set(type, newCount);
return newCount;
}
getErrorCount(type) {
return this.errorCounts.get(type) || 0;
}
clearErrorCounts() {
this.errorCounts.clear();
}
getRecentErrors() {
return [...this.lastErrors];
}
// Event emitter (simplified)
on(event, callback) {
if (!this.eventListeners) this.eventListeners = new Map();
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event).push(callback);
}
emit(event, data) {
if (!this.eventListeners) return;
if (this.eventListeners.has(event)) {
this.eventListeners.get(event).forEach((callback) => {
try {
callback(data);
} catch (error) {
console.error(`Error in ${event} handler:`, error);
}
});
}
}
}
// Usage
const client = new LilithWebSocketClient(apiToken);
const errorHandler = new WebSocketErrorHandler(client);
// Handle various error scenarios
errorHandler.on('auth_required', (error) => {
console.log('Authentication required:', error);
// Redirect to login or refresh token
redirectToLogin();
});
errorHandler.on('rate_limited', (error) => {
console.log(`Rate limited for ${error.retryAfter} seconds`);
showNotification(
`Rate limit reached. Please wait ${error.retryAfter} seconds.`
);
});
errorHandler.on('fatal_error', (error) => {
console.error('Fatal WebSocket error:', error);
showError('Connection failed. Please refresh the page.');
});
Reconnection Logic#
Intelligent Reconnection Strategy#
javascript
class ReconnectionManager {
constructor(client, options = {}) {
this.client = client;
this.isReconnecting = false;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = options.maxReconnectAttempts || 10;
this.baseDelay = options.baseDelay || 1000;
this.maxDelay = options.maxDelay || 30000;
this.backoffFactor = options.backoffFactor || 1.5;
this.jitter = options.jitter !== false; // Add randomness to prevent thundering herd
this.networkOnline = navigator.onLine;
this.setupNetworkMonitoring();
}
setupNetworkMonitoring() {
window.addEventListener('online', () => {
console.log('Network came back online');
this.networkOnline = true;
this.handleNetworkReconnect();
});
window.addEventListener('offline', () => {
console.log('Network went offline');
this.networkOnline = false;
});
}
async attemptReconnect() {
if (this.isReconnecting) {
console.log('Reconnection already in progress');
return;
}
if (!this.networkOnline) {
console.log('Network offline, waiting for connection');
return;
}
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('Max reconnection attempts reached');
this.emit('reconnect_failed', {
attempts: this.reconnectAttempts,
reason: 'MAX_ATTEMPTS_EXCEEDED',
});
return;
}
this.isReconnecting = true;
this.reconnectAttempts++;
console.log(
`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`
);
try {
await this.client.connect();
// Reconnection successful
console.log('Reconnection successful');
this.reconnectAttempts = 0;
this.isReconnecting = false;
this.emit('reconnected', { attempts: this.reconnectAttempts });
} catch (error) {
console.error('Reconnection failed:', error);
this.isReconnecting = false;
// Calculate next retry delay
const delay = this.calculateDelay();
console.log(`Next reconnection attempt in ${delay}ms`);
setTimeout(() => {
this.attemptReconnect();
}, delay);
this.emit('reconnect_attempt_failed', {
attempt: this.reconnectAttempts,
error: error,
nextRetryIn: delay,
});
}
}
calculateDelay() {
// Exponential backoff with jitter
let delay = Math.min(
this.baseDelay * Math.pow(this.backoffFactor, this.reconnectAttempts - 1),
this.maxDelay
);
// Add jitter to prevent thundering herd problem
if (this.jitter) {
delay = delay + Math.random() * delay * 0.3;
}
return Math.floor(delay);
}
handleNetworkReconnect() {
if (!this.client.isConnected() && !this.isReconnecting) {
// Network came back online and we're not connected
console.log('Network reconnected, attempting WebSocket reconnection');
this.reconnectAttempts = 0; // Reset attempts for network reconnection
setTimeout(() => this.attemptReconnect(), 1000);
}
}
handleConnectionLost(event) {
if (!event.wasClean) {
console.log('Connection lost unexpectedly, initiating reconnection');
setTimeout(() => this.attemptReconnect(), this.baseDelay);
}
}
reset() {
this.reconnectAttempts = 0;
this.isReconnecting = false;
}
// Event emitter (simplified)
on(event, callback) {
if (!this.eventListeners) this.eventListeners = new Map();
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event).push(callback);
}
emit(event, data) {
if (!this.eventListeners) return;
if (this.eventListeners.has(event)) {
this.eventListeners.get(event).forEach((callback) => callback(data));
}
}
}
// Integration with WebSocket client
class EnhancedLilithWebSocketClient extends LilithWebSocketClient {
constructor(apiToken, options = {}) {
super(apiToken, options);
this.reconnectionManager = new ReconnectionManager(
this,
options.reconnection
);
this.on('disconnected', (event) => {
this.reconnectionManager.handleConnectionLost(event);
});
// Expose reconnection events
this.reconnectionManager.on('reconnected', (data) => {
this.emit('reconnected', data);
});
this.reconnectionManager.on('reconnect_failed', (data) => {
this.emit('reconnect_failed', data);
});
}
isConnected() {
return this.ws && this.ws.readyState === WebSocket.OPEN;
}
}
Performance Optimization#
Message Queuing and Batching#
javascript
class MessageQueue {
constructor(client, options = {}) {
this.client = client;
this.queue = [];
this.batchSize = options.batchSize || 10;
this.flushInterval = options.flushInterval || 100; // ms
this.maxQueueSize = options.maxQueueSize || 1000;
this.flushTimer = null;
this.isProcessing = false;
}
enqueue(message) {
if (this.queue.length >= this.maxQueueSize) {
console.warn('Message queue full, dropping oldest messages');
this.queue.shift();
}
this.queue.push({
...message,
queued_at: Date.now(),
});
this.scheduleFlush();
}
scheduleFlush() {
if (this.flushTimer) return;
this.flushTimer = setTimeout(() => {
this.flush();
}, this.flushInterval);
}
flush() {
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
if (this.queue.length === 0 || this.isProcessing) return;
this.isProcessing = true;
// Process messages in batches
const batch = this.queue.splice(0, this.batchSize);
if (batch.length === 1) {
// Send single message
this.client.send(batch[0]);
} else if (batch.length > 1) {
// Send as batch
this.client.send({
type: 'batch',
data: {
messages: batch,
},
});
}
this.isProcessing = false;
// Continue processing if queue not empty
if (this.queue.length > 0) {
this.scheduleFlush();
}
}
clear() {
this.queue = [];
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
}
size() {
return this.queue.length;
}
}
// Connection pooling for multiple conversations
class ConnectionPool {
constructor(apiToken, options = {}) {
this.apiToken = apiToken;
this.maxConnections = options.maxConnections || 3;
this.connections = [];
this.roundRobinIndex = 0;
}
async getConnection() {
// Try to find an available connection
for (const conn of this.connections) {
if (conn.isReady() && !conn.isBusy()) {
return conn;
}
}
// Create new connection if under limit
if (this.connections.length < this.maxConnections) {
const conn = new EnhancedLilithWebSocketClient(this.apiToken);
await conn.connect();
this.connections.push(conn);
return conn;
}
// Use round-robin for busy connections
const conn = this.connections[this.roundRobinIndex];
this.roundRobinIndex = (this.roundRobinIndex + 1) % this.connections.length;
return conn;
}
async closeAll() {
for (const conn of this.connections) {
conn.disconnect();
}
this.connections = [];
}
}
Usage Examples#
Complete Chat Application#
javascript
class LilithChatApp {
constructor(apiToken) {
this.client = new EnhancedLilithWebSocketClient(apiToken);
this.conversations = new ConversationManager(
new LilithChatWebSocket(this.client)
);
this.errorHandler = new WebSocketErrorHandler(this.client);
this.setupEventHandlers();
}
async initialize() {
await this.client.connect();
console.log('Lilith Chat App initialized');
}
setupEventHandlers() {
this.client.on('connected', () => {
this.updateConnectionStatus('connected');
});
this.client.on('disconnected', () => {
this.updateConnectionStatus('disconnected');
});
this.client.on('reconnected', () => {
this.updateConnectionStatus('reconnected');
this.showNotification('Connection restored');
});
this.errorHandler.on('auth_required', () => {
this.handleAuthRequired();
});
this.errorHandler.on('rate_limited', (error) => {
this.showRateLimitWarning(error.retryAfter);
});
}
async startChat(persona, message) {
try {
const { conversationId } = await this.conversations.startConversation(
persona,
message
);
this.createChatInterface(conversationId);
return conversationId;
} catch (error) {
this.handleError('Failed to start conversation', error);
}
}
async sendMessage(conversationId, message) {
try {
await this.conversations.sendMessage(conversationId, message);
} catch (error) {
this.handleError('Failed to send message', error);
}
}
// UI methods (implement based on your framework)
updateConnectionStatus(status) {
console.log('Connection status:', status);
// Update UI connection indicator
}
showNotification(message) {
console.log('Notification:', message);
// Show user notification
}
showRateLimitWarning(retryAfter) {
console.log(`Rate limited for ${retryAfter} seconds`);
// Show rate limit warning to user
}
handleAuthRequired() {
console.log('Authentication required');
// Redirect to login or show auth modal
}
createChatInterface(conversationId) {
console.log('Creating chat interface for:', conversationId);
// Create/update chat UI
}
handleError(context, error) {
console.error(context, error);
// Show error to user
}
disconnect() {
this.client.disconnect();
}
}
// Usage
const chatApp = new LilithChatApp('your-jwt-token');
await chatApp.initialize();
// Start a conversation
const conversationId = await chatApp.startChat(
'zen_master',
'Hello, I need some guidance.'
);
// Send follow-up message
await chatApp.sendMessage(conversationId, 'Can you help me with meditation?');
Quick Reference#
Connection URL#
text
wss://api.lilith.app/ws
Authentication Methods#
- Post-connection: Send
authmessage with JWT token - Headers: Include
Authorization: Bearer <token>(Node.js only)
Common Message Types#
| Type | Purpose |
|---|---|
auth |
Authenticate connection |
chat |
Send chat message |
audio_request |
Request audio synthesis |
ping |
Keep connection alive |
Error Handling#
- Always implement reconnection logic
- Handle authentication errors gracefully
- Monitor connection status
- Queue messages during disconnections
Performance Tips#
- Use connection pooling for multiple conversations
- Implement message queuing for high-frequency updates
- Add jitter to reconnection delays
- Monitor network status for smarter reconnections
The WebSocket integration provides the foundation for building real-time, interactive applications with the Lilith API while maintaining robust error handling and optimal performance.