# Persona Management API

This document provides comprehensive documentation for the Lilith Content
Service Persona Management API, including CRUD operations, configuration, A/B
testing, versioning, and localization.

## Overview

The Persona Management API enables management of AI teacher/guide personas with:

- **CRUD Operations**: Full create, read, update, delete for personas
- **Configuration**: Speaking style, voice settings, prompt templates, 3D models
- **A/B Testing**: Variant creation, weighted selection, metrics tracking
- **Status Workflow**: Draft → Review → Published → Archived workflow
- **Versioning**: Version history with snapshots and rollback
- **Localization**: Multi-language support with translation tracking
- **Engagement Metrics**: Conversations, sessions, ratings, favorites

---

## Table of Contents

1. [Types and Enums](#types-and-enums)
2. [Configuration Objects](#configuration-objects)
3. [CRUD Operations](#crud-operations)
4. [Filtering Endpoints](#filtering-endpoints)
5. [Status Workflow](#status-workflow)
6. [Versioning](#versioning)
7. [Localization](#localization)
8. [A/B Testing](#ab-testing)
9. [Engagement Metrics](#engagement-metrics)
10. [Error Handling](#error-handling)

---

## Types and Enums

### Persona Types

| Type        | Description                   |
| ----------- | ----------------------------- |
| `teacher`   | Educational instructor        |
| `guide`     | Spiritual or meditation guide |
| `mentor`    | Personal development mentor   |
| `sage`      | Wise philosophical advisor    |
| `counselor` | Supportive counselor          |
| `narrator`  | Story narrator                |
| `companion` | Supportive companion          |

### Voice Gender

| Gender    | Description          |
| --------- | -------------------- |
| `male`    | Male voice           |
| `female`  | Female voice         |
| `neutral` | Gender-neutral voice |

### Status Types

| Status      | Description              |
| ----------- | ------------------------ |
| `draft`     | Initial creation state   |
| `review`    | Pending editorial review |
| `published` | Live and accessible      |
| `archived`  | Removed from active use  |
| `deleted`   | Soft-deleted             |

---

## Configuration Objects

### Speaking Style

```json
{
  "formality": "formal",
  "metaphorical": true,
  "poetic": true,
  "directness": "balanced",
  "emotionalTone": "warm",
  "vocabularyLevel": "moderate",
  "customAttributes": {}
}
```

| Field             | Values                                           | Description                  |
| ----------------- | ------------------------------------------------ | ---------------------------- |
| `formality`       | `formal`, `informal`, `neutral`                  | Communication formality      |
| `metaphorical`    | boolean                                          | Uses metaphors and analogies |
| `poetic`          | boolean                                          | Poetic language style        |
| `directness`      | `direct`, `indirect`, `balanced`                 | Communication directness     |
| `emotionalTone`   | `warm`, `calm`, `energetic`, `serene`, `neutral` | Emotional tone               |
| `vocabularyLevel` | `simple`, `moderate`, `advanced`                 | Vocabulary complexity        |

### Voice Config

```json
{
  "voiceId": "voice_abc123",
  "gender": "female",
  "accent": "british",
  "speed": 1.0,
  "pitch": 1.0
}
```

### Avatar Variants

```json
{
  "default": "https://cdn.lilith.app/avatars/default.png",
  "greeting": "https://cdn.lilith.app/avatars/greeting.png",
  "thinking": "https://cdn.lilith.app/avatars/thinking.png",
  "teaching": "https://cdn.lilith.app/avatars/teaching.png",
  "meditating": "https://cdn.lilith.app/avatars/meditating.png",
  "farewell": "https://cdn.lilith.app/avatars/farewell.png"
}
```

### Model Config (3D)

```json
{
  "modelUrl": "https://cdn.lilith.app/models/persona.glb",
  "scale": 1.0,
  "position": { "x": 0, "y": 0, "z": 0 },
  "rotation": { "x": 0, "y": 0, "z": 0 },
  "animations": ["idle", "talking", "meditating"],
  "customSettings": {}
}
```

### Prompt Templates

```json
{
  "greeting": "Welcome, dear student...",
  "teaching": "Let me guide you through...",
  "meditation": "Close your eyes and breathe...",
  "counseling": "I understand your feelings...",
  "farewell": "Go in peace...",
  "encouragement": "You are doing wonderfully...",
  "reflection": "Take a moment to consider..."
}
```

### Persona Object

```json
{
  "id": "uuid",
  "slug": "wise-sage",
  "name": "Master Wisdom",
  "title": "Enlightened Sage",
  "bio": "A wise teacher of ancient traditions...",
  "description": "Master Wisdom guides students through meditation and philosophy",
  "type": "sage",
  "tradition": "zen",
  "era": "modern",
  "origin": "East Asia",
  "personalityTraits": ["calm", "patient", "wise", "compassionate"],
  "speakingStyle": { "formality": "formal", "emotionalTone": "calm" },
  "sampleGreeting": "Welcome, dear student...",
  "sampleFarewell": "May peace be with you...",
  "voiceId": "voice_abc123",
  "voiceGender": "male",
  "voiceAccent": "neutral",
  "voiceSpeed": 0.9,
  "voicePitch": 1.0,
  "avatarUrl": "https://cdn.lilith.app/avatars/wise-sage.png",
  "fullImageUrl": "https://cdn.lilith.app/images/wise-sage-full.png",
  "avatarVariants": { "default": "...", "teaching": "..." },
  "backgroundColor": "#1a1a2e",
  "themeColor": "#eab308",
  "modelUrl": "https://cdn.lilith.app/models/wise-sage.glb",
  "modelConfig": { "scale": 1.0, "position": { "x": 0, "y": 0, "z": 0 } },
  "systemPrompt": "You are a wise sage who guides students...",
  "promptTemplates": { "greeting": "..." },
  "knowledgeAreas": ["meditation", "philosophy", "mindfulness"],
  "teachingMethods": ["socratic", "experiential", "contemplative"],
  "associatedCourses": ["uuid-1", "uuid-2"],
  "associatedMeditations": ["uuid-3"],
  "associatedWisdoms": ["uuid-4"],
  "isPremium": false,
  "isDefault": true,
  "status": "published",
  "publishedAt": "2024-01-01T00:00:00.000Z",
  "conversationCount": 5000,
  "sessionCount": 3000,
  "averageRating": 4.9,
  "ratingCount": 500,
  "favoriteCount": 1200,
  "sortOrder": 1,
  "locale": "en",
  "availableLocales": ["en", "es", "fr"],
  "deletedAt": null,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}
```

---

## CRUD Operations

### Create Persona

Create a new AI persona.

**Endpoint:** `POST /v1/personas`

**Request Body:**

| Field                   | Type     | Required | Description                       |
| ----------------------- | -------- | -------- | --------------------------------- |
| `slug`                  | string   | Yes      | URL-friendly identifier           |
| `name`                  | string   | Yes      | Display name                      |
| `title`                 | string   | No       | Professional title                |
| `bio`                   | string   | No       | Biography                         |
| `description`           | string   | No       | Full description                  |
| `type`                  | string   | No       | Persona type (default: teacher)   |
| `tradition`             | string   | No       | Spiritual/philosophical tradition |
| `era`                   | string   | No       | Historical era                    |
| `origin`                | string   | No       | Geographic origin                 |
| `personalityTraits`     | string[] | No       | Personality traits                |
| `speakingStyle`         | object   | No       | Speaking style configuration      |
| `sampleGreeting`        | string   | No       | Sample greeting message           |
| `sampleFarewell`        | string   | No       | Sample farewell message           |
| `voiceId`               | string   | No       | Voice synthesis ID                |
| `voiceGender`           | string   | No       | Voice gender                      |
| `voiceAccent`           | string   | No       | Voice accent                      |
| `voiceSpeed`            | number   | No       | Voice speed (0.5-2.0)             |
| `voicePitch`            | number   | No       | Voice pitch (0.5-2.0)             |
| `avatarUrl`             | string   | No       | Avatar image URL                  |
| `fullImageUrl`          | string   | No       | Full-body image URL               |
| `avatarVariants`        | object   | No       | Avatar state variants             |
| `backgroundColor`       | string   | No       | Theme background color            |
| `themeColor`            | string   | No       | Theme accent color                |
| `modelUrl`              | string   | No       | 3D model URL                      |
| `modelConfig`           | object   | No       | 3D model configuration            |
| `systemPrompt`          | string   | No       | AI system prompt                  |
| `promptTemplates`       | object   | No       | Prompt templates                  |
| `knowledgeAreas`        | string[] | No       | Knowledge domains                 |
| `teachingMethods`       | string[] | No       | Teaching methods                  |
| `associatedCourses`     | uuid[]   | No       | Associated course IDs             |
| `associatedMeditations` | uuid[]   | No       | Associated meditation IDs         |
| `associatedWisdoms`     | uuid[]   | No       | Associated wisdom IDs             |
| `isPremium`             | boolean  | No       | Premium persona flag              |
| `isDefault`             | boolean  | No       | Default persona flag              |
| `sortOrder`             | integer  | No       | Display order                     |
| `locale`                | string   | No       | Primary locale                    |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/personas" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "meditation-guide",
    "name": "Serenity",
    "title": "Meditation Guide",
    "type": "guide",
    "tradition": "mindfulness",
    "speakingStyle": {
      "formality": "informal",
      "emotionalTone": "calm"
    },
    "systemPrompt": "You are Serenity, a gentle meditation guide...",
    "knowledgeAreas": ["meditation", "mindfulness", "breathing"]
  }'
```

### List Personas

Retrieve personas with filtering and pagination.

**Endpoint:** `GET /v1/personas`

**Query Parameters:**

| Parameter        | Type    | Description                            |
| ---------------- | ------- | -------------------------------------- |
| `status`         | string  | Filter by status                       |
| `type`           | string  | Filter by persona type                 |
| `tradition`      | string  | Filter by tradition                    |
| `era`            | string  | Filter by era                          |
| `isPremium`      | boolean | Filter premium personas                |
| `isDefault`      | boolean | Filter default persona                 |
| `knowledgeAreas` | string  | Comma-separated knowledge areas        |
| `search`         | string  | Full-text search                       |
| `page`           | integer | Page number (default: 1)               |
| `limit`          | integer | Items per page (max: 100, default: 20) |
| `sortBy`         | string  | Sort field (default: created_at)       |
| `sortOrder`      | string  | `asc` or `desc` (default: desc)        |

### Get Default Persona

Retrieve the default persona.

**Endpoint:** `GET /v1/personas/default`

### Get Persona by ID

**Endpoint:** `GET /v1/personas/:personaId`

### Get Persona by Slug

**Endpoint:** `GET /v1/personas/by-slug/:slug`

### Update Persona

**Endpoint:** `PUT /v1/personas/:personaId` or `PATCH /v1/personas/:personaId`

### Delete Persona

**Endpoint:** `DELETE /v1/personas/:personaId`

**Query Parameters:**

| Parameter | Type    | Description                          |
| --------- | ------- | ------------------------------------ |
| `hard`    | boolean | Perform hard delete (default: false) |

### Restore Persona

**Endpoint:** `POST /v1/personas/:personaId/restore`

---

## Filtering Endpoints

### Filter by Type

**Endpoint:** `GET /v1/personas/by-type/:type`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/personas/by-type/guide" \
  -H "Authorization: Bearer <access_token>"
```

### Filter by Tradition

**Endpoint:** `GET /v1/personas/by-tradition/:tradition`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/personas/by-tradition/zen" \
  -H "Authorization: Bearer <access_token>"
```

### Search by Knowledge Areas

Search personas by knowledge domains.

**Endpoint:** `POST /v1/personas/search/by-knowledge`

**Request Body:**

| Field      | Type     | Required | Description                        |
| ---------- | -------- | -------- | ---------------------------------- |
| `areas`    | string[] | Yes      | Knowledge areas to search          |
| `matchAll` | boolean  | No       | Require all areas (default: false) |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/personas/search/by-knowledge" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "areas": ["meditation", "mindfulness"],
    "matchAll": true
  }'
```

---

## Status Workflow

### Transition Status

**Endpoint:** `POST /v1/personas/:personaId/status`

### Publish Persona

**Endpoint:** `POST /v1/personas/:personaId/publish`

### Archive Persona

**Endpoint:** `POST /v1/personas/:personaId/archive`

### Set as Default

Set a persona as the default.

**Endpoint:** `POST /v1/personas/:personaId/set-default`

### Get Allowed Transitions

**Endpoint:** `GET /v1/personas/:personaId/allowed-transitions`

---

## Versioning

### List Versions

**Endpoint:** `GET /v1/personas/:personaId/versions`

### Get Current Version

**Endpoint:** `GET /v1/personas/:personaId/versions/current`

### Get Specific Version

**Endpoint:** `GET /v1/personas/:personaId/versions/:versionNumber`

### Create Version

**Endpoint:** `POST /v1/personas/:personaId/versions`

### Restore Version

**Endpoint:** `POST /v1/personas/:personaId/versions/:versionNumber/restore`

---

## Localization

### List Locales

**Endpoint:** `GET /v1/personas/:personaId/locales`

### Create Locale

**Endpoint:** `POST /v1/personas/:personaId/locales`

**Request Body:**

| Field            | Type    | Required | Description                       |
| ---------------- | ------- | -------- | --------------------------------- |
| `locale`         | string  | Yes      | Locale code (e.g., `es`, `fr-CA`) |
| `isDefault`      | boolean | No       | Set as default locale             |
| `name`           | string  | No       | Translated name                   |
| `title`          | string  | No       | Translated title                  |
| `bio`            | string  | No       | Translated biography              |
| `description`    | string  | No       | Translated description            |
| `sampleGreeting` | string  | No       | Translated greeting               |
| `sampleFarewell` | string  | No       | Translated farewell               |
| `localizedData`  | object  | No       | Additional localized fields       |
| `translatorId`   | uuid    | No       | Translator user ID                |

### Get/Update/Delete Locale

- `GET /v1/personas/:personaId/locales/:locale`
- `PUT /v1/personas/:personaId/locales/:locale`
- `DELETE /v1/personas/:personaId/locales/:locale`

### Set Default Locale

**Endpoint:** `POST /v1/personas/:personaId/locales/:locale/set-default`

---

## A/B Testing

A/B testing allows you to create variants of a persona with different
configurations and measure their effectiveness.

### Variant Object

```json
{
  "id": "uuid",
  "personaId": "uuid",
  "variantName": "Variant A - Formal",
  "description": "More formal speaking style",
  "systemPrompt": "You are a formal meditation guide...",
  "speakingStyle": { "formality": "formal" },
  "promptTemplates": { "greeting": "Good day, dear student..." },
  "weight": 50,
  "isControl": false,
  "isActive": true,
  "conversationCount": 1500,
  "averageRating": 4.7,
  "ratingCount": 120,
  "completionRate": 0.85,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}
```

### List Variants

Retrieve all A/B test variants for a persona.

**Endpoint:** `GET /v1/personas/:personaId/variants`

**Response:**

```json
{
  "variants": [
    {
      "id": "variant_1",
      "variantName": "Control",
      "weight": 50,
      "isControl": true,
      "isActive": true,
      "conversationCount": 1500
    },
    {
      "id": "variant_2",
      "variantName": "Variant A - Formal",
      "weight": 50,
      "isControl": false,
      "isActive": true,
      "conversationCount": 1450
    }
  ]
}
```

### Create Variant

Create a new A/B test variant.

**Endpoint:** `POST /v1/personas/:personaId/variants`

**Request Body:**

| Field             | Type    | Required | Description               |
| ----------------- | ------- | -------- | ------------------------- |
| `variantName`     | string  | Yes      | Variant name              |
| `description`     | string  | No       | Variant description       |
| `systemPrompt`    | string  | No       | Override system prompt    |
| `speakingStyle`   | object  | No       | Override speaking style   |
| `promptTemplates` | object  | No       | Override prompt templates |
| `weight`          | number  | No       | Selection weight (0-100)  |
| `isControl`       | boolean | No       | Is control group          |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/personas/persona_123/variants" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "variantName": "Variant B - Poetic",
    "description": "More poetic speaking style",
    "speakingStyle": {
      "poetic": true,
      "metaphorical": true
    },
    "weight": 25
  }'
```

### Select Variant

Select a variant based on weighted random selection.

**Endpoint:** `GET /v1/personas/:personaId/variants/select`

**Response:**

```json
{
  "id": "variant_2",
  "variantName": "Variant A - Formal",
  "systemPrompt": "...",
  "speakingStyle": { "formality": "formal" }
}
```

### Get Variant

**Endpoint:** `GET /v1/variants/:variantId`

### Update Variant

**Endpoint:** `PUT /v1/variants/:variantId`

### Delete Variant

**Endpoint:** `DELETE /v1/variants/:variantId`

### Record Variant Metrics

Record engagement metrics for variant analysis.

**Record Conversation:**

```bash
POST /v1/variants/:variantId/record-conversation
```

**Record Rating:**

```bash
POST /v1/variants/:variantId/record-rating
Body: { "rating": 4.5 }
```

**Record Completion:**

```bash
POST /v1/variants/:variantId/record-completion
```

---

## Engagement Metrics

### Record Conversation

Increment conversation count.

**Endpoint:** `POST /v1/personas/:personaId/conversation`

### Record Session

Increment session count.

**Endpoint:** `POST /v1/personas/:personaId/session`

### Add Rating

**Endpoint:** `POST /v1/personas/:personaId/rate`

**Request Body:**

| Field    | Type   | Required | Description        |
| -------- | ------ | -------- | ------------------ |
| `rating` | number | Yes      | Rating value (0-5) |

### Add to Favorites

**Endpoint:** `POST /v1/personas/:personaId/favorite`

### Remove from Favorites

**Endpoint:** `DELETE /v1/personas/:personaId/favorite`

---

## Error Handling

### Error Codes

| Code                 | HTTP Status | Description                       |
| -------------------- | ----------- | --------------------------------- |
| `NOT_FOUND`          | 404         | Persona or variant not found      |
| `INVALID_TRANSITION` | 400         | Invalid status transition         |
| `DUPLICATE`          | 409         | Persona with slug already exists  |
| `INVALID_VERSION`    | 400         | Version number must be an integer |
| `INTERNAL_ERROR`     | 500         | Unexpected server error           |

---

## SDK Integration

### TypeScript/JavaScript

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

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

// Create a persona
const persona = await client.content.createPersona({
  slug: 'meditation-guide',
  name: 'Serenity',
  type: 'guide',
  speakingStyle: { emotionalTone: 'calm' },
});

// Get default persona
const defaultPersona = await client.content.getDefaultPersona();

// Search by knowledge areas
const sages = await client.content.searchPersonasByKnowledge({
  areas: ['meditation', 'philosophy'],
  matchAll: true,
});

// Create A/B test variant
const variant = await client.content.createVariant(persona.id, {
  variantName: 'Formal Variant',
  speakingStyle: { formality: 'formal' },
  weight: 25,
});

// Select variant for user
const selectedVariant = await client.content.selectVariant(persona.id);

// Record variant engagement
await client.content.recordVariantConversation(variant.id);
await client.content.recordVariantRating(variant.id, { rating: 4.5 });

// Set as default
await client.content.setDefaultPersona(persona.id);
```

---

## Related Documentation

- [Lesson API](./lesson-api.md) - Course lesson management
- [Meditation API](./meditation-api.md) - Meditation content management
- [Prompt Management](./prompt-management.md) - Versioned prompts and feature
  flags
- [Authentication](./authentication.md) - API authentication

---

## Questions?

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