Sub topic 14
When to Move History Out of the Prompt Entirely
This chapter assumes you have read the earlier chapters. You should know how a sliding window and a rolling summary work, and you should be comfortable with chat message roles and token budgets.
The limit of in-prompt memory
Truncation and summaries both keep history inside the prompt. Every request still carries the system prompt, a summary, and recent messages, and all of it must fit in the input budget. That design has two limits.
- The budget is fixed. A summary of a very long relationship (months of sessions) either grows past its cap or drops detail.
- Repeated summarization compounds loss. Each pass rewrites text that was already a rewrite.
External memory removes both limits. You store history outside the prompt, then retrieve only the parts that matter for the current request.
How external memory works
The pattern has two operations: write and read.
- Write: after each turn, or after a session ends, save the content in a store. The content can be raw messages, extracted facts, or per-session summaries.
- Read: before each request, use the newest user message to find relevant stored items.
- Inject: add the retrieved items to the prompt, in the same place where the summary went.
The store can be a database table, a key-value store, or a vector index. Retrieval can use keyword search, embedding similarity, or a lookup by user ID.
A minimal example
The sketch below stores short facts per user and retrieves them by keyword overlap. It is deliberately simple. A real system would use a database and better ranking.
import re
def words(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
class MemoryStore:
def __init__(self):
self.facts = {} # user_id -> list of fact strings
def add(self, user_id, fact):
self.facts.setdefault(user_id, []).append(fact)
def search(self, user_id, query, limit=3):
query_words = words(query)
scored = []
for fact in self.facts.get(user_id, []):
score = len(query_words & words(fact))
if score > 0:
scored.append((score, fact))
scored.sort(key=lambda pair: pair[0], reverse=True)
return [fact for _, fact in scored[:limit]]
store = MemoryStore()
store.add("u1", "The user deploys to AWS region eu-west-1.")
store.add("u1", "The user prefers Python 3.12 and type hints.")
store.add("u1", "The user's dog is named Biscuit.")
print(store.search("u1", "Which AWS region should the deploy script use?"))Run it and it prints the AWS region fact. The other two facts share no words with the query, so they stay out of the prompt. The cost of the retrieved memory is bounded by limit, whatever the size of the store.
Choosing between approaches
| Situation | Better choice |
|---|---|
| One session that fits in a few windows | Truncation plus a rolling summary |
| Many sessions per user, returning over days | External memory |
| Exact values must be recalled (IDs, paths, figures) | External memory with stored raw text |
| Strict latency or no extra infrastructure | In-prompt strategies |
| Large documents the user refers back to | Retrieval over the documents |
The hybrid strategy from earlier chapters and external memory also combine well. Keep the summary and recent messages for the current session, and add retrieved facts from past sessions.
Common errors
- Retrieving on stale input. If the user's message is "yes, do that", the query has no content. Build the query from the last few turns, or rewrite it first.
- Storing everything. A store full of low-value chatter returns noise. Save decisions, preferences, and exact values.
- Letting retrieved text act as instructions. Stored content may come from users or documents. Label it as reference data in the prompt, and do not place it in the system role as commands.
- Ignoring privacy. Persistent memory keeps personal data. Scope every lookup by user ID, and give users a way to delete their records.
- Skipping the budget. Retrieved items consume input tokens like any other text. Subtract them from the budget before you size the recent window.
Exercise
A support assistant serves the same customers across weeks. Customers often ask about an order number they gave in an earlier session. A rolling summary sometimes drops or alters these numbers. What change fits best, and why?
Show answer
Extract order numbers and similar exact values into an external store, keyed by customer ID, and retrieve them for each request. The store keeps the raw values unchanged, so they do not pass through repeated summarization, and the prompt only pays for the few items that match the current question.
Exercise
You add retrieval of three stored facts to every request. Which step of the earlier budget calculation must you update?
Show answer
Subtract the token cost of the retrieved facts (along with the system prompt, summary, and reserved output space) from the context window before sizing the recent verbatim window.