Eve library

API Best Practices Guide

Guide

Revision 1

On this page

Comprehensive guide for building robust, secure, and performant applications with the Lilith API.

Table of Contents#

Security Best Practices#

1. API Key and Token Management#

Never hardcode credentials:

javascript
// ❌ Don't hardcode API keys
const apiKey = 'sk-1234567890abcdef';

// ✅ Use environment variables
const apiKey = process.env.LILITH_API_KEY;

// ✅ Use a secrets manager
const apiKey = await secretsManager.getSecret('lilith-api-key');

Secure storage by platform:

Platform Recommended Storage
Web (SPA) httpOnly cookies, memory only
Web (Server) Environment variables, secrets manager
iOS Keychain Services
Android EncryptedSharedPreferences
Desktop OS credential store

Token lifecycle management:

javascript
class TokenManager {
  constructor() {
    this.accessToken = null;
    this.refreshToken = null;
    this.expiresAt = null;
    this.refreshThreshold = 5 * 60 * 1000; // 5 minutes
  }

  async getValidToken() {
    // Check if token needs refresh
    if (this.shouldRefresh()) {
      await this.refreshAccessToken();
    }
    return this.accessToken;
  }

  shouldRefresh() {
    if (!this.accessToken || !this.expiresAt) return true;
    return Date.now() >= this.expiresAt - this.refreshThreshold;
  }

  async refreshAccessToken() {
    try {
      const response = await fetch('/v1/auth/refresh', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ refresh_token: this.refreshToken }),
      });

      if (!response.ok) {
        throw new Error('Token refresh failed');
      }

      const data = await response.json();
      this.accessToken = data.token;
      this.expiresAt = Date.now() + data.expires_in * 1000;
    } catch (error) {
      // Clear tokens on refresh failure
      this.clearTokens();
      throw error;
    }
  }

  clearTokens() {
    this.accessToken = null;
    this.refreshToken = null;
    this.expiresAt = null;
  }
}

2. Request Security#

Always use HTTPS:

javascript
// ❌ Never use HTTP
const response = await fetch('http://api.lilith.app/v1/chat');

// ✅ Always use HTTPS
const response = await fetch('https://api.lilith.app/v1/chat');

Include security headers:

javascript
const headers = {
  Authorization: `Bearer ${token}`,
  'Content-Type': 'application/json',
  'User-Agent': 'MyApp/1.0.0',
  'X-Request-ID': generateUUID(), // For request tracing
  'X-Idempotency-Key': generateIdempotencyKey(), // For safe retries
};

Validate SSL certificates:

javascript
// Node.js - Ensure SSL verification is enabled
const https = require('https');

const agent = new https.Agent({
  rejectUnauthorized: true, // Default, but be explicit
  minVersion: 'TLSv1.2',
});

fetch('https://api.lilith.app/v1/chat', { agent });

3. Input Validation#

Validate before sending:

javascript
function validateChatRequest(input) {
  const errors = [];

  if (!input.persona || !isValidPersona(input.persona)) {
    errors.push('Invalid persona');
  }

  if (!input.text || input.text.length === 0) {
    errors.push('Text is required');
  }

  if (input.text && input.text.length > 10000) {
    errors.push('Text exceeds maximum length');
  }

  if (errors.length > 0) {
    throw new ValidationError(errors);
  }

  return sanitizeInput(input);
}

function sanitizeInput(input) {
  return {
    ...input,
    text: input.text.trim(),
    // Remove any potentially dangerous content
    metadata: sanitizeMetadata(input.metadata),
  };
}

4. Sensitive Data Handling#

Never log sensitive data:

javascript
// ❌ Don't log tokens or sensitive data
console.log('Request:', { token, user_id, password });

// ✅ Redact sensitive fields
console.log('Request:', {
  token: '[REDACTED]',
  user_id,
  password: '[REDACTED]',
});

// ✅ Use structured logging with redaction
logger.info('API request', {
  endpoint: '/v1/chat',
  user_id,
  // Token automatically redacted by logger config
});

Error Handling#

1. Error Response Structure#

The Lilith API returns errors in a consistent format:

