Sub topic 14
When to Move History Out of the Prompt Entirely
This chapter assumes you have read the earlier chapters on token budgets, sliding-window truncation, and rolling summaries. You should be comfortable with chat message roles and with the Python helpers estimate_tokens, truncate_history, compact, and build_request from those chapters.
Truncation and summaries share one design: the prompt carries everything the model may need. Past a certain point that design stops working. This chapter covers how to recognize that point and what to do about it. The coverage is shallow by design, because external memory is a large topic of its own. The goal is to help you decide when to leave the prompt and what the options are.
Where the in-prompt approach runs out
The hybrid strategy (system prompt, rolling summary, recent verbatim messages) works well for a single conversation of moderate length. It has three structural limits.
- The summary has a size cap. The summarization prompt asks for under 300 words. Every fact you keep in it competes with every other fact. Once a conversation has produced more important details than fit in 300 words, something is dropped.
- Summaries lose detail on each pass. In a rolling summary, a fact that survives ten compactions has been rewritten ten times. Exact values such as file paths, order numbers, and amounts are the first to drift.
- Nothing outlives the conversation. If the user comes back tomorrow and starts a new thread, the old summary is not in the new request unless you put it there.
Raising the budget does not fix these. A larger window costs more per request, adds latency, and still ends at some limit. The alternative is to store information outside the prompt and put only the relevant part back in when needed.
Signs you need external memory
Look for these symptoms before you add infrastructure. Each one points to a problem that in-prompt strategies cannot solve well.
| Symptom | Why truncation and summaries fall short | What to consider |
|---|---|---|
| Users expect the assistant to remember across sessions | The prompt exists only for one request chain | Persist facts or summaries per user |
| Tests for exact values keep failing after compaction | Summaries paraphrase and compress | Store exact values in a structured record |
| Conversations reference old turns that are no longer in the window | The turns were dropped or merged into a summary | Keep the full transcript and retrieve from it |
| The summary hits its length cap and keeps losing items | One summary cannot hold everything | Split it into several stored notes |
| A large document or log is pasted into the chat | One message consumes most of the budget | Store the document and retrieve passages |
| Cost per request is dominated by repeated history | Every turn resends the same tokens | Send only what is relevant to this turn |
If none of these applies, stay with the hybrid strategy. It has no extra moving parts and is easy to test.
The three main patterns
Most external memory designs are combinations of three patterns.
Full transcript storage
Keep every message in a database, outside the prompt. The prompt still uses the hybrid strategy, but nothing is ever truly lost. This gives you an audit trail and lets you rebuild summaries if your summarization prompt improves. It also makes the other two patterns possible, since they need a source to draw from.
On its own, a stored transcript does not help the model. The model sees only what you put in the request.
Structured facts
Some information is better as data than as prose: the user's name, their preferred language, the file they are working on, the decision they made about a database. Extract these into a small key-value record and render them into the prompt in a fixed format.
Compared with a free-text summary, structured facts have two advantages. Exact values are copied rather than paraphrased, and you can update one field without rewriting the rest.
The code below keeps a fact store and renders it as a system message. It reuses the idea from build_request, which places a system message between the main prompt and the recent window.
def render_facts(facts):
# facts: dict of short keys to exact string values.
if not facts:
return None
lines = [f"- {key}: {value}" for key, value in sorted(facts.items())]
return {
"role": "system",
"content": "Known facts about this user and task:\n" + "\n".join(lines),
}
def build_request_with_facts(system_prompt, facts, summary, recent):
messages = [{"role": "system", "content": system_prompt}]
facts_message = render_facts(facts)
if facts_message:
messages.append(facts_message)
if summary:
messages.append({
"role": "system",
"content": "Summary of the earlier conversation:\n" + summary,
})
messages.extend(recent)
return messages
facts = {
"database": "PostgreSQL 16",
"deploy_target": "eu-west-1",
"user_name": "Priya",
}
request = build_request_with_facts(
"You are a helpful assistant.",
facts,
"",
[{"role": "user", "content": "Which region are we deploying to?"}],
)
for message in request:
print(message["role"], "|", message["content"].replace("\n", " / "))The harder part is deciding how facts get into the store. You can extract them with a model call after each turn, or let the assistant call a "remember" tool. Either way, treat the extraction as a write path that can fail, and log what was written.
Retrieval
Retrieval stores chunks of past content (old messages, documents, notes) along with an index, and fetches the few most relevant chunks for each new user message. The usual index is an embedding index. An embedding is a list of numbers produced by a model so that texts with similar meaning have similar numbers. You embed each chunk when you store it, embed the new query at request time, and return the chunks closest to the query.
The retrieved chunks are added to the prompt in a labeled block, in the same way the summary is. The prompt size then depends on how many chunks you retrieve, not on how long the conversation has been.
Keyword search, such as full-text search in a database, is a valid alternative. It works well when users refer to exact names or identifiers, where embedding search can miss.
How the pieces fit together
The hybrid strategy is not replaced. It gains two more sources of context, each filled from storage.
Each source takes part of the input token budget. Decide the split up front, for example: system prompt 500 tokens, facts 300, retrieved chunks 1,500, summary 400, and the rest for recent messages. Without explicit allocations, a retrieval step that returns too much will push out the recent window, and the model will lose the immediate conversation.
Costs and failure modes
External memory trades one set of problems for another. Know these before committing.
- Retrieval misses. If the relevant chunk is not among the top results, the model answers as if the information did not exist. Vague follow-ups such as "what about the second one?" contain little to search on. A common fix is to build the query from the last few messages instead of only the newest one.
- Retrieval returns noise. Irrelevant chunks use budget and can mislead the model. Set a minimum similarity score and allow zero results.
- Stale facts. If the user changes their mind, the store must be updated or the old value will keep coming back. Store a timestamp with each fact and make updates replace, not append.
- Wrong facts get stored. A model-driven extractor can record something the user never said. Because stored facts persist, the error repeats in every later session. Keep extraction conservative and let users view and delete what is stored.
- Privacy and retention. Persisted conversation data is personal data. Decide how long you keep it, who can read it, and how a user deletes it. In-prompt history disappears when the session ends. Stored history does not.
- More to operate. A database, an index, and a write path each need monitoring and tests.
A decision guide
Use this order of questions to pick a design.
- Does the whole conversation fit in the budget with room for the reply? Send it as is.
- Does it fit after truncation, and is losing the oldest turns acceptable? Use a sliding window with a pinned system prompt.
- Do older turns matter in general terms but not in exact detail? Add a rolling summary and use the hybrid strategy.
- Do exact values need to survive, or must memory last across sessions? Add structured facts.
- Does the assistant need to look up large or numerous past items on demand? Add retrieval over a stored transcript or documents.
Move down this list only when the earlier option fails a test you wrote. The evaluation chapter covers how to write those tests, and the same tests tell you when a step down is justified. If your compaction test for exact values fails, that is evidence for structured facts. It is a better reason than a general sense that more memory is better.
Exercises
Exercise
A support assistant uses a rolling summary capped at 300 words. In testing, order numbers mentioned early in long conversations come back wrong or missing after several compactions. Which external memory pattern fits best, and why?
Show answer
Structured facts. Order numbers are exact values, and a rolling summary rewrites them on every pass, so they drift or get dropped when the 300-word cap is reached. Storing them in a key-value record copies them exactly and lets you update one field without touching the rest. Render the record into the prompt as its own system message, and keep the summary for general context.
Exercise
You add retrieval and set it to return the 10 closest chunks per request. After the change, the assistant starts ignoring what the user said two messages ago. What is the likely cause, and what are two fixes?
Show answer
The retrieved chunks are using too much of the input token budget and pushing out the recent verbatim messages. Fixes: give retrieval a fixed token allocation and reduce the number of chunks to fit it, and apply a minimum similarity score so weak matches are dropped. Reserving a minimum size for the recent window before filling the rest also works.