Context Engineering with DSPy: Self-Optimizing Prompt Pipelines for Building Reliable AI Agents
Context Engineering with DSPy: Self-Optimizing Prompt Pipelines for Building Reliable AI Agents
By: Mike Taylor | Publisher: Shroff/O'Reilly | Year: 2026
ISBN: 9789368082613
MRP: Rs. 2,000.00
You Pay: Rs. 1,800.00
You save: Rs. 200.00 ( 10% )
MRP: Rs. 2,000.00
You Pay: Rs. 1,800.00
You save: Rs. 200.00 ( 10% )
Usually ships in 2-3 days
Reward points: 18 points
⚠️ Ships only in Bangladesh, Bhutan, India, Maldives, Nepal, Sri Lanka, and the United Republic of Tanzania.
The E-Book is delivered digitally worldwide within 24 hours.
The Combo includes the US imported edition, delivered worldwide.
Description
AI agents need the right context at the right time to do a good job. Too much input increases cost and harms accuracy, while too little causes instability and hallucinations. Context Engineering with DSPy introduces a practical, evaluation-driven way to design AI systems that remain reliable, predictable, and easy to maintain as they grow.
AI engineer and educator Mike Taylor explains DSPy in a clear, approachable style, showing how its modular structure, portable programs, and built-in optimizers help teams move beyond guesswork. Through real examples and step-by-step guidance, you'll learn how DSPy's signatures, modules, datasets, and metrics work together to solve context engineering problems that evolve as models change and workloads scale.
This book supports AI engineers, data scientists, machine learning practitioners, and software developers building AI agents, retrieval-augmented generation (RAG) systems, and multistep reasoning workflows that hold up in production.
- Understand the core ideas behind context engineering and why they matter
- Structure LLM pipelines with DSPy's maintainable, reusable components
- Apply evaluation-driven optimizers like GEPA and MIPROv2 for measurable improvements
- Create reproducible RAG and agentic workflows with clear metrics
- Develop AI systems that stay robust across providers, model updates, and real-world constraints
About the Author
Mike Taylor
Table of Contents
Table of Contents
Preface....................................................................................................... xiii
1.
Introduction to Context
Engineering................................................................. 1
Defining Context Engineering 1
Context Engineering Versus Prompt Engineering 3
Introducing DSPy 4
Failure Modes for Long Contexts 7
Context Overflow 8
Token Costs 9
Context Distraction 9
Lost in the Middle 10
Prompt Injection 11
Context Confusion 12
Context Fragmentation 13
Context Clash 13
Context Drift 14
Context Poisoning 14
Context Underspecification 15
Context Engineering Techniques 16
Context Editing 17
Context Summarization 18
Memory Offloading 19
Prompt Optimization 20
Few-Shot Learning 22
Retrieval-Augmented Generation 23
Tool Loadout 24
Guardrails 25
Control Flow 26
Subagents 27
Conclusion 29
2.
Introduction to DSPy.................................................................................... 31
Language Models 32
Setting Up Language Models 32
Changing LM Provider 33
Signatures 33
Defining a Signature 34
Get Over the
Unfamiliarity 36
Modules 36
Predict Module 37
Built-In Modules 37
ReAct Agents 38
Stacking Signatures Together 39
Recursive Language Models 40
Evaluation 41
Example Datasets 42
Evaluation Metrics 43
Running Evaluations 44
Train-Test Split 45
Optimizers 47
DSPy’s Philosophy 49
How I Use DSPy 50
Conclusion 52
3.
DSPy in Eight Steps........................................................................................... 53
Configuring Our Program 53
Specify Your
Signatures 54
Humanize AI Text 55
Detect AI Text 55
Build Your Modules 55
TextTransformer 56
AIDetector 56
Explore a Few Examples 57
Run Your Program 57
Inspect History 59
MLflow Traces 60
Collect Your Dataset 61
Example Dataset 61
Load from CSV 63
Convert to DSPy Example Format 63
Train-Test Split 63
Define Your Metrics 64
Exact Match 64
LLM Judge 65
Testing Your Metric 66
Establish a Baseline 67
Evaluate Your Judge 67
Evaluate Your Task 69
Optimize Your Program 69
Running the GEPA Optimizer 70
LLM Judge Metric 72
Optimizing Your Task Program 74
Evaluating Your Optimized Program 76
Test and Iterate 76
Conclusion 78
4.
Strategies for Collecting Datasets............................................................................ 79
Error Analysis 80
Manually Review and Annotate Data 80
Categorize Errors 83
Define a Dataset 84
Domain Experts 88
Qualitative Interview 88
Example Correction 90
Gold Standard or Fool’s Gold? 91
Third-Party Datasets 94
Built-In DSPy Datasets 94
Hugging Face Datasets 96
Kaggle Datasets 98
Practical Example: Combining Third-Party and Custom Data 99
Synthetic Bootstrapping 100
Model Distillation 101
Data Enrichment 102
Synthetic de-identification 102
Conclusion 104
5.
Evaluation Metrics......................................................................................... 107
String Comparison 109
Regex Match 109
Edit Distance 111
Semantic Similarity 112
Embedder 114
Embedding Distance 114
NLP Classifiers 117
LLM-as-a-Judge 118
Human-in-the-Loop 119
Training a Classifier 121
Evaluator-Optimizer Pattern 123
Cost Management 124
Panel of Judges 124
Criteria Rubrics 125
Weighted Scoring 125
Multi-Predictor Feedback 126
Conclusion 131
6.
Deep Dive into Prompt Optimizers........................................................................... 133
Setting Up the AI Detection
Module 134
Automatic Few-Shot Learning
Optimizers 136
LabeledFewShot 137
BootstrapFewShot 138
BootstrapFewShotWithRandomSearch (BootstrapRS) 139
KNNFewShot 140
Automatic Instruction Optimizers 141
COPRO 141
MIPROv2 143
GEPA 144
SIMBA 149
Automatic Fine-Tuning Optimizers 150
BootstrapFinetune 151
BetterTogether 153
Program Transformations with Ensemble 154
Choosing the Right Optimizer 157
Conclusion 159
7.
Custom Modules, Types, and Adapters...................................................................... 161
Built-In Modules 162
Predict 162
ChainOfThought 162
BestOfN 163
Refine 164
MultiChainComparison 165
ReAct 166
ProgramOfThought 166
CodeAct 168
Recursive Language Models 169
Flex 170
Built-In Module Summary 171
Custom DSPy Programs 172
Patterns for Building
Programs with Multiple
Modules 172
Building a Custom Module: Verbalized Sampling 176
Other Components 178
Majority 178
Parallel 179
Multimodal Types 180
Images 180
Audio 181
Subclassing Type for Videos 182
Chat Adapters 188
ChatAdapter 188
JSONAdapter 189
XMLAdapter 190
TwoStepAdapter 190
Building Custom Adapters 191
Conclusion 193
8.
Building AI Agents........................................................................................... 195
Agents Versus Workflows 196
Definition of an Agent 196
Agentic Design Patterns 197
When to Use Agents Versus
Workflows 198
DSPy’s ReAct Agent 199
Defining Tools 199
ReAct Module 200
Subagents as Tools 201
Framework Comparison 202
Tracing Trajectories 205
MCP Integrations 206
Adding Retrieval to Agents 208
Retrieval Clients 208
Web Search Tools 211
Multi-Hop Search 212
Giving Agents Memory 214
Conversation History 215
Memory Editing 216
Editing Tool Results 217
Memory with Mem0 217
Context Management with RLMs 220
Conclusion 221
9.
Real-World Use Cases....................................................................................... 223
Social Media Sentiment Classifier 224
Capturing Your Team’s Preferences as Examples 225
Optimizing with BootstrapFewShotWithRandomSearch 225
Invoice Entity Extraction 226
Few-Shot Examples 226
Majority Voting 228
GEPA Instruction Learning 229
Marketing Content Generator 230
Generating Custom Styles 230
Style Transfer 231
Semantic Distance 232
News Research Summarizer 233
Web Search 234
Chunking Strategy 236
Recursive Summarization 237
Fashion Video Generator 238
Generate Text-to-Image Tool 238
Generate Image-to-Video Tool 239
Evaluator-Optimizer Pattern 240
Customer Service RAG Agent 241
RAG Retrieval Client 242
Prompt Injection Guardrails 243
Privacy Guardrails 244
Financial Analyst Agent 245
Document Parsing 246
RLM for Financial Analysis 247
Trajectory Evaluation 248
Conclusion 251
10.
Putting DSPy into Production................................................................................ 253
Monitoring and Observability with MLflow 254
Setting Up MLflow 255
Viewing Logs 255
Tracing Optimizers 256
Tracking Experiments 257
Querying Traces with the MLflow
MCP Server 258
Deployment with FastAPI 260
FastAPI Route 260
Saving and Loading Programs 262
Exporting Prompts in OpenAI Format 263
Avoiding DSPy-Flavored Markers in Exported
Prompts 264
Guardrails 265
Async 268
Streaming 269
Error Handling and Rate Limits 270
Caching in Production 271
Building a Gradio
User Interface (DSPyUI) 275
Signatures 276
Modules 277
Datasets 278
Optimization 278
Inference 280
DSPy in Other Languages 281
Conclusion 282
11.
Optimizing Coding Agents with DSPy....................................................................... 285
Optimizing a SKILL.md End-to-End 286
Turning Failed Sessions into Skills 286
The optimize_anything Library 289
Building CLIs with DSPy 292
Task Decomposition 292
Synthetic Task Generation 296
Testing Cheaper Models 298
Self-Evolving Agents 299
Automated Skill Discovery with RLMs 299
Testing AGENTS.md Instructions 301
Clawsona: Optimizing Agent Personas 303
The Optimizer Is a Commodity 308
What You Built 309
Closing Thoughts 310
Index......................................................................................................... 313
Preface....................................................................................................... xiii
1.
Introduction to Context
Engineering................................................................. 1
Defining Context Engineering 1
Context Engineering Versus Prompt Engineering 3
Introducing DSPy 4
Failure Modes for Long Contexts 7
Context Overflow 8
Token Costs 9
Context Distraction 9
Lost in the Middle 10
Prompt Injection 11
Context Confusion 12
Context Fragmentation 13
Context Clash 13
Context Drift 14
Context Poisoning 14
Context Underspecification 15
Context Engineering Techniques 16
Context Editing 17
Context Summarization 18
Memory Offloading 19
Prompt Optimization 20
Few-Shot Learning 22
Retrieval-Augmented Generation 23
Tool Loadout 24
Guardrails 25
Control Flow 26
Subagents 27
Conclusion 29
2.
Introduction to DSPy.................................................................................... 31
Language Models 32
Setting Up Language Models 32
Changing LM Provider 33
Signatures 33
Defining a Signature 34
Get Over the
Unfamiliarity 36
Modules 36
Predict Module 37
Built-In Modules 37
ReAct Agents 38
Stacking Signatures Together 39
Recursive Language Models 40
Evaluation 41
Example Datasets 42
Evaluation Metrics 43
Running Evaluations 44
Train-Test Split 45
Optimizers 47
DSPy’s Philosophy 49
How I Use DSPy 50
Conclusion 52
3.
DSPy in Eight Steps........................................................................................... 53
Configuring Our Program 53
Specify Your
Signatures 54
Humanize AI Text 55
Detect AI Text 55
Build Your Modules 55
TextTransformer 56
AIDetector 56
Explore a Few Examples 57
Run Your Program 57
Inspect History 59
MLflow Traces 60
Collect Your Dataset 61
Example Dataset 61
Load from CSV 63
Convert to DSPy Example Format 63
Train-Test Split 63
Define Your Metrics 64
Exact Match 64
LLM Judge 65
Testing Your Metric 66
Establish a Baseline 67
Evaluate Your Judge 67
Evaluate Your Task 69
Optimize Your Program 69
Running the GEPA Optimizer 70
LLM Judge Metric 72
Optimizing Your Task Program 74
Evaluating Your Optimized Program 76
Test and Iterate 76
Conclusion 78
4.
Strategies for Collecting Datasets............................................................................ 79
Error Analysis 80
Manually Review and Annotate Data 80
Categorize Errors 83
Define a Dataset 84
Domain Experts 88
Qualitative Interview 88
Example Correction 90
Gold Standard or Fool’s Gold? 91
Third-Party Datasets 94
Built-In DSPy Datasets 94
Hugging Face Datasets 96
Kaggle Datasets 98
Practical Example: Combining Third-Party and Custom Data 99
Synthetic Bootstrapping 100
Model Distillation 101
Data Enrichment 102
Synthetic de-identification 102
Conclusion 104