json
{
  "error": {
    "type": "https://docs.lilith.app/errors/validation_error",
    "title": "Validation Error",
    "status": 400,
    "detail": "The 'persona' field is required",
    "code": "validation_error",
    "trace_id": "abc123def456",
    "errors": [
      {
        "field": "persona",
        "message": "This field is required"
      }
    ]
  }
}

2. Comprehensive Error Handler#

javascript
class APIError extends Error {
  constructor(response, body) {
    super(body.error?.detail || 'API Error');
    this.name = 'APIError';
    this.status = response.status;
    this.code = body.error?.code;
    this.traceId = body.error?.trace_id;
    this.errors = body.error?.errors || [];
    this.retryable = this.isRetryable();
  }

  isRetryable() {
    // 429 (rate limit) and 5xx errors are retryable
    return this.status === 429 || this.status >= 500;
  }
}

async function apiRequest(url, options = {}) {
  const response = await fetch(url, {
    ...options,
    headers: {
      Authorization: `Bearer ${await tokenManager.getValidToken()}`,
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  if (!response.ok) {
    const body = await response.json().catch(() => ({}));

    // Handle specific error codes
    switch (response.status) {
      case 401:
        // Token expired - try refresh
        if (body.error?.code === 'token_expired') {
          await tokenManager.refreshAccessToken();
          return apiRequest(url, options); // Retry once
        }
        // Invalid token - redirect to login
        redirectToLogin();
        break;

      case 403:
        // Insufficient permissions
        throw new PermissionError(body.error?.detail);

      case 429:
        // Rate limited - will be handled by retry logic
        break;

      default:
        // Log error with trace ID for debugging
        console.error('API Error:', {
          status: response.status,
          code: body.error?.code,
          traceId: body.error?.trace_id,
          detail: body.error?.detail,
        });
    }

    throw new APIError(response, body);
  }

  return response.json();
}

3. Error Recovery Patterns#

javascript
class ErrorRecovery {
  static async withRecovery(operation, options = {}) {
    const {
      maxRetries = 3,
      onRetry = () => {},
      shouldRetry = (error) => error.retryable,
    } = options;

    let lastError;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        lastError = error;

        if (attempt === maxRetries || !shouldRetry(error)) {
          throw error;
        }

        // Calculate backoff
        const delay = this.calculateBackoff(error, attempt);

        onRetry({ attempt, error, delay });

        await this.sleep(delay);
      }
    }

    throw lastError;
  }

  static calculateBackoff(error, attempt) {
    // Use Retry-After header if present
    if (error.retryAfter) {
      return error.retryAfter * 1000;
    }

    // Exponential backoff with jitter
    const baseDelay = 1000;
    const maxDelay = 30000;
    const exponentialDelay = Math.min(
      baseDelay * Math.pow(2, attempt - 1),
      maxDelay
    );
    const jitter = Math.random() * 0.3 * exponentialDelay;

    return exponentialDelay + jitter;
  }

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

// Usage
const result = await ErrorRecovery.withRecovery(
  () => apiRequest('/v1/chat', { method: 'POST', body }),
  {
    maxRetries: 3,
    onRetry: ({ attempt, error, delay }) => {
      console.log(`Retry ${attempt} after ${delay}ms: ${error.message}`);
    },
  }
);

Rate Limiting Strategies#

1. Respect Rate Limit Headers#

javascript
class RateLimitAwareClient {
  constructor() {
    this.rateLimitInfo = {
      limit: Infinity,
      remaining: Infinity,
      resetAt: null,
    };
  }

  updateRateLimitInfo(response) {
    const limit = response.headers.get('RateLimit-Limit');
    const remaining = response.headers.get('RateLimit-Remaining');
    const reset = response.headers.get('RateLimit-Reset');

    if (limit) this.rateLimitInfo.limit = parseInt(limit);
    if (remaining) this.rateLimitInfo.remaining = parseInt(remaining);
    if (reset) this.rateLimitInfo.resetAt = new Date(parseInt(reset) * 1000);
  }

  async request(url, options) {
    // Check if we should wait before making request
    await this.waitIfNeeded();

    const response = await fetch(url, options);
    this.updateRateLimitInfo(response);

    if (response.status === 429) {
      const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
      await this.sleep(retryAfter * 1000);
      return this.request(url, options); // Retry
    }

    return response;
  }

  async waitIfNeeded() {
    if (this.rateLimitInfo.remaining <= 0 && this.rateLimitInfo.resetAt) {
      const waitTime = this.rateLimitInfo.resetAt - Date.now();
      if (waitTime > 0) {
        console.log(`Rate limit reached, waiting ${waitTime}ms`);
        await this.sleep(waitTime);
      }
    }
  }

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

2. Client-Side Rate Limiting#

Prevent hitting rate limits by implementing client-side throttling:

javascript
class Throttle {
  constructor(maxRequests, windowMs) {
    this.maxRequests = maxRequests;
    this.windowMs = windowMs;
    this.requests = [];
    this.queue = [];
  }

  async acquire() {
    return new Promise((resolve) => {
      this.queue.push(resolve);
      this.processQueue();
    });
  }

  processQueue() {
    const now = Date.now();

    // Remove old requests outside the window
    this.requests = this.requests.filter((time) => now - time < this.windowMs);

    // Process queued requests if capacity available
    while (this.queue.length > 0 && this.requests.length < this.maxRequests) {
      const resolve = this.queue.shift();
      this.requests.push(now);
      resolve();
    }

    // Schedule next processing if queue not empty
    if (this.queue.length > 0) {
      const oldestRequest = this.requests[0];
      const nextSlot = oldestRequest + this.windowMs - now;
      setTimeout(() => this.processQueue(), nextSlot);
    }
  }
}

// Usage: 60 requests per minute
const throttle = new Throttle(60, 60000);

async function throttledRequest(url, options) {
  await throttle.acquire();
  return fetch(url, options);
}

3. Request Batching#

Combine multiple requests to reduce API calls:

javascript
class RequestBatcher {
  constructor(batchSize = 10, delayMs = 50) {
    this.batchSize = batchSize;
    this.delayMs = delayMs;
    this.queue = [];
    this.timer = null;
  }

  add(request) {
    return new Promise((resolve, reject) => {
      this.queue.push({ request, resolve, reject });

      if (this.queue.length >= this.batchSize) {
        this.flush();
      } else if (!this.timer) {
        this.timer = setTimeout(() => this.flush(), this.delayMs);
      }
    });
  }

  async flush() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }

    const batch = this.queue.splice(0, this.batchSize);
    if (batch.length === 0) return;

    try {
      const response = await fetch('/v1/batch', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          requests: batch.map((b) => b.request),
        }),
      });

      const results = await response.json();

      batch.forEach((item, index) => {
        if (results[index].error) {
          item.reject(new Error(results[index].error));
        } else {
          item.resolve(results[index].data);
        }
      });
    } catch (error) {
      batch.forEach((item) => item.reject(error));
    }
  }
}

