Eve library

TypeScript SDK Integration Guide

Guide

Revision 1

On this page

Complete guide for integrating the Lilith TypeScript SDK into your web applications and Node.js projects.

Installation#

NPM Installation#

bash
npm install @lilith/sdk-ts

Yarn Installation#

bash
yarn add @lilith/sdk-ts

CDN Installation#

html
<script src="https://cdn.jsdelivr.net/npm/@lilith/sdk-ts@latest/dist/index.js"></script>

Configuration#

Basic Setup#

typescript
import { LilithClient } from '@lilith/sdk-ts';

const client = new LilithClient({
  apiKey: 'your-api-key-here',
  baseURL: 'https://api.lilith.app',
  timeout: 30000,
});

Environment Configuration#

typescript
// Development
const devClient = new LilithClient({
  apiKey: process.env.LILITH_DEV_API_KEY,
  baseURL: 'https://staging-api.lilith.app',
  debug: true,
});

// Production
const prodClient = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
  baseURL: 'https://api.lilith.app',
  retryAttempts: 3,
});

Basic Usage#

Authentication#

typescript
// Login with email/password
const auth = await client.auth.login({
  email: 'user@example.com',
  password: 'secure-password',
});

console.log('Access Token:', auth.access_token);

Chat Interactions#

typescript
// Simple chat
const response = await client.chat.create({
  persona: 'zen_master',
  input: {
    text: 'What is mindfulness?',
  },
  mode: 'text',
  options: {
    stream: false,
    cite: true,
  },
});

console.log('AI Response:', response.text);

Streaming Chat#

typescript
// Streaming chat with real-time tokens
const stream = await client.chat.createStream({
  persona: 'zen_master',
  input: {
    text: 'Tell me about meditation practices',
  },
  mode: 'text',
});

stream.on('token', (data) => {
  process.stdout.write(data.text);
});

stream.on('citation', (citation) => {
  console.log('Citation:', citation.source_uri);
});

stream.on('done', (metadata) => {
  console.log('Response complete. Message ID:', metadata.message_id);
});

stream.on('error', (error) => {
  console.error('Stream error:', error);
});

Text-to-Speech#

typescript
// Generate speech audio
const tts = await client.tts.synthesize({
  voice_id: 'calm_female_01',
  ssml: '<speak>Welcome to your mindfulness practice.</speak>',
  format: 'mp3',
  stream: false,
});

console.log('Audio URL:', tts.audio_url);
console.log('Duration:', tts.duration_ms);

Advanced Features#

WebSocket Integration#

typescript
// Real-time WebSocket chat
const ws = client.createWebSocketConnection();

ws.on('connected', () => {
  console.log('WebSocket connected');

  ws.sendMessage({
    type: 'chat',
    data: {
      persona: 'philosopher',
      input: { text: 'What is the meaning of life?' },
      mode: 'text',
    },
  });
});

ws.on('message', (message) => {
  if (message.type === 'token') {
    process.stdout.write(message.data.text);
  }
});

ws.connect();

Custom Error Handling#

typescript
import { LilithError, AuthError, RateLimitError } from '@lilith/sdk-ts';

