# NPC API

AI-powered non-player character behavior, dialogue, and interactions.

## Overview

The NPC API provides intelligent character behavior powered by large language
models. NPCs can engage in natural conversations, remember interactions, pursue
goals, and respond dynamically to world events.

**Base Path:** `/v1/npcs`

**Authentication:** Bearer token required

## Endpoints Summary

| Method | Path                         | Description                |
| ------ | ---------------------------- | -------------------------- |
| POST   | `/create`                    | Create new NPC             |
| GET    | `/{npcId}`                   | Get NPC details            |
| PATCH  | `/{npcId}`                   | Update NPC                 |
| DELETE | `/{npcId}`                   | Delete NPC                 |
| GET    | `/`                          | List NPCs                  |
| POST   | `/{npcId}/chat`              | Chat with NPC              |
| POST   | `/{npcId}/action`            | Execute NPC action         |
| GET    | `/{npcId}/memory`            | Get NPC memories           |
| POST   | `/{npcId}/memory`            | Add memory                 |
| DELETE | `/{npcId}/memory/{memoryId}` | Remove memory              |
| POST   | `/{npcId}/goal`              | Set NPC goal               |
| GET    | `/{npcId}/state`             | Get emotional/mental state |
| POST   | `/{npcId}/react`             | Trigger reaction to event  |
| POST   | `/conversation`              | Multi-NPC conversation     |

---

## NPC Management

### Create NPC

Create a new NPC with personality, background, and behavioral traits.

```http
POST /v1/npcs/create
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Elena Brightwood",
  "role": "merchant",
  "projectId": "proj_abc123",
  "personality": {
    "traits": ["friendly", "shrewd", "curious", "patient"],
    "values": ["fairness", "prosperity", "knowledge"],
    "fears": ["poverty", "dishonesty"],
    "quirks": ["speaks in proverbs", "counts coins nervously"]
  },
  "background": {
    "age": 45,
    "occupation": "General goods merchant",
    "history": "Former adventurer who settled down after discovering a talent for trade. Lost her husband to bandits ten years ago. Now runs the most successful shop in town.",
    "secrets": ["Knows location of hidden treasure", "Was once a member of the Thieves Guild"],
    "relationships": [
      { "npcId": "npc_guard_captain", "type": "friend", "history": "Adventured together" },
      { "npcId": "npc_mayor", "type": "business", "sentiment": "neutral" }
    ]
  },
  "knowledge": {
    "world": ["Local rumors", "Trade routes", "Market prices"],
    "skills": ["Appraisal", "Negotiation", "Herbalism"],
    "languages": ["Common", "Elvish", "Trade Tongue"]
  },
  "behavior": {
    "defaultMood": "cheerful",
    "schedule": [
      { "time": "06:00-08:00", "activity": "opening_shop", "location": "shop" },
      { "time": "08:00-18:00", "activity": "working", "location": "shop" },
      { "time": "18:00-20:00", "activity": "dinner", "location": "tavern" },
      { "time": "20:00-22:00", "activity": "socializing", "location": "tavern" },
      { "time": "22:00-06:00", "activity": "sleeping", "location": "home" }
    ],
    "reactions": {
      "theft": "call_guards",
      "compliment": "pleased",
      "threat": "defensive"
    }
  },
  "voice": {
    "voiceId": "voice_merchant_female",
    "speechPattern": "formal_friendly",
    "accent": "northern"
  },
  "appearance": {
    "description": "Middle-aged woman with silver-streaked auburn hair, kind eyes with laugh lines, and calloused hands.",
    "clothing": "Practical merchant attire with a leather apron",
    "distinguishingFeatures": ["Silver ring on left hand", "Small scar on chin"]
  },
  "model": "claude-3-sonnet",
  "safetyLevel": "standard"
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "npcId": "npc_elena_abc123",
    "name": "Elena Brightwood",
    "status": "active",
    "createdAt": "2024-01-15T10:00:00Z"
  }
}
```

### Get NPC

```http
GET /v1/npcs/{npcId}
Authorization: Bearer <token>
```

### Update NPC

```http
PATCH /v1/npcs/{npcId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "personality": {
    "traits": ["friendly", "shrewd", "curious", "patient", "suspicious"]
  },
  "knowledge": {
    "world": ["Local rumors", "Trade routes", "Market prices", "Recent bandit activity"]
  }
}
```

### List NPCs

```http
GET /v1/npcs?projectId=proj_abc123&role=merchant&limit=20
Authorization: Bearer <token>
```

---

## Conversation

### Chat with NPC

Engage in conversation with an NPC.