// Usage
const batcher = new RequestBatcher();

// These will be batched together
const results = await Promise.all([
  batcher.add({ path: '/v1/content/1' }),
  batcher.add({ path: '/v1/content/2' }),
  batcher.add({ path: '/v1/content/3' }),
]);

Performance Optimization#

1. Request Optimization#

Only request what you need:

javascript
// ❌ Fetching all fields
const response = await fetch('/v1/content/courses');

// ✅ Use field selection
const response = await fetch('/v1/content/courses?fields=id,title,duration');

Use appropriate pagination:

javascript
// ❌ Fetching maximum limit always
const response = await fetch('/v1/content/courses?limit=100');

// ✅ Match your UI needs
const response = await fetch('/v1/content/courses?limit=20'); // If showing 20 per page

2. Connection Management#

javascript
// Reuse connections with connection pooling
const https = require('https');
const http = require('http');

const agent = new https.Agent({
  keepAlive: true,
  maxSockets: 50,
  maxFreeSockets: 10,
  timeout: 60000,
});

const client = {
  request: (url, options) => fetch(url, { ...options, agent }),
};

3. Streaming for Large Responses#

javascript
// For AI chat responses, use streaming
async function streamChat(message) {
  const response = await fetch('/v1/chat', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
      Accept: 'text/event-stream',
    },
    body: JSON.stringify({
      input: { text: message },
      options: { stream: true },
    }),
  });

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

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

    const chunk = decoder.decode(value);
    // Process streaming tokens as they arrive
    processStreamChunk(chunk);
  }
}

