Working memory: the context window as a budget
Working memory is everything the model can read on one call: instructions, facts, retrieved text, recent turns, and the new message. Design it as a budget, because it is limited and paid per token.
Working memory in 60 seconds
- What: all the text the model can see on a single call, called the context window.
- Why it matters: the model knows nothing beyond this window, so what you include decides what it can do.
- Limits: the window has a maximum size, you pay for every token in it on every call, and long prompts slow responses.
- Weak spot: details buried in the middle of a long prompt are used less reliably than those at the start or end.
- Framing: the CoALA framework (Sumers et al., 2023) treats this as the working memory of a language agent.
Where this type fits
The types of memory hub groups memory into short-term (working and session), long-term (semantic, episodic, procedural), and organisation (tiered and shared). Working memory is the innermost short-term layer. Every other memory type exists to decide what gets copied into it, because the model can only act on what is there.
The problem it solves
A model has no memory between calls. Each call starts blank. Whatever it needs to know, from your instructions to the customer's last message, must be sent again as text. Without a deliberate design, teams fall into one of two traps. Some send too little, and the model forgets the goal or contradicts earlier answers. Others send everything, and the call becomes slow, expensive, and sometimes less accurate.
Size is only part of the issue. Position matters too. The 'Lost in the Middle' study (Liu et al., 2023) found that models used information at the start or end of a long context more reliably than information in the middle. A bigger window does not mean every token in it gets equal attention.
Working memory design answers three questions. What belongs in the window every time? What gets added only when needed? And what must be left out or shortened to stay within the limit? Treating the window as a budget, with a planned amount for each part, makes the answers explicit.
How it works
- Set a budget: choose a maximum prompt size below the model's limit, leaving room for the answer. Split it into shares for each section.
- Place fixed parts first: system instructions, rules, and tool descriptions go at the top. They rarely change, which also helps caching.
- Pin the essentials: the user's goal and any key facts stay in every call, near the start or end where they are used more reliably.
- Add retrieved text: passages from search or memory stores fill a share of the budget, ranked by relevance, and cut when the share is full.
- Add recent turns: the latest messages go in full. Older ones are shortened or summarised, or dropped.
- Add the new message and call the model: the model reads the whole window, answers, and forgets it. The next call rebuilds the window from scratch.
The dashed outline is the key idea: anything outside it does not exist for the model. The five boxes are your levers. Instructions and pinned facts are small and stable. Retrieved passages and recent turns are large and variable, so they are where you trim when space runs short.
The notes on cost and position follow from how the model works. The model reads every token on every call, so cost grows with window size and the same tokens are paid for again on each turn. The prefix cache can reduce that cost for the stable top of the prompt, which is another reason to keep fixed content first.
A worked example
Acme runs a support assistant on a model with an 8,000 token window. The team sets a 6,500 token prompt budget and reserves 1,500 for the reply. Shares: instructions and tool descriptions 900, pinned facts 300, retrieved passages 2,500, recent turns 2,200, new message 600.
A customer, Priya, is on her sixth message. Her goal, 'cancel the Team plan before the renewal on 14 March', and her plan name are pinned, using 120 tokens. Search returns six policy passages of about 600 tokens each, 3,600 in all. Only the top four fit the 2,500 share, so the last two are dropped. The conversation so far is 3,400 tokens, but the recent-turns share is 2,200. The last three turns are kept in full, 1,300 tokens, and the earlier three are replaced by a 250 token summary.
{
"budget": 6500,
"sections": {
"instructions": 900,
"pinned": 120,
"retrieved": 2400,
"recent_turns": 1300,
"summary_of_older_turns": 250,
"new_message": 85
},
"total": 5055,
"dropped": ["policy passage 5", "policy passage 6"]
}The total is 5,055, comfortably under budget. The pinned goal sits right after the instructions, so the model sees the cancellation date early. The policy about cancellation, ranked first by search, is placed last, next to the new message, where it is least likely to be overlooked. The reply has room to run.
Building it
# count_tokens(), summarise(), and llm are placeholders for your own
# tokeniser, summariser, and model call.
BUDGET = 6500
SHARES = {'retrieved': 2500, 'turns': 2200}
def take_within(items, limit):
# Keep items in order until the limit is hit. Never cut one in half.
kept, used = [], 0
for item in items:
cost = count_tokens(item)
if used + cost > limit:
break
kept.append(item)
used += cost
return kept
def build_prompt(instructions, pinned, passages, history, message):
# Stable text first so a prompt cache can reuse it.
parts = [instructions, 'Pinned facts:\n' + '\n'.join(pinned)]
# Passages arrive ranked best first. Keep the best that fit.
kept_passages = take_within(passages, SHARES['retrieved'])
# Recent turns: walk backwards so the newest are kept in full.
kept_turns = list(reversed(take_within(list(reversed(history)), SHARES['turns'])))
older = history[: len(history) - len(kept_turns)]
if older:
parts.append('Earlier in this chat: ' + summarise(older))
# Best passage goes last, next to the question, because middle text
# is used less reliably in long prompts.
parts.append('Reference passages:\n' + '\n---\n'.join(reversed(kept_passages)))
parts.append('Conversation:\n' + '\n'.join(kept_turns))
parts.append('User: ' + message)
prompt = '\n\n'.join(parts)
if count_tokens(prompt) > BUDGET:
# Last resort: drop the weakest passage rather than send an oversize call.
kept_passages = kept_passages[:-1]
return build_prompt(instructions, pinned, kept_passages, history, message)
return prompt
def answer(instructions, pinned, passages, history, message):
return llm.generate(build_prompt(instructions, pinned, passages, history, message))The code never cuts a passage in half, because a half sentence can mislead. It also keeps a final guard that shrinks the prompt rather than sending an oversize call. Count tokens with the tokeniser that matches your model, since word counts only approximate them.
Design decisions
- Budget size: default to a prompt well below the model's maximum. A smaller window is cheaper and faster, and often just as accurate.
- Section shares: give each section a fixed share and trim the variable ones first, which are retrieved text and old turns.
- Order: put stable content first for caching, and put the most important evidence near the end or start, not the middle.
- Overflow policy: decide in advance what gets dropped, summarised, or moved to a store. Unplanned truncation cuts things at random.
- Tool results: cap the size of each tool output before it enters the window. One huge result can crowd out everything else.
- Access control: put only what this user may see in the window. Anything in it can leak into the answer.
- Versioning: version the prompt template, because a change in layout changes behaviour and cache hits.
Measuring it
- Window utilisation: prompt tokens divided by budget, per section. It shows which section is crowding out others.
- Truncation rate: the share of calls where content was dropped or summarised. A high rate means the budget is too small for the task.
- Position test: run the same question with the key fact at the start, middle, and end. A drop in the middle case shows how much placement matters for your model.
- Answer quality against window size: score answers on a fixed test set with different budgets. Find the point where more context stops helping.
- Cost and latency per call: tokens in, tokens out, and response time. Track the 95th percentile.
- Context-caused errors: sample bad answers and label whether the needed fact was missing, buried, or contradicted by other text.
def position_test(question, key_fact, filler_passages, expected):
# filler_passages and llm are placeholders; run many questions in practice.
results = {}
for where in ('start', 'middle', 'end'):
passages = list(filler_passages)
index = {'start': 0, 'middle': len(passages) // 2, 'end': len(passages)}[where]
passages.insert(index, key_fact)
reply = llm.generate('\n'.join(passages) + '\nQuestion: ' + question)
results[where] = expected.lower() in reply.lower()
return resultsWhen to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Every model call | Always | The window is the only thing the model reads, so it is always in play. |
| Short chats with few documents | Yes, keep it simple | Everything fits, so a basic template with recent turns is enough. |
| Long chats | Yes, plus session memory | Old turns must be summarised or stored, or the window overflows. |
| Large knowledge bases | Yes, plus retrieval | Search selects which passages enter the window instead of sending everything. |
| Facts needed across many sessions | Not alone | The window is wiped each call. Use semantic memory for durable facts. |
| Putting a whole document set in the prompt | Rarely | Cost, latency, and the middle-of-context weakness usually make retrieval better. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | More relevant context helps, but irrelevant context can distract | Rank and cut passages, and test with and without extra text. |
| Latency | Longer prompts take longer to process before the first token | Trim to what is needed and keep a stable prefix for caching. |
| Cost | Every token is billed on every call, including repeated history | Summarise old turns, cap tool output, and use a prefix cache. |
| Complexity | Budgeting, ordering, and summarising add code to maintain | Build one prompt assembly function and test it with fixed examples. |
| Failure modes | Overflow errors, silent truncation, lost key facts, and leaked data | Count tokens, plan overflow, pin key facts, and filter by access. |
Compared with related types
Session memory is the stored conversation from which the window is rebuilt each turn. Working memory is the rebuilt result. Tiered memory manages what lives in the window and what moves out to storage when space runs short. The KV cache is a different thing despite similar words: it is the model server's internal speed-up for tokens it has already processed, not memory the application controls.
What this means for your role
Common mistakes
Further reading
- Types of memory: the hub that compares every memory type.
- Lost in the Middle, Liu et al., 2023: models used information at the start or end of a long context more reliably than information in the middle.
- Cognitive Architectures for Language Agents (CoALA), Sumers et al., 2023: a framework that organises language-agent memory into working, episodic, semantic, and procedural memory.
- Prefix (prompt) cache: lowering the cost of the stable top of the prompt.
- Vector search and chunking: choosing which passages deserve a place in the window.
Working memory is small by design, so the craft is choosing well. Plan the budget, pin what matters, and let the other memory types feed it.