```http
POST /v1/npcs/{npcId}/chat
Authorization: Bearer <token>
Content-Type: application/json

{
  "playerId": "player_001",
  "message": "Hello! I'm looking for healing potions. Do you have any in stock?",
  "context": {
    "location": "shop_counter",
    "timeOfDay": "morning",
    "playerReputation": 75,
    "playerAppearance": "armored_warrior",
    "recentEvents": ["player_helped_find_lost_goods"],
    "playerInventory": {
      "gold": 500,
      "items": ["rusty_sword", "travelers_pack"]
    }
  },
  "conversationId": "conv_abc123",
  "generateVoice": true,
  "maxTokens": 200
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "response": "Ah, good morning, friend! Yes, yes, I have several healing potions in stock. *gestures to shelf* As they say, 'A wise warrior prepares before the battle, not during.' I have minor healing at 25 gold, standard at 50, and greater healing at 150. Given you helped me find my lost shipment last week, I'll give you a 10% discount on any purchase today.",
    "emotion": "pleased",
    "mood": "friendly",
    "intent": "offer_discount",
    "actions": [
      { "type": "gesture", "target": "shelf" },
      { "type": "facial_expression", "value": "warm_smile" }
    ],
    "audioUrl": "https://cdn.yemaya.io/voice/npc_elena_resp_123.wav",
    "conversationId": "conv_abc123",
    "memoryUpdated": true,
    "shopAvailable": true,
    "suggestedResponses": [
      "I'll take three minor healing potions.",
      "What else do you have for sale?",
      "That's very kind of you. How have you been?"
    ],
    "tokensUsed": 156
  }
}
```

### Multi-NPC Conversation

Create a conversation between multiple NPCs.

```http
POST /v1/npcs/conversation
Authorization: Bearer <token>
Content-Type: application/json

{
  "participants": [
    { "npcId": "npc_elena_abc123", "role": "speaker" },
    { "npcId": "npc_guard_captain", "role": "speaker" },
    { "npcId": "npc_mayor", "role": "listener" }
  ],
  "topic": "Recent bandit attacks on trade caravans",
  "location": "town_hall",
  "context": {
    "urgency": "high",
    "recentEvents": ["caravan_attacked", "merchant_killed"],
    "playerPresent": true,
    "playerId": "player_001"
  },
  "turns": 5,
  "generateVoice": true
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "conversationId": "conv_multi_abc123",
    "turns": [
      {
        "speaker": "npc_elena_abc123",
        "text": "Captain, we've lost three caravans this month alone! My suppliers are refusing to travel the northern road.",
        "emotion": "worried",
        "audioUrl": "https://cdn.yemaya.io/voice/conv_t1.wav"
      },
      {
        "speaker": "npc_guard_captain",
        "text": "I understand your concerns, Elena. We've doubled patrols, but these bandits are clever. They strike and vanish into the forest.",
        "emotion": "frustrated",
        "audioUrl": "https://cdn.yemaya.io/voice/conv_t2.wav"
      },
      {
        "speaker": "npc_elena_abc123",
        "text": "*glances at player* Perhaps... we need outside help? Someone who can track them to their hideout?",
        "emotion": "hopeful",
        "audioUrl": "https://cdn.yemaya.io/voice/conv_t3.wav"
      }
    ],
    "observedBy": ["player_001"],
    "questHook": {
      "type": "bounty",
      "target": "bandit_leader",
      "reward": 500
    }
  }
}
```

---

## Memory System

### Get Memories

Retrieve NPC memories about players and events.

```http
GET /v1/npcs/{npcId}/memory?playerId=player_001&type=interaction&limit=10
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": {
    "memories": [
      {
        "id": "mem_001",
        "type": "interaction",
        "timestamp": "2024-01-14T15:30:00Z",
        "summary": "Player helped find lost goods shipment",
        "sentiment": "positive",
        "importance": 0.8,
        "details": {
          "playerId": "player_001",
          "action": "completed_quest",
          "reward_given": "gold:50"
        }
      },
      {
        "id": "mem_002",
        "type": "interaction",
        "timestamp": "2024-01-13T10:00:00Z",
        "summary": "First meeting with player, purchased supplies",
        "sentiment": "neutral",
        "importance": 0.5,
        "details": {
          "playerId": "player_001",
          "action": "purchase",
          "items": ["torch", "rope"]
        }
      }
    ],
    "relationshipScore": 75,
    "lastInteraction": "2024-01-14T15:30:00Z"
  }
}
```

### Add Memory

Manually add a memory to an NPC.

```http
POST /v1/npcs/{npcId}/memory
Authorization: Bearer <token>
Content-Type: application/json

{
  "type": "world_event",
  "summary": "Heard about dragon sighting near mountain",
  "importance": 0.9,
  "source": "tavern_gossip",
  "details": {
    "location": "Dragon Peak",
    "witness": "traveling_merchant"
  }
}
```

### Remove Memory

```http
DELETE /v1/npcs/{npcId}/memory/{memoryId}
Authorization: Bearer <token>
```

---

## Goals & Actions

### Set Goal

Assign a goal for the NPC to pursue.