Caching Patterns#

1. In-Memory Cache#

javascript
class APICache {
  constructor(options = {}) {
    this.cache = new Map();
    this.defaultTTL = options.defaultTTL || 300000; // 5 minutes
    this.maxSize = options.maxSize || 1000;
  }

  generateKey(url, options = {}) {
    const params = new URLSearchParams(options.params).toString();
    return `${options.method || 'GET'}:${url}${params ? '?' + params : ''}`;
  }

  get(key) {
    const entry = this.cache.get(key);
    if (!entry) return null;

    if (Date.now() > entry.expiresAt) {
      this.cache.delete(key);
      return null;
    }

    return entry.data;
  }

  set(key, data, ttl = this.defaultTTL) {
    // Evict oldest entries if cache is full
    if (this.cache.size >= this.maxSize) {
      const oldestKey = this.cache.keys().next().value;
      this.cache.delete(oldestKey);
    }

    this.cache.set(key, {
      data,
      expiresAt: Date.now() + ttl,
      createdAt: Date.now(),
    });
  }

  invalidate(pattern) {
    for (const key of this.cache.keys()) {
      if (key.includes(pattern)) {
        this.cache.delete(key);
      }
    }
  }

  async getOrFetch(url, options = {}) {
    const key = this.generateKey(url, options);
    const cached = this.get(key);

    if (cached) {
      return cached;
    }

    const response = await fetch(url, options);
    const data = await response.json();

    // Only cache successful responses
    if (response.ok) {
      this.set(key, data, options.ttl);
    }

    return data;
  }
}

const cache = new APICache({ defaultTTL: 60000 }); // 1 minute default

// Usage
const courses = await cache.getOrFetch('/v1/content/courses', {
  ttl: 300000, // Cache for 5 minutes
});

2. Cache Invalidation#

javascript
class CacheInvalidator {
  constructor(cache) {
    this.cache = cache;
    this.patterns = {
      'content.created': ['content:list', 'content:search'],
      'content.updated': (event) => [
        `content:${event.data.id}`,
        'content:list',
      ],
      'content.deleted': (event) => [
        `content:${event.data.id}`,
        'content:list',
      ],
    };
  }

  invalidateForEvent(event) {
    const patterns = this.patterns[event.type];

    if (!patterns) return;

    const keysToInvalidate =
      typeof patterns === 'function' ? patterns(event) : patterns;

    keysToInvalidate.forEach((pattern) => {
      this.cache.invalidate(pattern);
    });
  }
}

3. Conditional Requests#

javascript
class ConditionalCache {
  constructor() {
    this.etags = new Map();
  }

  async request(url, options = {}) {
    const cachedEtag = this.etags.get(url);

    const headers = { ...options.headers };
    if (cachedEtag) {
      headers['If-None-Match'] = cachedEtag.etag;
    }

    const response = await fetch(url, { ...options, headers });

    if (response.status === 304) {
      // Not modified - return cached data
      return cachedEtag.data;
    }

    const data = await response.json();
    const newEtag = response.headers.get('ETag');

    if (newEtag) {
      this.etags.set(url, { etag: newEtag, data });
    }

    return data;
  }
}

Retry Logic#

1. Exponential Backoff with Jitter#

javascript
class RetryHandler {
  constructor(options = {}) {
    this.maxRetries = options.maxRetries || 3;
    this.baseDelay = options.baseDelay || 1000;
    this.maxDelay = options.maxDelay || 30000;
    this.jitterFactor = options.jitterFactor || 0.3;
  }

