All guides
Expert • 3 h3 h (théorie + exercices interactifs)Free Guide

Context Engineering

Maîtrisez la discipline clé de l'IA moderne : concevoir, optimiser et gouverner le contexte fourni aux LLMs pour des performances de production.

The Four Pillars

Loading diagram…

The Four Pillars in Detail

What goes into a context window and why

Pillar 1, Instructions

The system prompt defines WHO the model is, WHAT it should do, and HOW it should behave. This is the foundation of every interaction.
code
You are a financial advisor for retail investors.

Rules:
- Never recommend specific stocks
- Always include risk disclaimers
- Use simple language (8th grade reading level)
- If the user asks about crypto, redirect to our crypto specialist

Tone: Professional but approachable. Use analogies.

💡 Good instructions are specific about what NOT to do. Constraints prevent errors.

1/4

The honest read on "context engineering" as a newly-named discipline, tracked across r/MachineLearning, r/LocalLLaMA, and r/PromptEngineering: the four-pillars framing is useful as a checklist, and the community's sharper observation is that the bottleneck in production LLM systems is almost never "we didn't give the model enough context" — it's "we gave the model too much context, badly ordered, and it lost track of what mattered". The lost-in-the-middle paper (Liu et al., 2023), the Anthropic long-context benchmarks, and the LLMlingua prompt compression research all point to the same pattern: more tokens is not better, relevant-tokens-first is better.

Where the community correctly pushes back on the "200K context solves everything" pitch: large context windows make it easy to be lazy about retrieval. The teams getting good results are still doing the hard work of scoring, ranking, and pruning their context to the smallest set that lets the model answer — exactly as if the window were 8K. The RAG vs long-context ablations from the Chroma team are clear: curated 16K beats dumped 128K on most downstream metrics.

Pragmatic rule from people running real context pipelines: write a context budget per task (tokens for system, tokens for retrieval, tokens for examples, tokens for user input), enforce it in code, and when you exceed it, cut rather than upgrade to a bigger model. The discipline of cutting forces you to learn what the model actually needs to answer, which is worth more than the extra tokens.

Context Budget Management

Context vs Performance

Token BudgetWhat You Can FitTypical Use Case
4K tokensSystem prompt + 1 query + short responseSimple chatbot, Q&A
16K tokensSystem prompt + 3-5 RAG chunks + conversation historyDocument-grounded assistant
128K tokensSystem prompt + full document + extensive history + examplesComplex analysis, code review
1M+ tokensMultiple documents, entire codebases, full conversation archivesDeep research, codebase Q&A

← Scroll horizontally →

Quick Check

Why should RAG knowledge get the largest share of context (50%)?

Advanced Techniques

Click to expand
Click to expand

Test Your Understanding

Question 1 of 5.

Context Engineering Knowledge Check

0 / 5 answered

Q1.What are the four pillars of context engineering?

5 questions remaining

Where to Go From Here

You now understand context architecture. Next, explore a specific challenge: the Lost-in-the-Middle problem, why models struggle with information buried in long contexts, and how to engineer around it.


Continue to Lost-in-the-Middle: Advanced RAG to learn about context position effects.


The Lost-in-the-Middle Effect

Why Attention Drops in the Middle

Understanding the mechanism behind the effect

Primacy Bias

Transformer attention mechanisms naturally weight the first tokens more heavily. The system prompt and early context set the frame for interpretation.

💡 First impressions matter even for AI, early context shapes how subsequent information is interpreted.

1/4

The honest read on lost-in-the-middle three years after the original Liu et al. paper, tracked across r/MachineLearning, r/LocalLLaMA, and r/LangChain: the effect is real, it has softened with newer models but not disappeared, and every vendor claim of "perfect recall across 1M tokens" is marketing until you verify it on your data. The NoLiMA benchmark from Anthropic, the RULER benchmark, and the Chroma context rot research all show the same picture: synthetic needle-in-a-haystack tests overstate real-world performance, because real documents contain distractors, partial matches, and semantically related noise that pure needle tests don't.

Where the community correctly pushes back on the "long context kills RAG" framing: long context and RAG are complementary, not competing. The teams with the best retrieval quality combine a 10-15K window of carefully ranked context with a long-context model that can hold the conversation history and user instructions. Dumping 128K of unranked chunks into the window performs worse than classic 8K RAG on most real queries; ranking matters more than window size.

Pragmatic rule from people who run production RAG: always do a reranking pass (Cohere Rerank, Jina Reranker, or a cross-encoder you host yourself), always put your highest-scored chunks at the start and the end of the context, and always measure recall on your own eval set — not on MTEB, not on BEIR, not on marketing slides. The position-sensitivity curve is subtle and model-specific, and you only learn yours by testing.

Advanced RAG Architecture

Basic RAG vs Optimized RAG

AspectBasic RAGOptimized RAG
RetrievalTop-K by similarityRetrieve + rerank by relevance AND diversity
Document CountAs many as fit5-7 high-quality chunks
OrderingBy retrieval scoreMost relevant at start AND end, supporting in middle
RedundancyDuplicate information commonDeduplicated and compressed
Answer LocationAnywhere in contextForced to beginning or end via reranking

