LevelUpWith

Explore / AI Engineering

Context Engineering and Memory for LLM Agents

Decide what goes into an agent's context window, build hybrid retrieval and code indexes, compact long sessions and design memory that stays lean, then prove with evals that you cut tokens with no loss in quality.

Read lesson 1 free →

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor.

Photographic 3D course artwork for Context Engineering and Memory for LLM Agents

Expert · 42 levels · 4 free · Created Nov 2026 · Professionally curated by levelupwith.com

What's inside

  1. Level 1: Tokens: What the Model Actually ReadsFree
    Learn how text, code and JSON become tokens, why each provider's tokenizer counts the same input differently, and why the context window is a limited budget and not free space.
    • Count tokens for the same prompt with the token-counting tools or endpoints of Claude, OpenAI, Gemini and an open-weight model, in Python or TypeScript
    • Explain why code, JSON and non-English text use tokens at different rates than prose
    • Tell the difference between a model's maximum context size and the amount of context it handles well
  2. Level 2: Anatomy of an Agent RequestFree
    Take apart a real agent call into its parts (system prompt, tool definitions, conversation history, tool results and the user turn) and log how many tokens each part uses.
    • Wrap an agent's model client so that every request records a per-part token ledger
    • Find which parts of a coding agent's context grow with each turn and which stay fixed
    • Read the usage fields that each provider returns and match them against your own counts
  3. Level 3: Input Tokens Drive Cost and Latency
    Work out why agent loops spend mostly on input tokens: the full history is sent again on every turn, so cost and time-to-first-token grow with each step.
    • Model the total input tokens of an N-turn agent loop in code and compare it with measured usage
    • Turn a token ledger into dollar cost and latency estimates using current published prices
    • Pick out which turns of a recorded session caused most of its cost
  4. Level 4: Context Rot: Quality Falls with Clutter
    Build a small harness that adds more and more irrelevant or near-miss material around a task, and measure how answer quality drops as the context fills up.
    • Write a Python or TypeScript harness that inserts controlled distractors at increasing context lengths
    • Plot accuracy against context size for two or more models and describe how each one degrades
    • Explain why distractors that look like the right answer do more damage than random filler
  5. Level 5: Position Effects: Where Information Sits
    Test how a fact's position (start, middle or end of the context) changes whether the model uses it, and turn the results into rules for laying out prompts.
    • Run a position sweep that moves a key fact or instruction through the context and records how often the model uses it
    • Choose where to place standing instructions, the current task and retrieved evidence based on your own measurements
    • Say which position findings held across the models you tested and which did not
  6. Level 6: Setting and Enforcing a Context Budget
    Set per-part token budgets for an agent, cut oversized parts before they enter the context, and raise alerts when a request goes over budget.
    • Define budgets for the system prompt, tools, history and tool results, and enforce them in a middleware layer
    • Truncate oversized tool output by head, tail or middle, and leave a clear marker saying what was dropped
    • Write budget-violation reports that show which part and which turn broke the limit
  7. Level 7: Progressive Disclosure of Instructions
    Replace one huge system prompt with a short index of capabilities whose detailed instructions load only when a task needs them, the pattern behind skill-style instruction files.
    • Split a large system prompt into a short index plus instruction files that load on demand
    • Write the one-line descriptions the model uses to decide what to load, and test whether it loads the right file
    • Measure the token savings, and any quality change, against the original single prompt
  8. Level 8: Just-in-Time Tool Loading
    Deal with tool-definition bloat from large tool sets and MCP servers by deferring tool schemas and letting the agent search for the tools it needs.
    • Measure how many tokens a set of MCP servers' tool definitions uses on every request
    • Build a tool-search step in Python or TypeScript that exposes only the tool schemas relevant to the task
    • Check tool-selection accuracy after the change so that savings do not hide wrong tool calls
  9. Level 9: Just-in-Time Files: References, Not Contents
    Teach agents to work from file paths, search results and line ranges, and read full file contents only when a task truly needs them.
    • Give an agent list, grep and ranged-read tools in place of pasting whole files into the prompt
    • Compare tokens and task success between preloading files and loading them on demand
    • Spot tasks where loading on demand costs more round trips than it saves
  10. Level 10: Shaping Tool Results Before They Land
    Keep tool output from flooding the context by filtering, paginating, trimming and structuring results at the tool boundary.
    • Change a noisy tool (logs, test output, API responses) so that it returns only the fields the agent needs
    • Add pagination and 'more available' hints the agent can follow when it needs more
    • Decide when to summarise a result with a cheaper model and when to filter it with plain code
  11. Level 11: How Prompt Caching Works
    Understand prompt caching as reuse of computed prefix state: why only an exact matching prefix hits the cache, and why ordering a prompt from stable content to volatile content decides whether it pays off.
    • Explain prefix matching and why one changed token early in a prompt prevents reuse of everything after it
    • Reorder an agent's request so that tools and instructions come before the history and fresh input
    • Estimate the savings of caching for an agent loop from its token ledger
  12. Level 12: Caching Rules Across Providers
    Compare the current caching rules of Claude, OpenAI, Gemini and open-weight servers such as vLLM side by side: explicit or automatic caching, minimum sizes, lifetimes and pricing, checked against each provider's documentation.
    • Enable caching correctly for the same agent prompt on Claude, OpenAI, Gemini and a self-hosted open-weight server
    • Make a reference table of each provider's cache triggers, minimum lengths, lifetimes and discounts, citing the current documentation
    • Choose cache breakpoints or prompt structure to suit each provider's model
  13. Level 13: Measuring and Protecting Cache Hits
    Read cache usage fields to track hit rates, and find the common cache-busters such as timestamps, reordered tools and changing system prompts.
    • Log cached and uncached input tokens per request for each provider and compute a hit rate
    • Find and fix at least three cache-busting patterns in a sample agent
    • Weigh trade-offs between caching and just-in-time loading when loading content changes the prompt prefix
  14. Level 14: Retrieval Baseline: BM25 and a Labelled Query Set
    Start retrieval with a labelled set of queries and a keyword BM25 baseline, so that every later change can be measured with recall@k and MRR.
    • Build a small labelled set of queries and their relevant documents from a real document collection
    • Run BM25 retrieval in Python or TypeScript and report recall@k and MRR
    • Explain where keyword search does well (identifiers, error codes, rare terms) and where it fails
  15. Level 15: Embeddings and Dense Vector Search
    Add dense retrieval with embedding models from several vendors and an open-weight option, and see where meaning-based matching helps and where it fails.
    • Embed a collection with two or more embedding models and search it with a vector index
    • Compare dense retrieval with BM25 on the same labelled queries
    • Name typical dense-retrieval failures such as exact identifiers, negation and domain jargon
  16. Level 16: Hybrid Search with Rank Fusion
    Combine BM25 and embedding results with reciprocal rank fusion, and tune the combination using your query set instead of guesswork.
    • Implement reciprocal rank fusion over keyword and vector result lists in a few lines of code
    • Measure the hybrid system against each single retriever on recall@k and MRR
    • Tune candidate depth and fusion weighting, and record which settings actually changed the results
  17. Level 17: Chunking That Preserves Meaning
    Compare fixed-size, structure-aware and context-enriched chunking, and measure how each one changes retrieval quality and the tokens added to the prompt.
    • Chunk the same documents three ways, including by headings or code structure
    • Add document-level context to chunks and measure the effect on retrieval
    • Balance chunk size against retrieval precision and the context tokens each retrieved chunk adds
  18. Level 18: Rerankers: Precision at the Top
    Add a cross-encoder or hosted reranker after the hybrid search so that fewer, better chunks reach the model, and weigh the extra latency and cost.
    • Rerank hybrid candidates with a hosted reranker and with an open-weight one
    • Show how reranking lets you send fewer chunks to the model without losing answer quality
    • Measure the latency and cost the reranker adds, and decide when it is worth it
  19. Level 19: Classic RAG vs Agentic Search
    Run the same tasks with a single retrieval step and with an agent that searches iteratively using grep and other tools, and work out when each approach wins.
    • Build both a one-shot RAG pipeline and an agentic-search loop over the same collection
    • Compare their accuracy, tokens, latency and number of tool calls on your query set
    • Write decision rules for choosing between them, and note where current practice is still unsettled
  20. Level 20: Parsing a Codebase with Tree-sitter
    Use tree-sitter to parse source files in Python and TypeScript into syntax trees and pull out functions, classes and signatures as the units of a local code index.
    • Parse a multi-language repository with tree-sitter and extract symbols with their file and line ranges
    • Generate compact signature-only outlines of files that an agent can read for a fraction of the tokens
    • Update the index incrementally when files change instead of rebuilding it from scratch
  21. Level 21: Symbol Graphs from Tree-sitter Parses
    Turn tree-sitter parse trees into a symbol graph of definitions, references, imports and calls, so a coding agent can follow a function to its callers and dependencies instead of grepping blindly.
    • Extract definitions and references from a Python or TypeScript repo with tree-sitter queries and store them as graph edges
    • Answer 'who calls this?' and 'what does this depend on?' from the graph, and list where name-based resolution breaks (dynamic dispatch, re-exports, monkey-patching)
    • Update the index incrementally when files change instead of rebuilding it from scratch
  22. Level 22: Serving a Code Index to an Agent Within Budget
    Expose the code index as a ranked repo map and a set of lookup tools, and measure whether it beats plain grep-and-read agentic search on token cost and task success.
    • Build a repo map ranked by graph centrality and trimmed to a fixed token budget
    • Wrap symbol lookup, find-references and read-definition as agent tools with small, predictable outputs
    • Run the same coding tasks with and without the index and compare tokens, tool calls and pass rate
  23. Level 23: Anatomy of a Long Session
    Break down how a long agent session fills its context, with tool outputs, stale file reads, dead ends and repeated instructions, and decide which kinds of content must survive and which can go.
    • Instrument a session transcript to show token share by message type over time
    • Sort context into must-keep (goals, decisions, constraints, open tasks), recoverable (file contents, search results) and disposable
    • Choose a compaction trigger point from measured quality loss rather than the hard window limit
  24. Level 24: Clearing Tool Results Before Summarising
    Apply the cheapest compaction first by clearing or stubbing old tool results that can be fetched again, using both your own code and the context-management features providers now offer.
    • Replace stale tool outputs with short placeholders that tell the agent how to re-fetch them
    • Compare a hand-written clearing pass with a provider's built-in context editing and note what each keeps
    • Measure the tokens saved and check whether the agent ends up re-reading the same files
  25. Level 25: Summarisation Compaction Without Losing Facts
    Write a compaction step that summarises a session into a structured handoff, and test it with planted facts so you can see exactly what the summary drops.
    • Design a compaction prompt with fixed sections for goal, decisions, constraints, file state and next steps
    • Plant key facts in long transcripts and score how many survive one, two and three rounds of compaction
    • Spot and reduce summary drift, where repeated compactions bend or invent details
  26. Level 26: Sub-Agents with Fresh Context
    Hand exploration-heavy subtasks to sub-agents that start with a clean, narrow context, and learn when the isolation pays for its extra calls and when it doesn't.
    • Implement a parent agent that spawns a sub-agent with only a task brief and a scoped tool set
    • Compare total tokens and outcome quality for a search-heavy task done inline and done by a sub-agent
    • Name the cases where sub-agents hurt: tightly coupled edits, lost shared context and duplicated work
  27. Level 27: Briefs and Return Contracts for Sub-Agents
    Define what goes into a sub-agent's brief and what shape its result must come back in, so the parent gets a compact answer it can check rather than a transcript dump.
    • Write a brief template covering objective, boundaries, known facts and stopping criteria
    • Enforce a structured return schema with findings, evidence references and confidence, and validate it in code
    • Cap sub-agent output size and handle failures, timeouts and partial results in the parent
  28. Level 28: Shared State Across Multiple Agents
    Design the state that several agents read and write, such as task boards, scratchpads and artefact stores, so they coordinate without each one copying everything into its context.
    • Model shared state as structured records with ownership, versions and status, not one shared chat log
    • Give each agent a filtered view of shared state sized to its role
    • Detect and resolve conflicting writes and stale reads between concurrent agents
  29. Level 29: What Agent Memory Is For and When to Skip It
    Separate long-term memory from session context and retrieval over documents, and decide which facts are worth remembering across sessions at all.
    • Classify candidate memories as user preferences, project facts, procedures or episodic history
    • Explain how unchecked memory adds clutter, stale beliefs and privacy risk to every future prompt
    • Write a one-page memory charter for an agent stating what it may remember and why
  30. Level 30: Memory as Files and Append-Only Logs
    Build the simplest durable memory, plain markdown files plus an append-only event log, and see why many coding agents start here.
    • Implement memory files the agent can read, edit and load on demand with progressive disclosure
    • Keep an append-only log as the source of truth and generate readable memory views from it
    • Weigh the trade-offs: easy to inspect and diff, but no relevance ranking and growth you have to manage
  31. Level 31: Memory in Vector Stores
    Store memories as embedded entries and recall them by similarity, and measure where semantic recall helps and where it pulls back irrelevant or outdated items.
    • Implement write and recall over a vector store with metadata filters for user, project and time
    • Evaluate recall precision on a labelled set of queries and memories
    • Combine similarity with recency and importance signals and observe how the ranking changes
  32. Level 32: Structured Records as Memory
    Model memory as typed records with keys, schemas and provenance so facts can be updated in place, queried exactly and checked for contradictions.
    • Design a schema for preferences, entities and facts with source, timestamp and confidence fields
    • Let the agent read and write records through typed tools instead of free text
    • Choose between files, vectors and records for a given use case, or combine them, and justify the choice
  33. Level 33: Write Policies and Compressing Before Adding
    Decide what gets saved, when and by whom, and compress candidate memories into short, deduplicated, self-contained entries before they are stored.
    • Implement a write gate that rejects transient, duplicate or sensitive candidates
    • Write a compression step that turns a raw observation into an atomic fact with provenance
    • Compare memories written in the hot path with memories extracted in the background after a session
  34. Level 34: Update and Delete Policies for Memory
    Handle memories that become wrong or contradicted by superseding, expiring or deleting them, so the agent stops acting on outdated beliefs.
    • Implement add, update, supersede and delete operations, with conflict detection against existing entries
    • Attach expiry rules and staleness checks to memory types that decay
    • Test that a corrected fact actually replaces the old one at recall time
  35. Level 35: Memory Budgets and Consolidation Passes
    Put a hard token budget on memory and run scheduled consolidation passes that merge, generalise and prune entries so memory stays useful as it grows.
    • Set per-scope memory budgets and enforce them at load time
    • Build a consolidation job that merges duplicates, rolls episodes up into general facts and drops low-value entries
    • Check that consolidation keeps recall quality on a held-out query set
  36. Level 36: Assessing Provider Memory Features
    Review the memory and state features that Claude, OpenAI and Gemini platforms and open-weight frameworks currently offer, verified against their current docs, and decide when to use them and when to own memory yourself.
    • Map each provider feature to the patterns from earlier levels (files, stored state, retrieval)
    • Assess portability, inspectability, data residency and deletion guarantees for each option
    • Write a short decision record choosing provider-managed or self-managed memory for a sample agent
  37. Level 37: Building an Eval Set for Context Changes
    Assemble an eval set that can show whether a context change such as trimming, caching, retrieval or memory helped or hurt, covering both outcomes and token use.
    • Collect representative and adversarial tasks, including long-session and memory-dependent cases
    • Define graders: exact checks, programmatic assertions and calibrated LLM judges where needed
    • Record tokens, cache hits, latency and cost next to the quality scores for every run
  38. Level 38: Running Context Ablations Honestly
    Compare context variants against a baseline with repeated runs and simple statistics, so you can tell a real improvement from noise.
    • Run baseline and variant several times and report spread, not a single score
    • Use paired comparisons per task to find regressions that an average hides
    • Set a pass rule such as 'no task class drops and tokens fall by X%' before looking at results
  39. Level 39: Privacy Risks in Stored Memory
    Find where personal and sensitive data ends up in memory, logs, summaries, indexes and caches, and reduce what is collected in the first place.
    • Trace one piece of personal data through every store an agent writes to
    • Add detection and redaction of sensitive data in the memory write path
    • Scope memory per user and tenant and test that one user's memories never reach another's context
  40. Level 40: Deletion and Retention Across Every Store
    Implement real forgetting: retention limits and user deletion requests that reach memory records, embeddings, derived summaries, logs and provider-side state.
    • Build a deletion routine that uses provenance to remove an entry and everything derived from it
    • Apply retention schedules per memory type and verify them with automated tests
    • Document which provider-side copies such as caches, stored responses and files you control, and how to delete them
  41. Level 41: Baseline and Plan the Token Cut
    Before the final challenge, you freeze a baseline for a working agent: its eval scores, a per-component token breakdown and its cost per task. From those numbers you build a ranked plan of context changes, each with an estimated saving and risk, and test each change on its own.
    • Run the agent's eval set several times to pin down baseline pass rates, input/output/cached token counts, latency and cost per task, along with the run-to-run noise. The noise sets the smallest difference you can treat as a real regression.
    • Break baseline input tokens down by source (system prompt, tool definitions, retrieved chunks, file reads, conversation history, memory entries) and rank candidate changes by expected saving against risk to quality.
    • Write a one-change-at-a-time ablation harness in Python or TypeScript. It applies a single context change, re-runs the evals and reports the change in tokens and in score against the baseline, so no change ships without measured evidence.
  42. Level 42: Final Challenge: Cut Tokens, Keep the Evals Exam
    The capstone review of the whole course: you cut a provided agent's input tokens substantially with no loss on its eval set. You combine just-in-time loading, cache-friendly prompt order, hybrid retrieval or agentic search, code indexes, compaction, sub-agents and a budgeted memory layer, then defend every trade-off with measurements.
    • Apply and stack changes from every phase: tools and instructions loaded only when needed, prompts reordered so they hit each provider's cache, retrieval tuned with rank fusion and reranking, history compacted, side tasks handed to sub-agents with fresh context, and memory consolidated. Show a substantial drop in input tokens and cost per task, with eval scores no worse than baseline beyond the measured noise.
    • Run the final configuration on at least two providers or model families, for example Claude, OpenAI, Gemini or an open-weight model. Report where the savings carry over and where provider-specific behaviour, such as caching rules or how a model handles long context, changes the result.
    • Write a short engineering report covering the before/after token and score table, the changes you rejected and why, the privacy and deletion handling of any stored memory, and the open risks and areas where practice is still unsettled. A reviewer should be able to reproduce the result from it.

Access

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor. Every level, the podcast edition and the AI tutor come with All Access at £4.99/month or any Creator plan — see pricing.

Read lesson 1 free →

More like this