An AI model knows two things: what it learned in training, and what's in its context window right now, meaning everything sent with your request. It has no other memory. It can't look things up unless you give it a tool, and it doesn't even know today's date. So when an AI app gives a bad answer, the cause is very often not the model, but the context: something important was missing, or buried under things that didn't matter.
Prompt engineering is about writing good instructions. Context engineering is the bigger job of deciding everything the model sees, which matters more and more as apps become agents that work through many steps.
What's in a context window?
πInstructions (system prompt)
Who it is, the rules, the answer format
πKnowledge and memory
Facts it can't know on its own
Retrieved documents
from RAG search
Long-term memory
"prefers Hindi", past orders
Facts of the moment
today's date, the user's plan
π οΈTools
What it can do, and what those actions returned
Tool descriptions
e.g. via MCP
Tool results
order lookups, search results
π¬Conversation so far
Recent messages, or a summary of older ones
βThe current question
What the user just asked
Every one of these is a choice. Context engineering is making those choices on purpose, for every request, instead of dumping everything in.
Why not just send everything?
Modern models accept hundreds of thousands of tokens. So why not send all of it? Because more context isn't free:
- Cost and speed. You pay for every input token, on every request, and long inputs take longer to process. A chatbot that sends 100,000 tokens per question costs far more than one that sends 3,000.
- Attention gets spread thin. Researchers found models use information at the start and end of a long input better than information in the middle (the βlost in the middleβ effect), and that answer quality tends to drop as inputs get longer, which some call context rot.
- Noise and contradictions. An old message, an outdated policy or a tool result full of junk can steer the answer the wrong way.
- Missing pieces still happen. Sending everything you have doesn't mean sending what's needed. Today's date, for example, is in none of your documents.
Try it. Build the context for one real support question, block by block:
Build the context for one support question
Context size
117,040 tokens
β $351.12 per 1,000 questions, before the model writes a word.
6 problems
- β οΈInstructions: No rules: tone, format and "say you don't know" are left to chance.
- β οΈKnowledge: The one useful article is buried among 500. Facts in the middle of long contexts are often missed, and every reply is slow and expensive.
- β οΈChat history: Old, unrelated messages compete for the model's attention with the actual question.
- β οΈTools: 40 similar tool descriptions: the model is more likely to call the wrong one.
- β οΈTool results: Thousands of tokens of tracking events, when only the delivery date matters.
- β οΈToday's date: The model can't know today's date, so it can't tell whether 7 days have passed.
The question: βCan I still return my kurta? It was delivered on 17 November.β Token counts are typical sizes and the price is an example ($3 per million input tokens), for illustration.
The four techniques: write, select, compress, isolate
Almost every context engineering trick falls into one of four groups:
βοΈWrite
Save it outside the context
Agent keeps a notes / plan file
Long-term memory of user facts
Bring it back only when needed
π―Select
Pull in only what's relevant
RAG: top few documents
Only the tools for this task
The memories that apply
ποΈCompress
Keep the meaning, drop tokens
Summarise old messages
Trim long tool results
Keep only needed fields
π§ͺIsolate
Split work into separate contexts
Sub-agents for sub-tasks
Each returns a short result
Main context stays clean
| Technique | Use it when | Example |
|---|---|---|
| Write | Something will matter later, but not right now | A coding agent saves "tests pass, next: fix the login page" to a notes file |
| Select | You have far more information than one answer needs | Retrieve the returns article for a returns question |
| Compress | The context keeps growing: long chats, many tool calls | Summarise messages 1β50 into two lines |
| Isolate | A big task has independent parts | Three sub-agents each research one competitor |
See it work: a context builder in Python
Here's a small, runnable version of what real AI apps do before every model call. ShopKart's support bot has five help articles (two of them long and irrelevant), a 34-message chat, and a huge order record from a tool. The script builds the context two ways: naive (everything) and engineered (select + compress, plus today's date). No API key needed: we only build and measure the context.
# Context engineering, small and runnable: build what the model sees, within a token budget.
# Runs anywhere (no API key): the "model call" is left out, we only build and measure the context.
def tokens(text: str) -> int:
"""Rough token count: about 4 characters per token for English."""
return max(1, len(text) // 4)
SYSTEM = (
"You are ShopKart's support assistant. Answer only from the POLICY section. "
"If the answer isn't there, say you'll connect the customer to a human. Be brief."
)
# ShopKart's help-centre articles (in a real app: a search index or vector database)
DOCS = {
"returns": "Returns: items can be returned within 7 days of delivery. Refunds reach the original payment method in 5-7 working days.",
"delivery": "Delivery: metro cities in 2-3 days, other cities in 4-6 days. Free delivery on orders above Rs 499.",
"payments": "Payments: UPI, cards, net banking and cash on delivery (COD up to Rs 10,000).",
"careers": "Careers: ShopKart is hiring engineers in Bengaluru and Pune. " + "Long article text. " * 120,
"history": "Company history: founded in 2019 in Kolkata. " + "Long article text. " * 150,
}
# A long chat so far (oldest first)
HISTORY = [("user", "Hi, I ordered a kurta last week."), ("assistant", "Happy to help! What's your question?")]
HISTORY += [("user", f"Also, small question number {i} about sizes and colours?") for i in range(1, 31)]
HISTORY += [("assistant", "Sizes run true to fit; colours may vary slightly on screen.")]
# The last tool call returned a huge order record
TOOL_RESULT = "order #A1043: kurta, size M, delivered 2026-11-17, paid by UPI. " + "raw tracking event... " * 200
QUESTION = "Can I still return it? It was delivered on 17 November."
TODAY = "20 November 2026" # the model can't know this unless we tell it
def naive_context() -> str:
"""Everything we have, dumped in."""
docs = "\n".join(DOCS.values())
chat = "\n".join(f"{who}: {text}" for who, text in HISTORY)
return f"{SYSTEM}\n\nPOLICY:\n{docs}\n\nCHAT:\n{chat}\n\nTOOL:\n{TOOL_RESULT}\n\nUSER: {QUESTION}"
def keywords(text: str) -> set[str]:
"""First 5 letters of each longer word, so "return", "returns" and "returned" all match."""
words = "".join(c if c.isalnum() else " " for c in text.lower()).split()
return {w[:5] for w in words if len(w) >= 4}
def select_docs(question: str, k: int = 2) -> list[str]:
"""SELECT: keep only the k articles that share the most keywords with the question.
(A real app would use a search index or embeddings: see the RAG lesson.)"""
q = keywords(question)
ranked = sorted(DOCS.values(), key=lambda doc: len(q & keywords(doc)), reverse=True)
return ranked[:k]
def compress_history(history, keep_last: int = 4) -> str:
"""COMPRESS: summarise old turns in one line, keep the newest turns word for word."""
old, recent = history[:-keep_last], history[-keep_last:]
summary = f"(Earlier: {len(old)} messages about a kurta order and sizes/colours.)"
return summary + "\n" + "\n".join(f"{who}: {text}" for who, text in recent)
def trim_tool(result: str, max_chars: int = 120) -> str:
"""COMPRESS: keep the useful start of a long tool result."""
return result if len(result) <= max_chars else result[:max_chars] + " β¦(trimmed)"
def engineered_context() -> str:
docs = "\n".join(select_docs(QUESTION))
return (
f"{SYSTEM}\nToday's date: {TODAY}.\n\nPOLICY:\n{docs}\n\nCHAT:\n{compress_history(HISTORY)}\n\n"
f"TOOL:\n{trim_tool(TOOL_RESULT)}\n\nUSER: {QUESTION}"
)
for name, ctx in [("Naive (everything)", naive_context()), ("Engineered", engineered_context())]:
print(f"=== {name}: {tokens(ctx):,} tokens ===")
print(f" has the returns policy: {'7 days of delivery' in ctx}")
print(f" has the delivery date: {'delivered 2026-11-17' in ctx}")
print(f" has today's date: {TODAY in ctx}")
print("\n--- The engineered context the model would see ---")
print(engineered_context())We ran it. This is the real output:
=== Naive (everything): 3,063 tokens ===
has the returns policy: True
has the delivery date: True
has today's date: False
=== Engineered: 236 tokens ===
has the returns policy: True
has the delivery date: True
has today's date: True
--- The engineered context the model would see ---
You are ShopKart's support assistant. Answer only from the POLICY section. If the answer isn't there, say you'll connect the customer to a human. Be brief.
Today's date: 20 November 2026.
POLICY:
Returns: items can be returned within 7 days of delivery. Refunds reach the original payment method in 5-7 working days.
Delivery: metro cities in 2-3 days, other cities in 4-6 days. Free delivery on orders above Rs 499.
CHAT:
(Earlier: 29 messages about a kurta order and sizes/colours.)
user: Also, small question number 28 about sizes and colours?
user: Also, small question number 29 about sizes and colours?
user: Also, small question number 30 about sizes and colours?
assistant: Sizes run true to fit; colours may vary slightly on screen.
TOOL:
order #A1043: kurta, size M, delivered 2026-11-17, paid by UPI. raw tracking event... raw tracking event... raw tracking β¦(trimmed)
USER: Can I still return it? It was delivered on 17 November.- 13Γ smaller (3,063 β 236 tokens), and nothing the answer needs was lost: the returns policy and the delivery date are both still there.
- The naive version is bigger and worse: it's missing today's date, so the model can't tell whether 7 days have passed. More context didn't mean the right context.
- Order matters too: the stable part (instructions) comes first and the question comes last. Many AI providers can cache a repeated beginning of the context, which makes later requests cheaper and faster, so put what never changes at the top.
Context engineering for agents
Agents make this harder, because every step adds to the context: the model calls a tool, the result comes back into the context, it thinks, calls another tool, and so on. After a few dozen steps the context can be mostly old tool output. What well-built agents do:
- Few, clear tools. Every tool description costs tokens on every step, and similar tools confuse the model. Load extra instructions only when needed, which is exactly what agent skills do.
- Just-in-time information. Instead of loading every file up front, give the agent tools to search and read what it needs, when it needs it.
- Clear old tool results once they've been used, and summarise (βcompactβ) the conversation when it gets long, keeping decisions and open problems.
- Notes outside the context. A plan or progress file lets the agent pick up where it left off, even in a fresh context.
- Sub-agents for big searches. A helper reads 30 pages in its own context and returns one paragraph.
A checklist for every AI feature
| Ask | If not⦠|
|---|---|
| Does the model have every fact the answer depends on? | Add it: retrieved docs, the user's data, today's date |
| Is anything in the context not needed for this step? | Remove, trim or summarise it |
| Are the instructions clear about format and what to do when unsure? | Add rules: "If it's not in the policy, say so" |
| Are there only the tools this task needs? | Load tools for the task, not all of them |
| Is the stable part at the start, the question at the end? | Reorder: instructions β knowledge β history β question |
| Have you measured it? | Run an eval before and after the change |
π― Spot the pattern: is it Select?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Retrieve the 3 most relevant help articles instead of all 500
2. Keep a notes file where the agent writes its plan and progress, and re-read it later
3. Show the model only the 4 tools this task needs, not all 40
4. Replace 50 old chat messages with a two-line summary
5. Let a sub-agent read 30 web pages and return a one-paragraph answer
6. Look up the customer's order and include only its delivery date
π― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is the difference between prompt engineering and context engineering?Fresher+
Q2Your chatbot gets worse as conversations get longer. Why, and what would you do?1β3 yrs+
Q3How would you decide which tools to give an agent?1β3 yrs+
Q4Design context management for a long-running coding agent.3+ yrs+
Key takeaways
- βThe context decides the answer: the model can't use what it doesn't see.
- βBigger isn't better: send what this step needs, in a sensible order.
- βWrite, select, compress and isolate cover nearly every technique.
- βAgents need it most, because every step adds to the context.
- βMeasure with evals; don't tune context by feel.
Next: when AI acts on its own, the context can also be used against it. Learn the defences in AI Agent Security.
Frequently asked questions
What is context engineering?
Context engineering is deciding everything an AI model sees when it answers: the instructions, the facts it needs, the relevant part of the conversation, the tools it can use and their results, all in the right amount and order. The model only knows its training plus this context, so the context decides the answer.
Is context engineering the same as prompt engineering?
Prompt engineering is about writing good instructions. Context engineering is the bigger job: the instructions are one part, alongside retrieved documents, memory, chat history, tools and tool results. It matters most for chatbots and agents that run many steps, where the context keeps growing.
If models have huge context windows, why not put everything in?
Three reasons: cost and speed grow with every token you send, models pay less attention to facts buried in the middle of long contexts, and irrelevant or out-of-date text can confuse the answer. A big window is room to work with, not a reason to fill it.
What are the main context engineering techniques?
Four groups: write (save notes and memory outside the context to bring back later), select (pull in only the relevant documents, memories and tools), compress (summarise old messages, trim long tool results) and isolate (give sub-tasks to sub-agents that each have their own small context).
How do I know if my context engineering is working?
Measure it. Build a small eval set of real questions, run it with your current context and with your changed context, and compare correctness, token count and speed. Our AI evals lesson shows how.
π§ Quick check: context engineering
1. A support bot says returns are allowed for 30 days, but the policy says 7. Its context had no policy text. What's the fix?
2. After 200 steps, an agent's context is full of old tool outputs. Which technique helps most?
3. Why should you tell the model today's date?
4. A research agent hands each of 5 topics to a helper agent and gets back short summaries. That's...
Checking your accessβ¦