> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Keep long roleplay memory consistent while controlling token cost

> Structure character cards, lorebooks, prompt prefixes, SillyTavern config.yaml cache flags, and batch summaries to hit BeatAPI cached input and prevent mid-story amnesia.

Every turn in a roleplay client resends the active system prompt, character card, triggered lorebook entries, and chat history. Without structure, turn 50 pays for turn 1 fifty times. Combining **a byte-identical prompt prefix** (for BeatAPI cached input), **keyword-triggered lorebooks**, and **batch summarization before full context** keeps memory coherent while bounding per-turn spend.

## Deliverable and verification standard

A completed long-memory setup enforces three rules:

1. Static instructions and character definitions stay byte-identical at the start of every request so BeatAPI cached-input pricing applies.
2. Dynamic items (timestamps, lorebook triggers, Author's Notes) stay near the end of history so they do not break the cached prefix.
3. Active history gets summarized in batches before hitting the client's Context Size limit, preventing sliding-window cache misses and high-context pricing tiers.

Verify the setup in [Dashboard → Usage](https://beatapi.io/dashboard) across 10 consecutive turns: per-turn input cost should stabilize instead of rising linearly.

## Step 1: Turn on caching and lock a byte-identical prefix

BeatAPI bills cached input below fresh input when the client sends cache breakpoints and consecutive requests start with identical bytes.

When running Claude in SillyTavern, enable the two caching flags in `config.yaml` and restart SillyTavern (both flags default to off):

```yaml
claude:
  enableSystemPromptCache: true
  cachingAtDepth: 2
```

In SillyTavern's **Prompt Manager** (or Tavo / OMate preset ordering), order blocks from static to dynamic:

1. **System prompt and writing rules** (fixed)
2. **Character card core definition and user persona** (fixed)
3. **Rolling story summary** (updated in batches every 15–20 turns)
4. **Chat history** (oldest to newest)
5. **Triggered lorebook entries and Author's Note** (inserted at depth 2–4 near the bottom of history, below the static prefix)

Keep dynamic macros (`{{time}}`, `{{date}}`, random dice rolls, or shuffled world-info blocks) out of the top blocks, because any byte change at the top invalidates the entire cached prefix. Keep `cache_control` off historical thinking blocks.

## Step 2: Move background lore into keyword-triggered lorebooks

Placing 10,000 tokens of world background directly inside a character description charges those tokens on every turn, including quiet two-character scenes that never reference those locations or factions.

* Keep only core personality, speech habits, and current relationships inside the character card.
* Move side characters, locations, past arcs, and world rules into **Lorebook (World Info)** entries triggered by explicit keywords.
* Set a **Lorebook token budget** of `1500`–`2500` tokens so a turn mentioning several keywords does not inject dozens of entries at once.

## Step 3: Prevent full-context sliding-window cache misses

Once a chat hits the configured **Context Size** ceiling, every new turn drops the oldest message from the front of history. Removing turn 1 changes every byte that follows, so prompt caching stops hitting on new turns and hits only on **Regenerate / Swipe**. Certain models also switch to a higher per-token tier above a context threshold (most GPT-6 models above 272K input tokens and Grok above 200K input tokens; see [Cost optimization](/faq/cost-optimization)).

* Set the client's **Context Size** slider to the story length you actually need (`16,000`–`32,000` tokens for most long stories).
* Before the chat reaches that ceiling, summarize and trim the oldest **25%–50%** of turns into 3–5 factual bullet points (location, relationship shifts, promises, inventory, unresolved conflicts) using `glm-5.3-flash` or `deepseek-v4.1-flash`. Freeing 25%–50% of the window lets the next 15–20 turns accumulate against one stable cached prefix. See [Dual-model roleplay workflow](/guides/roleplay-dual-model-workflow).
* Leave the summary text unchanged between batch updates, and keep reply intervals inside the \~5-minute cache TTL during continuous play.

## Step 4: Watch peak-hour pricing and stream every turn

* **Peak-hour rules**: BeatAPI's DeepSeek HC (`-hc`) models apply peak-hour multipliers on weekdays 09:00–12:00 and 14:00–18:00 Beijing time. Regular paid DeepSeek models (`deepseek-v4-pro-0813`, `deepseek-v4.1-flash`) bill one flat rate all day. Exact hours appear in the [pricing page](https://beatapi.io/pricing) footnotes.
* **Streaming enabled**: Keep streaming on so you can stop an off-character or repetitive reply after 100 tokens instead of paying for a 2,000-token swipe.

## Related

* [Prompt caching not hitting](/faq/roleplay-prompt-caching-not-working)
* [Dual-model roleplay workflow](/guides/roleplay-dual-model-workflow)
* [Cost optimization](/faq/cost-optimization)
* [Roleplay timeouts and cut-offs](/faq/roleplay-timeout-truncation)