Conversation Memory is a pattern that maintains context across multiple turns of a dialogue by storing and retrieving previous messages. Because LLM APIs are stateless, the application has to manage conversation history, summarization, and context window limits itself.
At a Glance
- Problem: LLM APIs are stateless, so the client must resend history with every turn. As conversations grow, that history raises cost and latency, weakens attention to details in the middle, and eventually exceeds the context window.
- Forces: Complete context versus a fixed token budget; compression saves tokens, but the model may summarize away a detail that matters later; preprocessing history preserves more, but adds model calls and response latency.
- Solution: Choose a strategy for what history enters each call: full history for short sessions, a sliding window of recent turns, a running summary of older turns, extracted entity facts, or a hybrid of these.
- Consequences: Gains: coherent multi-turn dialogue within a bounded context budget. Costs: dropped or summarized turns lose information for good, summarization and entity extraction add model calls and engineering, and entity records need validation to stay accurate.
What problem does Conversation Memory solve?
LLM APIs are stateless. That sounds obvious once you know it, yet it catches many developers off guard: when you send a message to a model, it has no idea what you said five minutes ago. Each API call stands on its own. The model receives a block of text, generates a response, and forgets everything.
A chatbot only seems to remember because the client does the remembering. The application keeps track of the message history and sends the entire conversation, every previous turn, with each new request. The model reads all of it and responds as if it had been participating all along.
This works for short conversations, but conversations grow. A 20-turn conversation might consume 8,000 tokens of context just for the history, and a technical support session that goes back and forth for an hour could exceed 30,000 tokens. Eventually the history no longer fits in the context window, and it causes problems well before that. The model takes longer to respond because it processes more tokens, and costs rise because you pay per token. Attention can also degrade over very long contexts, so the model misses details buried in the middle of the history.
You need a strategy for deciding what conversation history goes into the context window, chosen from what your application needs to remember rather than copied from a default.
How does Conversation Memory work?
Conversation memory is the set of techniques for deciding which parts of the conversation history to include in each API call. The main strategies follow.
Full history is the simplest approach. Include every message from the conversation in every request. This preserves complete context and is the right choice for short conversations where you will never approach the context limit. Most prototypes start here. Eventually the history exceeds the context window and you have to truncate anyway. But for conversations where total history stays under roughly 20% of your model's context window (about 60 turns at 400 tokens per turn for a 128K-token model), full history is adequate and the simplest thing that works.
Sliding window keeps only the most recent N turns. Older messages are dropped. This guarantees a fixed context size and works well for applications where recent context matters more than distant history. A coding assistant that helps you debug step by step mostly needs the last few exchanges. What you discussed 50 turns ago is rarely relevant to the current error message. You lose information abruptly, though. If the user stated a critical constraint in turn 3 and you are now on turn 25 with a window of 10, that constraint is gone.
Summary memory periodically compresses older turns into a condensed summary. You keep the recent turns in full and prepend a summary of everything that came before. When the history grows beyond a threshold, you ask the model to summarize the oldest unsummarized turns and replace them with that summary. The summary preserves the gist of earlier conversation while using far fewer tokens. Unlike a sliding window, it lets important information from early turns survive in compressed form.
Entity memory takes a structured approach. Instead of summarizing the conversation as prose, you extract and maintain a running record of entities mentioned, their attributes, and relationships. The user mentioned they work at Acme Corp on the billing team and their manager is Sarah. You store these facts as structured entries and inject them into the context as a factsheet, independent of the conversation turns. This works well when the conversation revolves around specific entities (people, projects, products) and you need to track evolving facts about them.
Hybrid approaches combine multiple strategies. A common production setup uses summary memory for older turns, full history for the most recent turns, and entity memory for key facts. The summary carries general context, the recent turns keep the conversational flow, and the entity facts hold the details you cannot afford to lose.
When should you use Conversation Memory?
Every conversational LLM application needs some form of conversation memory. The question is which strategy fits your use case.
Start with full history if your conversations are typically short (total history stays under roughly 20% of your model's context window) and your context window is large. Do not over-engineer memory management for conversations that will never hit the limit.
Use a sliding window when recency is what matters. Customer support chats where each question is relatively self-contained, coding assistants where the current task is all that matters, and casual chatbots all work well with a window of the last 5-10 turns.
Use summary memory when conversations are long and the early context stays relevant. Consulting sessions, tutoring interactions, and project planning conversations all need a compressed record of what was discussed earlier.
Use entity memory when your application revolves around tracking specific objects or people. CRM assistants, project management tools, and relationship management applications need to know facts about entities rather than the flow of conversation.
When not to use it: Single-turn tasks such as one-off classification or extraction have no history to manage, so send each request on its own. If the assistant must recall preferences or facts in a new session days later, a per-session strategy cannot help, because history ends with the session; use Long-Term Memory. And when sessions stay short, skip summary and entity memory entirely, since they add model calls and lossy compression for no saving over full history.
Implementation
# Using OpenAI SDK for illustration — swap client for any provider
from openai import OpenAI
client = OpenAI()
class SlidingWindowMemory:
"""Keep only the last N turns in the conversation history."""
def __init__(self, window_size: int = 10, system_prompt: str = "You are a helpful assistant."):
self.window_size = window_size
self.system_message = {"role": "system", "content": system_prompt}
self.messages: list[dict] = []
def add_user_message(self, content: str):
self.messages.append({"role": "user", "content": content})
self._trim()
def add_assistant_message(self, content: str):
self.messages.append({"role": "assistant", "content": content})
self._trim()
def _trim(self):
# Keep last window_size * 2 messages (each turn = user + assistant)
max_messages = self.window_size * 2
if len(self.messages) > max_messages:
self.messages = self.messages[-max_messages:]
# Never start the window on a reply whose question was trimmed away
while self.messages and self.messages[0]["role"] != "user":
self.messages.pop(0)
def get_context(self) -> list[dict]:
return [self.system_message] + self.messages
def chat(self, user_input: str) -> str:
self.add_user_message(user_input)
response = client.chat.completions.create(
model="gpt-4o",
messages=self.get_context(),
)
reply = response.choices[0].message.content
self.add_assistant_message(reply)
return reply
# Usage
memory = SlidingWindowMemory(window_size=5)
print(memory.chat("My name is Alice."))
print(memory.chat("What's my name?")) # Should remember: "Alice"
Worked Example: Cost and Latency
A support chat runs 40-turn sessions on the large model, with a 500-token system prompt and 200-token user and assistant messages, so 400 tokens per turn, matching the 20-turn, 8,000-token example above.
| Strategy | Model calls per session | Input tokens per session | Input tokens at turn 40 | Cost per 1,000 sessions |
|---|---|---|---|---|
| Full history | 40 | 340,000 | 16,300 | $1,140.00 |
| Sliding window (last 10 turns) | 40 | 166,000 | 4,700 | $618.00 |
| 800-token summary (small model, every 10 turns) + turns since | 43 | 124,000 | 5,100 | $495.48 |
Every strategy writes 40 × 200 = 8,000 output tokens, or $0.12 per session at $15.00 per million, and each turn takes 0.5 s + 200 / 60 ≈ 3.8 s under our latency formula, which ignores input length, so the difference shows up in cost. Full history sends 500 + 400 × (t − 1) + 200 tokens at turn t, which adds up to 340,000 input tokens, or $1.02 at $3.00 per million. The window caps history at 4,000 tokens, for 166,000 tokens and $0.50. The summary strategy makes three extra small-model calls after turns 10, 20, and 30, each reading up to 4,800 tokens and writing 800, for $0.0035 per session, and its main calls read 124,000 tokens, or $0.37.
Over 40 turns the window and summary strategies cut cost by about 46% and 57%, but for sessions of 10 turns or fewer all three send the same tokens, so full history is the right default there.
What are the common pitfalls?
Summary compression loses information. The model decides what is "important" when generating the summary, and it does not always decide correctly. A detail that seemed minor at the time might become critical later. Once it is summarized away, it is gone. A conservative summarization prompt that errs toward keeping detail reduces the loss, but you always trade compression ratio against how much information survives.
Sliding windows create a jarring experience when users reference things from before the window. "Remember when I said I needed the blue version?" The model has no memory of that exchange and either confesses ignorance or, worse, confabulates an answer. If your application uses a sliding window, consider telling users about the memory horizon or letting them pin important messages.
Entity extraction makes mistakes. The model may miss entities, extract incorrect attributes, or fail to update an entity when new information is provided. Entity memory needs validation and correction steps to stay accurate over time.
Context window cost is often underestimated. If you are using summary memory with a 2,000-token summary plus the last 10 turns plus a system prompt, you might be using 5,000 tokens of context before the model generates a single token. At API pricing, that adds up across millions of conversations.
What are the trade-offs?
Simpler strategies (full history, sliding window) are easier to implement but less effective at preserving important information over long conversations. Complex strategies (summary memory, entity memory, hybrids) preserve more information but require more engineering effort, more model calls for summarization and extraction, and more careful testing.
Summary memory costs extra because each summarization step is an additional model call. If you summarize every 10 turns, you add roughly 10% overhead in model calls. That is usually worth it for the context savings, but it is a real cost.
There is a latency component to any strategy that pre-processes history. Summarizing older turns or extracting entities before generating a response adds time. For applications where every millisecond of response time matters, you may need to run these processes asynchronously between turns rather than synchronously during generation.
No strategy fully solves the underlying problem. Context windows are finite and conversations have no fixed length, so some information will always be lost or degraded. Aim to lose the least important information first and keep what matters most for the user's current needs.
Goes Well With
Long-Term Memory extends conversation memory across sessions. Conversation memory manages the current session. Long-term memory persists important facts and preferences to an external store that survives between sessions. Most applications that care about memory need both layers.
Prompt Caching reduces the cost of conversation memory. If the beginning of your prompt (system message, summary, entity facts) stays stable across turns, prefix caching avoids reprocessing those tokens. Summary memory gains the most, because its compressed history changes infrequently.
Basic RAG can supplement conversation memory with external knowledge. When the conversation references information that is neither in the history nor in the model's training data, RAG retrieves it from a knowledge base. The combination of conversation memory (what was discussed) and RAG (what the system knows) gives the model both kinds of context when it writes a response.
References
- Park, J.S., et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. UIST 2023. arXiv