Use cases

NPC memory for AI-driven games

Give game characters a memory of each player that lasts between sessions, stays consistent as the story changes and keeps every save separate.

An NPC with memory remembers what the player did, what they said and how they treated it, and lets that history shape the next conversation. A blacksmith who recalls that you haggled him down last week, a companion who still resents being left behind in a dungeon, a quest-giver who knows you already turned her down: these are the moments players notice and talk about. Building them on top of a language model needs a memory layer that stores what happened for each player, keeps it consistent as the story moves on, and returns the relevant part quickly enough for dialogue.

This page describes how to build that layer on Exabase: a Base per player or save file, structured memories for what each character knows, lore stored as searchable resources, and Workers that tidy up between sessions. Exabase is the substrate here. Dialogue generation, game logic, voice and moderation stay in your engine and your model of choice.

The problem

Most LLM-driven NPCs start stateless. Each conversation begins from a system prompt describing the character, plus whatever the last few turns contain. That gives a convincing first meeting and a forgetful second one. The player returns after a weekend and the innkeeper greets them as a stranger, even though they saved her daughter in the previous session.

The usual fix is to append the conversation history to the prompt. It works for a short demo and breaks in a real game. A player who spends forty hours in a world produces far more dialogue than fits in a context window, and every extra token adds cost and latency to each line the NPC speaks. Trimming the oldest turns throws away the facts that matter most, such as the promise the player made in the first hour. Research on long inputs points the same way: models use the middle of a long prompt poorly, a pattern known as lost in the middle, so a longer history can leave an NPC less consistent.

The next fix is a vector database of past lines. Similarity search finds what resembles the current question, which is often a different thing from what is currently true. If the player sided with the rebels in act one and betrayed them in act three, both facts sit in the index with similar embeddings, and the NPC may thank the player for a loyalty that no longer exists. Games are full of state changes like this. Alliances shift, characters die, debts get paid and reputations rise and fall, and each change is a chance for memory drift.

Games also add constraints that chat products rarely face. Every player has their own version of the world, so one player’s choices must never leak into another’s save. Some facts are canon and must hold however a conversation goes. Dialogue sits in a real-time loop, so retrieval has to be quick. And players probe for weaknesses, so a memory that accepts anything said in conversation as truth invites memory poisoning and prompt injection.

What Exabase unlocks

With Exabase, each player’s history becomes a set of memories maintained by the M-1 engine: facts (“the player owes Brann 40 gold”), preferences (“the player prefers talking to fighting”) and events (“the player burned the mill in chapter two”). When a later event contradicts an earlier fact, contradiction resolution happens at write time, so the NPC retrieves one current state of the relationship instead of two conflicting ones. Before each dialogue turn, your game asks for the memories relevant to this character and this moment, and receives a short, ranked list ready for the prompt. It is the same approach set out in the agent memory solution, applied to characters rather than assistants.

Take a companion character in a role-playing game. In the first session the player rescues her from bandits and promises to help find her brother. Ten hours later the player leaves her behind to save a village. In the next session she should remember both the rescue and the abandonment, weigh them, and speak accordingly, while a shopkeeper in the same town knows only the public version of events. With a Base per save file and memories written as the story unfolds, the companion’s prompt carries a dozen or so relevant memories instead of ten hours of transcript. Each line stays consistent, and token costs stay flat as the playthrough grows.

How it works

Five parts of Exabase carry NPC memory: Bases to separate players and saves, Memory for what characters know, Resources and Deep Search for lore, and Workers for upkeep between sessions.

Bases

A Base is an isolated environment with its own memory, files and search index, created with one API call. The natural unit for a game is one Base per player, or one per save slot when players run several playthroughs. Because a scoped call cannot reach another Base’s data, one player’s betrayal never appears in another player’s world, and there is no tenant filter for a query to forget. This is the tenant isolation pattern used for multi-tenant SaaS, applied to save files.

Pass the Base ID on the SDK client or in the X-Exabase-Base-Id header, and every memory, search and Worker call is scoped to that save. The memory scoping guide covers the details. The Free plan allows up to 100 Bases and paid plans up to 10,000, with higher limits on request, so a game with a large audience should plan its Base allocation early; pricing lists the current plans.

Memory

Send dialogue to the Memory API after each conversation, or after each meaningful beat, with the source set to text. M-1 extracts the facts, preferences and events, connects them to existing concepts and resolves contradictions. Inferred memories are processed asynchronously, so writing them never blocks the next line of dialogue. For facts the game itself establishes, such as a quest outcome or a reputation change, set infer to false and store the exact text; verbatim memories are stored immediately.