  async execute(operation) {
    let lastError;

    for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        lastError = error;

        if (attempt === this.maxRetries || !this.shouldRetry(error)) {
          throw error;
        }

        const delay = this.calculateDelay(error, attempt);
        await this.sleep(delay);
      }
    }

    throw lastError;
  }

  shouldRetry(error) {
    // Retry on rate limits and server errors
    if (error.status === 429) return true;
    if (error.status >= 500 && error.status < 600) return true;

    // Retry on network errors
    if (error.name === 'TypeError' && error.message.includes('fetch')) {
      return true;
    }

    return false;
  }

  calculateDelay(error, attempt) {
    // Use Retry-After header if available
    if (error.retryAfter) {
      return error.retryAfter * 1000;
    }

    // Exponential backoff
    const exponentialDelay = this.baseDelay * Math.pow(2, attempt);
    const cappedDelay = Math.min(exponentialDelay, this.maxDelay);

    // Add jitter to prevent thundering herd
    const jitter = cappedDelay * this.jitterFactor * Math.random();

    return cappedDelay + jitter;
  }

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

// Usage
const retryHandler = new RetryHandler({ maxRetries: 3 });

const result = await retryHandler.execute(async () => {
  const response = await fetch('/v1/chat', options);
  if (!response.ok) {
    const error = new Error('Request failed');
    error.status = response.status;
    throw error;
  }
  return response.json();
});

2. Circuit Breaker#

javascript
class CircuitBreaker {
  constructor(options = {}) {
    this.failureThreshold = options.failureThreshold || 5;
    this.resetTimeout = options.resetTimeout || 60000;
    this.state = 'closed';
    this.failures = 0;
    this.lastFailureTime = null;
  }

  async execute(operation) {
    if (this.state === 'open') {
      if (Date.now() - this.lastFailureTime >= this.resetTimeout) {
        this.state = 'half-open';
      } else {
        throw new Error('Circuit breaker is open');
      }
    }

    try {
      const result = await operation();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }

  onSuccess() {
    this.failures = 0;
    this.state = 'closed';
  }

  onFailure() {
    this.failures++;
    this.lastFailureTime = Date.now();

    if (this.failures >= this.failureThreshold) {
      this.state = 'open';
      console.warn('Circuit breaker opened due to failures');
    }
  }

  getState() {
    return {
      state: this.state,
      failures: this.failures,
      lastFailure: this.lastFailureTime,
    };
  }
}

// Usage
const circuitBreaker = new CircuitBreaker({
  failureThreshold: 5,
  resetTimeout: 60000,
});

try {
  const result = await circuitBreaker.execute(() => fetch('/v1/chat', options));
} catch (error) {
  if (error.message === 'Circuit breaker is open') {
    // Show cached data or fallback UI
    showOfflineMode();
  }
}

Logging and Monitoring#

1. Structured Logging#

javascript
class APILogger {
  constructor(options = {}) {
    this.serviceName = options.serviceName || 'lilith-client';
    this.sensitiveFields = ['token', 'password', 'secret', 'authorization'];
  }

  log(level, message, context = {}) {
    const entry = {
      timestamp: new Date().toISOString(),
      level,
      service: this.serviceName,
      message,
      ...this.sanitize(context),
    };

    console[level](JSON.stringify(entry));
  }

  sanitize(obj) {
    const sanitized = {};

    for (const [key, value] of Object.entries(obj)) {
      if (this.sensitiveFields.some((f) => key.toLowerCase().includes(f))) {
        sanitized[key] = '[REDACTED]';
      } else if (typeof value === 'object' && value !== null) {
        sanitized[key] = this.sanitize(value);
      } else {
        sanitized[key] = value;
      }
    }

    return sanitized;
  }

  request(url, options) {
    this.log('info', 'API request', {
      url,
      method: options.method || 'GET',
      headers: options.headers,
    });
  }

  response(url, response, duration) {
    this.log('info', 'API response', {
      url,
      status: response.status,
      duration_ms: duration,
      rateLimit: {
        remaining: response.headers.get('RateLimit-Remaining'),
        limit: response.headers.get('RateLimit-Limit'),
      },
    });
  }

