# What is context engineering? Vs prompt engineering, with code

URL: https://sdclabs.com/glossary/context-engineering/

> Context engineering decides what an LLM sees on every call. How it differs from prompt engineering, which API features help, and a runnable Python example.

# What is context engineering?

[Mykhailo Poliarush](https://sdclabs.com/author/poliarush/) 2026-11-26

Definition

Context engineering is the practice of choosing what a language model sees on each call: instructions, tool definitions, retrieved data, message history and earlier tool results. It extends prompt engineering, because an agent's input changes every turn. The goal is the smallest set of relevant tokens that still gets the task done.

## How is context engineering different from prompt engineering?

Prompt engineering is about wording one set of instructions. Context engineering is about everything the model receives, and it repeats on every call. Anthropic's Applied AI team made the distinction in [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) , published September 29, 2025 (just over a year old). It calls context engineering "the natural progression of prompt engineering" and describes it as curating what goes into a limited window "from that constantly evolving universe of possible information."

|   | Prompt engineering | Context engineering |
|---|---|---|
| Unit of work | One prompt, usually the system prompt | The full input of each model call |
| When it happens | Once, before release | Every turn, while the agent runs |
| What changes | Words, structure, examples | Which files, tool results, history and tools are present |
| Typical failure | Vague or contradictory instructions | The right fact is missing, or buried under stale output |
| Where it lives | A prompt file | Code: retrieval, trimming, summarizing, memory |

The right-hand column matters more once agents enter. A chatbot answering one question has little to curate. An agent that has run 40 tool calls has a history full of file dumps, test logs and dead ends, and something has to decide which of those the next call still needs.

## Why does context engineering matter for agents?

LangChain's documentation puts the case plainly: when an agent fails, either the model is not capable enough or the right context never reached it, and "more often than not" it is the second ([LangChain, context engineering in agents](https://docs.langchain.com/oss/python/langchain/context-engineering) ).

More text is not a fix. Anthropic's post explains why long inputs degrade, a pattern known as context rot, which the post says needle-in-a-haystack benchmark studies uncovered. One cause sits in the transformer itself: every token attends to every other token, which makes n² pairwise relationships for n tokens, so attention spreads thinner as input grows. Another is training data, where shorter sequences are more common than long ones. Anthropic's advice is to aim for "the smallest possible set of high-signal tokens" that gets the result. The context window entry covers size limits and measured drops in accuracy.

## What parts of the context can you control?

LangChain splits context into three types, which is a practical checklist even outside its framework:

| Context type | What you control | Lasts |
|---|---|---|
| Model context | Instructions, message history, tools, response format for one call | One call |
| Tool context | What tools can read and write: state, stores, runtime settings | Across turns |
| Life-cycle context | What happens between model and tool calls: summaries, guardrails, logging | Across turns |

The split matters because the fixes differ. You can filter model context per call without losing anything. A summary written into life-cycle context replaces what was there, so a bad summary is permanent.

## Which techniques do model APIs support today?

Providers now ship context engineering as API features, so you do not have to write all of it yourself. On the Claude API, as of November 2026:

- **Tool result clearing.** The clear_tool_uses_20250919 strategy removes the oldest tool results once context passes a threshold you set, and puts placeholder text where they were ([context editing docs](https://platform.claude.com/docs/en/build-with-claude/context-editing) , beta).
- **Thinking block clearing.** clear_thinking_20251015 controls how much reasoning from earlier turns stays in context. The default differs by model class, so the docs advise setting keep explicitly when code runs across several model classes.
- **Compaction.** The server replaces older turns with a summary, either when you ask or when input reaches a token threshold ([compaction docs](https://platform.claude.com/docs/en/build-with-claude/compaction) , beta). The [context editing docs](https://platform.claude.com/docs/en/build-with-claude/context-editing) call it the primary strategy for long-running conversations in most use cases.

Structured notes, just-in-time retrieval and memory outside the window are covered in our guide on [how to build AI agents](https://sdclabs.com/blog/how-to-build-ai-agents/) . Isolation is the other lever: subagents explore in their own window and return only a short summary.

## Example: building the next call from a long history

This script decides what the model sees after four tool calls. It keeps the instructions and a notes file pinned, keeps the two newest tool results word for word, and replaces older results with a placeholder the model can act on. Word counts stand in for tokens.

# context.py: decide what the model sees on its next call. Word counts stand in for tokens # here; use your provider's token counting endpoint for real numbers. SYSTEM = "You fix failing tests in this repo. Run the tests after every edit." NOTES = "notes.md: test_total fails; cause is in src/price.py; do not touch migrations/" history = [ {"role": "tool", "name": "run_tests", "text": "FAILED test_total " + "trace " * 400}, {"role": "tool", "name": "read_file", "text": "src/price.py " + "line " * 300}, {"role": "assistant", "text": "The bug is a minus sign in total(). Editing it now."}, {"role": "tool", "name": "edit_file", "text": "wrote src/price.py"}, {"role": "tool", "name": "run_tests", "text": "1 passed"}, ] def build_context(history, keep_tool_results=2): """Pin instructions and notes, keep recent tool results, clear the older ones.""" tool_turns = [i for i, m in enumerate(history) if m["role"] == "tool"] keep = set(tool_turns[-keep_tool_results:]) msgs = [] for i, m in enumerate(history): if m["role"] == "tool" and i not in keep: msgs.append({**m, "text": f"[{m['name']} result cleared, rerun if needed]"}) else: msgs.append(m) return [{"role": "system", "text": SYSTEM}, {"role": "user", "text": NOTES}] + msgs size = lambda msgs: sum(len(m["text"].split()) for m in msgs) raw = [{"role": "system", "text": SYSTEM}, {"role": "user", "text": NOTES}] + history ctx = build_context(history) print(f"raw history: {size(raw)} words, engineered context: {size(ctx)} words") for m in ctx: print(f" {m['role']:9} {m['text'][:60]}")
Output under Python 3.11:

raw history: 742 words, engineered context: 51 words system You fix failing tests in this repo. Run the tests after ever user notes.md: test_total fails; cause is in src/price.py; do not tool [run_tests result cleared, rerun if needed] tool [read_file result cleared, rerun if needed] assistant The bug is a minus sign in total(). Editing it now. tool wrote src/price.py tool 1 passed
The model's own conclusion ("a minus sign in total()") survives, and the 700 words of trace and file content it was based on do not. The placeholder tells the model how to get the data back, so clearing is reversible.

## When is context engineering worth the effort?

It pays off when calls build on each other: agents with many tool calls, long chat sessions, and tasks that cross several context windows. That code usually lives in the [agent harness](https://sdclabs.com/glossary/agent-harness/) .

It matters little for a single classification or extraction call with a short input. There, a clear prompt and good examples do most of the work.

## What should you check before shipping it?

1. **Log the exact input of every call.** You cannot debug context you never saw.
1. **Test the summary, not only the answer.** Run tasks where a detail from early in the run is needed at the end.
1. **Make cleared data recoverable.** Leave a path, a query or a tool name in its place.
1. **Treat tool output and memory as untrusted.** Retrieved text can carry instructions, so include hostile documents and web pages in your tests.

SDCLabs designs context handling as part of the [AI agents](https://sdclabs.com/services/ai-agents/) we build, with engineers reviewing what the agent sees and tests checking what it does.

## Sources

1. [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) , Anthropic, 2025-09-29
1. [Context engineering in agents](https://docs.langchain.com/oss/python/langchain/context-engineering) , LangChain, 2026-11-12
1. [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) , Anthropic, 2026-11
1. [Compaction overview](https://platform.claude.com/docs/en/build-with-claude/compaction) , Anthropic, 2026-11

## Frequently asked questions

### Is context engineering a new idea?

The name is recent. Anthropic's September 2025 post describes it as a term that had just come to prominence after a few years in which prompt engineering got most of the attention. The post does not credit anyone with coining it.

### Is context engineering replacing prompt engineering?

No. Writing clear instructions is still part of the job. Context engineering adds the decisions about everything else that lands in the input, such as tool results, retrieved documents and history.

### Is RAG a form of context engineering?

Yes. Retrieval decides which documents enter the input, which is one context decision. Agents add others, such as clearing old tool output or summarizing history. See [agentic RAG](https://sdclabs.com/glossary/agentic-rag/) for retrieval inside an agent loop.

### Do bigger context windows make context engineering unnecessary?

No. Anthropic expects context windows of all sizes to suffer from context pollution and relevance problems for the foreseeable future, so curating the input still matters with a 1M-token window.

Services

- [AI agents](https://sdclabs.com/services/ai-agents/)
- [Generative AI](https://sdclabs.com/services/generative-ai/)

Read next

- [How to build AI agents that still work after the demo](https://sdclabs.com/blog/how-to-build-ai-agents/)
- [An agent that passes once can fail twice: a practical guide to AI agent testing](https://sdclabs.com/blog/ai-agent-testing/)

Related terms

- [Agent harness](https://sdclabs.com/glossary/agent-harness/)
- [Agentic RAG](https://sdclabs.com/glossary/agentic-rag/)

[Mykhailo Poliarush](https://sdclabs.com/author/poliarush/) Founder and CEOLeads SDCLabs, an AI development company founded in Krakow in 2011.[LinkedIn](https://www.linkedin.com/in/poliarush/) [GitHub](https://github.com/poliarush)

## Building with AI agents? Talk to an engineer.

[Start a project](https://sdclabs.com/contact/) [Book a call with the CEO](https://calendly.com/sdclabs/60min)
