Context Assembly, Retrieval, Compression and Caching
How to decide what goes into each model call, what stays outside until it is needed, and how to stop long runs from becoming slow, costly and confused.
Context assembly is the code that builds each model request: it gathers candidates, scores them, removes duplicates and fits them into a token budget. Compression shrinks what you already hold, just-in-time loading fetches detail only when a step needs it, and prompt caching makes the unchanged front of a request cheaper to send again. Measure all four by task success, not only by tokens saved.
What you will learn: how to build an assembly pipeline, score and de-duplicate candidates, compact a long history safely, choose between preloading and loading on demand, and lay out a prompt so caching works.
Prerequisites: What Is Context Engineering? Stack and Token Budgets and a basic idea of the agent loop. The examples use only the Python standard library.
Why assembly is a job of its own
A model sees only what is in the request. Everything it knows about your task arrives through that one channel: instructions, tool definitions, earlier messages, retrieved passages, memories and the results of tool calls. In a chat demo a person types the context by hand. In an agent, code assembles it again on every turn, often dozens of times for one task. If that code is careless, the model works from a cluttered desk.
The window is large but not free. Every token costs money and time, and attention is spread across all of them. Research published as Lost in the Middle found that models use information at the start and end of a long input more reliably than information buried in the middle. Later work on what is often called context rot reports that answers can degrade as inputs grow, even when the needed fact is present. The practical lesson is the same: send the smallest set of high-value information that lets the next step succeed.
What competes for space
| Source | Changes how often? | Typical treatment |
|---|---|---|
| System instructions and rules | Rarely | Always include, keep short, place first |
| Tool definitions | Rarely | Include the tools this task can use |
| Current request and goal | Every turn | Always include, restate the goal in long runs |
| Conversation history | Every turn | Keep recent turns, compact older ones |
| Retrieved documents | Per question | Rank, trim to passages, label the source |
| Memory about the user or task | Occasionally | Recall only what relates to this step |
| Tool results | Every tool call | Summarize or point to a file once used |
The slow-changing rows belong at the front of the request and the fast-changing rows at the end. This ordering helps caching, which is covered below. For the budget arithmetic itself, the page on context engineering basics shows a small priority-based packer.
Selecting the right information at the right time
Selection answers a narrow question: for the step the agent is about to take, which items would a capable colleague want in front of them? Start with hard filters, because they are cheap and certain. Remove anything the user may not see, anything expired and anything from a source you do not trust for this purpose. Only then rank what is left. Ranking first and filtering later risks leaking restricted text into logs, summaries or the model itself.
Prioritization and relevance scoring
A score usually blends several signals. Relevance asks whether the item relates to the current step, using keyword overlap, embedding similarity or a reranking model. Importance reflects what you know in advance: a safety rule outranks a pleasantry. Recency favors newer facts, often with a half-life so that old items fade instead of vanishing at a cut-off. Trust reflects where the item came from. After scoring, drop near-duplicates, since three copies of one policy teach the model nothing new and crowd out the order record it needs.
"""Score candidates, drop near-duplicates, and pack them into a token budget."""
import re
def words(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
def overlap(a, b):
return len(a & b) / len(a | b) if a | b else 0.0
QUERY = "refund for damaged order delivered last week"
CANDIDATES = [ # id, text, trust 0-1, age in days, tokens
("policy-v3", "Refund policy: damaged order refund allowed within 30 days of delivery", 1.0, 20, 220),
("policy-copy", "Refund policy: damaged order refund allowed within 30 days of delivery day", 0.8, 20, 230),
("order", "Order 118 delivered last week, customer reports damaged lamp", 1.0, 2, 90),
("forum", "I heard every refund is instant if the order looks damaged", 0.2, 5, 60),
("shipping", "Shipping times for delivery to islands", 1.0, 100, 180),
("history", "Customer asked about a damaged order refund by chat yesterday", 0.9, 1, 70),
]
def score(text, trust, age):
relevance = len(words(QUERY) & words(text)) / len(words(QUERY))
recency = 0.5 ** (age / 90) # halves every 90 days
return 0.6 * relevance + 0.25 * trust + 0.15 * recency
def select(budget, min_trust=0.5, duplicate_at=0.8):
chosen, used, log = [], 0, []
ranked = sorted(CANDIDATES, key=lambda c: -score(c[1], c[2], c[3]))
for cid, text, trust, age, tokens in ranked:
points = round(score(text, trust, age), 2)
if trust < min_trust:
reason = "low trust"
elif any(overlap(words(text), words(t)) >= duplicate_at for _, t in chosen):
reason = "near duplicate"
elif points < 0.45:
reason = "weak score"
elif used + tokens > budget:
reason = "no room"
else:
reason = "IN"
chosen.append((cid, text))
used += tokens
log.append((cid, points, reason))
return [c for c, _ in chosen], used, log
ids, used, log = select(budget=450)
for cid, points, reason in log:
print(f"{cid:12} {points:.2f} {reason}")
print("selected:", ids, "tokens:", used)
Output:
order 0.83 IN
policy-v3 0.64 IN
history 0.63 IN
policy-copy 0.59 near duplicate
forum 0.45 low trust
shipping 0.41 weak score
selected: ['order', 'policy-v3', 'history'] tokens: 380
Read the log column. The forum rumor reached the score floor but was refused on trust, the copied policy was refused as a duplicate, and the shipping note was simply too weak. That record is as valuable as the selection: when an answer is wrong, you can see whether the needed fact was missing, outscored or filtered out. The weights here are invented. Tune yours against real tasks with known answers.
Filling leftover space with weak items feels harmless and often is not. A minimum score lets the assembler send a short, clean request when there is little worth sending. If nothing clears the floor for a question that needs evidence, the right behavior is to search again or to say the evidence is missing.
Order and form
Once chosen, items need a layout. Group them under clear labels such as policy, order record and earlier conversation, give each an identifier, and keep the question or instruction for this step near the end. Prefer compact structured data for records and plain prose for explanations. Do not mix instructions into data blocks; the model should be able to tell what it was told to do from what it was given to read. That separation also matters for prompt injection.
Contextual retrieval and just-in-time loading
There are two ways to supply knowledge. Preloading retrieves likely material before the model runs. Just-in-time loading gives the agent light references, such as file paths, record identifiers, saved queries or links, and tools that open them when needed. Anthropic's engineering guidance on context describes this second style and notes that it mirrors how people use file systems and bookmarks instead of memorizing everything.
| Aspect | Preload | Just in time |
|---|---|---|
| Latency | One model call may be enough | Extra tool calls before answering |
| Token use | Pays for material that may not matter | Pays only for what is opened |
| Freshness | As fresh as the retrieval moment | Read at the point of use |
| Failure mode | Needed item ranked too low | Agent never looks, or wanders |
| Good fit | Predictable questions over documents | Open-ended work in code bases or data |
Most production agents mix the two: preload the rules and a few highly likely facts, then let the agent explore. Name your references well, because a path such as reports/2026-q3-refunds.csv tells the model far more than file7.
Contextual retrieval
A related technique improves the chunks themselves. A passage that says revenue rose by three percent is hard to find if it never says which company or quarter. Anthropic's contextual retrieval method asks a model to write a short note situating each chunk within its document, and prepends that note before both the embedding and the keyword index are built. In its published tests, the approach combined with keyword search reduced failed retrievals by 49 percent, and adding reranking raised the reduction to 67 percent. Your corpus will differ, so treat those figures as a reason to test, not a promise. Embeddings, Vector and Hybrid Search, Reranking explains the search methods involved.
Compression and summarization
Compression makes held information smaller. It comes in several strengths, and the gentlest one that solves your problem is usually the best.
| Technique | What happens | Risk |
|---|---|---|
| Trimming | Cut boilerplate, unused fields and repeated headers | Low if rules are explicit |
| Tool result clearing | Replace an old result with a pointer to where it is stored | Low if it can be fetched again |
| Extraction | Keep only the sentences or fields that matter | The wrong sentences are kept |
| Summarization | A model rewrites older history in fewer words | Details and caveats disappear, errors creep in |
| Reset with handoff | Start a fresh window from a written briefing | Anything missing from the briefing is gone |
The safest design separates what must never be paraphrased from what may be condensed. Goals, constraints, decisions and unresolved problems are copied verbatim. Bulky tool output is replaced by a reference. Small talk is dropped.
"""Compact a long agent history but keep what later steps depend on."""
HISTORY = [
{"turn": 1, "kind": "goal", "text": "Migrate the billing report to the new warehouse"},
{"turn": 2, "kind": "rule", "text": "Never write to production tables"},
{"turn": 3, "kind": "tool", "text": "schema dump " + "col " * 400, "ref": "files/schema.txt"},
{"turn": 4, "kind": "decision", "text": "Use view finance.v_invoices, not the raw table"},
{"turn": 5, "kind": "chat", "text": "Looking at the next query now " * 10},
{"turn": 6, "kind": "tool", "text": "query result " + "row " * 600, "ref": "files/run1.csv"},
{"turn": 7, "kind": "open", "text": "Totals differ by 0.4 percent; cause unknown"},
{"turn": 8, "kind": "chat", "text": "I will check currency rounding"},
{"turn": 9, "kind": "tool", "text": "rounding check: 12 rows differ", "ref": "files/run2.csv"},
]
KEEP_VERBATIM = {"goal", "rule", "decision", "open"}
def tokens(text):
return len(text) // 4
def compact(history, recent=2):
out = []
for i, item in enumerate(history):
if item["kind"] in KEEP_VERBATIM or i >= len(history) - recent:
out.append(f"[{item['kind']} t{item['turn']}] {item['text']}")
elif item["kind"] == "tool": # clear the body, keep a pointer
out.append(f"[tool t{item['turn']}] result stored at {item['ref']}")
return out # plain chat is dropped
def must_survive(history, compacted):
joined = "\n".join(compacted)
return [h["turn"] for h in history
if h["kind"] in KEEP_VERBATIM and h["text"] not in joined]
before = sum(tokens(h["text"]) for h in HISTORY)
small = compact(HISTORY)
after = sum(tokens(line) for line in small)
print("\n".join(small))
print(f"tokens before {before}, after {after}")
print("lost critical turns:", must_survive(HISTORY, small))
Output:
[goal t1] Migrate the billing report to the new warehouse
[rule t2] Never write to production tables
[tool t3] result stored at files/schema.txt
[decision t4] Use view finance.v_invoices, not the raw table
[tool t6] result stored at files/run1.csv
[open t7] Totals differ by 0.4 percent; cause unknown
[chat t8] I will check currency rounding
[tool t9] rounding check: 12 rows differ
tokens before 1135, after 92
lost critical turns: []
The history shrinks by more than ninety percent, mostly by moving two large tool results out of the window. The last line is a check that no goal, rule, decision or open issue was lost. Keep a check like it in your test suite. When a model writes the summary, ask it for fixed headings (goal, constraints, decisions, current state, open questions, next step), keep the original transcript outside the window, and test whether an agent that sees only the summary can finish the task.
If a summary states a guess as a fact, every later turn inherits it. Summarizing a summary makes this worse. Re-derive summaries from original records where you can, and mark unverified statements as unverified.
Compression features from providers
Some APIs now manage part of this for you. The Claude API, for example, documents server-side compaction that summarizes earlier turns as a conversation approaches the window limit, context editing that clears old tool results, and a memory tool whose storage your application controls. Availability, beta status and supported models change, so read the current documentation before depending on a feature, and keep your own record of anything you cannot afford to lose.
Caching and reuse for long-running agents
An agent resends most of its context on every turn. Prompt caching lets the provider reuse its processing of an unchanged prefix, meaning everything from the start of the request up to some point. Cached tokens are billed at a lower rate and processed faster. The rules differ by provider. At the time of writing, Claude documentation prices a five-minute cache write at 1.25 times the base input price and a cache read at 0.1 times, with exceptions for some models, while OpenAI documentation gives a minimum cacheable prefix of 1,024 tokens for GPT-5.6 and later. Check the current pages before you estimate a bill.
One rule holds across designs: a change near the front invalidates everything after it. A timestamp in the first line of the system prompt can quietly remove the entire benefit.
"""Why order matters for prompt caching. Multipliers are examples only."""
WRITE, READ, PLAIN = 1.25, 0.10, 1.0 # relative to the base input price
def cost(turns, stable, per_turn, stable_first):
"""Relative input cost of a conversation that grows by per_turn tokens."""
total, cached = 0.0, 0
for turn in range(1, turns + 1):
size = stable + per_turn * turn
if stable_first: # the old prefix is unchanged
new = size - cached
total += cached * READ + new * WRITE
cached = size
else: # a changing line sits at the top
total += size * PLAIN
return round(total)
for turns in (1, 2, 5, 20):
good = cost(turns, stable=6000, per_turn=500, stable_first=True)
bad = cost(turns, stable=6000, per_turn=500, stable_first=False)
print(f"{turns:2} turns cached {good:7} uncached {bad:7} ratio {good / bad:.2f}")
Output:
1 turns cached 8125 uncached 6500 ratio 1.25
2 turns cached 9400 uncached 13500 ratio 0.70
5 turns cached 13525 uncached 37500 ratio 0.36
20 turns cached 40900 uncached 225000 ratio 0.18
The model is deliberately simple. It assumes every turn arrives before the cache expires and ignores output tokens and minimum sizes. Even so it shows the shape: a single call costs more with caching, because writing carries a premium, and a long conversation costs a fraction. Measure real behavior from the usage fields your provider returns, and watch the share of input tokens served from cache after every prompt change.
Habits that protect the cache
- Append to history; do not rewrite earlier messages on each turn.
- Serialize tool definitions and JSON in a fixed order.
- Move dates, request identifiers and user-specific data toward the end.
- Compact at planned moments, accepting one expensive rewrite, instead of editing a little every turn.
- Never share cached prefixes across customers in any layer you build yourself; see Context Isolation, Provenance and Governance.
Other things worth caching
Beyond the provider's prompt cache, you can store retrieval results, embeddings, rendered documents and the answers of read-only tools. Each needs a key that includes everything affecting the result (including the user's permissions) and a lifetime that matches how fast the truth changes. A cached permission check or account balance is a bug waiting to happen.
Cutting cost without cutting quality
Work from measurements. Log the tokens contributed by each source for a sample of tasks, then act on the largest. In tool-heavy agents that is often old results; in document assistants it is often too many retrieved passages; in agents with large tool catalogs it can be the definitions themselves. Typical levers, in rough order of safety, are caching, clearing used results, retrieving fewer but better passages, loading tools only when relevant, summarizing history and finally routing easy steps to a smaller model. Methods that compress prompts with a second model, such as the LLMLingua research line, exist, but they alter text in ways that are hard to audit, so test them carefully on your own tasks.
Evaluate every change
Keep a fixed set of tasks with known good outcomes. For each variant record success rate, input tokens, latency and cost per successful task. A change that halves tokens and loses two tasks in twenty may be a poor trade, and averages can hide that the two lost tasks were the risky ones. Long-Horizon, Multi-Agent and Enterprise Context describes measures of completeness, relevance and accuracy for the context itself.
Common mistakes
- Sending everything because the window allows it.
- Filtering by permission after ranking or summarizing.
- Putting volatile text at the top of the prompt.
- Summarizing away the constraint that made the task safe.
- Offering references with no tool that can open them.
- Reporting token savings without a success measure.
A worked order of operations
A support agent starts well and becomes sluggish after fifteen turns. Logging shows that full order histories returned by one tool make up most of the input. The team changes the tool to return the ten fields in use, stores the full record behind an identifier, clears results older than three turns and moves the current date to the end of the request. They replay their task set before and after, compare success and cost per task, and keep the change only because success held.
Checklist
- Permission, freshness and trust filters run before ranking.
- Each item carries an identifier and source label.
- The assembler logs what was included and why others were not.
- Near-duplicates are removed and weak items have a floor.
- Goals, rules, decisions and open issues survive compaction verbatim.
- Large results can be fetched again from outside the window.
- Stable content comes first and cache hit rate is monitored.
- Every change is checked against a fixed task set.
Frequently asked questions
If windows keep growing, does this still matter?
Yes. Larger windows raise the ceiling, but cost and latency still rise with size, and extra irrelevant text can still distract the model. Selection also remains your control point for permissions.
When should compaction start?
Before you hit the limit, at a point you choose from tests. Natural boundaries, such as the end of a subtask, are better than arbitrary moments because less is in progress.
Is prompt caching the same as storing answers?
No. Prompt caching reuses processing of an input prefix, and the model still generates a new answer. Answer caching returns an earlier response and needs much more care about matching and permissions.
Should a model do the selection?
A model can rerank candidates or decide what to fetch next. Keep hard rules such as access control, trust and budget limits in code.
References and further reading
- Anthropic: Effective context engineering for AI agents
- Anthropic: Introducing Contextual Retrieval
- Claude documentation: Prompt caching
- OpenAI documentation: Prompt caching
- Claude documentation: Context editing
- Liu et al.: Lost in the Middle
- Chroma research: Context rot
- Jiang et al.: LLMLingua prompt compression
Next steps
Context Isolation, Provenance and Governance
Keep users and tasks apart, and know where every item came from.
Long-Horizon, Multi-Agent and Enterprise Context
Long-horizon work, multi-agent context and evaluation.
Reducing Tokens, Tool Calls and Spend
The wider set of levers for a cheaper agent.