try {
  const response = await client.chat.create(chatRequest);
} catch (error) {
  if (error instanceof AuthError) {
    console.error('Authentication failed:', error.message);
    // Redirect to login
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded:', error.retryAfter);
    // Wait and retry
  } else if (error instanceof LilithError) {
    console.error('API error:', error.code, error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}

Request Interceptors#

typescript
// Add request interceptor
client.interceptors.request.use((config) => {
  // Add custom headers
  config.headers['X-Client-Version'] = '1.0.0';
  config.headers['X-Request-ID'] = generateUUID();

  // Log outgoing requests
  console.log('Making request:', config.method, config.url);

  return config;
});

// Add response interceptor
client.interceptors.response.use(
  (response) => {
    console.log('Response received:', response.status);
    return response;
  },
  (error) => {
    console.error('Request failed:', error.response?.status);
    return Promise.reject(error);
  }
);

Batch Operations#

typescript
// Execute multiple operations in parallel
const [chatResponse, ttsResponse, healthStatus] = await Promise.all([
  client.chat.create({
    persona: 'zen_master',
    input: { text: 'What is meditation?' },
    mode: 'text',
  }),
  client.tts.synthesize({
    voice_id: 'calm_female_01',
    ssml: '<speak>Hello world</speak>',
    format: 'mp3',
  }),
  client.health.getStatus(),
]);

Conversation Management#

typescript
// Manage conversation context
class ConversationManager {
  private conversations = new Map<string, any[]>();

  async startConversation(userId: string, persona: string) {
    const conversationId = `conv_${Date.now()}_${userId}`;
    this.conversations.set(conversationId, []);

    return conversationId;
  }

  async sendMessage(conversationId: string, text: string) {
    const conversation = this.conversations.get(conversationId) || [];

    const response = await client.chat.create({
      conversation_id: conversationId,
      persona: this.getPersonaForConversation(conversationId),
      input: { text },
      mode: 'text',
    });

    // Store message and response
    conversation.push(
      { role: 'user', content: text },
      { role: 'assistant', content: response.text }
    );

    this.conversations.set(conversationId, conversation);
    return response;
  }

  getConversationHistory(conversationId: string) {
    return this.conversations.get(conversationId) || [];
  }
}

Content Ingestion#

typescript
// Submit content for knowledge base
const ingestion = await client.ingestion.submit({
  source_uri: 'https://example.org/wisdom-article.pdf',
  license: 'CC-BY-4.0',
  tags: ['meditation', 'mindfulness', 'research'],
  priority: 'normal',
  metadata: {
    title: 'The Science of Mindfulness',
    authors: ['Dr. Jane Smith'],
    publication_date: '2023-01-15',
  },
  webhook_url: 'https://yourapp.com/webhooks/ingestion-complete',
});

console.log('Ingestion Job ID:', ingestion.job_id);
console.log('Status:', ingestion.status);

Advanced Authentication#

typescript
// Multi-tenant authentication
const multiTenantClient = new LilithClient({
  apiKey: 'tenant-specific-key',
  headers: {
    'X-Tenant-ID': 'tenant_123',
  },
});

// OAuth authentication
const oauthAuth = await client.auth.oauth({
  provider: 'google',
  redirect_uri: 'https://yourapp.com/auth/callback',
  scope: 'read write',
});

// WebAuthn authentication
const webauthn = await client.auth.webauthn.authenticate({
  email: 'user@example.com',
});

Type Safety and Validation#

typescript
// Strict typing for chat requests
interface StrictChatRequest {
  persona: 'zen_master' | 'philosopher' | 'stoic' | 'mystic' | 'teacher';
  input:
    | {
        text: string;
      }
    | {
        audio: string; // base64 encoded
      };
  mode: 'text' | 'voice';
  options?: {
    cite?: boolean;
    depth?: 'practical' | 'scholarly';
    stream?: boolean;
    language?: string;
  };
}

// Runtime validation
import { z } from 'zod';

const ChatRequestSchema = z.object({
  persona: z.enum(['zen_master', 'philosopher', 'stoic', 'mystic', 'teacher']),
  input: z.union([
    z.object({ text: z.string().max(2000) }),
    z.object({ audio: z.string() }),
  ]),
  mode: z.enum(['text', 'voice']),
  options: z
    .object({
      cite: z.boolean().optional(),
      depth: z.enum(['practical', 'scholarly']).optional(),
      stream: z.boolean().optional(),
    })
    .optional(),
});

function validateChatRequest(request: unknown): StrictChatRequest {
  return ChatRequestSchema.parse(request);
}

Performance Optimization#

typescript
// Connection pooling
const client = new LilithClient({
  apiKey: 'your-key',
  pool: {
    maxConnections: 10,
    keepAlive: true,
    timeout: 5000,
  },
});

// Response caching
const cachedClient = new LilithClient({
  apiKey: 'your-key',
  cache: {
    enabled: true,
    ttl: 300000, // 5 minutes
    maxEntries: 1000,
  },
});

// Request retries with exponential backoff
const resilientClient = new LilithClient({
  apiKey: 'your-key',
  retry: {
    attempts: 3,
    exponentialBackoff: true,
    retryOn: [408, 429, 500, 502, 503, 504],
  },
});

Examples#

React Integration#

typescript
import React, { useState, useEffect } from 'react';
import { LilithClient } from '@lilith/sdk-ts';

const ChatComponent: React.FC = () => {
  const [client, setClient] = useState<LilithClient | null>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [input, setInput] = useState('');

  useEffect(() => {
    const lilithClient = new LilithClient({
      apiKey: process.env.REACT_APP_LILITH_API_KEY!
    });
    setClient(lilithClient);
  }, []);

  const sendMessage = async () => {
    if (!client || !input.trim()) return;

    try {
      const response = await client.chat.create({
        persona: 'zen_master',
        input: { text: input },
        mode: 'text',
        options: { stream: false, cite: true }
      });

      setMessages(prev => [
        ...prev,
        { role: 'user', content: input },
        { role: 'assistant', content: response.text, citations: response.citations }
      ]);

      setInput('');
    } catch (error) {
      console.error('Chat error:', error);
    }
  };

  return (
    <div>
      <div className="messages">
        {messages.map((msg, idx) => (
          <div key={idx} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
      />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
};

Node.js Server Integration#

typescript
import express from 'express';
import { LilithClient } from '@lilith/sdk-ts';

const app = express();
const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY!,
});

app.use(express.json());

app.post('/api/chat', async (req, res) => {
  try {
    const { message, persona } = req.body;

    const response = await client.chat.create({
      persona,
      input: { text: message },
      mode: 'text',
      options: { stream: false },
    });

    res.json({
      success: true,
      response: response.text,
      citations: response.citations,
    });
  } catch (error) {
    console.error('Chat API error:', error);
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

API Reference#

For complete API documentation, see: