Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Context engineering techniques: what the model should see

What to put in a model's context at each step, what to leave out, and how instruction files, retrieval and tools fit.

By Updated Intermediate30 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

A prompt is one message. Context is everything the model sees when it produces its next token: the system prompt, instruction files, examples, retrieved documents, tool definitions, the results of earlier tool calls and the conversation so far. In a chat app most of that is assembled for you. As soon as you build anything that runs for more than one turn, assembling it becomes your job, and it is where most quality problems come from.

Anthropic’s engineering team described context engineering in a September 2025 post as curating “the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome.” This tutorial turns that sentence into practical context engineering techniques, then builds a small context assembler in Python so you can see each decision in code. If you want the definition and the history of the term first, read what is context engineering?

Why more context is not better

Current models accept very large inputs. Claude’s newer models take a million tokens, so it is tempting to send everything and let the model sort it out. Three things go wrong when you do:

  1. Attention thins out. As the window fills, recall of any one detail gets less reliable. Anthropic calls this context rot. An instruction on line 12 of a 300,000-token input competes with everything after it.
  2. Irrelevant text misleads. A pasted document that is nearly relevant (last year’s pricing page, the v1 API) is worse than no document, because the model will use it.
  3. Cost and latency grow with every token, on every turn, because the whole context is sent again each time.

So the question at each step is not “what might help?” but “what does the model need to do this step well, and what would distract it?”

The parts of a context

It helps to name the pieces, because each one has a different lifecycle.

Part Changes Typical size Who controls it
System prompt and role Rarely Hundreds of tokens You, in code
Instruction files (CLAUDE.md, AGENTS.md, rules) Per project Hundreds to a few thousand The team, in the repo
Tool definitions Per release Grows with every tool You, or MCP servers you connect
Retrieved material Every turn The largest variable part Your retrieval step
Tool results Every step Can be huge (a file, a log) The tools
Conversation history Grows every turn Unbounded unless managed Your loop

Stable parts belong at the start and should not change between calls. That is good for the model and also for cost: providers cache the stable prefix of a request, and any change early in the prompt invalidates the cache for everything after it.

Five decisions that shape context

Instructions: short, specific, stable

Write instructions for things the model cannot discover by reading the code or the documents: build and test commands, conventions that are not obvious, what to never touch. Keep them short enough that each line matters. Claude Code’s documentation suggests keeping a CLAUDE.md under about 200 lines and moving anything that applies to only part of a codebase into path-scoped rules. The CLAUDE.md and AGENTS.md tutorial covers this in detail.

Retrieval: just in time, not just in case

There are two ways to get documents in front of a model. Pre-loading puts them in the context up front. Just-in-time retrieval gives the model a lightweight pointer (a file path, a search tool, a URL) and lets it fetch what it needs. Coding agents work this way: they do not paste your whole repository into context, they search and open files as needed.

Pre-load when the material is small and always relevant. Retrieve when the corpus is large or the relevant part depends on the question.

Tool results: trim before they land

A tool that returns a 5,000-line log puts 5,000 lines into every later turn. Have tools return what the model needs: the matching lines, the first error, a count plus a sample. If the model needs more, give it a way to ask for the next page.

History: keep recent turns, summarise the rest

Old turns are rarely needed verbatim. Keep the last few exchanges as they were and replace older ones with a short summary. Agents that run for a long time do the same thing at a larger scale, which is called compaction: when the context approaches its limit, the conversation so far is summarised and the summary starts a fresh window.

Isolation: give big sub-tasks their own context

When a step needs to read a lot to produce a little (“find every place we call the payments API”), run it in a separate model call or sub-agent and pass back only the answer. The main conversation stays clean.

Build a small context assembler

The example below is a support assistant for a fictional app called Tasklane. It shows four of the decisions in code: a stable system prompt, retrieval per question, a token budget, and history that stores the questions and answers but not the documents used to answer them.

Set up a folder with a few Markdown files in docs/ (any short help pages will do), then install the SDK:

pip install anthropic
export ANTHROPIC_API_KEY="your-key"
# assemble.py
from dataclasses import dataclass, field
from pathlib import Path

import anthropic

client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"

SYSTEM = """You are the support assistant for Tasklane, a project-management app.
Answer from the documentation excerpts provided in <docs>. If they do not cover the
question, say you don't know and offer to pass the question to a human.
Keep answers under 120 words and link the doc page you used."""


@dataclass
class Doc:
    path: str
    text: str


@dataclass
class Conversation:
    summary: str = ""
    turns: list[dict] = field(default_factory=list)


def load_docs(folder: str) -> list[Doc]:
    return [Doc(str(p), p.read_text(encoding="utf-8")) for p in sorted(Path(folder).glob("*.md"))]


