← All posts

Building with LLMs › Prompts and context

What is context engineering? Choosing what an LLM sees

Context engineering means deciding what an LLM sees at every step. Where the term came from, why longer context can hurt, and the techniques agents use.

If you’ve been reading about AI agents, or tried to build something on top of a large language model, you’ve probably come across the phrase context engineering. It turns up in posts about agents and in the engineering blogs of AI companies, often right next to the older phrase prompt engineering. At first it may sound like a new name for something you were already doing. In part it is, but the name brings out a side of the work that was easy to miss.

Context engineering is the work of designing and managing everything a model sees at each step. That includes the system prompt, the descriptions of the tools it can call, the conversation so far, the material retrieved for it, and the notes it keeps. A model knows nothing about your task beyond this input, which is called its context. And since an agent calls the model again and again in a loop, the context has to be put together anew at every step. So the question shifts from how to word one instruction to what should be in front of the model right now. As agents became common, that question became hard to avoid, and the name for it spread quickly from the middle of 2025.

How the term spread

It isn’t clear who used the term first. On June 19, 2025, Shopify co-founder Tobi Lütke wrote on X that he liked the term context engineering better than prompt engineering. In his words, “the art of providing all the context for the task to be plausibly solvable by the LLM” is the core skill, and the new term describes it better. Six days later, AI researcher Andrej Karpathy agreed. In industrial-strength LLM apps, he wrote, “the delicate art and science of filling the context window with just the right information for the next step” is what context engineering is about. He also warned that too little context leaves the model short, while too much or too irrelevant context might raise costs and lower performance.

On September 29, 2025, Anthropic laid out the idea in Effective context engineering for AI agents. The post sees context engineering as the natural progression of prompt engineering, and describes it as curating and maintaining the best set of tokens while the model runs. A token is a small piece of text, such as a word or part of a word, and it’s the unit models read and count in. The post’s guiding principle is to find the smallest possible set of high-signal tokens that makes the result you want most likely.

What the model sees at each step

Anthropic’s context window docs call the context window the model’s working memory, and note that everything in a request counts toward it, from the system prompt and tool definitions to every message, tool results included. Laid out piece by piece, it looks like this.

Piece What it holds What you decide
System prompt Standing instructions and role How specific to be
Tool descriptions Names, purposes, and parameters Which tools to offer, without overlap
Conversation history Earlier turns and tool results What to keep, summarize, or clear
Retrieved material Documents, search results, file contents What’s relevant to this step
Notes Files kept outside the window What must survive a reset

Why more context isn’t always better

Context windows keep growing, and when I checked on October 27, 2026, the same docs listed a 1M-token window for recent Claude models. Even so, the page says plainly that more context isn’t automatically better, because accuracy and recall degrade as the token count grows. It calls this context rot.

Research points the same way. In Lost in the Middle (2023), Nelson F. Liu and colleagues found that models often did best when the relevant information sat at the beginning or end of a long input, and significantly worse when it sat in the middle. In NoLiMa (2025), 13 models that claim to handle at least 128K tokens answered questions that shared few words with the passage holding the answer, and at 32K tokens, 11 of them fell below half of their short-input scores. Chroma’s Context Rot report from July 2025 tested 18 models. In one of its tasks, answering questions about a long chat history, all the models did significantly better with only the relevant part, about 300 tokens, than with the whole history of about 113,000 tokens.

Anthropic explains this with an attention budget. Every token relates to every other token, so the longer the input, the thinner the model’s attention is spread. That’s why the post suggests treating context as a finite resource whose returns diminish as you add more.

Building a context within a token budget

Let’s make this concrete. The Python example below assembles the context for a notes app’s help assistant within a budget of 90 tokens, kept tiny so each decision is easy to see. The system prompt and the question always go in. Documents go in only if they share words with the question, most shared words first. Recent turns come next, newest first, and once one turn is cut, every older turn goes too so the conversation doesn’t skip a step. Tokens are counted with tiktoken, a tokenizer library from OpenAI.

import re
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
def count(text): return len(enc.encode(text))
def words(text): return set(re.findall(r"[a-z]{4,}", text.lower()))

system = "You are the help assistant for a notes app. Answer in two sentences."
docs = {"sync.md": "Notes sync every 5 minutes. To sync at once, tap Sync now in Settings.",
        "offline.md": "Notes edited offline sync after the phone reconnects to the internet.",
        "themes.md": "Dark mode and font size live under Settings, then Appearance."}
history = ["user: How do I export my notes?", "assistant: Use Export in the File menu.",
           "user: My phone was offline on the train today.", "assistant: Got it. Anything else?"]
question = "user: My new notes are not showing up on my phone. How do I sync?"
BUDGET, kept = 90, [system, question]  # the system prompt and the question always go in

