Built with Tutify.io

    AIStudyLabs

    Context Engineering for AI Agents: Memory, Retrieval and Context Windows

    Context Engineering for AI Agents: Memory, Retrieval and Context Windows

    An agent that works well for ten turns and then starts repeating itself, forgetting instructions or calling the wrong tool usually hasn't hit a model limit. It has hit a context problem. Somewhere along the way its context window filled with stale tool output, half-relevant documents and a summary that got one fact wrong, and the model did its best with what it was given. Context engineering is the discipline of deciding what goes into that window, step by step, so the model has what it needs and little else.

    The governed store of business meaning, rules and permissions that agents draw from is covered in the series overview on the context layer. Here the focus is the runtime side: how an agent picks from that store and everything else, one model call at a time.

    What is context engineering?

    Anthropic's engineering team defines it as "the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference." That's a broader job than writing a good prompt. It covers the system prompt, tool definitions, retrieved documents, memories, conversation history and tool results, and how all of them change over a long task.

    The term caught on in June 2025. Shopify's CEO Tobi Lütke said he preferred it to "prompt engineering," Andrej Karpathy agreed, and Simon Willison wrote up the exchange. Karpathy described the job as filling the context window "with just the right information for the next step." LangChain's write-up adds his broader analogy: the model is like a CPU and the context window is like its RAM.

    The distinction from prompt engineering matters in practice. A prompt is written once. Context is assembled on every call, from sources that change as the agent works.

    Why a bigger context window doesn't solve it

    Context windows now run to hundreds of thousands or millions of tokens, so it's tempting to put everything in and let the model sort it out. The research says that doesn't work.

    Lost in the middle. A 2023 study by Liu and colleagues, "Lost in the Middle", found a U-shaped accuracy curve. Models used information best when it sat at the start or end of the input, and noticeably worse when it sat in the middle, even models built for long contexts.

    Context rot. Chroma's July 2025 "Context Rot" report tested 18 models and found performance grew "increasingly unreliable as input length grows," even on simple tasks. Adding a single distractor passage hurt accuracy, and four distractors hurt it more.

    Attention budget. Anthropic describes context as "a finite resource with diminishing marginal returns." Every extra token competes for the model's attention with the tokens that matter.

    Then there's cost and latency. A context window filled to the brim costs more per call and responds slower, on every call of a long-running agent.

    So the goal of context engineering is the smallest set of high-signal tokens that lets the model do the next step well, not the largest set that fits.

    How contexts fail

    Drew Breunig's June 2025 post, "How Contexts Fail", gave names to four failure modes:

    | Failure | What happens | Example from the post | |---|---|---| | Poisoning | A hallucination enters the context and keeps getting referenced | Gemini's Pokémon-playing agent kept pursuing goals based on a hallucinated game state | | Distraction | The context grows so long the model leans on history over reasoning | Past roughly 100k tokens, the Pokémon agent repeated old actions | | Confusion | Irrelevant content, often too many tools, degrades answers | A quantized Llama 3.1 8B failed with 46 tools and succeeded with 19 | | Clash | Parts of the context contradict each other | Splitting a prompt across turns caused a 39% average drop |

    Most of the fixes map onto four strategies.

    The four strategies of context engineering

    LangChain's July 2025 post grouped context engineering techniques into four buckets. They're a good way to organize your own design.

    Diagram of the four context engineering strategies around an agent's context window: write to memory and scratchpads, select through retrieval, compress with summaries and clearing, and isolate with sub-agents

    Write: save it outside the context window

    Not everything the agent learns needs to stay in the window. Write notes, plans and intermediate results to a scratchpad file or a memory store, and read them back when needed. Anthropic's guide describes structured note-taking, such as a NOTES.md file or a to-do list, that survives even when the conversation is compacted.

    Select: pull in what the step needs

    Instead of loading everything up front, keep lightweight identifiers such as file paths, table names or document IDs, and fetch the content with a tool when the step calls for it. Anthropic calls this just-in-time retrieval. It's how coding agents explore a large codebase without reading every file.

    Selection applies to tools too. Loading 50 tool definitions when the task needs five is a direct route to confusion.

    Compress: keep the meaning, drop the tokens

    When the window fills, summarize it and continue in a fresh one. That's compaction. The hard part is deciding what to keep. Anthropic suggests tuning for recall first, so nothing important gets lost, then for precision.

    A lighter technique is tool-result clearing: once a tool result has been used, replace it with a short placeholder. Anthropic calls it one of the safest, lightest-touch forms of compaction. In its own evaluation, context editing that cleared stale tool results cut token use by 84% in a 100-turn web search task.

    Isolate: split the work

    Give sub-agents their own clean context windows for focused tasks, and have them return condensed summaries instead of their full working history. Anthropic notes that sub-agents typically return condensed summaries of about 1,000 to 2,000 tokens, however much they read. The trade-off is cost: every sub-agent, like every compaction, is an extra model call, so use them for work that would otherwise flood the main window.

    Agent memory: what to keep between calls

    Agent memory is the "write" strategy made permanent. It's what lets an agent remember a user's preferences next week, or avoid repeating a mistake it was corrected on.

    The LangGraph documentation splits it into a few types:

    There's also a design choice about when memories get written. Writing in the hot path, during the agent's run, makes new memories available at once but adds latency. Writing in a background job avoids that latency but takes effect later.

    Systems such as MemGPT, now developed as Letta, borrow from operating systems and page data between memory tiers. Mem0 reports, from its own benchmarks, large cuts in latency and token cost compared with sending full history. Treat vendor-run numbers as directional. Start with the simplest agent memory that solves a real problem, usually a short list of preferences the user has confirmed.

    A warning that applies to every agent memory design: memory turns one-off mistakes into permanent ones. A wrong fact written to memory is context poisoning with no expiry date. Store corrections that a person confirmed, give memories timestamps, and make them easy to inspect and delete.

    A worked example: a context budget in Python

    Here's a small context assembler that applies three of the strategies: clearing old tool results, filling a token budget by priority, and putting stable content first.

    from dataclasses import dataclass
    
    def count_tokens(text: str) -> int:
        # Rough rule of thumb: about 4 characters per token for English text.
        return max(1, len(text) // 4)
    
    @dataclass
    class Item:
        slot: str        # system, memory, docs, history, tool
        text: str
        priority: int    # lower number = more important
        stable: bool = False  # stable items go first so the prompt cache can reuse them
    
    def assemble(items: list[Item], budget: int, keep_tool_results: int = 1):
        # 1. Clear old tool results, keeping only the most recent ones.
        tools = [i for i in items if i.slot == "tool"]
        cleared = tools[:-keep_tool_results] if keep_tool_results else tools
        items = [i for i in items if i not in cleared]
        if cleared:
            items.append(Item("tool", f"[cleared: {len(cleared)} older tool results]", 9))
    
        # 2. Fill the budget in priority order, dropping what does not fit.
        chosen, dropped, used = [], [], 0
        for item in sorted(items, key=lambda i: i.priority):
            cost = count_tokens(item.text)
            if used + cost <= budget:
                chosen.append(item)
                used += cost
            else:
                dropped.append(item)
    
        # 3. Order the final context: stable content first, then the rest.
        chosen.sort(key=lambda i: (not i.stable, i.priority))
        return chosen, dropped, used
    
    items = [
        Item("system", "You are a finance analyst agent. Use governed metrics only. " * 6, 0, stable=True),
        Item("memory", "User prefers EMEA figures in EUR. Q4 2023 has a known data gap.", 1),
        Item("docs", "Net revenue = gross bookings - refunds - intercompany sales. " * 8, 2),
        Item("docs", "Old wiki page: revenue includes intercompany sales. " * 10, 5),
        Item("history", "User: How did EMEA net revenue compare with plan last quarter?", 1),
        Item("tool", "list_metrics -> 214 metrics ... " * 30, 4),
        Item("tool", "query_metrics(net_revenue, region=EMEA) -> 4.2M vs plan 4.5M", 3),
    ]
    
    chosen, dropped, used = assemble(items, budget=280)
    for i in chosen:
        print(f"{i.slot:8} {count_tokens(i.text):4} tokens")
    print("dropped:", [f"{d.slot} (p{d.priority})" for d in dropped])
    print(f"used {used} of 280 tokens")
    

    Output:

    system     90 tokens
    memory     15 tokens
    history    15 tokens
    docs      122 tokens
    tool       15 tokens
    tool        7 tokens
    dropped: ['docs (p5)']
    used 264 of 280 tokens
    

    The 240-token list_metrics dump was replaced by a seven-token placeholder, because only the latest tool result is kept. The governed revenue definition made it in. The outdated wiki page, which would have clashed with it, was dropped because it was the first item that didn't fit in the remaining budget. The small placeholder still fit after it. The system prompt comes first so a provider's prompt cache can reuse it across calls.

    A production version would use the model's real tokenizer, score documents by relevance instead of fixed priorities, and log what was dropped so you can debug bad answers later. The shape stays the same.

    Prompt caching and context order

    Prompt caching makes a stable prefix cheap to resend, and it shapes how you should order the context window. Anthropic's prompt caching docs describe a cache that is built in the order tools, then system prompt, then messages. A change at one level invalidates the cache for that level and everything after it.

    The practical rules:

    This lines up with "lost in the middle" too. Stable instructions at the start, the current question at the end, and the variable material between them.

    Where the context comes from

    Context engineering decides what goes into the window. It doesn't decide whether that content is correct. If the retrieved metric definition is wrong, or the table the agent queries was deprecated last month, perfect window management just delivers the wrong answer efficiently.

    That's the job of the layers underneath. A semantic layer gives governed metric definitions. The trade-offs are covered in context layer vs semantic layer, and a hands-on example is in the dbt Semantic Layer for AI agents. A knowledge graph gives relationships that vector search misses, as knowledge graphs for AI agents explains. Platforms such as Snowflake Horizon Context and Microsoft Fabric IQ bundle these pieces for agents.

    Most of those sources reach the agent as tools over the Model Context Protocol, which is why tool selection and tool-result clearing matter so much. Designing the governed side from scratch is covered in how to build a context layer for AI.

    Context engineering vs prompt engineering vs RAG

    The three terms overlap, and it helps to see them side by side.

    | | Prompt engineering | RAG | Context engineering | |---|---|---|---| | Question it answers | How should the instructions be phrased? | Which documents are relevant to this query? | What should the model see at this step, from every source? | | When it happens | Once, at design time | Per query | Per model call, across a long task | | Inputs | System prompt, examples | A document index | Instructions, tools, memory, retrieval, history, tool results | | Typical failure | Ambiguous or conflicting instructions | Missing or irrelevant chunks | Bloated, stale or contradictory context |

    RAG is one way to do the select step. Prompt engineering is still how you write the stable parts. Context engineering is the umbrella over both, plus everything that changes during a run.

    How to debug a context problem

    When an agent gives a wrong answer, look at what it saw before you change the prompt or the model. A practical routine:

    1. Log the full context window for every model call, including tool results, with token counts per section.
    2. Find the first step where the agent went wrong, not the last one. Errors early in a run compound.
    3. Check whether the right information was present. If it wasn't, it's a selection problem, so fix retrieval or tool choice.
    4. If it was present, check where it sat and what surrounded it. Information buried in the middle of a long window, or contradicted by an older tool result, points to compression or clearing.
    5. If a summary or memory introduced a wrong fact, trace where it came from and fix the write path.

    Many "the model got it wrong" reports turn out to be one of these, and logging the context makes them quick to spot.

    Common context engineering mistakes

    Key takeaways