# @lilith/sdk

A comprehensive TypeScript SDK for the Lilith AI Wisdom Platform. Works in
browsers, Node.js 18+, and edge runtime environments with native `fetch`
support.

## Features

- 🔐 **Authentication** - JWT token management and secure API communication
- 💬 **Real-time Chat** - Streaming and non-streaming chat with AI personas
- 🎵 **Text-to-Speech** - High-quality voice synthesis with multiple voices
- 📚 **Lecture Generation** - AI-powered content creation with citations
- 🔄 **Streaming Support** - Server-Sent Events (SSE) for real-time responses
- 📦 **Type Safety** - Full TypeScript support with comprehensive type
  definitions
- 🌐 **Universal** - Works in browsers, Node.js, and edge environments
- 🎯 **Lightweight** - Minimal dependencies with tree-shaking support

## Installation

### Local Development (Current)

This package is scaffolded in-repo; for local development:

```bash
# Install dependencies
npm install

# Build the SDK
npm run build

# Use via relative path or npm link
import { APIClient } from './dist/index.js';
```

### Future Published Package (TBD)

```bash
npm install @lilith/sdk
```

## Quick Start

### Basic Setup

```typescript
import { APIClient } from '@lilith/sdk';

// Initialize the client
const api = new APIClient({
  baseUrl: 'https://api.lilith.ai',
  token: 'your-jwt-token-here',
});
```

### Authentication

```typescript
import { APIClient } from '@lilith/sdk';

const api = new APIClient({
  baseUrl: 'https://api.lilith.ai',
});

// Sign up
const user = await api.auth.signUp({
  email: 'user@example.com',
  password: 'securePassword123',
  firstName: 'John',
  lastName: 'Doe',
});

// Sign in
const authResponse = await api.auth.signIn({
  email: 'user@example.com',
  password: 'securePassword123',
});

// Use the token for future requests
const authenticatedApi = new APIClient({
  baseUrl: 'https://api.lilith.ai',
  token: authResponse.access_token,
});
```

### Chat Interactions

#### Non-Streaming Chat

```typescript
const response = await api.chat({
  persona: 'zen_master',
  input: { text: 'How do I work with anger?' },
  mode: 'text',
  options: {
    stream: false,
    cite: true,
    temperature: 0.7,
    max_tokens: 1000,
  },
});

console.log(response.text);
console.log(response.citations); // Array of citations if requested
```

#### Streaming Chat (SSE)

```typescript
const chatStream = api.streamChat({
  persona: 'stoic_mentor',
  input: { text: 'A brief meditation practice, please.' },
  mode: 'text',
  options: {
    temperature: 0.8,
    stream: true,
  },
});

// Process streaming response
for await (const event of chatStream) {
  switch (event.event) {
    case 'token':
      // Individual token from the AI response
      process.stdout.write(event.data?.text ?? '');
      break;

    case 'citations':
      // Citations for the response
      console.log('Citations:', event.data);
      break;

    case 'audio':
      // Audio metadata (if audio generation enabled)
      console.log('Audio stream:', event.data);
      break;

    case 'done':
      // Streaming complete
      console.log('Response complete');
      break;

    case 'error':
      // Error occurred
      console.error('Error:', event.data);
      break;
  }
}
```

#### Voice Input

```typescript
// For voice input, you'll need to first convert speech to text
// Then send the text to chat
const voiceChatResponse = await api.chat({
  persona: 'meditation_guide',
  input: {
    text: transcribedText,
    audio_url: 'https://example.com/audio.wav', // Optional audio reference
  },
  mode: 'voice', // Enable voice-specific responses
  options: {
    stream: true,
    voice: 'calm_female_01',
  },
});
```

### Content Generation

#### Generate Lectures

```typescript
const lecture = await api.generateLecture({
  topic: 'Introduction to Mindfulness',
  duration_min: 10,
  tradition: ['Buddhism', 'Secular'],
  lang: 'en',
  voice: 'calm_male_01',
  outline_level: 'introductory',
  include_citations: true,
  target_audience: 'beginners',
});

console.log('Lecture generated:', lecture);
console.log('Audio stream URL:', lecture.stream_url);
console.log('Transcript:', lecture.transcript);
```

#### Generate Meditations

```typescript
const meditation = await api.generateMeditation({
  type: 'guided_meditation',
  duration_min: 5,
  tradition: 'vipassana',
  focus_area: 'breath_awareness',
  voice: 'calm_female_01',
  background_music: 'ambient_nature',
  include_affirmations: true,
});

console.log('Meditation script:', meditation.script);
console.log('Audio URL:', meditation.audio_url);
```

### Text-to-Speech

#### Basic TTS

```typescript
const ttsResponse = await api.synthesizeSpeech({
  text: 'Welcome to your meditation practice',
  voice: 'calm_female_01',
  format: 'mp3',
  speed: 1.0,
  pitch: 1.0,
});

console.log('Audio URL:', ttsResponse.audio_url);
```

#### Streaming TTS