def retrieve(docs: list[Doc], question: str, k: int = 3) -> list[Doc]:
    """Deliberately simple keyword overlap. Swap in vector search later without changing the rest."""
    words = {w for w in question.lower().split() if len(w) > 3}
    scored = [(sum(w in d.text.lower() for w in words), d) for d in docs]
    return [d for score, d in sorted(scored, key=lambda x: -x[0])[:k] if score > 0]


def build_messages(convo: Conversation, docs: list[Doc], question: str, keep_turns: int = 6) -> list[dict]:
    excerpts = "\n\n".join(f'<doc path="{d.path}">\n{d.text}\n</doc>' for d in docs) or "(no matching docs)"
    preamble = f"<summary_of_earlier_conversation>\n{convo.summary}\n</summary_of_earlier_conversation>\n\n" if convo.summary else ""
    recent = convo.turns[-keep_turns:]
    return [*recent, {"role": "user", "content": f"{preamble}<docs>\n{excerpts}\n</docs>\n\n<question>{question}</question>"}]


def token_count(messages: list[dict]) -> int:
    return client.messages.count_tokens(model=MODEL, system=SYSTEM, messages=messages).input_tokens


def answer(convo: Conversation, all_docs: list[Doc], question: str, budget: int = 20_000) -> str:
    docs = retrieve(all_docs, question)
    messages = build_messages(convo, docs, question)
    while token_count(messages) > budget and len(docs) > 1:
        docs = docs[:-1]  # drop the weakest excerpt first
        messages = build_messages(convo, docs, question)
    response = client.messages.create(model=MODEL, max_tokens=1000, system=SYSTEM, messages=messages)
    text = "".join(b.text for b in response.content if b.type == "text")
    convo.turns += [{"role": "user", "content": question}, {"role": "assistant", "content": text}]
    return text


if __name__ == "__main__":
    convo = Conversation()
    docs = load_docs("docs")
    print(answer(convo, docs, "How do I export a project to CSV?"))

Walk through what each function decides:

  • SYSTEM never changes between calls. It states the role, the source of truth and the escape hatch (“say you don’t know”), and nothing else.
  • retrieve picks at most three documents per question. It is naive on purpose. The point is the seam: you can replace it with vector search later and nothing else changes.
  • build_messages wraps documents in tags with their path, so the model can cite them, and keeps only the last six turns.
  • answer checks the size with the token-counting endpoint before sending and drops the weakest document if the request is over budget. It then stores the question and answer in history, but not the documents. Next turn retrieves fresh documents for the new question instead of carrying old ones forward.

To complete the picture, add a summarise_history step that runs when turns grows past, say, twenty entries: send the oldest turns to the model with “Summarise the facts and decisions in this support conversation in under 100 words”, store the result in convo.summary and delete those turns.

Pitfalls

Changing the start of the prompt every call. Putting a timestamp or a request ID in the system prompt makes each request look new, so prompt caching never hits. Put volatile values at the end.

Tool definitions as an afterthought. Every connected tool’s name, description and schema sits in context on every call. Ten MCP servers with twenty tools each is a lot of tokens before the user has said anything. Connect what the task needs.

Old tool results riding along. In a long agent run, the full text of a file read in step 3 is still there in step 40. If your framework supports clearing old tool results or compaction, turn it on; if you write the loop yourself, replace old results with a one-line note.

Contradictions between layers. A system prompt that says “be brief” and an instruction file that says “explain every change in detail” leaves the model to pick one. Review the layers together.

Assuming the model saw something. Log the exact context of a bad answer. It is common to discover that retrieval returned nothing, or the wrong version of a document, and the model did its best.

Next steps

Covers

Check your understanding

Context engineering basics quiz

What a model should see at each step: instructions, retrieved text, tools, history and what to leave out.

7 questions · pass mark 70%

Question 1 of 70 answered
  1. What is context engineering mostly about?
  • What is context engineering?

    Context engineering is deciding what a model sees at each step. Why the term replaced prompt engineering for people building agents, and what the work involves.

    Article

  • CLAUDE.md and AGENTS.md: instruction files for coding agents

    CLAUDE.md vs AGENTS.md: what to put in each, where Claude Code, Codex, Cursor and Copilot look for them, and how to keep one source of truth without drift.

    TutorialBeginner20 min

  • RAG fundamentals: retrieval before generation

    What RAG is and how retrieval-augmented generation works, when it beats long context or fine-tuning, and a minimal working pipeline in about 80 lines of Python.

    TutorialBeginner30 min

  • Context engineering

    Deciding what information, tools and history a model sees at each step, and what to leave out, to get the result you want.

    Glossary

  • Context window

    The maximum number of tokens a model can consider in one request, covering both the input you send and the output it writes.

    Glossary

Back to top