# Chat API Reference

Complete reference for Lilith's conversational AI APIs including chat,
conversations, personas, and streaming.

---

## Chat Endpoints

### Send Chat Message

```http
POST /v1/chat
```

Send a message to an AI persona and receive a response.

**Request Body:**

```json
{
  "conversation_id": "conv_abc123",
  "persona": "zen-master",
  "input": {
    "text": "What is the nature of mindfulness?",
    "audio": null
  },
  "mode": "text",
  "options": {
    "cite": true,
    "depth": "scholarly",
    "tone": "gentle",
    "language": "en"
  }
}
```

**Response (Streaming SSE):**

```
event: token
data: {"text": "Mindfulness", "index": 0}

event: token
data: {"text": " is", "index": 1}

event: citation
data: {"source": "Satipatthana Sutta", "url": "...", "span": "..."}

event: done
data: {"message_id": "msg_xyz", "total_tokens": 150}
```

**Response (Non-streaming):**

```json
{
  "message_id": "msg_xyz789",
  "conversation_id": "conv_abc123",
  "text": "Mindfulness is the quality of being fully present...",
  "citations": [
    {
      "source": "Satipatthana Sutta",
      "url": "https://lilith.app/sources/satipatthana",
      "text_span": "awareness of the body...",
      "confidence": 0.95
    }
  ],
  "audio_url": null,
  "metrics": {
    "latency_ms": 450,
    "tokens_in": 12,
    "tokens_out": 150
  }
}
```

### Chat Completion (OpenAI-compatible)

```http
POST /v1/chat/completion
```

OpenAI-compatible chat completion endpoint for drop-in replacement.

**Request Body:**

```json
{
  "model": "lilith-guide-v1",
  "messages": [
    { "role": "system", "content": "You are a Zen meditation guide." },
    { "role": "user", "content": "Guide me through a breathing exercise." }
  ],
  "temperature": 0.7,
  "max_tokens": 500,
  "stream": true
}
```

---

## Conversations

### Create Conversation

```http
POST /v1/conversations
```

**Request Body:**

```json
{
  "persona": "stoic-mentor",
  "title": "Evening reflection",
  "metadata": {
    "session_type": "meditation",
    "tradition": "stoicism"
  }
}
```

**Response:**

```json
{
  "conversation_id": "conv_new123",
  "persona": "stoic-mentor",
  "created_at": "2026-01-03T10:00:00Z",
  "title": "Evening reflection"
}
```

### List Conversations

```http
GET /v1/conversations
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `limit` | number | Max results (default:
20, max: 100) | | `offset` | number | Pagination offset | | `persona` | string |
Filter by persona | | `since` | ISO8601 | Filter by date |

**Response:**

```json
{
  "conversations": [
    {
      "conversation_id": "conv_abc123",
      "persona": "zen-master",
      "title": "Morning meditation",
      "message_count": 12,
      "created_at": "2026-01-02T08:00:00Z",
      "updated_at": "2026-01-02T08:30:00Z"
    }
  ],
  "total": 45,
  "has_more": true
}
```

### Get Conversation

```http
GET /v1/conversations/{conversationId}
```

**Response:**

```json
{
  "conversation_id": "conv_abc123",
  "persona": "zen-master",
  "title": "Morning meditation",
  "messages": [
    {
      "message_id": "msg_001",
      "role": "user",
      "text": "Good morning. I'd like to meditate.",
      "created_at": "2026-01-02T08:00:00Z"
    },
    {
      "message_id": "msg_002",
      "role": "assistant",
      "text": "Good morning. Let us begin with awareness of breath...",
      "citations": [...],
      "created_at": "2026-01-02T08:00:05Z"
    }
  ],
  "metadata": {...}
}
```

### Get Conversation Messages

```http
GET /v1/conversations/{conversationId}/messages
```

Paginated message retrieval for long conversations.

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `limit` | number | Max messages
(default: 50) | | `before` | string | Message ID for cursor pagination | |
`after` | string | Message ID for cursor pagination |

### Delete Conversation

```http
DELETE /v1/conversations/{conversationId}
```

### Reset Conversation

```http
POST /v1/conversations/{conversationId}/reset
```

Clears conversation history while preserving metadata.

---

## Personas

### List Personas

```http
GET /v1/personas
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `tradition` | string | Filter by tradition
(zen, stoic, sufi, etc.) | | `style` | string | Filter by teaching style | |
`language` | string | Filter by supported language |

**Response:**

```json
{
  "personas": [
    {
      "persona_id": "zen-master",
      "name": "Zen Master Takeshi",
      "description": "A gentle guide in the Zen Buddhist tradition...",
      "tradition": "zen",
      "teaching_style": ["gentle", "socratic", "experiential"],
      "voice_id": "zen-master-01",
      "avatar_url": "https://cdn.lilith.app/avatars/zen-master.png",
      "capabilities": ["meditation", "koans", "mindfulness"]
    }
  ]
}
```

### Get Persona Details

```http
GET /v1/personas/{personaId}
```

**Response:**

```json
{
  "persona_id": "zen-master",
  "name": "Zen Master Takeshi",
  "description": "...",
  "tradition": "zen",
  "lineage": "Rinzai",
  "teaching_style": ["gentle", "socratic"],
  "personality_traits": {
    "warmth": 0.8,
    "formality": 0.6,
    "directness": 0.7,
    "humor": 0.4
  },
  "voice_id": "zen-master-01",
  "supported_languages": ["en", "ja"],
  "topics": ["meditation", "koans", "impermanence", "mindfulness"],
  "boundaries": ["no_medical_advice", "no_predictions"],
  "sample_prompts": [
    "What is the sound of one hand clapping?",
    "Guide me through zazen meditation"
  ]
}
```