```typescript
const ttsStream = api.streamSynthesizeSpeech({
  text: 'This is a longer text that will be streamed as audio',
  voice: 'calm_male_01',
  format: 'mp3',
});

// Process streaming audio chunks
for await (const event of ttsStream) {
  switch (event.event) {
    case 'audio_chunk':
      // Handle audio chunk data
      await playAudioChunk(event.data);
      break;
    case 'metadata':
      console.log('Audio metadata:', event.data);
      break;
    case 'complete':
      console.log('TTS generation complete');
      break;
    case 'error':
      console.error('TTS error:', event.data);
      break;
  }
}
```

## Advanced Usage

### Custom Configuration

```typescript
const api = new APIClient({
  baseUrl: 'https://api.lilith.ai',
  token: 'your-jwt-token',
  timeout: 30000, // 30 seconds timeout
  retries: 3, // Number of retry attempts
  headers: {
    'X-Custom-Header': 'custom-value',
  },
});
```

### Error Handling

```typescript
try {
  const response = await api.chat({
    persona: 'zen_master',
    input: { text: 'Your question here' },
  });
} catch (error) {
  if (error instanceof LilithAPIError) {
    switch (error.type) {
      case 'AuthenticationError':
        console.log('Please check your credentials');
        break;
      case 'RateLimitError':
        console.log('Rate limit exceeded. Please try again later.');
        break;
      case 'ValidationError':
        console.log('Invalid request:', error.details);
        break;
      case 'NetworkError':
        console.log('Network issue:', error.message);
        break;
      default:
        console.log('Unexpected error:', error.message);
    }
  }
}
```

### Working with Different Personas

```typescript
// Available personas
const personas = [
  'zen_master',
  'stoic_mentor',
  'buddhist_monk',
  'yoga_instructor',
  'mindfulness_coach',
  'philosophy_professor',
];

// Use different personas for specific needs
const philosophicalResponse = await api.chat({
  persona: 'philosophy_professor',
  input: { text: 'What is the meaning of life according to existentialism?' },
});

const meditationGuidance = await api.chat({
  persona: 'mindfulness_coach',
  input: { text: "I'm having trouble staying focused during meditation" },
});
```

### Content Customization

```typescript
const customizedLecture = await api.generateLecture({
  topic: 'The Four Noble Truths',
  duration_min: 15,
  tradition: ['Buddhism'],
  lang: 'en',
  voice: 'calm_female_01',
  outline_level: 'intermediate',
  include_citations: true,
  target_audience: 'intermediate',
  additional_context: {
    focus_areas: ['suffering', 'origin', 'cessation', 'path'],
    practical_applications: true,
    historical_context: false,
  },
});
```

## API Reference

### Authentication Methods

- `auth.signUp(userData)` - Create new user account
- `auth.signIn(credentials)` - Authenticate existing user
- `auth.refreshToken(refreshToken)` - Refresh access token
- `auth.signOut()` - Sign out current user

### Chat Methods

- `chat(request)` - Send chat message (non-streaming)
- `streamChat(request)` - Send chat message (streaming)
- `getThreadHistory(threadId)` - Retrieve conversation history
- `createThread(options)` - Create new conversation thread

### Content Generation Methods

- `generateLecture(request)` - Generate educational lecture
- `generateMeditation(request)` - Generate guided meditation
- `synthesizeSpeech(request)` - Convert text to speech
- `streamSynthesizeSpeech(request)` - Streaming text-to-speech

### Utility Methods

- `getVoices()` - List available TTS voices
- `getPersonas()` - List available AI personas
- `getUsageStats()` - Get API usage statistics

## Streaming Events

### Chat Stream Events

- `token` - Individual response token
- `citations` - Citation information
- `audio` - Audio metadata (if applicable)
- `done` - Stream completion
- `error` - Error information

### TTS Stream Events

- `audio_chunk` - Audio data chunk
- `metadata` - Audio metadata
- `complete` - Generation complete
- `error` - Error information

## TypeScript Support

The SDK includes comprehensive TypeScript types:

```typescript
interface ChatRequest {
  persona: string;
  input: {
    text: string;
    audio_url?: string;
  };
  mode: 'text' | 'voice';
  options?: {
    stream?: boolean;
    cite?: boolean;
    temperature?: number;
    max_tokens?: number;
    voice?: string;
  };
}

interface ChatResponse {
  text: string;
  citations?: Citation[];
  metadata?: Record<string, any>;
}

interface Citation {
  source: string;
  title: string;
  url?: string;
  relevance_score: number;
}
```

## Browser Support

- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+

## Node.js Support

- Node.js 18.0+
- Uses native `fetch` API
- Compatible with CommonJS and ES modules

## Environment Variables

```bash
# Optional environment variables
LILITH_API_BASE_URL=https://api.lilith.ai
LILITH_API_TIMEOUT=30000
LILITH_DEBUG=true
```

## Examples

See the `examples/` directory for complete examples:

- Basic chat application
- Voice integration example
- Lecture generation demo
- Meditation guide application

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request

## License

This SDK is licensed under the MIT License.

## Support

- GitHub Issues: https://github.com/lilith-ai/lilith-ts-sdk/issues
- Documentation: https://docs.lilith.ai
- Email: sdk-support@lilith.ai

---

**Lilith Development Team** Building the future of AI-powered wisdom and
wellness.
