O’Reilly Media
Context Engineering with DSPy
Self-Optimizing Prompt Pipelines for Building Reliable AI Agents
AI models work best when you give them the right information, in the right format, at the right time. Too little and they guess. Too much and performance rots. This book shows you how to manage that with DSPy: define the task, collect examples, write a metric, and let an optimizer write the prompt.
ISBN 979-8-341-67126-3 · Companion code on GitHub
Why this book
Stop tinkering with prompt strings
As models have become better at reasoning, the wording of a prompt matters less than the inputs the model has to reason through. Context engineering is the discipline of curating what a language model receives so it performs well without wasting tokens or making errors.
DSPy is the framework for putting that into practice. You declare what your system should do as inputs and outputs, pair it with a dataset and an evaluation metric, and DSPy’s prompt optimizers improve the program for you. The result is portable across models, built from maintainable modules, and improved through evaluation instead of guesswork.
- 24% → 51%success on question answering with search
- 66% → 87%accuracy on classification tasks
- +10%document retrieval quality
- 10% to 100%+improvements in the author’s own consulting work
What’s inside
Eleven chapters, from first Signature to production
Introduction to Context Engineering
Context rot, the 11 ways long contexts fail, and the 10 techniques that fix them. No DSPy required.
Introduction to DSPy
Language models, Signatures, modules, evaluation and optimizers, and the philosophy behind the framework.
DSPy in Eight Steps
Build and optimize a program end to end: train an AI-text detector as a judge, then train a rewriter to beat it.
Strategies for Collecting Datasets
Error analysis, domain experts, third-party data and synthetic bootstrapping. Why 10 to 50 good examples is enough to start.
Evaluation Metrics
LLM evaluation in practice: string and semantic metrics, LLM-as-a-judge, training a judge from human labels, and panels of judges.
Deep Dive into Prompt Optimizers
GEPA, MIPROv2, BootstrapFewShot, SIMBA, fine-tuning and more, benchmarked on one task with cost and time for each.
Custom Modules, Types, and Adapters
ChainOfThought, ReAct, Refine, recursive language models (RLMs), multimodal types and the adapter system.
Building AI Agents
Agents versus workflows, ReAct agents with tools, MCP, retrieval, memory, and how DSPy compares with other agent frameworks.
Real-World Use Cases
Seven projects, from a sentiment classifier and invoice extraction to a customer service RAG agent and a financial analyst.
Putting DSPy into Production
Observability with MLflow, deployment with FastAPI, exporting optimized prompts, and a user interface for non-developers.
Optimizing Coding Agents with DSPy
Use GEPA to improve the Claude skills, SKILL.md, AGENTS.md and CLAUDE.md files your coding agent already runs on.
Chapter 3
DSPy in eight steps
The process the book uses for every DSPy program. The chapter applies it to a task with no obvious metric, rewriting AI-generated text to sound human, by training an LLM judge first and then optimizing against it. GEPA takes the judge from 85% to 100% accuracy and the rewriter from 0% to 40%.
- Specify your SignaturesDeclare the task as inputs and outputs instead of a prompt.
- Build your modulesWrap each Signature in an inference strategy such as ChainOfThought.
- Explore a few examplesRun the program, inspect the history and read the traces.
- Collect your datasetLoad examples, convert them to DSPy format, split train and test.
- Define your metricsStart with exact match, then add an LLM judge for fuzzy tasks.
- Establish a baselineEvaluate the judge and the task before changing anything.
- Optimize your programLet GEPA rewrite the instructions against your metric.
- Test and iterateTry BestOfN, swap in another model, and measure again.
Mike walked through this chapter live with DSPy lead maintainer Isaac Miller and Drew Breunig: watch “Context Engineering With DSPy” on YouTube.
More from the author
DSPy tutorials, talks and code
Watch
- Context Engineering With DSPy (livestream)Every’s launch session for the book, working through the eight-step process.
- Solving the Long Prompt ProblemO’Reilly talk on using DSPy to make a prompt radically shorter at the same performance.
- Train a judge, then optimize against itShort demo of the evaluator-optimizer pattern for creative tasks.
Read
- I’ve Stopped Writing Prompts—DSPy Does It BetterEvery. Why a prompt engineer handed prompt writing to an optimizer.
- This Prompt Optimizer Learns From Its Mistakes Like DNAEvery. How the GEPA optimizer works.
- Context Engineering Is Knowing When to Start OverEvery. Seven causes of context rot, adapted from Chapter 1 for chat users.
- Correcting Bias in LLMs with DSPyAsk Rally. Calibrating 500 AI personas against real election results.
- Optimizing to Remove Political Bias Removes Other Bias TooAsk Rally. The follow-up experiment.
- The Pairwise Gold TriadSaxifrage. Hill climbing with subjective evals.
Build
- Companion code for the bookNotebooks for every chapter, pinned to DSPy 3.3.0 and Python 3.12 to 3.14.
- DSPyUIAn open source Gradio interface for defining Signatures, uploading data and running DSPy optimizers without code.
- ClawsonaOptimize an agent’s persona file against a rubric, from Chapter 11.
- DSPy documentationThe official docs for the framework.
Questions
DSPy, GEPA and context engineering, explained
What is DSPy?
DSPy stands for Declarative Self-improving Python. It is an open source framework, released under the MIT license in October 2023 and developed from work by Omar Khattab and colleagues at Stanford. Instead of writing a prompt, you define an AI task by its inputs and outputs in a Signature, combine tasks into modules, and use optimizers to improve the program against a dataset and an evaluation metric.
What is context engineering?
Context engineering is the discipline of systematically curating what information a language model receives, to maximize performance while minimizing costs and errors. The context is everything the model can see when it responds: system instructions, messages, conversation history, tool definitions and results, retrieved documents, memories and examples.
What is the difference between context engineering and prompt engineering?
Prompt engineering is concerned with changes inside the prompt: instructions, examples and fixed chains of prompts. Context engineering also covers the wider system around the prompt: retrieving documents and memories, formatting content, designing the harness, and pruning irrelevant information on long-running tasks. The book treats prompt engineering as a subset of context engineering.
What is context rot?
Context rot is the way model performance degrades as the input gets longer, a term from the vector database company Chroma. Chapter 1 describes 11 ways long contexts fail, including context distraction, lost in the middle, context confusion, context clash, context drift and context poisoning, and 10 techniques for fixing them.
What is GEPA in DSPy?
GEPA (Genetic-Pareto) is a DSPy optimizer that rewrites your prompt instructions by reflecting on where the program failed. It is the author’s default optimizer once a dataset has 10 or more examples. In the book’s benchmark of optimization approaches on one AI-detection task, GEPA took accuracy from 53.75% to 80% for about $0.58.
What is harness engineering, and how does it relate to context engineering?
Harness engineering is OpenAI’s term for the runtime scaffolding around a model: the environment, tools, feedback loops and control systems that deliver context to an agent and act on its outputs. The book’s view is that this is still context engineering. The harness is what delivers the context, and getting the context right is what delivers performance.
What is prompt optimization?
Prompt optimization means improving a prompt against a dataset and an evaluation metric instead of by trial and error. In DSPy, a prompt optimizer selects or generates few-shot examples, proposes and tests better instructions, or both. The book’s Chapter 1 example cuts a 1,784-token prompt to 43 tokens while accuracy moves from 64% to 67%.
What is LLM-as-a-judge?
LLM-as-a-judge uses one language model to evaluate another model’s output, which makes it possible to score subjective tasks like writing. The book’s method is to label 20 to 50 outputs yourself, train the judge on those labels until it agrees with you 80 to 90 percent of the time, and then use the judge as the metric an optimizer works against.
What is MIPROv2?
MIPROv2 is a DSPy optimizer that searches over both instructions and few-shot examples. The book recommends trying it when you have a large dataset of 200 or more examples and a substantial optimization budget. In the Chapter 6 benchmark it reached 80% on validation but 66.25% on the locked test, a reminder to hold out data.
How does DSPy compare with LangChain or Pydantic AI?
Chapter 8 builds the same agent in DSPy, LangChain, Pydantic AI, the OpenAI Agents SDK and CrewAI. The book’s argument for DSPy is that every agent is a DSPy program, so it can be evaluated and optimized. You don’t have to choose one: many teams optimize a prompt with DSPy, export it, and run it in the framework they already use, which Chapter 10 covers.
Do I need to know DSPy before reading the book?
No. Chapter 1 covers context engineering without any DSPy, Chapter 2 introduces the framework’s five core abstractions, and Chapter 3 builds a first program end to end. The examples are in Python, and the concepts transfer to DSPy ports such as Ax for TypeScript, dspy.rb for Ruby and dspy-go.
How many examples do I need to optimize a prompt with DSPy?
Fewer than most people expect. The book’s guidance is that 10 to 50 well-chosen examples combined with an optimizer will often outperform a handcrafted prompt, and that you can start with 10 to 20 and grow the dataset from the errors you see in production.
Is DSPy used in production?
Yes. The book cites Shopify using DSPy with GEPA to extract structured metadata across every shop, Dropbox optimizing the relevance judge behind Dash, and Databricks building DSPy-powered judges and RAG pipelines, along with JetBlue, Replit and Moody’s.
What are recursive language models (RLMs)?
A recursive language model puts a large input into a code environment and calls the model on smaller parts of it, rather than loading everything into one context window. DSPy provides the pattern as dspy.RLM. The book uses it for documents too large to fit in context, such as financial filings.
Can I optimize Claude skills, SKILL.md, CLAUDE.md or AGENTS.md files with DSPy?
Yes, and Chapter 11 is about exactly that. A skill is a Markdown instruction file (SKILL.md) that a coding agent such as Claude Code, Codex or Cursor loads for a task, so it can be tested against failed sessions and rewritten by GEPA. The same approach works for the always-loaded AGENTS.md or CLAUDE.md file and for agent persona files.
Which version of DSPy does the book use?
The companion repository pins DSPy 3.3.0 and supports Python 3.12 through 3.14. Each chapter has notebooks you can run locally, and many run in Google Colab.