### Persona Settings

```http
GET /v1/personas/{personaId}/settings
PATCH /v1/personas/{personaId}/settings
```

User-specific persona customization:

```json
{
  "tone": "challenging",
  "depth": "scholarly",
  "cite_mode": "dense",
  "audio_enabled": true,
  "preferred_voice": "zen-master-02"
}
```

---

## Citations

### Get Message Citations

```http
GET /v1/conversations/{conversationId}/messages/{messageId}/citations
```

**Response:**

```json
{
  "citations": [
    {
      "citation_id": "cite_001",
      "source": "Satipatthana Sutta",
      "source_url": "https://lilith.app/sources/satipatthana",
      "text_span": "awareness of the body in the body...",
      "page": 12,
      "tradition": "theravada",
      "confidence": 0.95,
      "license": "public_domain"
    }
  ]
}
```

### Verify Citation

```http
GET /v1/citations/{citationId}
```

---

## Streaming

### SSE Streaming

Chat responses are streamed via Server-Sent Events (SSE).

**Event Types:** | Event | Description | |-------|-------------| | `token` |
Individual text token | | `citation` | Citation reference | | `tool_call` | Tool
invocation | | `tool_result` | Tool response | | `metrics` | Response metrics |
| `done` | Stream complete | | `error` | Error occurred |

**Connection:**

```javascript
const eventSource = new EventSource('/v1/chat?stream=true', {
  headers: { Authorization: 'Bearer <token>' },
});

eventSource.addEventListener('token', (e) => {
  const data = JSON.parse(e.data);
  console.log(data.text);
});
```

### WebSocket Chat

```http
WS /v1/chat/ws
```

For bidirectional real-time chat with voice support.

**Message Format:**

```json
{
  "type": "message",
  "conversation_id": "conv_123",
  "content": {
    "text": "Hello",
    "audio": "<base64>"
  }
}
```

---

## Comparative Views

### Compare Tradition Responses

```http
POST /v1/chat/compare
```

Get parallel responses from multiple personas on the same question.

**Request Body:**

```json
{
  "question": "What is the nature of suffering?",
  "personas": ["zen-master", "stoic-mentor", "sufi-mystic"],
  "options": {
    "include_synthesis": true
  }
}
```

**Response:**

```json
{
  "question": "What is the nature of suffering?",
  "responses": [
    {
      "persona": "zen-master",
      "text": "Suffering arises from attachment...",
      "citations": [...]
    },
    {
      "persona": "stoic-mentor",
      "text": "Suffering is not in events themselves...",
      "citations": [...]
    },
    {
      "persona": "sufi-mystic",
      "text": "The pain of separation from the Beloved...",
      "citations": [...]
    }
  ],
  "synthesis": "While each tradition approaches suffering differently...",
  "common_themes": ["attachment", "perception", "transformation"]
}
```

---

## Daily Content

### Get Daily Reflection

```http
GET /v1/chat/daily
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `tradition` | string | Preferred tradition
| | `persona` | string | Preferred persona | | `date` | ISO8601 | Specific date
|

---

## Context & Memory

### Get Conversation Context

```http
GET /v1/conversations/{conversationId}/context
```

**Response:**

```json
{
  "summary": "User is exploring mindfulness practices...",
  "topics_discussed": ["breath awareness", "walking meditation"],
  "user_interests": ["beginner", "stress_relief"],
  "session_count": 5
}
```

### Update Context

```http
PATCH /v1/conversations/{conversationId}/context
```

---

## Feedback & Ratings

### Rate Response

```http
POST /v1/conversations/{conversationId}/messages/{messageId}/feedback
```

**Request Body:**

```json
{
  "rating": 5,
  "helpful": true,
  "accurate": true,
  "flags": [],
  "comment": "Very insightful response"
}
```

### Report Message

```http
POST /v1/conversations/{conversationId}/messages/{messageId}/report
```

**Request Body:**

```json
{
  "reason": "inaccurate_citation",
  "details": "The source attribution appears incorrect"
}
```

---

## Error Codes

| Code                       | Description                       |
| -------------------------- | --------------------------------- |
| `chat.rate_limited`        | Request limit exceeded            |
| `chat.model_unavailable`   | AI model temporarily unavailable  |
| `chat.guardrail_violation` | Response blocked by safety filter |
| `chat.context_exceeded`    | Conversation context too long     |
| `persona.not_found`        | Persona ID not found              |
| `conversation.not_found`   | Conversation ID not found         |

---

## Rate Limits

| Endpoint          | Limit       |
| ----------------- | ----------- |
| Chat messages     | 60 req/min  |
| Conversation list | 100 req/min |
| Persona queries   | 200 req/min |
| Comparative views | 10 req/min  |

---

## Related Documentation

- [Chat Integration Guide](/docs/guides/chat-integration.md)
- [WebSocket Integration](/docs/guides/websocket-integration.md)
- [Persona Authoring Handbook](/docs/internal-handbooks/persona-authoring.md)
- [TypeScript SDK](/docs/sdk/typescript-sdk.md)