  error(url, error, context = {}) {
    this.log('error', 'API error', {
      url,
      error: error.message,
      code: error.code,
      traceId: error.traceId,
      ...context,
    });
  }
}

const logger = new APILogger({ serviceName: 'my-app' });

2. Performance Monitoring#

javascript
class APIMetrics {
  constructor() {
    this.metrics = {
      requests: 0,
      errors: 0,
      latencies: [],
      rateLimitHits: 0,
    };
  }

  recordRequest(url, method, duration, status) {
    this.metrics.requests++;

    if (status >= 400) {
      this.metrics.errors++;
    }

    if (status === 429) {
      this.metrics.rateLimitHits++;
    }

    this.metrics.latencies.push({
      url,
      method,
      duration,
      status,
      timestamp: Date.now(),
    });

    // Keep only last 1000 latency records
    if (this.metrics.latencies.length > 1000) {
      this.metrics.latencies.shift();
    }
  }

  getStats() {
    const latencies = this.metrics.latencies.map((l) => l.duration);

    return {
      totalRequests: this.metrics.requests,
      errorRate: this.metrics.errors / this.metrics.requests,
      rateLimitHits: this.metrics.rateLimitHits,
      latency: {
        avg: latencies.reduce((a, b) => a + b, 0) / latencies.length,
        p50: this.percentile(latencies, 50),
        p95: this.percentile(latencies, 95),
        p99: this.percentile(latencies, 99),
      },
    };
  }

  percentile(arr, p) {
    const sorted = [...arr].sort((a, b) => a - b);
    const index = Math.ceil(sorted.length * (p / 100)) - 1;
    return sorted[index];
  }
}

const metrics = new APIMetrics();

// Wrapper to collect metrics
async function instrumentedFetch(url, options = {}) {
  const start = Date.now();

  try {
    const response = await fetch(url, options);
    metrics.recordRequest(
      url,
      options.method || 'GET',
      Date.now() - start,
      response.status
    );
    return response;
  } catch (error) {
    metrics.recordRequest(url, options.method || 'GET', Date.now() - start, 0);
    throw error;
  }
}

Testing Strategies#

1. Unit Testing API Clients#

javascript
// Mock fetch for unit tests
global.fetch = jest.fn();

describe('LilithClient', () => {
  beforeEach(() => {
    fetch.mockClear();
  });

  describe('chat', () => {
    it('should send chat request with correct parameters', async () => {
      fetch.mockResolvedValueOnce({
        ok: true,
        json: () =>
          Promise.resolve({
            message_id: 'msg_123',
            text: 'Response text',
          }),
      });

      const client = new LilithClient({ apiKey: 'test-key' });
      const result = await client.chat({
        persona: 'zen_master',
        text: 'Hello',
      });

      expect(fetch).toHaveBeenCalledWith(
        expect.stringContaining('/v1/chat'),
        expect.objectContaining({
          method: 'POST',
          headers: expect.objectContaining({
            Authorization: 'Bearer test-key',
          }),
        })
      );

      expect(result.text).toBe('Response text');
    });

    it('should handle rate limit errors with retry', async () => {
      fetch
        .mockResolvedValueOnce({
          ok: false,
          status: 429,
          headers: new Headers({ 'Retry-After': '1' }),
          json: () =>
            Promise.resolve({ error: { code: 'rate_limit_exceeded' } }),
        })
        .mockResolvedValueOnce({
          ok: true,
          json: () => Promise.resolve({ text: 'Success' }),
        });

      const client = new LilithClient({ apiKey: 'test-key' });
      const result = await client.chat({
        persona: 'zen_master',
        text: 'Hello',
      });

      expect(fetch).toHaveBeenCalledTimes(2);
      expect(result.text).toBe('Success');
    });
  });
});

2. Integration Testing#

javascript
describe('API Integration', () => {
  const client = new LilithClient({
    apiKey: process.env.LILITH_TEST_API_KEY,
    baseUrl: process.env.LILITH_TEST_BASE_URL,
  });

  it('should authenticate and make API calls', async () => {
    // Health check
    const health = await client.health();
    expect(health.status).toBe('ok');

    // Chat interaction
    const chat = await client.chat({
      persona: 'zen_master',
      text: 'What is mindfulness?',
    });

    expect(chat.message_id).toBeDefined();
    expect(chat.text).toBeTruthy();
  });

  it('should handle streaming responses', async () => {
    const chunks = [];

    await client.chatStream(
      {
        persona: 'zen_master',
        text: 'Explain meditation briefly',
      },
      (chunk) => {
        chunks.push(chunk);
      }
    );

    expect(chunks.length).toBeGreaterThan(0);
    expect(chunks.some((c) => c.type === 'token')).toBe(true);
    expect(chunks.some((c) => c.type === 'done')).toBe(true);
  });
});

API Versioning#

1. Handling API Versions#

javascript
class VersionedAPIClient {
  constructor(options = {}) {
    this.baseUrl = options.baseUrl || 'https://api.lilith.app';
    this.apiVersion = options.apiVersion || '2025-01-01';
  }

