> For the complete documentation index, see [llms.txt](https://docs.meganova.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.meganova.ai/character-studio/character-features/lorebooks.md).

# Lorebooks

> **Note:** Lorebooks are knowledge bases that inject context into conversations based on keywords. They help characters maintain consistent world knowledge without bloating the character definition.

## Overview

Lorebooks provide:

* **Keyword-triggered** context injection
* **Separate storage** for world information
* **Reusable** knowledge across multiple characters
* **Token-efficient** context management

## How Lorebooks Work

1. **You create** lorebook entries with keywords
2. **User sends** a message during chat
3. **System scans** the message for keywords
4. **Matching entries** are injected into context
5. **Character responds** with that knowledge available

### Example Flow

**Lorebook Entry:**

```
Keywords: Hogwarts, school, castle
Content: Hogwarts School of Witchcraft and Wizardry is a magical
boarding school located in Scotland. It has four houses: Gryffindor,
Hufflepuff, Ravenclaw, and Slytherin.
```

**User Message:** "Tell me about Hogwarts."

**Result:** The lorebook content is injected, and the character can respond accurately about Hogwarts.

## Creating a Lorebook

### Step 1: Access Lorebook Manager

1. Click **Lorebooks** in the sidebar, or
2. Open a character → **Lore** tab → **Manage Lorebooks**

### Step 2: Create New Lorebook

1. Click **Create Lorebook**
2. Enter a **name** (e.g., "Fantasy World Lore")
3. (Optional) Add a **description**
4. Click **Create**

### Step 3: Add Entries

1. Open your lorebook
2. Click **Add Entry**
3. Fill in entry details:

| Field               | Description                           | Example                              | Default |
| ------------------- | ------------------------------------- | ------------------------------------ | ------- |
| **Title**           | Entry name (for organization)         | "Hogwarts School"                    | -       |
| **Content**         | The information to inject             | "Hogwarts is a magical school..."    | -       |
| **Keywords (Keys)** | Trigger words (comma-separated list)  | "hogwarts, wizarding school, castle" | `[]`    |
| **Priority**        | Injection order (higher = first)      | 10                                   | `10`    |
| **Tags**            | Organizational tags (comma-separated) | "location, school"                   | `[]`    |

**Additional fields:**

* **Enabled** — Toggle button in entry list to activate/deactivate entries (default: `true`)
* **Visibility** — Entry visibility setting (default: `"public"`)
* **Conditions** — Advanced metadata for custom trigger logic (JSON format, default: `{}`)

## Attaching Lorebooks to Characters

**Important:** Only **ONE lorebook** can be attached to a character at a time.

1. Open a character in Character Studio
2. Go to the **Lore** tab
3. Click **Attach Lorebook**
4. Select a lorebook to attach
5. Configure **Token Budget** (0-100%, default 25%)
6. Save the character

When you attach a new lorebook, any previously attached lorebook will be automatically detached.

## Token Budget

The token budget controls how much context space lorebooks can use:

| Budget  | Description                               |
| ------- | ----------------------------------------- |
| 0-25%   | Minimal lore, more space for conversation |
| 25%     | Balanced (default)                        |
| 50%     | Heavy lore usage                          |
| 75-100% | Extensive world-building                  |

**Formula:** If your model has 8K context and budget is 25%, lorebooks can use up to 2K tokens.

You can adjust the budget using a slider (0-100%) in the Lore tab.

## Keyword Strategies

### Choosing Good Keywords

Keywords are a single list (no primary/secondary distinction):

```
Entry: "Dragon Flight Rules"
Keywords: "flying, flight, wings, dragon, sky, soar"
```

### Keyword Tips

1. **Use variations**: "magic, magical, mage, wizard"
2. **Include phrases**: "dark magic" as a keyword
3. **Consider context**: What words would users naturally use?
4. **Avoid common words**: "the", "is", "and" trigger too often
5. **Use comma-separated format**: The UI accepts comma-separated keywords

## Entry Organization

### Using Priority

Higher priority entries inject first (default is 10):

* **Priority 20**: Critical world rules
* **Priority 10**: Important facts (default)
* **Priority 5**: Nice-to-have details
* **Priority 1**: Optional flavor text

### Using Tags

Organize entries with tags:

* `location` — Places in the world
* `character` — NPCs and important figures
* `rule` — World rules and mechanics
* `history` — Historical events

## AI-Assisted Generation

Generate lorebook entries automatically from character data:

**API Endpoint:** `POST /api/lorebooks/generate-from-character/{character_id}`

**Options:**

* `model` (optional) — AI model to use (default: `meganova-ai/manta-flash-1.0`)
* `entry_count` (3-15) — Number of entries to generate (default: 6)
* `focus_areas` (optional) — Specific areas to focus on (e.g., `["history", "magic", "politics"]`)

The AI analyzes the character's:

* Name, description, personality
* Scenario and background
* Blueprint sections (origin, world, current situation)

And extracts key lore elements such as:

* Locations (places, regions, buildings)
* Other Characters (allies, enemies, factions)
* Historical Events (wars, disasters, important moments)
* Concepts (magic systems, technology, religions)
* Objects (artifacts, weapons, items)

## Semantic Search

Lorebooks support two search modes:

### Keyword Mode (Default)

Exact substring matching (case-insensitive). Entry fires when trigger words appear literally in the message.

**Example:**

* Keyword: "sword"
* Triggers on: "your sword", "the sword", "SWORD"
* Does NOT trigger on: "blade", "weapon"

### Semantic Mode

AI-powered matching based on meaning, even if exact words aren't used.

**Requirements:**

1. Click **Index All** to generate embeddings
2. Wait for indexing to complete
3. Search by meaning instead of exact words

**Example:**

* Entry content: "The ancient blade of kings"
* Semantic query: "tell me about royal weapons" → Matches!

### Using Semantic Search

1. Switch to **Semantic** mode in the lorebook editor
2. Click **Index All** to embed all entries
3. Check **embed status**: shows `X/Y indexed`
4. Adjust **min relevance** slider (default: 30%)
5. Search by meaning in the search bar

**API Endpoints:**

* `POST /api/lorebooks/{lorebook_id}/search` — Search entries
* `POST /api/lorebooks/{lorebook_id}/embed-all` — Index all entries
* `GET /api/lorebooks/{lorebook_id}/embed-status` — Check indexing status
* `POST /api/lorebooks/{lorebook_id}/sync` — Sync embeddings (force=true to re-index)

## Import/Export

### Importing Lorebooks

Character Studio supports imports from:

* **SillyTavern** format (`.stlore`, `.json`)
* **ChubAI** format (`.json`)
* **Generic JSON** format
* **YAML** format (`.yaml`, `.yml`)

To import:

1. Open Lorebook Manager
2. Click **Import**
3. Upload file
4. Review imported entries

The import process automatically normalizes different formats:

* Handles both `entries` as array or dictionary
* Supports various keyword field names (`keys`, `key`, `keywords`, `keyword`)
* Merges primary and secondary keywords into single `keys` array
* Converts priority/order/insertion\_order to priority
* Handles SillyTavern's `disable` flag (converts to `enabled`)
* Preserves advanced conditions in metadata

### Exporting Lorebooks

**Note:** Export functionality is not yet implemented. Lorebooks are stored in the database and can be accessed via API.

## Best Practices

### 1. Keep Entries Focused

One concept per entry. Don't combine unrelated information.

### 2. Use Specific Keywords

"Elvish language rules" is better than "elves".

### 3. Balance Token Usage

Monitor how much context lorebooks consume. Use the token budget slider to control usage.

### 4. Test Keyword Triggers

Chat and verify entries activate when expected. Use the Arena tab for testing.

### 5. Only One Lorebook Per Character

The system enforces one active lorebook per character. When you attach a new lorebook, the previous one is automatically detached.

## Advanced Usage

### Conditional Entries

Use entries that only trigger in specific contexts:

```
Keywords: "secret identity, reveal, truth"
Content: [Character's secret backstory]
Priority: 1 (only when specifically asked)
```

### Entry Conditions

The `conditions` field (JSON) can store advanced trigger metadata from platforms like SillyTavern:

```json
{
  "constant": false,
  "selective": true,
  "probability": 80,
  "scan_depth": 10,
  "case_sensitive": false
}
```

### Nested Knowledge

Create hierarchical knowledge:

```
Entry 1 (Priority 10): "Basic world overview"
Keywords: "world, setting"

Entry 2 (Priority 5): "Detailed location info"
Keywords: "city, town, village"
```

## Troubleshooting

### Entry not triggering

* Check keywords match message content
* Verify entry is **enabled** (toggle in entry list)
* Ensure lorebook is **attached** to character
* Check token budget isn't exhausted

### Too many entries triggering

* Use more specific keywords
* Remove common words from keywords
* Lower token budget
* Adjust priorities

### Lore seems inconsistent

* Review for contradictory entries
* Check priority ordering
* Ensure keywords don't overlap unexpectedly

### Semantic search not working

* Click **Index All** to generate embeddings
* Wait for indexing to complete (check embed status)
* Adjust min relevance threshold
* Try different search queries

## Technical Details

### How Keyword Matching Works

The system uses **simple case-insensitive substring matching**:

```python
# Scans last 10 messages for keywords
# Matches any entry where at least one keyword appears in lowercase text
# No regex, no wildcards, just simple "in" check
```

### Context Injection Format

Matched entries are injected with this format:

```
[WORLD INFORMATION - Use this knowledge about the world]

[Entry Title 1]: Entry content here...
[Entry Title 2]: Entry content here...
```

### Token Estimation

Budget is enforced using approximate token counting:

* Budget percent is stored in character blueprint: `blueprint.lorebook.budgetPercent`
* Default: 25% of model's context window
* Entries are sorted by priority (high to low)
* System injects entries until budget is reached

## See Also

* [Character Versions](https://docs.meganova.ai/character-studio/character-features/character-versions.md) — Version-control your characters
* [Advanced Settings](https://docs.meganova.ai/character-studio/character-features/advanced-settings.md) — System prompt and advanced character controls
* [Memory System](https://docs.meganova.ai/character-studio/chat-features/memory-system.md) — Conversation memory system
* [Token Management](https://docs.meganova.ai/character-studio/advanced/token-management.md) — Understanding token usage