Canon belongs in immutable memories. Mark a memory immutable and the self-organising process will not modify, consolidate or delete it. Use this for whatever must stay true regardless of what a player says: the king is dead, the player chose the northern route, the companion’s brother is called Aldric. It also limits what a player can achieve by trying to talk an NPC into a false belief. Conversation can still add memories, but the engine will not rewrite canon to match them.

Before an NPC speaks, call memory search with a query built from the situation: the character’s name, the location and the player’s last line. Search is hybrid, combining semantic and keyword matching with recency weighting, so recent events outrank old ones. Three parameters tune it. expandQueries (1 to 5) adds related queries when the answer spans several memories, a form of query expansion; rerankCandidates (1 to 500) sets how many candidates the reranking step considers; and rerankThreshold drops the weakest share of results. Simple retrieval returns in about 200ms. Expansion and reranking use a small amount of credits, so many games keep them for important conversations and use plain search for ambient barks.

For yes-or-no checks that do not need prompt assembly, such as whether the player has met the smith before, memories.ask returns a natural-language answer built from the relevant memories.

Memory is scoped by Base, not by character. Your game decides what each NPC witnessed or heard about, and writes memories with that in mind: “Mira saw the player steal from the temple” rather than “the player stole from the temple”. Include the character’s name in the search query and the right memories rank first. For relationships that must be strictly separate, such as a spy who must never learn what a priest heard in confession, give that relationship its own Base. This is a design choice for your writers more than an infrastructure one, and it pairs well with entity memory conventions for naming characters consistently.

Resources and Deep Search

Lore is a different kind of knowledge from memory. Item descriptions, faction histories, quest scripts and character bibles are shared by every player and change only with a patch. Store them as resources, and they are processed and indexed on upload, including PDFs and Word documents from the design team, through the same pipeline as Extract. Search runs against one Base at a time, so a game typically keeps lore in its own Base and queries it alongside the player’s save.

Deep Search returns the passage that answers a question, with a relevance score, instead of a whole document. The precision parameter (0 to 1, default 0.3) lets a quest-giver ask a narrow factual question at a high setting while a scholar who likes to ramble about history searches more broadly. This is retrieval-augmented generation for lore, and keeping it apart from player memory is deliberate: lore is the same for everyone, while memory is personal and changes with every session. The RAG vs agent memory entry explains the split in more detail.

Workers

Workers run jobs inside a Base, on a schedule or on demand. In a game they take the slow work out of the dialogue loop. After a session ends, a Worker can read the session log saved as a note, summarise what changed for each major character and update memories, since Workers have access to memory tools. Every run is recorded as a conversation with its tool calls, so a writer can see why a character’s view of the player changed. The creating Workers guide shows the configuration. For simpler games, M-1’s own memory consolidation is enough, and Workers can be added later.

Example architecture

The shape is a lore Base shared by all players, a Base per save file, a write path after each conversation and a read path before each line.

Set up. When a new game starts, create a Base for the save and write the starting canon as immutable memories: the player’s chosen background, each companion’s backstory and any facts the opening establishes.

Before a line. Build a query from the character, the location and the player’s last line. Search the save’s memories and keep the top few results. For lore questions, search the lore Base with a high precision setting. Put both into the character’s prompt next to its character sheet.

After a conversation. Send the exchange to the Memory API as text so M-1 can extract what it established. Write outcomes the game decided, such as a completed quest, as verbatim memories. Neither step blocks gameplay.

Between sessions. Run a Worker on the save’s Base to process the session log, or rely on M-1’s consolidation for simpler games. When a player deletes a save, delete its Base, which removes its memories, files and history permanently.

Game need

Exabase part

Notes

Separate playthroughs

Bases

One per save; up to 10,000 on paid plans

What an NPC knows about the player

Memory

Facts, preferences and events, contradictions resolved on write

Canon that must not change

Immutable memories

Not modified, consolidated or deleted by the engine

Context before a line

Memory search

About 200ms for simple retrieval

Lore and item text

Resources and Deep Search

Passages with relevance scores

Upkeep between sessions

Workers

Scheduled or on demand, every run inspectable

Deleting a save

Base deletion

Permanent; confirmation email unless force is set

Latency and rate limits

