Course / Module 23
Context engineering and memory
Prompt engineering writes the instructions. Context engineering decides everything the model sees at each step. Learn what to put in, what to keep out, and how to design memory that helps without leaking or misleading.
In short
- The model only knows what is in its context at that step, so curate it on purpose
- More context is not better context: irrelevant or stale text lowers quality and raises cost
What you will learn
- Explain context engineering and how it differs from prompt engineering
- List what can enter a model's context at each step and who controls each part
- Recognize the common ways long conversations fail and how to detect them
- Choose between writing, selecting, compressing and isolating context for a given problem
- Design a memory policy for a support assistant: what to remember, what never to, consent and forgetting
Where this fits in the course
This is module 23. It is best read after module 9. It is numbered at the end so that existing links and saved progress keep working.
From prompts to context
A prompt is the text you write. Context is everything the model can see when it produces its next output: your instructions, the conversation so far, documents you retrieved, the results of tool calls, and anything you remembered from earlier sessions. Prompt engineering tunes the first part. Context engineering designs all of it, on every step, as a system.
The shift matters because assistants and agents run for many turns and call tools. A perfect prompt inside a cluttered context still produces poor answers, and a plain prompt inside a clean, relevant context often works well. The model is the runtime. The context is what you give it to run on.
Where this fits
module 3 covers the system prompt as a design document, module 6 covers retrieval, and module 9 covers state. This module connects them: deciding, at each step, what the model should see.
What goes into the context
| Part | Example | Who controls it | Typical failure |
|---|---|---|---|
| Instructions | System prompt, policies, tone | You | Too long, contradictory, buried |
| Conversation history | Earlier turns | The user and the system | Grows until it crowds out everything else |
| Retrieved content | Help-center passages (module 6) | Your retrieval | Stale or off-topic passages |
| Tool definitions and results | Order lookup response | Your tools | Huge payloads, irrelevant fields |
| Memory | "Prefers email, open case 4821" | Your memory layer | Out of date, wrong user, poisoned |
| State | Current step of the flow, collected slots | Your orchestrator | Lost between turns |
Ask of each part: is it needed for this step, is it current, is it trusted, and what does it cost in tokens and latency?
How long conversations go wrong
- Burying. An important rule sits among thousands of tokens of history and is followed less reliably.
- Distraction. Irrelevant passages or many similar tools make the model choose badly.
- Staleness. An old answer, price or policy stays in the context after it changed.
- Clash. Two sources disagree and the model picks one (module 7).
- Poisoning. Untrusted text, such as a retrieved page, a ticket or a saved memory, carries instructions (module 18).
- Cost and latency. Every token is paid for and processed again on each step.
Models can lose details in the middle of long contexts and give extra weight to the most recent text. Degradation as irrelevant text accumulates is often called context rot. Do not assume a larger window removes the problem. Test it.
Four moves: write, select, compress, isolate
| Move | What it means | Use when | Watch for |
|---|---|---|---|
| Write | Save information outside the window: notes, a scratchpad, memory | The agent works over many steps or sessions | Writing wrong or untrusted facts |
| Select | Pull in only what is relevant now: retrieval, filters, tool results trimmed to the needed fields | The source is large and the step needs a little | Missing the one passage that mattered |
| Compress | Summarize or trim history and tool output | The conversation is long | Losing a detail a later step needs |
| Isolate | Give each sub-task or sub-agent its own focused context | Tasks differ in tools or knowledge (module 9) | Handoffs that drop shared state |
Most problems need one or two moves. Start with select (retrieve less, trim tool results), then compress, and use isolation when one context is serving jobs that do not belong together.
def build_context(system, state, memory, history, passages, tool_results, budget=6000): """Assemble context in priority order. The fixed parts stop at the budget; recent turns are always kept and older ones are summarized.""" parts = [("system", system), ("state", state), ("memory", memory)] parts += [("passage", p) for p in passages[:4]] # select: a few, not all parts += [("tool", trim(r, fields=("status", "eta"))) for r in tool_results] used, out = 0, [] for kind, text in parts: cost = count_tokens(text) if used + cost > budget: break out.append((kind, text)); used += cost recent = summarize(history[:-6]) + history[-6:] # compress old turns, keep recent ones verbatim return out + [("history", h) for h in recent]
Sessions and memory
A session is the raw record of one conversation. It is useful for coherence inside that conversation and unsuited to long-term use: it is noisy, temporary and large. Memory is what you extract and keep from sessions on purpose.
| Kind | What it holds | Example |
|---|---|---|
| Working | What is in the window now, assembled each turn | The current order and the last three messages |
| Facts | Durable statements about the user or world | "Prefers email. Account is on the business plan" |
| Episodes | What happened before | "Refund requested on 12 May, approved, shipped" |
| Procedures | How to behave | "This customer wants short answers" |
Retrieval and memory are different. Retrieval (RAG) brings in your content. Memory is about this user or this task. Treat them as separate sources with separate rules.
A memory policy for support
Decide before you build. A table like this goes into your design document, and its consent and deletion rows become test cases (module 15).
| Question | Example answer |
|---|---|
| What do we remember? | Open case numbers, language and channel preference, products owned |
| What do we never remember? | Payment details, health or other sensitive data, passwords, anything said in distress |
| How long? | Case data until closed plus 30 days; preferences until the customer changes them |
| Who consented, and how? | Shown in the first message; the customer can say "forget this" at any time |
| How does the customer see and delete it? | A "what you remember about me" command and a deletion path that also removes copies |
| Who can write to memory? | Only validated extractions, never raw user or tool text |
Memory is personal data
In most places what you remember about a person is personal data. GDPR and LGPD give people the right to see it and to have it deleted, so the policy above is also a compliance question. Check it with your privacy team before you build.
Memory is attack surface
Anything saved to memory comes back later as context. If an attacker can get text into memory (through a ticket, an email or a web page the agent read), they can steer future conversations. Validate what you write, and keep untrusted content away from memory that holds instructions (module 18).
Test your context
- Late rule test. Put a rule in the system prompt, run 30 turns of unrelated chat, then ask something the rule governs.
- Needle test. Place one fact in a long history and ask for it.
- Staleness test. Change a policy and check the old answer is gone from every source.
- Conflict test. Give two sources that disagree and see what it does.
- Deletion test. Ask to forget something, then try to get it back.
- Injection test. Store a hostile instruction in memory and see if it is obeyed.
Run them as part of the evaluation set (module 24) and re-run them when you change the model, because context behavior differs between models (module 5).
Try it: write a context budget
Pick an assistant you know. For one step, list each part of its context, how many tokens it uses, whether it is needed, and whether it is trusted. Remove or shorten two parts. Predict what improves, then test it.
Key takeaways
- The model only knows what is in its context at that step, so curate it on purpose
- More context is not better context: irrelevant or stale text lowers quality and raises cost
- Write, select, compress and isolate are the four moves; most problems need one or two
- Memory is curated knowledge about a user or task, not a pile of old chat logs
- Treat everything that enters context, including memory, as untrusted until proven otherwise