  async request(endpoint, options = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        ...options.headers,
        'Lilith-Version': this.apiVersion,
      },
    });

    // Check for deprecation warnings
    const deprecationWarning = response.headers.get(
      'X-Lilith-Deprecation-Warning'
    );
    if (deprecationWarning) {
      console.warn(`API Deprecation Warning: ${deprecationWarning}`);
    }

    return response;
  }
}

2. Version Migration#

javascript
class VersionMigrator {
  constructor() {
    this.migrations = new Map();
  }

  registerMigration(fromVersion, toVersion, transformer) {
    this.migrations.set(`${fromVersion}->${toVersion}`, transformer);
  }

  transform(data, fromVersion, toVersion) {
    const migrationKey = `${fromVersion}->${toVersion}`;
    const migration = this.migrations.get(migrationKey);

    if (!migration) {
      throw new Error(`No migration path from ${fromVersion} to ${toVersion}`);
    }

    return migration(data);
  }
}

// Example migration
const migrator = new VersionMigrator();

migrator.registerMigration('2024-01-01', '2025-01-01', (data) => {
  // Transform old response format to new format
  return {
    ...data,
    message_id: data.id, // Field renamed
    created_at: data.timestamp, // Field renamed
  };
});

SDK Usage#

1. TypeScript SDK Setup#

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

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
  baseUrl: 'https://api.lilith.app',
  timeout: 30000,
  retries: 3,
});

// Type-safe API calls
const response = await client.chat.create({
  persona: 'zen_master',
  input: { text: 'What is mindfulness?' },
  options: { stream: false },
});

// Streaming with proper types
for await (const chunk of client.chat.stream({
  persona: 'zen_master',
  input: { text: 'Explain meditation' },
})) {
  if (chunk.type === 'token') {
    process.stdout.write(chunk.token);
  }
}

2. SDK Best Practices#

typescript
// Create a singleton client
let clientInstance: LilithClient | null = null;

export function getClient(): LilithClient {
  if (!clientInstance) {
    clientInstance = new LilithClient({
      apiKey: process.env.LILITH_API_KEY!,
      // Use custom fetch for additional features
      fetch: instrumentedFetch,
    });
  }
  return clientInstance;
}

// Use typed request builders
import { ChatRequestBuilder } from '@lilith/sdk-ts';

const request = new ChatRequestBuilder()
  .persona('zen_master')
  .text('What is mindfulness?')
  .withCitations(true)
  .depth('practical')
  .build();

const response = await getClient().chat.create(request);

Summary Checklist#

Before Production#

  • API keys stored securely (not in code)
  • Token refresh implemented
  • Error handling covers all status codes
  • Retry logic with exponential backoff
  • Rate limiting respected
  • Caching implemented where appropriate
  • Logging configured (without sensitive data)
  • Monitoring and metrics in place
  • Tests covering critical paths
  • SSL/TLS properly configured

Performance Checklist#

  • Connection pooling enabled
  • Request batching where applicable
  • Streaming used for large responses
  • Appropriate pagination limits
  • Cache invalidation strategy defined
  • Circuit breaker for resilience

Security Checklist#

  • HTTPS only
  • Webhook signatures verified
  • Input validation implemented
  • Sensitive data never logged
  • Tokens stored securely by platform
  • Credentials rotated regularly