SkillHack

How to become a Context Engineer

Step by step and free: 12 phases, 85 topics and 279 graded practice questions.

Practise this roadmap free

What is a Context Engineer?

A context engineer decides what a language model sees on each request and in what order: instructions, retrieved passages, tool definitions and results, conversation history and memory. They set token budgets, rank and trim candidates, compact long sessions, lay out prompts for cache hits, and measure whether the context, not just the answer, was good. They work alongside AI engineers, agent builders and the owners of the data sources.

Who this roadmap is for

AI engineers and developers who have already shipped an LLM feature or agent and watched it fail on long conversations, noisy retrieval or a rising token bill. You should be able to call a model API and write the code that assembles a prompt. It is not a beginner's guide to prompting, nor to training models.

What you will be able to do

You will be able to assemble context as tested code, budget and select what enters the window, decide when to retrieve or call tools, compress history without losing what matters, design long-term memory, raise cache hit rates, measure context quality with ablations, and defend context against injection, poisoning and data leaks.

The Context Engineer roadmap

Context Engineer

  1. Phase 1 Foundations: how models read context

  2. Phase 2 Assembling the context

  3. Phase 3 Budgets and selection

  4. Phase 4 Retrieval as a context source

  5. Phase 5 Tools and their results as context

  6. Phase 6 History, compression and compaction

  7. Phase 7 Memory and state

  8. Phase 8 Caching, cost and latency

  9. Phase 9 Measuring context quality

  10. Phase 10 Context in production

  11. Phase 11 Security and privacy of context

  12. Phase 12 Advanced context systems

All topics, in order