def offer(label, text, why=""):
    if not why and sum(map(count, kept)) + count(text) > BUDGET: why = "over budget"
    if not why: kept.append(text)
    print(f"{label:<26}{count(text):>3}  {'dropped, ' + why if why else 'kept'}")
    return why

print(f"{'system + question':<26}{count(system) + count(question):>3}  kept")
for name in sorted(docs, key=lambda d: -len(words(docs[d]) & words(question))):
    n = len(words(docs[name]) & words(question))  # words shared with the question
    offer(f"doc {name} ({n} shared)", docs[name], "" if n else "unrelated")
cut = ""  # walk from the newest turn; once one is cut, every older turn goes too
for i, turn in reversed(list(enumerate(history, 1))):
    cut = offer(f"turn {i} ({turn.split(':')[0]})", turn, cut and "too old")
print(f"total {sum(map(count, kept))} of {BUDGET} tokens")
system + question          33  kept
doc offline.md (3 shared)  13  kept
doc sync.md (2 shared)     18  kept
doc themes.md (0 shared)   12  dropped, unrelated
turn 4 (assistant)          8  kept
turn 3 (user)              11  kept
turn 2 (assistant)          9  dropped, over budget
turn 1 (user)               9  dropped, too old
total 83 of 90 tokens

Look at themes.md first. There was still room in the budget, yet it was dropped because it has nothing to do with the question. Free space alone is no reason to fill the context. Next, offline.md came first even though the question never says offline, because it shares notes, sync, and phone. Together with turn 3, where the user mentioned the phone was offline on the train, it gives the model what it needs to point to a likely cause. The older exchange about exporting was cut when the budget ran out, which costs little since it’s unrelated.

Of course, this is only a sketch. Counting shared words is a crude stand-in for real retrieval, which often uses embedding search, a way of finding text with similar meaning, or lets the agent search for itself. tiktoken also counts each piece on its own, so an API will report a slightly different number for a real request, and a model with another tokenizer will count differently.

Four techniques you’ll see often

The first is loading things only when they’re needed. Rather than putting every document in up front, the agent keeps light references such as file paths or links, and loads the data with tools when it needs it. The Anthropic post calls this just in time. Claude Code, for example, reads its CLAUDE.md file at the start, then finds other files with search tools like grep as it goes. The cost is speed, since exploring at runtime is slower than handing over data prepared in advance.

The second is summarizing, also called compaction. When a conversation nears the limit, you summarize it and start a fresh context window with the summary. According to the post, Claude Code keeps decisions, unresolved bugs, and implementation details, and drops redundant tool output. Still, the post warns that compacting too aggressively can lose details whose importance only shows up later.

The third is keeping notes outside the window. The agent writes progress and decisions to a file such as NOTES.md, and reads it back after the context resets. In Claude Code, the CLAUDE.md file you write and the auto memory notes Claude writes for itself both load at the start of every session. Its memory docs suggest keeping each CLAUDE.md under 200 lines, since longer files take up more context and are followed less reliably.

The fourth is splitting work across sub-agents. A sub-agent is a separate agent that handles a side task in its own clean context window and hands back only a summary, and Claude Code’s sub-agent docs suggest one when search results or logs would flood the main conversation. In Anthropic’s June 2025 write-up of its multi-agent research system, Claude Opus 4 leading Claude Sonnet 4 sub-agents outperformed a single Claude Opus 4 agent by 90.2% on an internal research eval. That came at a price, though, since multi-agent systems used about 15 times as many tokens as chats.

How it differs from prompt engineering

Prompt engineering is about how to write and organize the instructions you give a model. Context engineering includes that, and also covers everything else that ends up in the window. And while a prompt is usually written once, the choice of context is made again at every step. So a good prompt still matters, as one part of the context. Further out, harness engineering builds the layer around the model that, as the Claude Code docs put it, provides the tools and manages the context the model sees, and loop engineering decides when the agent runs and stops.

When it matters and when it doesn’t

Context engineering matters most when things pile up. Agents that take many steps, long conversations, apps that search many documents, and work that spans several sessions all belong here. In these cases the context grows bigger and messier unless something decides what stays.

On the other hand, for a single short request, like classifying one review, the prompt is nearly the whole context, so careful prompt writing is usually enough. Every summary step or sub-agent you add is also one more thing that can go wrong. The Anthropic post itself says that with the field moving this fast, “do the simplest thing that works” will likely remain its best advice.

Where to start

If you’re building an LLM app, I’d suggest first printing the exact context it sends at one step and counting its tokens. Perhaps you’ll find old tool output or documents nobody needed. If you use Claude Code, running /context shows what’s taking up space. I ran the example above on October 27, 2026, with Python 3.13.12 and tiktoken 0.14.0.

AI tools helped with the research for this post.