Dialogue is where players feel latency most. Simple memory retrieval takes about 200ms, which fits inside the time a model takes to produce its first words, but it should run alongside other work rather than in front of it. Start the memory search as soon as the player opens a conversation, and reuse the results for the rest of that exchange. That keeps time to first token close to what the model alone would give.

Rate limits apply per developer account across all API keys: 1,000 requests an hour on Free and 5,000 on Scale, with HTTP 429 beyond that, as described in the rate limiting docs. That suits story-driven dialogue, where memory calls happen per conversation rather than per frame. A game with many concurrent players should batch writes at conversation boundaries and plan capacity with the Exabase team before launch, since Enterprise plans are set individually.

What compounds over time

An NPC with memory gets more interesting the longer someone plays. Relationships gather texture: the companion remembers the three times the player chose mercy, and her dialogue starts to reflect it. Because M-1 consolidates duplicates and resolves contradictions as it goes, the memory set stays compact instead of growing into a transcript, so retrieval quality and the cost of each line hold steady at hour forty much as they did at hour two. M-1 scores 96.4% on LongMemEval and leads BEAM at 100K, 1M and 10M tokens, with its lead widest at 10M, which is roughly the scale of a long playthrough; the published research has the details.

This is the pattern explored in research on generative agents, where simulated characters store observations, reflect on them and plan from them. Exabase provides the storage, consolidation and retrieval half of that loop. Your game supplies the reflection prompts, the planning and the behaviour.

Boundaries

Exabase stores and retrieves what characters know. It does not generate dialogue, run game logic, decide which NPC witnessed which event, synthesise voice or moderate player input; those stay in your engine and your model. Memory is scoped by Base, so knowledge per character comes from how you write and query memories, or from separate Bases where relationships must be kept apart. Exabase offers a TypeScript SDK and a REST API rather than engine plugins, so calls go through your game backend, which also keeps the API key off players’ machines. Inferred memories are model output: test them with your writers, and keep anything that must not change in immutable memories.

Who’s building this

Studios building companion characters and narrative role-playing games, teams adding conversational NPCs to simulation and life games, interactive fiction platforms where each reader’s story branches, and educational games where a tutor character remembers what a student found hard, which overlaps with learning copilots. Many of the same needs appear in AI companion apps and in voice agents, where a spoken character has even less room for a long prompt. Teams in media, education and AI startups use the same building blocks.

Get started

Follow the getting started guide, create a Base for a test save, and write one character’s canon as immutable memories. Play through a short scene, send the dialogue to the Memory API, then search from a fresh session and see what the character can recall. The creating memories guide covers inferred and verbatim writes, and the retrieving memories guide covers the search parameters. To compare approaches first, Exabase vs Mem0, Exabase vs Letta and the best agent memory platforms roundup set out the options.

Frequently asked questions

What is NPC memory in AI games?

NPC memory is the record of what a non-player character knows about the player and the world, kept between conversations and sessions and given to the language model that writes the character’s dialogue. On Exabase it is a set of structured memories in a Base per save, retrieved before each line.

How is NPC memory different from dialogue history?

Dialogue history is every line spoken, while memory is what those lines established. Memory stays small and current as the story changes; history grows without limit and keeps outdated facts beside current ones. The summarization vs memory entry covers why summaries do not close the gap.

How do I stop players changing an NPC’s core facts through conversation?

Write canon as immutable memories. The self-organising process will not modify, consolidate or delete them, so dialogue can add new memories without rewriting what the game has fixed.

Can each NPC know different things about the player?

Yes, with some design. Memory is scoped by Base, so write memories that name the character who learned them and include that name in search queries. Relationships that must be strictly separate can have their own Base.

Is retrieval fast enough for real-time dialogue?

Simple retrieval takes about 200ms. Start the search when a conversation opens, run it alongside other work and reuse the results for the rest of the exchange.

What happens to memories when a player deletes a save?

Delete the save’s Base. That permanently removes its memories, files, search index and history. By default Exabase emails a confirmation link first; pass force=true to delete immediately.

Does Exabase run inside Unity or Unreal?

Exabase is a cloud API with a TypeScript SDK and a REST API. Call it from your game backend so the API key stays server-side, and send the results to the client.

Related pages: AI companions, Voice agents, Long-term memory, Agent memory solution, Generative agents, Episodic vs semantic memory, Agent memory, Exabase vs Zep, Voice agents need memory more than chatbots do

Cut your token spend and give your agent precise context.

Get started in minutes.

Cut your token spend and give your agent precise context.

Get started in minutes.