Mark each topic Learning, Done or Skip, and sign in to save your place to your account. Done is your own word, not passing: a topic is passed when you score 50 or more on its questions. This order is the study plan.

  1. Phase 1 · Foundations: how models read context

    1. What a context engineer does

      A context engineer decides what the model sees on every call: which instructions, tools, documents, memories, records and history go into the window, in what order, within what budget, and how anyone can tell it worked. A prompt engineer polishes the wording and a retrieval engineer builds the search index; you own the assembly that sits between them and the model. You are judged on answers that were right because the model had what it needed, at a cost the product can carry.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    2. The parts of a context window

      Every call's window is built from the same parts: system instructions, tool definitions, examples, retrieved knowledge, memories and profile, records from other systems, the conversation so far, tool results and the new user turn, with room left for the reply. Each part has a different owner, change rate and level of trust, and those decide where it sits and whether it can be cached. Start any design by listing the parts with their token cost and source before writing a line of prompt.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    3. Context windows and tokens

      The context window is one token budget shared by everything in the request and by the reply the model writes, reasoning tokens included. A request whose input alone is over the limit is rejected, and a reply that runs out of room is cut off mid-answer, so plan the space before you fill it: measure the assembled input, reserve enough for the longest answer you expect, and treat the advertised window as a ceiling rather than a target.

      Reading

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    4. Counting tokens before you send

      Tokens are pieces of words, and each model family splits text its own way, so the same paragraph can cost noticeably more on one model than another. Many non-English languages, code, and long numbers cost more tokens per character than English prose. Never budget from character counts: count with the provider's token counting endpoint or the model's own tokenizer, and count the fully assembled request, with tool definitions and images included.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. How a model reads a prompt: prefill and the KV cache

      Before writing a word, the model processes your whole input in one pass called prefill, storing keys and values for every token in a KV cache, then generates the reply one token at a time while reading that cache. Prefill work grows with input length, which is why long prompts are slow to start. Each token's stored state depends on every token before it, so reuse only works for an identical prefix: change one early token and everything after it is recomputed.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Effective context length

      A model that accepts a million tokens does not use a million tokens equally well. Simple needle tests, where one odd sentence hides in filler, overstate long-context ability; tests that need reasoning across the text, or where the needle shares no words with the question, show accuracy falling well before the limit. Find the length at which your own task still works, and design to stay under it rather than near the advertised window.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. What earns a place in context

      More text is not more information. Every block you add competes for the model's attention, adds cost and latency, and can pull the answer toward something that merely looks related. Put each candidate block to three tests: would the model do worse on this task without it, is this the most compact form of that information, and is it current. Include what passes, and keep the rest one lookup away instead of in the window just in case.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    8. Testable instructions

      Standing instructions apply to every call, so each one should be a rule someone could check in the output: the exact fields to return, what to do when a value is missing, what to leave out, when to decline. Adjectives such as accurate or concise give the model no target and give you nothing to test. If a reviewer cannot mark a rule pass or fail on a sample answer, rewrite it until they can, or drop it.

      Reading

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    9. Instruction sources and precedence

      Instructions reach the model from several places: the system or developer prompt, the user, saved memories, retrieved documents and tool results. Models are trained to rank them, with developer rules above the user and text found inside data treated as information rather than commands, but that ranking is a tendency, not a guarantee. Decide your own precedence, state it in the system prompt, and resolve conflicts you can foresee before assembly instead of leaving the model to sort them out.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions

    Chapter 1 lab

    Rewrite an instruction set whose rules contradict each other

    A prompt lab that closes the chapter: you write the instruction, and it is graded on a rubric.

    Start the lab
  2. Phase 2 · Assembling the context

    1. Prompt layout: stable first, variable last

      Lay out every request by how often each part changes: tool definitions and the system prompt first, then reference material shared by many users, then per-user context, then the conversation, and the new request last. That gives the model a predictable structure and lets prompt caching reuse the long unchanging head on every call. One volatile value near the top, such as a timestamp or request id, moves the cache boundary up to it, and you pay full price for everything after.

      Reading

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Ordering and position in long inputs

      Models recall material at the start and end of a long input more reliably than in the middle, so position is part of the design. Put long documents above the question rather than after it, sort retrieved passages by relevance rather than by date or file name, with the strongest at the edges, and restate the task after a long block of material. When an extraction misses items from the middle of a long transcript, split the input before rewriting the instruction.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    3. Delimiters and sections

      Wrap each part of the context in a clearly named section, for instance tags for instructions, documents, memory and the user's message, so the model can tell rules from material and you can refer to a section by name. Label every section, not only the risky one, and choose markers that cannot occur in the content, escaping them if they might. Delimiters help the model treat pasted text as data, but they are a first layer against injection, not a defence on their own.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    4. Rendering data for the model

      The same records can go in as JSON, a markdown table, YAML, CSV or sentences, and the choice changes token cost and accuracy. JSON repeats every key on every row; a table names each column once but loses nesting. Use readable field names instead of internal codes, give units and stable ids the model can cite, drop fields the task never reads, and test two formats on your own task, because format effects are real and differ between models.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Context assembly as code

      Treat the code that builds the context as a product component: one builder with named, typed slots for each part, a fixed order, a token limit and escaping per slot, rather than strings glued together across a dozen handlers. The same inputs should always produce byte-identical output, which keeps the cache warm and makes failures reproducible. Snapshot test the rendered context for representative cases, so a refactor that silently drops a section shows up in review.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Choosing examples at request time

      When no fixed set of examples covers every kind of input, keep a pool of vetted examples and retrieve the few most similar to the current request. Similar examples usually help more than random ones, but pure similarity can return near-copies that all carry the same label, so balance labels and add variety. Cap their tokens and log which ids were chosen. The model copies the format and details of examples, so vet the pool as carefully as the instructions.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Ambient facts: date, user and environment

      A model has no clock and knows nothing about the person or system it serves unless you say so, which is why assistants confidently use last year's date. Give each call the small facts it depends on: today's date and timezone, the user's role, locale and plan, and the product or environment it runs in. Put them after the cached prefix, and round values such as the time to the precision the task needs, so they do not change on every call.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions

    Chapter 2 lab

    Write the stable head of a multi-tenant support agent prompt

    A prompt lab that closes the chapter: you write the instruction, and it is graded on a rubric.

    Start the lab
  3. Phase 3 · Budgets and selection

    1. Context budgets

      When history, retrieval, tool results and memory compete for one window, decide in advance how much each may take. Give each component a cap sized by its value to the task, give the parts the task cannot do without (the instructions, the user's request and the reserved reply) a floor nothing can take, and define the order in which components are trimmed when the total runs over. A budget written as code is enforceable; a budget that lives in a prompt is a wish.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Measuring what fills the window

      You cannot budget what you do not measure. Count the tokens of each component as you assemble it, log the counts with the request, and reconcile the total with the usage the API returns, which also splits cached from uncached input. Chart each component's share across real traffic: it usually shows one source, often tool definitions, history or a verbose tool result, eating the window, and that is where the first fix goes.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    3. Ranking candidates for inclusion

      Most calls have more candidate context than room: passages, memories, earlier turns, records. Give every candidate a score, from a reranker, a similarity threshold, recency or a rule, then fill the budget from the top and stop when it is full or scores fall below a floor. Cutting by tokens and score beats a fixed top five, which sends five weak passages when only one is relevant, and drops the sixth when it was the one that mattered.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Removing duplicates and near-duplicates

      Retrieval over real corpora returns the same paragraph from three copies of a policy, memory stores collect one fact in five phrasings, and agents fetch the same record twice. Duplicates waste budget and, worse, tell the model one source matters more than it does. Drop exact copies by hash, collapse near-duplicates by similarity keeping the newest or most authoritative copy, and when picking several passages prefer ones that add something new, as maximal marginal relevance does.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Preload or fetch on demand

      Every piece of context is either loaded before the call or left for the model to fetch with a tool. Preloading is fast and reliable but spends tokens on every call whether they are needed or not; fetching keeps the window lean but costs extra round trips and fails when the model does not think to look. Preload what nearly every request needs or would be costly to miss, leave a short pointer such as a path or record id for the rest, and check traces for misses.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Progressive disclosure

      Progressive disclosure gives the model a short index first and the detail only when a task calls for it: a skill's name and one line description until it is needed, a tool catalog it searches instead of every schema, a document outline before the sections. One system can then carry far more than fits in a window. The index entries do the work, so write each so the model can tell from it alone when to open the full item.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Long context or retrieval

      With large windows you can often skip retrieval and send the whole document. That is simplest when the source fits comfortably, is asked about many times so it can be cached, or the task needs all of it, such as a summary. Retrieval wins when the corpus is bigger than the window, when most of it is irrelevant to each question, or when cost and latency per call matter. Many systems route: retrieve first, and fall back to the full document when the passages are not enough.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
  4. Phase 4 · Retrieval as a context source

    1. Retrieval into context

      Retrieval puts passages the model was never trained on into the window so it can answer from them, but what helps is the passage plus its label. Give each one its source, title, section and date, and a line on where it sits in its document, so near-duplicate passages from different products or versions can be told apart. Tell the model to answer only from what was retrieved, and to say so when the passages are on topic but do not hold the answer.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Deciding when to retrieve

      Retrieving on every turn is simple, but a greeting or a follow-up about the last answer gains nothing from a search and can be distracted by its results. Retrieve on a condition, such as a rule or small classifier that spots knowledge questions, or give the model search as a tool and let it decide, which handles multi-step questions but can skip a search it needed. Whichever you choose, log when retrieval ran and grade the turns where it did not.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    3. Turning a conversation into a search query

      Follow-ups such as and the annual plan, or what about the other one, mean nothing to a search index on their own. Before retrieving, rewrite the latest turn into a standalone query using the conversation so far, filling in the product, entity or period it refers to, and keep the user's original words for the answer step. A small, fast model is usually enough for the rewrite. Log both versions, so a bad retrieval can be traced back to the query.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Expanding hits into usable passages

      Small chunks match queries precisely, but a matched sentence often depends on what surrounds it: the condition before it, the table it belongs to, the heading that says which product it covers. Retrieve small, then expand before inserting: add neighbouring chunks or swap in the parent section, and prefix the document title and heading path. Expansion costs tokens, so expand only the top few hits and merge overlapping windows rather than repeating text.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Records and query results as context

      Much business context is not prose but records: a customer row from the CRM, an order from an API, the rows a SQL query returned. Select only the fields the task needs, rename cryptic columns, state units and currencies, translate codes into their meanings, and say when the data was fetched. Cap row counts and say how many were left out, because a model shown twenty rows of three thousand will happily describe them as the whole picture.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Conflicting and outdated sources

      Retrieved context often disagrees with itself: last year's price list beside this year's, a draft policy beside the approved one, a forum post beside the official guide. Left to choose, a model tends to follow whichever passage is most fluent, most repeated or closest to the question. Label every source with its date, version and authority, filter superseded documents out before assembly where you can, and give a rule for the rest, such as the newest approved source wins, with an instruction to mention the conflict.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Writing sources that models read well

      Much context comes from documents your organisation controls, so writing them for retrieval pays off on every call. Make each section stand on its own: name the product and version in it, define terms where they are used, avoid references like see above, and put the answer before the background. Publish clean text versions of key pages and an llms.txt index of what exists. Then test it: ask real questions against the docs and fix the sections that retrieval misses or the model misreads.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
  5. Phase 5 · Tools and their results as context

    1. Tool definitions are context

      Every tool you offer is sent as a name, description and input schema on every call, so a large tool set can spend thousands of tokens before the user has said anything. The descriptions are also instructions: they are how the model decides which tool fits, and vague or overlapping ones produce wrong calls. Keep the set as small as the task allows, say in each description when to use the tool and when not to, and measure what your definitions cost.

      Reading

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Choosing the tool set per request

      As catalogs grow, tool choice gets worse: as of November 2026 Anthropic's tool search docs report selection degrading past roughly 30 to 50 tools. Offer a per-request loadout instead, chosen by task type or found by a tool search step. Changing the tool list mid-conversation changes the cached prefix and can leave history pointing at tools that are gone, so some teams keep the list fixed and restrict which tools may be chosen at decoding time instead.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    3. Transforming payloads before they enter context

      Raw API responses are written for programs: nested objects, null fields, internal ids, millisecond timestamps, pagination metadata. Put a transform between the tool and the window that keeps only the fields the model uses, flattens nesting, turns codes into words, and keeps the stable ids the model may need to cite or pass to its next call. Offer a short and a detailed form when both are useful, and keep the raw payload in storage behind an id so nothing is lost.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Keeping errors and failed attempts visible

      It is tempting to hide a failed tool call and retry quietly, but a model that cannot see what went wrong tends to do it again. Leave the failed call and a clear error in the context, one that says what was wrong and what would work, so the next attempt changes course. Collapse repeats, though: after the third identical failure keep one entry with a count, or the history fills with the same message and pulls the model into a loop.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. MCP resources, prompts and tools as context

      The Model Context Protocol gives a server three ways into the window. Tools are chosen and called by the model; resources are data such as files, schemas or records that the host application decides to include; prompts are templates the user picks. Who chooses matters: a resource the app attaches costs tokens on every call that carries it, while a tool costs only its definition until it is called. Resources can carry priority and audience hints that help the host decide what to include.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Web pages and files as context

      A fetched web page is mostly navigation, scripts, cookie banners and adverts; sent raw, it wastes tokens and buries the article. Extract the main content first, convert it to plain text or markdown that keeps headings, lists and tables, and attach the URL, title and fetch date. Do the same for office files and PDFs. Anything fetched from outside is untrusted, so it belongs in a labelled data section, never beside your instructions.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Images, PDFs and audio in context

      Images, PDF pages and audio are turned into tokens too, and their cost grows with resolution and length, so a scanned forty-page contract sent as page images can cost far more than the same contract as extracted text. Resize images to the detail the task needs, send only the relevant pages, and prefer extracted text when layout does not matter. Check each provider's media limits and token rules in its docs, and place each image next to the text that refers to it.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
  6. Phase 6 · History, compression and compaction

    1. Managing conversation history

      Resending the whole conversation each turn is simplest and keeps every detail, until sessions grow slow, expensive or longer than the window. A sliding window keeps the last few turns but silently forgets early facts such as a constraint the user set at the start. The usual production answer is a summary of older turns plus recent turns verbatim, with key facts pinned in session state. Choose by how long your sessions really run, and test what a long session still remembers.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Compaction and summarization

      Compaction replaces older turns with a summary so a long session can continue past the window. Summaries are lossy, so the policy decides what survives: keep identifiers, numbers, decisions and their reasons, commitments made to the user and open tasks verbatim, condense the narrative around them, and leave the latest turns untouched. Trigger it at a set share of the window rather than at overflow. Providers now offer it server-side, but you still own what it must keep.

      Test yourself on this topic

      5 graded questions · scored out of 100 with feedback · free

      Start the 5 questions
    3. Clearing stale content

      Some content is dead weight once used: a tool result the model has already acted on, reasoning from an earlier turn, a document read for a finished subtask. Clearing swaps it for a short placeholder and keeps the record that the call happened, so the model does not repeat it. Because clearing edits earlier context, it invalidates the cache from that point on: clear in batches when a threshold is crossed rather than a little every turn, and never clear what the model saved to memory.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Token-level prompt compression

      Prompt compression uses a small model to drop the tokens that carry least information, shrinking long text several times over while keeping most of its meaning. It suits long, redundant material such as transcripts or retrieved background. It is a poor fit where exact wording matters: names, numbers, code, legal clauses and anything the model must quote. Compressed text also differs for every input, so it cannot sit in a cached prefix. Measure task accuracy before and after, not just the ratio.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Summarising long sources ahead of time

      Some questions need the gist of a large body of text, such as what a long report concludes, and neither a single retrieved chunk nor the full report serves them well. Build summaries before the request arrives: one per document or section, or a tree of summaries over clusters of chunks, stored beside the originals. Retrieve a summary for broad questions and original passages for specific ones, and regenerate summaries when their sources change, or they quietly go out of date.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Extract, then answer

      For a question over a long document, asking the model first to copy out the passages that bear on it, word for word, and only then to answer from those quotes often beats answering in one step. Extraction narrows attention to what matters, and the quotes give you something to check: a claim with no quote behind it did not come from the document. Do both steps in one call with labelled sections, or in two calls when the document is very long.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Testing that compression kept what matters

      Every summary, compaction or compression step is a place where facts can vanish, and the answer that suffers may come many turns later. Test it directly: take real long sessions, list the facts later steps will need (ids, decisions, constraints, open tasks), compress, then ask probe questions or run the next step and check those facts survived. Track which kinds of fact get lost most, and name them in the summary instructions as things to keep verbatim.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions

    Chapter 6 lab

    Write the compaction prompt for a long-running support session

    A prompt lab that closes the chapter: you write the instruction, and it is graded on a rubric.

    Start the lab
  7. Phase 7 · Memory and state

    1. Session state

      A multi-turn task needs a structured record of what it has gathered so far: the slots filled, the choices made, the step it is on. Keep it outside the transcript, update it by explicit rules after each turn, and render it into the prompt every turn, so facts do not scatter across forty messages and the assistant stops asking for details it was already given. When state and transcript disagree, the user's latest word wins and the state is corrected to match.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Recitation: keeping the goal in view

      In a long task the original goal ends up thousands of tokens back, in the part of the context the model attends to least. Recitation fixes this cheaply: have the model rewrite a short list of the goal, constraints and open items at the end of the context as it works, or append one yourself each turn, so the goal sits where attention is strongest. Keep it short and current, because a stale list recited every turn misleads as strongly as a fresh one helps.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    3. Long-term memory

      Long-term memory carries facts across sessions that may be weeks apart: preferences, past decisions, corrections. The window cannot hold an ever-growing archive, so memories live in a store outside the model and only the few that bear on the current task are read back into the prompt. Treat the window as working memory and the store as the record: write selectively, read selectively, and let users see and remove what is kept.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    4. Key-value or vector memory

      Match the memory store to how a fact will be found again. Exact facts looked up by a known key, such as a timezone, plan tier or account id, belong in a key-value store or database row, where a read returns exactly that value. Free-text notes recalled by meaning belong in a vector index, which returns the nearest matches, not guarantees. Many systems need both, and fields that change should not be embedded in vectors, where updates are slow and easy to miss.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    5. Bringing memories into the prompt

      Recall is a context decision: which memories, how many, when, and in what form. Retrieve by relevance to the current request, weighted by recency and importance, cap the count, and load stable facts once at session start instead of searching every turn. Render each memory as a dated, sourced statement in its own labelled section, for example that the user said in March they prefer metric units, so the model can weigh an old or second-hand memory and never mistakes one for an instruction.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    6. Consolidating and expiring memories

      A memory store that only grows becomes a source of contradictions: the old address beside the new one, a preference the user has since reversed, three phrasings of one fact. Consolidate on write or in a background pass: compare each new memory with similar existing ones, then add, update, merge, or mark the old one superseded. Give time-bound facts an expiry, keep a date and source on every memory, and prefer the newest when two still disagree.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. User profiles as standing context

      Some facts about a user matter on almost every call: role, language, units, expertise, standing preferences. Rather than searching memory for them each turn, keep a small structured profile updated by a background process, and render it as one compact block at the start of the per-user part of the context, where it changes rarely and caches well. Cap its size, keep it factual, show users what it says, and leave one-off or sensitive details to retrieved memories or out entirely.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions

    Chapter 7 lab

    Write the instruction for the session state update step

    A prompt lab that closes the chapter: you write the instruction, and it is graded on a rubric.

    Start the lab
  8. Phase 8 · Caching, cost and latency

    1. Cost and latency of context

      Context drives both the bill and the wait. Most production calls send far more input than they get back, so input tokens usually dominate cost, and the time before the first output token grows with input length. The biggest levers sit in the context itself: send less, keep the large stable part identical so it can be cached, and control growth per turn. Judge a change by cost per completed task, not per call, because a cut that causes extra turns can cost more overall.

      Reading

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. How prompt caching works

      Prompt caching stores the processed state of a request's prefix, so a later request that starts with exactly the same tokens skips that work, pays a reduced rate for it and starts faster. Matching is exact from the first token, in a fixed order (for Anthropic: tools, system, then messages). As of November 2026 Anthropic's cache lasts five minutes by default, refreshed on each hit, with an hour option, and OpenAI caches long prefixes automatically. Writes can cost more than plain input, so caching pays only on reuse.

      Reading

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    3. Designing contexts for cache hits

      Cache hits come from discipline more than settings. Keep the prefix byte-identical across calls: no timestamps, request ids or shuffled examples near the top, and JSON serialised with a fixed key order. Treat history as append-only instead of editing earlier turns, add per-user and per-turn content after the shared part, and avoid changing the tool list mid-session. Place cache breakpoints at the boundaries between parts that change at different rates.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Measuring cache hit rate and cost per task

      Responses report how many input tokens were read from cache, written to it, or processed fresh, so hit rate is something you measure rather than assume. Track the cached share of input per endpoint and per prompt version, alert when it drops (usually something volatile has crept into the prefix), and roll usage up into cost per finished task. Manus reports an input to output ratio near 100 to 1 for its agent, and calls cache hit rate its most important production metric.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Prefill latency and time to first token

      Time to first token is mostly prefill, and prefill grows with the uncached part of the input, so a long context makes people wait before anything appears. Send less, cache the stable prefix so only the new part is processed, and stream the reply so progress shows. Run slow lookups such as retrieval and memory recall in parallel rather than one after another, and budget the whole pipeline, since time spent assembling context before the call counts as much as the model's.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Prefix caching on self-hosted models

      When you serve open-weight models yourself, prefix reuse is your job. Serving engines such as vLLM and SGLang can keep the KV cache of earlier requests and reuse it when a new request starts with the same tokens, which pays off most for long shared system prompts and multi-turn chat. Reuse happens only on the server holding that cache, so route requests that share a prefix, such as one tenant or one conversation, to the same replica, and leave GPU memory for the cache.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Cheap models for context preparation

      Much of building a context is simple judgement at volume: rewriting a query, scoring passages, summarising a tool result, adding document context to a chunk, picking which memories apply. A small, fast model can do this for a fraction of the main model's cost and keep the expensive call's context lean. Evaluate each preparation step on its own, since its mistakes are invisible to the main model, and keep the small model's output in the trace.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
  9. Phase 9 · Measuring context quality

    1. Evaluating the context, not just the answer

      An answer-only eval tells you something failed, not where. Grade the assembled context as well: for each test case, write down what the model needed to see, then check whether that material was present, intact, labelled and placed where it would be read. Keep the rendered context with every eval result, so a failing case can be sorted into missing context, misleading context or a model error, and each change to assembly is judged by which bucket it shrinks.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Sufficient context and abstaining

      Some wrong answers happen because the answer was never in the context; others because it was there and the model missed it. Label your eval cases by whether the assembled context was sufficient to answer, using a grader model or a reviewer, and score the two groups separately. On insufficient cases the right behaviour is to say so or ask, and research on retrieval systems finds models often answer confidently anyway, so test and reward abstaining explicitly.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    3. Ablation: what each block is worth

      Context accumulates blocks that someone once thought would help and nobody has checked since. Ablation answers the question: run the same eval set with one block removed or replaced, the memory section, the examples, the third retrieved passage, and compare scores, cost and latency with the full version. A block whose removal changes nothing is paying rent for no reason; a block whose removal helps is actively distracting. Repeat runs, since small differences can be noise.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Context precision and recall

      Two numbers describe what retrieval handed the model. Context precision asks how much of what was included was relevant, and whether the relevant pieces ranked near the top; context recall asks how much of what the reference answer needed actually arrived. Low recall means the answer cannot be right; low precision means it is buried in noise. Measure both on a labelled set, and check any judge that scores them against human labels first.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Long-context tests on your own data

      Public long-context scores say little about your documents and questions. Build your own: take real material at the lengths you send in production, plant facts the task needs at different depths, including ones phrased unlike the question and ones surrounded by plausible distractors, and measure accuracy by position and total length. The result tells you how much context your model really handles for this task, and where in the window to put what matters.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Regression tests for context changes

      A change to assembly code, a template, a retrieval setting or a memory rule changes what the model sees on every call, so treat it like a code change with tests. Keep a set of golden cases with their expected outputs and run it in CI on every change, together with a diff of the rendered context and its token count per case. Many regressions show up first as a section that vanished or a context that doubled in size, before any answer changes.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Production signals of context problems

      Live traffic shows context failures before anyone files a bug. Watch for users repeating details they already gave, correcting the assistant, rephrasing the same question, or abandoning a session; and watch system signals such as overflow errors, compaction frequency, truncated replies and falling cache hit rate. Sample the sessions behind each spike, read their full contexts, and turn what you find into new eval cases.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
  10. Phase 10 · Context in production

    1. Context observability

      You can only debug context you can see. Logging prompts and outputs is not enough when the question is whether retrieval missed, the wrong memory loaded or compaction dropped a fact. For each call, record the rendered context or a way to rebuild it exactly, plus its provenance: template version, retrieved chunk ids and scores, memories injected, summaries used, token counts per section and cache usage. Redact sensitive fields before storage, so traces stay useful without becoming a data leak.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    2. Debugging a bad answer from its context

      When an answer is wrong, open the context the model actually received before touching the instructions, and ask four questions in order. Was the needed fact absent? Was it present but buried in the middle or among distractors? Was it contradicted by another source or an old memory? Or was it clearly there and the model ignored it? Each has a different fix: retrieval or assembly, ordering and trimming, conflict rules, or the instruction and the model.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    3. Context rot and drift

      Staying inside the window is not the same as having a clean context. As a session grows, stale tool output, abandoned plans and superseded facts pile up and dilute attention, and the model starts contradicting earlier decisions, repeating work and losing the goal. A bigger window or a lower temperature does not fix it. Reset instead: compact to a focused working state that keeps the goal, key decisions and open tasks, or start a fresh context from a written summary.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    4. Context poisoning

      Context poisoning happens when a wrong statement, a hallucinated fact, a misread tool result or a guess, gets written into the context and is then treated as established, so every later step builds on it. It spreads through summaries, session state and memory, which repeat it with growing confidence. Mark what was verified and what was assumed, keep sources attached to facts, check high-stakes facts again before acting on them, and when a poisoned fact is found, remove it everywhere it was copied.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Degrading gracefully when a source fails

      Context sources fail: the retrieval service times out, the memory store is down, a tool returns an error. Decide per source whether the call can go ahead without it, then assemble with what you have and tell the model what is missing, such as a note that order history was unavailable this turn, so it does not answer as if the data showed nothing. Set timeouts per source so one slow lookup cannot hold the whole request, and alert on degraded calls.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Versioning context configurations

      What the model sees depends on more than the prompt text: templates, retrieval settings such as top k and filters, memory rules, compaction thresholds, the tool set and the model itself. Version them together as one configuration, record that version on every trace, and roll changes out behind a flag or to a slice of traffic with the eval set as the gate. When quality drops, you can then name the exact change and roll it back in one step.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Moving a context to a new model

      A context tuned for one model is not automatically right for the next. A new model may count tokens differently, have a different window and cache minimum, follow instructions more literally, or weigh position differently, so a layout that worked can underperform. Before switching, rerun the eval set and the long-context tests, recheck token budgets with the new tokenizer, read the provider's migration notes, and adjust the context, not just the model id.

      Reading

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions

    Chapter 10 lab

    Write the instruction for handling conflicting facts in context

    A prompt lab that closes the chapter: you write the instruction, and it is graded on a rubric.

    Start the lab
  11. Phase 11 · Security and privacy of context

    1. Provenance and trust labels

      Everything in the window came from somewhere: your own instructions, a verified database, the user, a public web page, another agent. Attach that origin to each block as metadata the model can see, and group blocks into trust levels, so the system prompt can say plainly that only the instruction section gives orders and everything else is material. Provenance also lets your code apply rules the model cannot be trusted to apply, such as never acting on a web page alone.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    2. Indirect prompt injection through context

      Any text you put in the window can try to give orders: a retrieved page, an email being summarised, a tool result, a file. Labelling and marking untrusted text, for example by interleaving a marker through it, reduce the success of such attacks but do not stop them. The defences that hold are structural: process untrusted content in a call that has no tools or private data, and never let one context combine private data, untrusted input and a way to send data out.

      Test yourself on this topic

      4 graded questions · scored out of 100 with feedback · free

      Start the 4 questions
    3. Permission-aware assembly

      Once a document is in the window, the model can repeat it to whoever is asking, so access control has to happen before assembly, not in the prompt. Filter retrieval, memory and records by the requesting user's permissions in the query itself, carry the source system's access rules into your index, and recheck them at read time, since access changes. Test it with users who should see nothing, because a leak shows up as a correct-looking answer.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. Minimising personal data in context

      Every personal detail in the window is sent to a model provider, may be logged in traces and can surface in output, so send only what the task needs. Drop fields the task does not read, replace names and identifiers with placeholders the model can still refer to and swap them back afterwards, and run detection on free text such as tickets and transcripts. Data minimisation is a legal principle in the GDPR, not only good hygiene.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Secrets never belong in context

      Treat everything in the window as something the model might repeat, because with the right prompt it often will. API keys, passwords, connection strings and internal URLs that grant access stay in your code and tool layer, where the tool uses them without the model ever seeing them. The system prompt is not a vault either: assume it can be extracted, keep nothing in it whose disclosure would hurt, and enforce rules in code rather than by hiding them.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. Isolation in shared caches and memory

      Shared infrastructure can leak across users. Researchers in 2025 detected prompt caches shared across users at several API providers by timing responses, which can reveal that someone else sent a given prefix. Keep tenant-specific content out of prefixes shared across tenants, use separate cache keys or scopes where the provider offers them, and scope every memory and index query to its owner in the database query, never by asking the model to ignore other people's data.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    7. Memory poisoning

      An injection that reaches long-term memory outlives the session: a malicious page persuades the assistant to save a false preference or instruction, and every later session loads it as trusted context. Treat memory writes as a privileged action. Do not let content from untrusted sources write memories directly, store the source of each memory, show users what was saved, and scan memories for instruction-like text before injecting them.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
  12. Phase 12 · Advanced context systems

    1. Isolating context with sub-agents

      A sub-agent starts with a clean window, so it can read widely on one narrow job and return a short result, keeping the main context lean. The price is tokens and lost shared detail: Anthropic reports its multi-agent research system using about 15 times the tokens of a chat. Isolate work that splits into independent parts, give each sub-agent a complete brief since it cannot see the parent's history, and keep tightly linked work in one context.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    2. Context for coding assistants

      A repository is far bigger than any window, so a coding assistant lives on context selection. Common tools are a compact map of files and their key symbols, search by name or text, and reading only the files a change touches plus their direct dependencies. Project instruction files supply the conventions code cannot show. Many agents now search the repository live rather than relying on an embedding index, trading extra steps for results that are always current.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    3. Context for data and SQL agents

      A model writing SQL fails most often for lack of context, not syntax: it does not know which table is authoritative, what a status code means, how revenue is defined or which rows are test data. Give it a curated description of the tables it may use, column meanings, sample values, join paths and approved metric definitions, ideally from a semantic layer, and only the part relevant to the question. Keep the definitions owned and versioned, because a wrong one is wrong on every query.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    4. An organisation's shared context layer

      When every team builds its own assistant, each one restates company policies, product facts and terminology slightly differently. A shared context layer gives them one owned source: a glossary, policy snippets, product and customer facts, and data definitions, each with an owner and a review date, served to every agent through retrieval or MCP servers. The work is as much curation as engineering: keeping it current, removing contradictions and knowing who to ask.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    5. Contexts that learn from feedback

      Instead of a fixed system prompt, some systems keep a playbook of strategies and pitfalls that grows from experience: after each task, a reflection step proposes lessons and a curation step adds, edits or removes individual entries. Updating entry by entry matters, because asking a model to rewrite the whole playbook each time tends to shrink it into a vague summary and lose what was learned. Review what gets added, since a bad lesson spreads like any poisoned context.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions
    6. When context is the wrong lever

      Context is the fastest lever to pull, but not always the right one. If you send the same long block of style rules or domain knowledge on every call and the model still drifts, fine-tuning may teach it more cheaply. If the model must compute or look something up exactly, a tool beats text. If users keep asking for something the product cannot do, no context fixes that. Knowledge that changes often stays in context or retrieval, since fine-tuned facts go stale.

      Test yourself on this topic

      3 graded questions · scored out of 100 with feedback · free

      Start the 3 questions

Practise the Context Engineer roadmap

279 questions, each graded on the server out of 100. Free · no card.

All career paths