# Thread Management API

This document provides comprehensive documentation for the Lilith Conversation
Service Thread Management API, including CRUD operations for threads and
messages.

## Overview

The Thread Management API enables conversation organization with:

- **Thread CRUD**: Create, read, update, delete conversation threads
- **Message Management**: Add and retrieve messages within threads
- **Metadata**: Persona association, tags, and custom metadata
- **Pagination**: Efficient listing with filtering and sorting

---

## Table of Contents

1. [Thread Types](#thread-types)
2. [Thread Operations](#thread-operations)
3. [Message Operations](#message-operations)
4. [Error Handling](#error-handling)

---

## Thread Types

### Thread Object

```json
{
  "id": "thread-abc123",
  "title": "Morning Meditation Discussion",
  "metadata": {
    "user_id": "user_123",
    "persona": "meditation_guide",
    "tags": ["meditation", "morning"]
  },
  "created_at": "2024-01-01T00:00:00.000Z",
  "updated_at": "2024-01-01T00:00:00.000Z",
  "message_count": 5
}
```

### Message Object

```json
{
  "id": "msg-xyz789",
  "thread_id": "thread-abc123",
  "role": "user",
  "content": "How do I start a morning meditation practice?",
  "metadata": {
    "persona": "meditation_guide",
    "citations": [],
    "tool_calls": [],
    "tokens_in": 12,
    "tokens_out": null
  },
  "created_at": "2024-01-01T00:00:00.000Z"
}
```

### Message Roles

| Role        | Description             |
| ----------- | ----------------------- |
| `user`      | User-submitted messages |
| `assistant` | AI assistant responses  |
| `system`    | System context messages |

---

## Thread Operations

### Create Thread

Create a new conversation thread.

**Endpoint:** `POST /v1/threads`

**Request Body:**

| Field      | Type     | Required | Description                          |
| ---------- | -------- | -------- | ------------------------------------ |
| `title`    | string   | No       | Thread title (default: "New Thread") |
| `user_id`  | string   | No       | Owner user ID                        |
| `persona`  | string   | No       | Associated AI persona                |
| `tags`     | string[] | No       | Tags for organization                |
| `metadata` | object   | No       | Additional metadata                  |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/threads" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Morning Meditation Discussion",
    "user_id": "user_123",
    "persona": "meditation_guide",
    "tags": ["meditation", "morning"]
  }'
```

**Response (201 Created):**

```json
{
  "id": "thread-abc123",
  "title": "Morning Meditation Discussion",
  "metadata": {
    "user_id": "user_123",
    "persona": "meditation_guide",
    "tags": ["meditation", "morning"]
  },
  "created_at": "2024-01-01T00:00:00.000Z",
  "updated_at": "2024-01-01T00:00:00.000Z",
  "message_count": 0
}
```

### List Threads

Retrieve threads with optional filtering.

**Endpoint:** `GET /v1/threads`

**Query Parameters:**

| Parameter | Type    | Description                            |
| --------- | ------- | -------------------------------------- |
| `user_id` | string  | Filter by user ID                      |
| `limit`   | integer | Items per page (max: 500, default: 50) |
| `offset`  | integer | Pagination offset (default: 0)         |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/threads?user_id=user_123&limit=20" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "threads": [
    {
      "id": "thread-abc123",
      "title": "Morning Meditation Discussion",
      "metadata": { "user_id": "user_123", "persona": "meditation_guide" },
      "created_at": "2024-01-01T00:00:00.000Z",
      "updated_at": "2024-01-01T12:00:00.000Z",
      "message_count": 5
    }
  ],
  "total_count": 15,
  "has_more": false
}
```

### Get Thread

Retrieve a specific thread by ID.

**Endpoint:** `GET /v1/threads/:threadId`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/threads/thread-abc123" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "id": "thread-abc123",
  "title": "Morning Meditation Discussion",
  "metadata": {
    "user_id": "user_123",
    "persona": "meditation_guide",
    "tags": ["meditation", "morning"]
  },
  "created_at": "2024-01-01T00:00:00.000Z",
  "updated_at": "2024-01-01T12:00:00.000Z",
  "message_count": 5
}
```

### Update Thread

Update thread properties.

**Endpoint:** `PATCH /v1/threads/:threadId`

**Request Body:**

| Field      | Type   | Description       |
| ---------- | ------ | ----------------- |
| `title`    | string | New title         |
| `metadata` | object | Metadata to merge |

**Request:**

```bash
curl -X PATCH "https://api.lilith.app/v1/threads/thread-abc123" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Advanced Morning Meditation",
    "metadata": { "difficulty": "intermediate" }
  }'
```

### Delete Thread

Delete a thread and all associated messages.

**Endpoint:** `DELETE /v1/threads/:threadId`

**Request:**

```bash
curl -X DELETE "https://api.lilith.app/v1/threads/thread-abc123" \
  -H "Authorization: Bearer <access_token>"
```

**Response:** `204 No Content`

---

## Message Operations

### List Messages

Retrieve messages in a thread.

**Endpoint:** `GET /v1/threads/:threadId/messages`

**Query Parameters:**

| Parameter | Type    | Description                                |
| --------- | ------- | ------------------------------------------ |
| `limit`   | integer | Items per page (max: 500, default: 100)    |
| `offset`  | integer | Pagination offset (default: 0)             |
| `order`   | string  | Sort order: `asc` or `desc` (default: asc) |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/threads/thread-abc123/messages?limit=50&order=asc" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "messages": [
    {
      "id": "msg-001",
      "thread_id": "thread-abc123",
      "role": "user",
      "content": "How do I start a morning meditation practice?",
      "metadata": { "persona": "meditation_guide" },
      "created_at": "2024-01-01T08:00:00.000Z"
    },
    {
      "id": "msg-002",
      "thread_id": "thread-abc123",
      "role": "assistant",
      "content": "Starting a morning meditation practice...",
      "metadata": {
        "persona": "meditation_guide",
        "citations": [],
        "tokens_in": 12,
        "tokens_out": 150
      },
      "created_at": "2024-01-01T08:00:05.000Z"
    }
  ],
  "total_count": 5,
  "has_more": false
}
```

### Get Message

Retrieve a specific message.

**Endpoint:** `GET /v1/threads/:threadId/messages/:messageId`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/threads/thread-abc123/messages/msg-001" \
  -H "Authorization: Bearer <access_token>"
```

### Create Message

Add a new message to a thread.

**Endpoint:** `POST /v1/threads/:threadId/messages`

**Request Body:**

| Field        | Type    | Required | Description                                 |
| ------------ | ------- | -------- | ------------------------------------------- |
| `role`       | string  | Yes      | Message role: `user`, `assistant`, `system` |
| `content`    | string  | Yes      | Message content                             |
| `persona`    | string  | No       | Associated persona                          |
| `citations`  | array   | No       | Citation references                         |
| `tool_calls` | array   | No       | Tool call records                           |
| `tokens_in`  | integer | No       | Input token count                           |
| `tokens_out` | integer | No       | Output token count                          |
| `metadata`   | object  | No       | Additional metadata                         |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/threads/thread-abc123/messages" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "role": "user",
    "content": "What breathing technique should I use?",
    "persona": "meditation_guide"
  }'
```

**Response (201 Created):**

```json
{
  "id": "msg-003",
  "thread_id": "thread-abc123",
  "role": "user",
  "content": "What breathing technique should I use?",
  "metadata": {
    "persona": "meditation_guide",
    "citations": [],
    "tool_calls": [],
    "tokens_in": 8
  },
  "created_at": "2024-01-01T08:05:00.000Z"
}
```

---

## Error Handling

### Error Codes

| Code                      | HTTP Status | Description                      |
| ------------------------- | ----------- | -------------------------------- |
| `thread_not_found`        | 404         | Thread does not exist            |
| `message_not_found`       | 404         | Message does not exist in thread |
| `missing_required_fields` | 400         | Role and content are required    |

### Example Error Response

```json
{
  "code": "thread_not_found",
  "message": "Thread not found"
}
```

---

## SDK Integration

### TypeScript/JavaScript

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

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

// Create a thread
const thread = await client.conversation.createThread({
  title: 'Morning Meditation Discussion',
  user_id: 'user_123',
  persona: 'meditation_guide',
  tags: ['meditation', 'morning'],
});

// List user's threads
const threads = await client.conversation.listThreads({
  user_id: 'user_123',
  limit: 20,
});

// Get thread details
const threadDetails = await client.conversation.getThread('thread-abc123');

// Add a message
const message = await client.conversation.createMessage('thread-abc123', {
  role: 'user',
  content: 'How do I start a morning meditation practice?',
});

// List messages
const messages = await client.conversation.listMessages('thread-abc123', {
  limit: 50,
  order: 'asc',
});

// Update thread
await client.conversation.updateThread('thread-abc123', {
  title: 'Advanced Morning Meditation',
});

// Delete thread
await client.conversation.deleteThread('thread-abc123');
```

---

## Related Documentation

- [Streaming API](./streaming-api.md) - Real-time chat streaming
- [Chat API](./chat-api.md) - Chat completion API
- [Context API](./context-api.md) - Context window management
- [Authentication](./authentication.md) - API authentication

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
