Reliable conversation memory is less about sending every previous message and more about deciding what to retain, summarize, retrieve, and delete. This guide shows how to build an AI chatbot with memory by combining a context-window budget, structured session storage, rolling summaries, and explicit reset and expiration rules.
Overview
An AI chatbot does not automatically remember a conversation in the way a human does. In most LLM app development architectures, the application receives a new request, assembles relevant context, sends it to the model, and stores the result for later use. Conversation memory is therefore an application design problem.
The simplest implementation sends the complete message history with every request. This can work for short sessions, but the request grows as the conversation continues. Long histories consume more of the chatbot context window, increase processing cost when pricing is token-based, and may include outdated or sensitive details that are no longer needed.
A more durable design separates memory into layers:
- Recent messages: The latest turns, preserved nearly verbatim so the assistant can respond naturally.
- Conversation summary: A compact record of goals, decisions, constraints, and unresolved questions from older turns.
- Structured user memory: Stable facts such as preferred output format, account settings, or explicitly saved preferences.
- Retrieved knowledge: Documents or records fetched for the current request, rather than treated as permanent conversation history.
This layered approach helps you build an AI assistant that remembers what matters without assuming that every past message belongs in every prompt.
Memory strategy comparison
| Strategy | Best for | Primary limitation |
|---|---|---|
| Full message history | Short chats and prototypes | Context and request size grow continuously |
| Rolling summary plus recent turns | General-purpose chatbots | Summaries can omit details if not evaluated |
| Structured memory fields | Preferences and repeatable workflows | Requires a schema and update rules |
| Vector or document retrieval | Large knowledge collections | Retrieval quality must be tested separately |
| Hybrid memory | Production assistants with varied use cases | More components and failure modes to monitor |
How to estimate
Before selecting a storage system or framework, estimate how much context each request needs. The goal is not to fill the model’s maximum context window. Reserve space for the system instructions, retrieved material, the user’s new message, and the assistant’s response.
Use this repeatable worksheet:
- Available context: Start with the context capacity documented for the model and deployment you plan to use.
- Fixed instructions: Estimate the tokens used by the system prompt, tool definitions, output rules, and safety instructions.
- Retrieved context: Set a maximum for documents, database results, or tool output added to a request.
- Response reserve: Keep a deliberate allowance for the model’s answer, structured output, or tool calls.
- Memory budget: Subtract the previous three categories from the available context.
- Recent-turn budget: Reserve only part of the memory budget for verbatim messages; use the remainder for a summary or structured facts.
A simple expression is:
memory budget = context capacity - instructions - retrieved context - response reserve
Do not treat this as a precise cost forecast. Tokenization varies by language, formatting, and model. Instead, use measured token counts from representative conversations and track both average and high-percentile requests. A chatbot that appears efficient on short test prompts may behave differently when users paste logs, code, or long documents.
For operational cost estimation, record the input and output token counts for each request, then group them by route or feature. A useful planning formula is:
estimated usage = requests × average input tokens + requests × average output tokens
Keep model pricing as a replaceable input rather than embedding it in application logic. Provider prices, model limits, and API behavior can change, so the estimate should be recalculated from the current provider documentation before a launch or migration.
Inputs and assumptions
Store messages as events
A practical chatbot session-storage schema treats each message as an event rather than storing one large transcript blob. A relational design might include:
sessions
- id
- user_id
- status
- created_at
- updated_at
- expires_at
- summary
- summary_version
messages
- id
- session_id
- role
- content
- sequence_number
- token_count
- created_at
- redaction_status
memory_items
- id
- user_id or session_id
- category
- value
- source_message_id
- confidence
- created_at
- updated_at
- expires_at
The exact schema can differ, but keep session identity, message order, and timestamps explicit. Store token counts when available so budgeting and debugging use observed values. Keep summary versions so a faulty summarization pass can be identified or replaced.
Define what memory means
Separate facts the user explicitly asked the assistant to remember from facts inferred from casual conversation. For example, a saved preference such as a requested date format is different from an uncertain assumption about the user’s job or location. Your application should provide a way to inspect, edit, and delete durable memory.
Session memory also needs lifecycle rules. Decide whether an inactive session expires, whether users can start a fresh thread, and whether deleted sessions are removed immediately from active stores, search indexes, backups, or analytics pipelines. Avoid placing secrets, access tokens, or unnecessary personal information into a summary.
Use a controlled summary prompt
Summarization should preserve information that affects future decisions, not merely shorten the transcript. A reusable prompt template might look like this:
System: You maintain a factual summary of a chatbot session.
Update the existing summary using the new conversation turns.
Preserve:
- the user’s stated goal
- confirmed constraints and preferences
- decisions already made
- unresolved questions
- tasks and their status
Remove:
- greetings and repetition
- unsupported guesses
- sensitive data that is not required for the task
Label uncertainty clearly. Do not invent facts.
Return only the updated summary.
Existing summary:
[summary]
New turns:
[recent turns]
Run this update when the recent-message budget is exceeded, after a meaningful decision, or at a controlled checkpoint. Do not summarize after every short exchange unless testing shows that the additional latency and usage are justified.
Worked examples
Example 1: A short support session
Suppose a support chatbot handles a brief conversation with a small system prompt and no document retrieval. Full history may be the simplest choice. Store every message, load the session’s recent turns, and send them with the new request. Add a maximum message count or token threshold so an unexpectedly long user paste triggers compaction instead of an oversized request.
Example 2: A project-planning assistant
A planning assistant may need to remember a project goal, deadline, preferred format, and open decisions across many turns. Store those items as structured fields, retain a rolling summary for narrative context, and include only the latest turns verbatim. If the user corrects a deadline, update the structured field and record the change rather than allowing an older summary to override it.
Example 3: A document-aware chatbot
For a chatbot that answers questions about a document collection, conversation history and knowledge retrieval should remain separate. The session stores the user’s question and the assistant’s answer. A retrieval layer fetches relevant passages for each new question. If you need this architecture, a RAG document ingestion pipeline should track parsing, metadata, deduplication, and reindexing independently from chat memory.
When memory is assembled, use an explicit order: system instructions, durable preferences, session summary, recent turns, retrieved context, and the current user message. The order and labels should be stable enough to inspect in logs and evaluate in tests.
When to recalculate
Revisit your memory design whenever an input changes. Recalculate the context budget when you change models, system instructions, tool definitions, retrieval limits, response length, or output format. Recheck usage when conversation length, average user message size, or the proportion of document-heavy requests changes.
Review storage and retention assumptions when you add a new client, user-facing export, analytics destination, or memory feature. Confirm that reset and deletion actions reach every active representation of the session, including summaries and retrieved-memory indexes where applicable.
Use a small evaluation set before changing the summary prompt. Include conversations with corrections, conflicting preferences, long pasted content, unresolved tasks, and explicit requests to forget information. Measure whether the new summary preserves the facts needed for the next response and removes details that should no longer influence it. The production LLM evaluation dataset guide can help turn representative queries into repeatable tests.
Finally, add operational checks:
- Show users when they are starting a new session or resetting memory.
- Set maximum sizes for messages, summaries, retrieved context, and tool output.
- Log token counts, truncation events, summary updates, and retrieval identifiers without logging unnecessary sensitive content.
- Test expired sessions, duplicate requests, failed summary updates, and provider errors.
- Keep prompts versioned so memory changes can be compared and rolled back.
Reliable conversation memory is an iterative system, not a single database feature. Start with recent messages and a clear session key, add summaries when the measured context budget requires them, and introduce structured or retrieved memory only for a defined user need. Revisit the estimates whenever models, traffic, prompts, or retention requirements change.