MODULE 3 · LESSON 12 · 12 MIN
Context Engineering: Memory, Files, and Instruction Design
By Siten Sanghvi · Published · Updated
Context engineering is deciding what a model receives with each request: instructions, conversation history, files, retrieved text and tool results. The model keeps nothing between requests, so anything that must persist is something your application stores and sends again. The term is a practitioner label, not a standard. Anthropic's engineers (September 2025) use it for curating everything in a model's input, not just one prompt's wording.
Tokens, Embeddings, and Context Windows Explained defined the context window, and Prompt Engineering: A Systems Thinker's Framework covered writing one prompt. This lesson asks what to put in the window across a session or product, what to keep outside it, and what happens as it grows.
What one request contains
Under a chat interface, the model receives one sequence of tokens. Hugging Face's chat-template guide shows role-labelled messages (system, user, assistant) flattened into a single token sequence with special marker tokens, and notes that models use different formats. So "system prompt" and "user message" are formatting, not separate channels: the markers come from the model's chat template (documented for open models; hosted services do this on their side), and models are trained to treat them differently.
A request can include:
- System or developer instructions: standing rules from the application's builder, often hidden from users.
- Conversation history: earlier turns, only if the application resends them.
- Files: the application or the provider's service turns the file into text (sometimes images) and places it in the request. Anthropic's PDF documentation (checked 2026-11-09) says its system supplies each page as an image plus its extracted text, estimates 1,500 to 3,000 text tokens per page (one vendor's estimate, not a general rate), and warns that dense PDFs can fill the window before the page limit.
- Retrieved text: passages fetched at request time (BT-L13).
- Tool definitions and tool results: what the model may call and what came back (BT-L14).
Anthropic's context-window documentation counts all of these, plus the model's own output, against the window. Window sizes differ by model; check yours.
Adding context does not change the model. The GPT-3 paper tested few-shot prompting, which puts worked examples in the request, with no gradient updates, meaning no weight changes. Training weights and request context stay separate (BT-L07).
The model is stateless; memory is built around it
Stateless means it retains nothing from one request to the next. Anthropic's Messages API guide says you always send the full conversational history, and OpenAI's conversation-state guide says each text generation request is independent. Chat "memory" within a session is the application replaying earlier turns.
Some APIs can hold the history for you. OpenAI's guide says that when you chain responses this way, earlier input tokens are still billed as input. Whatever the API stores, the model still has to be given the earlier turns to use them; what changes is who sends them and what it costs.
Memory across sessions is also application work: store something, then put selected pieces into a later request. Examples checked 2026-11-09, which may change:
- Anthropic's memory tool is client-side, meaning it runs in your application, not on the provider's servers. The model asks to read or write files, and your application runs each operation and decides where data lives.
- Claude's consumer memory and chat search are described as product features. Chat search appears as tool calls and uses retrieval (BT-L13).
Researchers (CoALA) name working, episodic, semantic and procedural memory for language agents: design vocabulary for the data an agent keeps across model calls, a log of past episodes, a store of facts, and procedures (the agent's code plus what is in the model's weights). Each model input is assembled from that working data, so it is not simply the window. MemGPT is one design that lets the model use function calls to move information between its window and external storage. In it and in the memory tool, the model may request a read or write, but the application stores the data and runs it.
Memory can fail. LongMemEval reports in its abstract a 30% accuracy drop for commercial chat assistants and long-context models on sustained interactions; its detailed results vary. Its small manual check (August 2024, short histories) saw one assistant overwrite crucial information and another miss facts given indirectly. That is not a verdict on today's products.
Summaries lose detail. Anthropic's compaction overview replaces older turns with a model-written summary and lets you write your own summarization prompt when the default drops something a later turn needs. A summary is lossy: test what must survive, and keep critical facts as separate notes.
Fitting in the window is not the same as being used
A request can fit in the window and still be handled badly. Studies found that where a fact sits and how long the input is can both change accuracy. Lost in the Middle moved the relevant item around in multi-document question answering and key-value retrieval. On the 2023 models it tested, accuracy was often highest when the item was at the start or end and lower in the middle; for one GPT-3.5 model it could drop by more than 20%.
Later work looks at length. RULER ran 17 long-context models on 13 synthetic tasks (tasks built for testing, not real workloads). Nearly all handled simple needle retrieval (finding one planted fact in long filler text), but only about half kept satisfactory performance at 32K despite claiming 32K or more. NoLiMa tested 13 models claiming at least 128K tokens, using questions that share little wording with the answer. At 32K, 11 fell below half of their short-context scores, and even the top performers declined. None of this shows that every model, or your task, behaves this way. RULER does not control where the key information sits, and newer models may differ. Anthropic's documentation calls the effect context rot: accuracy and recall degrade as token count grows, so curating context matters as much as capacity.
What to do with that:
- Treat window size as a ceiling, not a promise. Test your task with the fact at the start, middle and end.
- Send less. Remove duplicates, stale versions and irrelevant passages. BT-L13 covers how retrieval picks passages and how it can miss or bury the right one.
- A file is not remembered knowledge; it is tokens in this request. Send only the pages or sections the task needs, or retrieve them.
- Ask the model to quote the passages it relied on before it answers. Anthropic's long-document guidance recommends this, and a quote can be checked against the source.
- The same guidance says to put long documents above the question, and that a query at the end can improve quality by up to 30% in tests the page does not describe. Treat it as vendor advice to test.
- Providers may cache an unchanged opening part (prefix) of a request to cut cost and latency without changing the answer. That saves work; it is not the model remembering anything (BT-L16 covers cost).
Instruction design
Different parts of a request deserve different trust. Developer instructions, a user's message and a retrieved web page are not equally reliable, but to the model they are all tokens. OpenAI's instruction-hierarchy paper argues a core weakness is that models often treat system prompts as equal in priority to untrusted text, and proposes training models to rank system, then user, then tool outputs. It reports better robustness on its tests, and also says its models are likely still vulnerable to strong attacks. A priority order is trained behavior, not a guarantee. BT-L11 covers what vendors document about priority (including OpenAI's Model Spec placing a builder's prompt at the developer level), and BT-L18 covers prompt injection.
Practitioner guidance that follows (not measured results):
- Put standing rules in the system instructions and the specific task in the user message. Keep them consistent. Where they conflict, which one wins is a trained tendency, not a guarantee, so test it.
- Label reference material as data. Anthropic recommends wrapping each document in tags with its source. Labels give the model clearer structure but do not prevent injection.
- Enforce permissions and secrets in code, not in the prompt. An instruction is a request the model may fail to follow.
- Start minimal, then add rules for observed failures. This is Anthropic's engineering opinion. Long lists of edge-case rules also consume the window.
Try it: budget a request
EXHIBIT 12 / CONTEXT
Explore the mechanismBuild the request.
Memory belongs to the application, not a weight update.
Headroom: 2400 tokens
Illustrative component sizes. Excluded components are not in this request. New session clears conversation history but can retain app-stored notes.
Inspect the example data and reasoning
| Element | What to notice |
|---|---|
| Instructions | 600 illustrative tokens |
| Tool definitions | 400 illustrative tokens |
| App memory notes | 300 illustrative tokens |
| History | 3200 illustrative tokens |
| Latest message | 100 illustrative tokens |
| Retrieved passages | Excluded |
| File text | Excluded |
| Output reserve | 1000 illustrative tokens |
Illustrative token counts, not provider limits. Fitting context does not guarantee equal use; summaries can omit details.
Read the mechanism without interacting
- Assembly
- The application chooses what information is included in each request.
- Budget
- Count input components and reserve room for the answer.
- Persistence
- An app can store and resend notes; request context does not update model weights.
The default uses 5,600 of an invented 8,000-token budget. Everything included uses 9,100; summarized history reduces that to 6,500.
Try explaining it: What must an app send again to make an assistant appear to remember last week?
Use these made-up numbers, not a provider's (BT-L05 has a similar exercise). Budget: 8,000 tokens. Instructions 600, tool definitions 400, memory notes 300, full history 3,200, new message 100, uploaded file 2,000, retrieved passages 1,500, output reserve 1,000.
Add them: 9,100, which is 1,100 over. Replacing the full history with a 600-token summary saves 2,600, giving 6,500 with 1,500 spare. The cost is whatever the summary left out.
Then try your own task. Paste a long document, bury one fact at the start, middle or end, and ask about it several times. One run proves little, so look for a pattern.
The takeaway
Each request is assembled from instructions, history, files, retrieved text and tool results. A model starts every request fresh, so your application's design supplies memory and decides what is stored, sent, summarized or left out. A window that holds your input does not guarantee reliable use: test your own task, send less, and enforce rules that matter in code.
Related lessons
- Tokens, Embeddings, and Context Windows Explained defines tokens and context windows and first raises the capacity-versus-use question.
- RAG: Retrieval-Augmented Generation Explained covers retrieval, chunking and what goes wrong when too much retrieved text is stuffed in.
- AI Hallucinations, Prompt Injection, and Safety Guardrails Explained covers prompt injection, which instruction design cannot solve on its own.
Up next
RAG: Retrieval-Augmented Generation Explained
Retrieval is how an application finds the right passages to put in the request. The next lesson covers how that works and where it fails.
VISUAL FIELDNOTES / 12
Keep the big picture.
A one-page visual companion. Save it, print it, or explain it to someone else.
View the full-size sheet ↗Build the request.
Memory belongs to the application, not a weight update.
One US Letter page · Vector artwork · Fits A4 when printed to fit
Read the key points as text
- Assembly
- The application chooses what information is included in each request.
- Budget
- Count input components and reserve room for the answer.
- Persistence
- An app can store and resend notes; request context does not update model weights.
Remember: The application chooses what information is included in each request.
Try it: The default uses 5,600 of an invented 8,000-token budget. Everything included uses 9,100; summarized history reduces that to 6,500.
Recall: What must an app send again to make an assistant appear to remember last week?
OPTIONAL CHECK
Check your understanding.
The optional check requires JavaScript. You can continue reading the lesson.
In message 10 of a chat, the assistant correctly uses a detail from message 2. Which explanation fits how a typical chat application works?
A team pastes ten worked examples into the instructions of every request. What changed?
An API stores your conversation server-side so you send only each new message. Which statement is still accurate?
What did the Lost in the Middle study show?
A 200-page contract fits in the window, but the assistant misses a clause on page 90. What is the best next step?
An assistant recalls a preference you stated last week, in a brand-new chat. Which design explains this without changing the model?
Why can summarizing older turns cause a failure later?
A retrieved web page contains 'ignore your previous instructions'. What does the instruction-hierarchy paper support?
A team uploads a 120-page PDF and asks about one section. Which statement about the file is accurate?
With the lesson's illustrative 8,000-token budget, a request totals 9,100. Which change fits it while keeping the uploaded file and retrieved passages?
Quiz complete
YOUR LEARNING
Keep your place.
Your progress is saved on this device.