```http
POST /v1/npcs/{npcId}/goal
Authorization: Bearer <token>
Content-Type: application/json

{
  "goal": "acquire_rare_item",
  "target": "ancient_tome",
  "priority": "high",
  "motivation": "Knowledge about her late husband's final adventure",
  "deadline": null,
  "shareWithPlayer": true,
  "offerQuest": true
}
```

### Execute Action

Trigger an NPC action.

```http
POST /v1/npcs/{npcId}/action
Authorization: Bearer <token>
Content-Type: application/json

{
  "action": "move",
  "parameters": {
    "destination": "tavern",
    "urgency": "normal",
    "reason": "evening_routine"
  },
  "notifyPlayers": ["player_001"]
}
```

**Action Types:**

| Action        | Description                        |
| ------------- | ---------------------------------- |
| `move`        | Move to location                   |
| `speak`       | Say something to nearby characters |
| `emote`       | Perform an emote/animation         |
| `interact`    | Interact with object               |
| `give_item`   | Give item to player/NPC            |
| `attack`      | Initiate combat                    |
| `flee`        | Run away                           |
| `trade`       | Open trade interface               |
| `quest_offer` | Offer a quest                      |

---

## Emotional State

### Get State

Get NPC's current emotional and mental state.

```http
GET /v1/npcs/{npcId}/state
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": {
    "mood": "content",
    "energy": 0.8,
    "stress": 0.2,
    "emotions": {
      "happiness": 0.7,
      "fear": 0.1,
      "anger": 0.0,
      "sadness": 0.2,
      "surprise": 0.0,
      "trust": 0.6
    },
    "needs": {
      "safety": 0.9,
      "social": 0.7,
      "purpose": 0.8,
      "rest": 0.6
    },
    "currentActivity": "working",
    "currentLocation": "shop",
    "activeGoals": [{ "goal": "acquire_rare_item", "progress": 0.2 }],
    "recentInfluences": [
      { "event": "good_sales_day", "effect": "+happiness" },
      { "event": "heard_about_bandits", "effect": "+fear" }
    ]
  }
}
```

### Trigger Reaction

Make NPC react to an event.

```http
POST /v1/npcs/{npcId}/react
Authorization: Bearer <token>
Content-Type: application/json

{
  "event": "combat_nearby",
  "details": {
    "combatants": ["player_001", "bandit_001"],
    "distance": 20,
    "severity": "moderate"
  },
  "generateResponse": true
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "reaction": "concerned",
    "actions": [
      { "type": "move", "destination": "behind_counter" },
      { "type": "speak", "text": "Oh my! Guards! Someone call the guards!" },
      { "type": "emote", "animation": "duck_cover" }
    ],
    "stateChanges": {
      "fear": "+0.3",
      "stress": "+0.2"
    },
    "audioUrl": "https://cdn.yemaya.io/voice/reaction_abc.wav"
  }
}
```

---

## Safety & Moderation

NPCs include built-in safety measures:

```http
POST /v1/npcs/create
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Safe NPC",
  "safetyLevel": "strict",
  "safetyConfig": {
    "blockViolence": true,
    "blockAdultContent": true,
    "blockProfanity": true,
    "blockRealPeople": true,
    "blockControversialTopics": true,
    "customBlacklist": ["specific_topic"],
    "gracefulRedirect": true
  }
}
```

**Safety Levels:**

| Level      | Description                              |
| ---------- | ---------------------------------------- |
| `strict`   | Maximum filtering, suitable for all ages |
| `standard` | Moderate filtering, T-rated content      |
| `mature`   | Minimal filtering, M-rated content       |
| `custom`   | Custom safety configuration              |

---

## Error Codes

| Code                 | Description                      |
| -------------------- | -------------------------------- |
| `NPC_NOT_FOUND`      | NPC ID does not exist            |
| `CONVERSATION_LIMIT` | Too many active conversations    |
| `MEMORY_LIMIT`       | NPC memory capacity exceeded     |
| `SAFETY_VIOLATION`   | Content blocked by safety filter |
| `MODEL_UNAVAILABLE`  | AI model temporarily unavailable |
| `CONTEXT_TOO_LARGE`  | Conversation context too long    |
| `INVALID_ACTION`     | Requested action not valid       |

---

## Rate Limits

| Endpoint               | Limit             |
| ---------------------- | ----------------- |
| Chat                   | 60/minute per NPC |
| Create NPC             | 10/minute         |
| Memory operations      | 100/minute        |
| Multi-NPC conversation | 10/minute         |
| Reactions              | 100/minute        |

---

## Best Practices

1. **Memory Management**: Periodically prune low-importance memories to maintain
   context quality
2. **Conversation Context**: Include relevant recent events for more natural
   responses
3. **Safety Configuration**: Always configure appropriate safety levels for your
   audience
4. **Voice Generation**: Cache frequently used responses to reduce latency
5. **Goal Setting**: Give NPCs meaningful goals for more engaging interactions
6. **Relationship Building**: Track player-NPC relationships for dynamic
   interactions