← Scroll horizontally →

Quick Check

What is the optimal number of RAG chunks for most queries?

Reranking: The Key to Quality

Click to expand
Click to expand

Test Your Understanding

Question 1 of 5.

Lost-in-the-Middle Knowledge Check

0 / 5 answered

Q1.What is the 'lost-in-the-middle' effect?

5 questions remaining

Next Steps

You understand how position affects AI context. The final article in this module covers prompt caching and MCP protocol, optimizing AI systems for production efficiency.


Continue to Prompt Caching & MCP Protocol to learn about production optimization.


The part of prompt caching nobody optimises for (until it bites)

The standard pitch is caching = save 80-90% on tokens. True. What gets left out of most write-ups, and what engineers on r/LangChain and r/OpenAI keep learning the hard way, is that caching is only a win when your cache hits. And whether it hits depends on architectural choices that look innocent until you measure them.

Three concrete traps worth naming:

  • →TTL asymmetry is real. Anthropic's default TTL is 5 minutes, OpenAI's 1 hour, Google's in between. If your traffic is bursty with 10+ minute quiet periods, Anthropic's cache will evaporate between bursts and your "savings" will quietly vanish. Anthropic's prompt caching docs now offer 1-hour cache tiers at a premium — worth the math for quiet-but-steady workloads.
  • →Cache boundaries must match change frequency. If you shuffle RAG chunks into a different order between requests, the cache breaks. Sort retrieved chunks by a stable key (document ID) before concatenating; this single change has single-handedly saved teams five-figure monthly bills.
  • →Dynamic system prompts are a silent cache killer. Injecting the current timestamp or a user ID into the system prompt seems harmless. It invalidates the cache on every request. Move anything dynamic to the end of your prompt, always.

On the MCP side, the official Model Context Protocol spec is short and readable; if you're still writing bespoke function schemas per vendor in 2026, you're building tech debt. The MCP announcement from Anthropic is worth five minutes to understand why this standard won the race.

Prompt Caching: Stop Paying Twice for the Same Tokens

Every API call sends your system prompt + RAG context + conversation history. If your system prompt is 2,000 tokens and stays the same across all queries, you are paying for those 2,000 tokens every single time. Prompt caching tells the API: "I already sent this prefix, just reuse it."

How Prompt Caching Works

From repeated payment to cached efficiency

Without Caching

Every request sends the full context. For a 10,000-token context window where 8,000 tokens are static (system prompt + knowledge base), you pay for 8,000 repeated tokens on every query.
code
Request 1: [8000 static tokens] + [2000 dynamic tokens] = 10,000 tokens billed
Request 2: [8000 static tokens] + [2000 dynamic tokens] = 10,000 tokens billed
Request 3: [8000 static tokens] + [2000 dynamic tokens] = 10,000 tokens billed

Total: 30,000 tokens billed for 6,000 tokens of unique content

💡 80% of your token spend is WASTED on resending identical content.

1/4
Quick Check

What is the best way to maximize cache hit rates?

MCP: The Model Context Protocol

Before vs After MCP

AspectBefore MCPWith MCP
Tool IntegrationCustom code for every tool and every modelStandard protocol: write once, works with all models
Adding a New ToolDays of custom developmentHours: implement the MCP server spec
Switching ModelsRewrite all tool integrationsJust point MCP at the new model
Tool DiscoveryHardcoded tool listsDynamic: model discovers available tools at runtime
SecurityAd hoc per integrationStandardized auth, permissions, and scoping

← Scroll horizontally →

MCP Architecture

How the protocol connects models to tools

MCP Server

Each tool or data source runs an MCP server that describes its capabilities: what tools it offers, what parameters they accept, and what they return.
code
MCP Server: 'Weather Service'
Tools:
  - get_weather(city, units)
  - get_forecast(city, days)
Resources:
  - weather://cities -> list of supported cities
  - weather://alerts -> active weather alerts

💡 An MCP server is a standardized wrapper around any API or data source.

1/4
Loading diagram…

Production Optimization Checklist

Click to expand
Click to expand

Test Your Understanding

Question 1 of 5.

Prompt Caching & MCP Knowledge Check

0 / 5 answered

Q1.How much can prompt caching reduce API costs?

5 questions remaining

Congratulations!

You have completed Module 9 and the entire advanced AI curriculum. You now understand:

  • →Context engineering, designing the information environment for AI
  • →Lost-in-the-middle, position effects and optimization
  • →Production optimization, caching, MCP, and cost management

These are the skills that separate prompt hobbyists from production AI engineers.


Return to the Module 9 overview to review your progress and explore next steps.

Your progress

Progress is self-reported and stored in your browser. The final completion record is not a qualification or an independent assessment.

View progress and completion record

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed
Go deeper — free guide

Introduction to Generative AI

One practical AI workflow in your inbox

Methods, resources and new exercises. Free, unsubscribe at any time.