One line, dspy.ChainOfThought(“question -> answer”), scores 50.0% on math word problems with GPT-3.5. Compile that same line and it scores 80.3%, with no prompt written by hand.
Compiling Declarative Language Model Calls into Self-Improving Pipelines: how a program that only says what each model call must do can find its own prompts.
Pick a program, then press each compile step in turn. The code at the top never changes. Only the prompt DSPy builds from it does. Then we build the whole system, piece by piece: the signature, the module, the program, and the compiler that finds the examples.
You need a little Python and a rough idea of what a prompt is (the text you send a language model). We build the rest from zero.
Paper: Omar Khattab, Arnav Singhvi, Paridhi Maheshwari, Zhiyuan Zhang, Keshav Santhanam, Sri Vardhamanan, Saiful Haq, Ashutosh Sharma, Thomas T. Joshi, Hanna Moazam, Heather Miller, Matei Zaharia and Christopher Potts, arXiv 2310.03714 (2023). Code at github.com/stanfordnlp/dspy. This is a reading for the lecture Context Evolution of MIT MAS.S62, How to AI an AI for (Almost) Anything. Every idea is re-taught here in our own words and devices.
Every bar is a dev-set accuracy from Table 1 of the paper (300 GSM8K questions; training set 200). Warm is GPT-3.5, blue is llama2-13b-chat. Hollow bars are the compile steps you have not chosen yet. The prompt descriptions follow Section 6 and Figures 9 and 10.
Chapter 0
See why a pipeline of language model calls built from hand-written prompts is hard to move, hard to fix and hard to trust
Picture a small tool that answers hard questions. A user asks, “The Victorians, a documentary series, was written by an author born in what year?” Your tool makes three moves. It rewrites the question as a search query. It looks up passages. Then it writes an answer from those passages.
Two of those moves are calls to a language model. You spend a week on the text of those two calls: you add rules, then examples, then more rules. At last the tool works. Then your team asks you to run it on a cheaper model. Both texts stop working, and you start again.
A language model (LM) takes a string of text and writes more text. One LM call is one trip: you send a string, you get a string back. The string you send is the prompt. A prompt often holds instructions (what to do) and demonstrations (a few worked examples of input and output, pasted in so the model can copy the pattern). Prompts with demonstrations are called few-shot prompts.
A pipeline chains several LM calls, and often a search step too. The output of one call feeds the next. Each call needs its own prompt. Developers usually write each prompt as a prompt template: a long string with blanks that the program fills in for each input.
The authors point at one habit. Almost every pipeline in research code and in popular developer libraries stores its prompts as hard-coded template strings, found by trial and error. They call this brittle and unscalable, and they use one comparison: it is like hand-tuning the weights of a classifier.
Think about what that comparison means. Nobody sets a million weights by hand and calls the result engineering. We write a model with layers, give it data and a loss, and let an optimizer find the weights. The authors ask why prompts should be different. A prompt is a set of numbers we tune, only written in words.
The pain gets worse in a pipeline. One prompt may not carry over to a new model, a new kind of data, or even a new input. In a pipeline there is a fourth way to fail: a change in call one alters what call two receives. Every prompt depends on its neighbours.
The paper backs the claim with a count. In late September 2023 the authors searched the LangChain codebase, a popular library of ready-made chains. They found 50 strings longer than 1,000 characters, mostly prompts, in 12 files named prompts.py and 42 named prompt.py. The DSPy library had none, and it contained no hand-written demonstration for any task. Appendix C lists eight large prompts. Weigh them yourself.
Each yellow bar is one real prompt from Appendix C, measured in characters. The pink sliver at the bottom is the DSPy signature “question -> answer”. Tap a prompt to compare it.
The word and character counts are Appendix C of the paper. The comparison is length only. It says nothing about which prompt works better; the next chapters show what DSPy builds from a signature. The signature “question -> answer” has 18 characters.
Length is not a flaw by itself. The flaw is that this text is the program. When it breaks, you have no part to fix and no test to run. You read a wall of text and guess.
The failure has a measurement. Look at the simplest program in the paper: one call, no examples, the question in and the answer out. On 300 dev questions from GSM8K (a set of grade school math word problems), GPT-3.5 gets 24.0%. The llama2-13b-chat model, a smaller open model, gets 7.0%. Same code, same task, same prompt. The model alone moves the score by a factor of 3.4.
Now the fix the paper tests. Keep the program as it is. Let a search find good demonstrations for each model. The same one-line program climbs to 64.7% and 37.3% after two rounds of the compiler. The hero at the top of this page shows each step. Nobody wrote a prompt.
The paper offers three abstractions. We take one per chapter.
The authors test three claims. H1: concise modules can replace prompt strings without losing quality. H2: treating prompts as something to optimize adapts better to different models, and may beat expert prompts. H3: with modules, you can explore more complex pipelines. Chapters 6 and 7 test them with real numbers.
Chapter 1
Declare the inputs and outputs of one model call, and let DSPy write the prompt skeleton around them
Ask a colleague, “Please translate this page from English to French.” You said what you want. You did not say how to read, how to look up words or how to phrase a sentence. Now imagine the same job written as a 4,000 character memo of rules. That memo is a prompt. The sentence is closer to a signature.
Programmers already know this split. A function type such as def f(question: str) -> str tells you what goes in and what comes out. It does not tell you how the body works. DSPy gives every LM call a type like this.
The paper defines a signature as a natural-language typed declaration of a function: a short spec of what a text transformation must do, rather than how one model should be prompted to do it. Formally it is a tuple of three things.
question, or context and question.answer or search_query.A field is a field name plus optional metadata, such as a short description. The name does real work. The paper says DSPy infers each field’s role from its name. A field called question is treated differently from one called answer, and the compiler refines how it uses each one.
For most uses you write the whole signature as one string with an arrow: inputs on the left, outputs on the right. This is a complete DSPy program.
pythonqa = dspy.Predict("question -> answer") qa(question="Where is Guaraní spoken?") # Out: Prediction(answer='Guaraní is spoken mainly in South America.')
Names carry meaning. DSPy expands english_document -> french_translation into a prompt for English to French translation, because the field names say so. Rename the fields and you change the task.
Where does the prompt come from? DSPy builds a skeleton from the field names. Figures 9 to 11 in the paper show the result. First comes one line that names the fields: “Given the fields question, produce the fields answer.” Next comes a format block with one line per field, each with a label and a blank. Then come the demonstrations, if any, and last the live inputs.
Try it. Type any signature in the box. Watch the skeleton and the shape of the reply.
The box holds a signature. Pink is structure DSPy wrote. Warm is the text the model writes. Try the presets, then try x -> y.
Illustrative layout, simplified from Figures 9 to 11 of the paper. The real library may add or change small details. The answer shown for the first preset is the paper’s own output from Section 3.1.
Look at what the device does with x -> y. The skeleton is still well formed, but the instruction line says only “Given the fields x, produce the fields y.” That is the failure mode. Symptom: the model answers something unrelated. Measurement: the instruction line contains no task words. Fix: name the fields for what they mean, or move to the longer form below.
The paper lists two benefits over a plain prompt string. First, a signature can be compiled into a prompt or a finetune that adapts to the pipeline. Chapter 4 shows how. Second, a signature handles formatting and parsing. The labels in the skeleton are the parsing key. When the model replies, DSPy reads the text after each label and fills the matching output field. Your program never splits strings by hand.
Follow one call to the end. The signature is “question -> answer”. The input is a Python dict with one key: {"question": "Where is Guaraní spoken?"}. DSPy builds the skeleton and ends the prompt with the label Answer:.
The model continues the text. Say it writes “Guaraní is spoken mainly in South America.” DSPy takes that text as the value of the field answer. If the signature had two outputs, such as rationale and answer, DSPy would cut the reply where the second label begins.
The result is a Prediction object. You read the field as pred.answer, a plain string. So the contract is simple: a dict of strings goes in, an object with named strings comes out. No string splitting appears in your program.
When you need more control, write the signature as a Python class (Appendix A). The class docstring becomes the instruction. Each field can carry a short description for the model.
pythonclass GenerateSearchQuery(dspy.Signature): """Write a simple search query that will help answer a complex question.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() query = dspy.OutputField(dtype=dspy.SearchQuery)
The paper is open about one limit. By default every field holds free-form text. Field types such as bool, int, float, list and dict were a work in progress, as in context, question -> answer found: bool. So in this version, a signature promises structure in the prompt, not a checked type in the output.
Chapter 2
Turn a signature into a real model call with Predict, then swap in chain of thought by changing one word
You now hold a signature: “question -> answer”. It is a promise with nothing behind it. Who builds the prompt, calls the model and reads the reply? The paper’s answer is a module: a callable object that implements a signature. Think of a PyTorch layer. You declare it once, then call it like a function.
A module is also where learning lives. In PyTorch a layer holds weights. In DSPy a module holds parameters that are not numbers but pieces of a prompt. This chapter shows what they are and why they are the right ones to learn.
Predict is the module all others build on. Inside it keeps three things: the signature, an optional LM to use (empty means “use the default”), and a list of demonstrations, empty at first. The paper gives pseudocode in Appendix D.1. Here it is, trimmed.
pythonclass Predict(dspy.Module): def __init__(self, signature, **config): self.signature = dspy.Signature(signature) self.config = config self.lm = dspy.ParameterLM(None) # parameter 1: which model self.demonstrations = dspy.ParameterDemonstrations([]) # parameter 3: the examples def forward(self, **kwargs): prompt = self.signature(demos=self.demos, **kwargs) # skeleton + demos + live inputs completions = lm.generate(prompt, **self.config) # list of strings prediction = Prediction.from_completions(completions, signature=self.signature) if dsp.settings.compiling is not None: # Chapter 4 uses this dspy.settings.traces.append(dict(predictor=self, inputs=kwargs, outputs=prediction)) return prediction
Walk one call through it. You write qa(question="Where is Guaraní spoken?"). The keyword arguments become kwargs, a dict with one string. Predict picks the LM, the signature and the demonstrations (none yet). It builds one prompt string: the skeleton from Chapter 1 plus the live question. The LM returns completions, a list of strings; usually it holds one. Predict parses it into a Prediction object with an answer field. If the compiler has switched on compile mode, Predict also saves the input and output as a trace. Remember the trace. Chapter 4 needs it.
The paper says any LM call has three things you could tune. One: which LM to call. Two: the instructions and the label text for each field. Three: the demonstrations, used as few-shot examples for a frozen model or as training data to finetune one.
Picture a mixing board with three sliders. DSPy mostly moves the third. The authors find that bootstrapping good demonstrations is a strong way to teach a pipeline new behavior. Why? Demonstrations show a model the exact format and the style of reasoning you want, in the model’s own words.
Chapter 4 shows how demonstrations are found. Here is what they do to a prompt. Figure 10 of the paper shows a ChainOfThought prompt for GSM8K after compiling. It starts with the instruction line. Then it shows the format: Question, Reasoning, Answer. Then come several demonstrations, each with all three fields filled in.
One demonstration is about Mark baking bread. The reasoning reads, “he needs to let it rise for 120 minutes twice, so that’s 240 minutes”, and ends with the answer 280. The live question goes last, with Reasoning and Answer left blank. The model copies the pattern: it reasons in the same style, then answers. This is why the list of demonstrations is the most useful parameter. It teaches format and style in one move.
Now the payoff. Other modules take a signature and wrap Predict. ChainOfThought adds one new output field at the front, a rationale (the model’s written reasoning), then calls Predict on the longer signature. That is the whole trick, in the paper’s own code.
pythonclass ChainOfThought(dspy.Module): def __init__(self, signature): # from `*inputs -> *outputs` to `*inputs -> rationale, *outputs` rationale_field = dspy.OutputField(prefix="Reasoning: Let's think step by step.") signature = dspy.Signature(signature).prepend_output_field(rationale_field) self.predict = dspy.Predict(signature) def forward(self, **kwargs): return self.predict(**kwargs)
Why does a field at the front help? A model writes one token at a time, and each token can use all the tokens before it. If the reasoning comes first, the answer can lean on it. If the answer comes first, the model must guess. The device below shows the new shape and the effect.
The signature stays “question -> answer”. Choose a module and watch the call change shape. The bars below are Table 1 with no compiling and no examples.
Accuracies are GSM8K dev numbers from Table 1 (rows with compilation none). The diagram follows the module code in Section 3.2 and Section 6. Reflection samples five reasoning chains and compares them with MultiChainComparison.
Read the bars. Adding a rationale lifts GPT-3.5 from 24.0% to 50.0%, a gain of 26.0 points. It lifts llama2-13b-chat from 7.0% to 26.7%, a gain of 19.7 points. Nobody wrote a reasoning prompt. The module expanded the signature and Predict did the rest.
DSPy ships more. ProgramOfThought has the model write code and runs it. MultiChainComparison reads several reasoning attempts and writes a final answer from the patterns it sees. ReAct lets the model act with tools in a loop. Each one generalizes a published technique, and each takes any signature. The authors say all of them are a few lines that expand the signature and call Predict one or more times.
Tools are modules too. dspy.Retrieve calls a search index and returns passages. It has built-in support for ColBERTv2, Pyserini and Pinecone. The paper also mentions experimental modules to run SQL and Python in a sandbox.
dspy.Predict("question -> answer") to dspy.ChainOfThought("question -> answer"). What exactly changes inside DSPy?Chapter 3
Wire modules into a pipeline with loops and variables, and count exactly how many calls it makes
Take the question from Chapter 0: “The Victorians, a documentary series, was written by an author born in what year?” One search is not enough. The first search finds the series. Only then do you know to search for its author. A pipeline for this question needs a loop: ask, look up, ask again.
The paper calls the thing you build a program. Programs are ordinary Python. The authors say they are inspired by PyTorch and Chainer, and they call the style define-by-run: the graph of steps is defined by running your code, not by drawing boxes in advance.
First, in __init__, you create the modules you need and store them on self. This lets DSPy find every module later, so the compiler can tune them. Second, in forward, you write the pipeline with any Python you like: if, for, try and except. The result is what the authors call a text transformation graph: an imperative computation graph where LMs are called through declarative modules.
The simplest useful program is retrieval-augmented generation (RAG): look up passages first, then answer from them. Here it is, from Section 3.2.
pythonclass RAG(dspy.Module): def __init__(self, num_passages=3): self.retrieve = dspy.Retrieve(k=num_passages) self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = self.retrieve(question).passages # list of 3 strings return self.generate_answer(context=context, question=question)
Follow the data. question is a string. retrieve sends it to a search index and returns passages, a list of k=3 strings. Those go into generate_answer as the context field. The module writes a rationale and an answer. To use it you write RAG()("Where is Guaraní spoken?"). Swap ChainOfThought for Predict and the program still runs. Change the signature to "context, question -> search_query" and the same program writes search queries instead.
It may look odd to create modules in __init__ and call them later. There is a reason. The compiler must find every module in your program, so it can attach demonstrations to each. A module stored on self can be found. A module made fresh inside forward on every call cannot.
PyTorch works the same way: layers are declared once, and the forward pass uses them. The big gain is freedom. Because forward is ordinary Python, you can print a value, set a breakpoint, or branch on a result. You do not learn a graph language. The authors credit Josh Purtell for the name “text transformation graph”.
RAG searches once, with the user’s own words. For the Victorians question that finds the series but not its author. Section 7 adds a loop. This program imitates the flow of earlier systems called Baleen and IRRR.
pythonclass BasicMultiHop(dspy.Module): def __init__(self, passages_per_hop): self.retrieve = dspy.Retrieve(k=passages_per_hop) self.generate_query = dspy.ChainOfThought("context, question -> search_query") self.generate_answer = dspy.ChainOfThought("context, question -> answer") def forward(self, question): context = [] for hop in range(2): query = self.generate_query(context=context, question=question).search_query context += self.retrieve(query).passages return self.generate_answer(context=context, question=question) multihop = BasicMultiHop(passages_per_hop=3)
Trace the Victorians question. Hop one starts with an empty context. The query module writes a search query from the question alone. The search returns three passages: one about a documentary series called The Victorians, one about an 1849 novel called The Caxtons, and one about a comic called The Victorian. Now context holds three strings.
Hop two shows the loop paying off. Those three passages go back into the same query module. In Figure 11 of the paper, the model reasons that the series “was written and presented by Jeremy Paxman. Therefore, we need to find the year in which Jeremy Paxman was born.” It writes the query Jeremy Paxman birth year. Three more passages arrive, and context grows to six. Last, the answer module reads all six passages and the question.
Programs are easy to write and easy to overspend. Count for the program above. There are 3 modules declared, and 2 of them call an LM. Yet there are 3 LM calls at run time: two queries and one answer. The same generate_query module runs twice. That detail matters in Chapter 4: one module means one list of demonstrations, shared by both hops.
Now let the numbers move. With h hops and k passages per hop, the program makes h + 1 LM calls, h searches, and the final prompt holds h × k passages.
Each pink tile is a model call. Each gray tile is a search. The yellow squares are passages in the context. The paper uses 2 hops of 3 passages.
Counts follow the BasicMultiHop code in Section 7: one query call and one search per hop, then one answer call. They are exact for that code. Real systems may add retries or other steps. The paper does not report cost per call.
Push hops to 4 and passages to 5. The final prompt now carries 20 passages, and you paid for 5 model calls. More hops can find more facts, but each one also adds text the final call must read. The program is yours to tune, and soon the compiler will tune it too.
One last point from Appendix B. Libraries like LangChain and LlamaIndex offer pre-packaged chains and tools. DSPy offers the small core operators instead: signatures, modules and teleprompters. Its program is just code that chains modules.
generate_query runs once per hop. How many separate lists of demonstrations can the compiler learn for it?Chapter 4
Run the program on training questions, keep the runs that end well, and use every step of those runs as a demonstration
Suppose you have 200 math questions with the right final number for each. You want a good few-shot prompt for the answer module. Easy: write out the reasoning for a few questions by hand. Now do it for the multi-hop program. You also need search queries for each hop, and you have none. Nobody labeled them. Nobody will.
The paper’s answer is the oldest trick in the book: let the machine try, and keep what works. The program runs on a training question. If its final answer is right, then the steps it took to get there are probably decent examples. Save them. This is bootstrapping: using a system’s own good outputs to improve it.
A teleprompter is an optimizer for DSPy programs. Its compile method takes three things and returns a new program.
The metric is where you put your goals. The paper gives one example. To push the RAG program to answer only from its sources, add a test: the answer must match and appear inside a retrieved passage.
pythondef answer_and_context_match(example, pred, trace=None): answer_match = dspy.evaluate.answer_exact_match(example, pred) context_match = any((pred.answer.lower() in c) for c in pred.context) return answer_match and context_match
Appendix E.1 gives the simplest teleprompter, BootstrapFewShot, in about 20 lines. In plain words it does this.
This is rejection sampling. You draw many tries and reject the bad ones. The same rule can be written in one line.
Take the CoT program on GSM8K. Training question: “Mark is baking bread. He has to let it rise for 120 minutes twice. He also needs to spend 10 minutes kneading it and 30 minutes baking it. How many minutes does it take Mark to finish making the bread?” The label is 280.
Step 1: the teacher runs with the zero-shot prompt. Step 2: the one trace has inputs {question: "Mark is baking bread..."} and outputs {rationale: "...120 minutes twice, so that’s 240 minutes. Then ... 240 + 10 + 30 = 280", answer: "280"}. Step 3: the metric extracts the final number, 280, and compares it with the label 280. It passes. Step 4: DSPy stores the trace as a demonstration with the flag automated=True. This is exactly the demonstration shown in Figure 10 of the paper. Had the answer been 260, the trace would be dropped.
Notice what the paper says about it. No one wrote that reasoning chain. The model wrote it, and a number check approved it.
The device runs this loop on a toy training set. The program is the two-hop one from Chapter 3, so the query module is called twice per run and fills twice as fast. Slide the pass rate and step through.
Each square is a training example. Press Step to run one. Green means the metric passed, so its traces become demonstrations (purple). Red means the traces are thrown away.
Illustrative toy. The outcomes come from fixed random numbers compared with your pass rate, so they are the same on every visit. Each module keeps at most 4 demonstrations here; the real limit is a setting. The paper’s rule is the same: run, test the final answer, keep the traces.
Slide the pass rate to 10% and run all twelve. You may get one passing run, or none. That is the failure mode. Symptom: the compiled program is no better than the zero-shot one. Measurement: the count of demonstrations is zero or tiny. Fix: use a stronger teacher, split the task into easier modules, or add more training questions. The paper puts it this way: a well-decomposed program can usually find at least a few training examples that pass.
Two more facts. The teacher may run several times on one example at a high temperature to get variety. And a teacher can be a bigger, costlier program than the student, so an expensive system supervises a cheap one.
Chapter 5
Pick the best set of demonstrations by trying many, then vote across programs or distill them into a small model
Chapter 4 gave you a pile of passing traces. Each module can use any few of them. Does it matter which few? It does. One set of examples may teach the format well, and another may mislead. You have no way to know in advance. So you try several and keep the one that scores best.
The paper splits a compile into three stages. Stage 1 made candidates. Stages 2 and 3 choose among them and go beyond them.
Now every module has a discrete set of options: a finite list of demonstrations, and maybe a few instruction strings. Picking from a finite list is a standard job called hyperparameter tuning, and standard tools do it. The paper names random search and tree-structured Parzen estimators (a method that learns from past trials which settings to try next), as in HyperOpt and Optuna.
The simplest tool is random search. Appendix E.2 shows it in 15 lines. In plain steps:
The Optuna version (Appendix E.3) replaces blind shuffling with a smarter search. Each trial picks one demonstration index per module with trial.suggest_int, and Optuna learns from past scores which indices to try next.
Scores on a validation set are noisy. A candidate can rank first because it is good, or because it got easy questions. The more trials you run, the more likely the top score includes luck. Then the winner scores a bit lower on fresh data. This is why the paper tunes on a dev set and reports on a separate test set, and says it compares widely on dev “to avoid overfitting on test”. Try it.
Each purple dot is a candidate program’s score on the dev set. The green line is the best score so far. The hollow ring is how the winner scores on fresh test data. Slide the trials, then roll new candidates.
Illustrative simulation, not from the paper. Each candidate has a true quality near 62% and its dev and test scores add independent noise of a few points. The number of trials, 16, is the default in Appendix E.2.
Roll a few times at 16 trials. The best dev score usually sits above the winner’s test ring. The extra trials bought a better pick, but part of the apparent gain is noise. That is the reason a clean held-out test matters.
Sometimes zero-shot is so weak that the first round finds almost no passing traces. The fix is to bootstrap twice. The compiled program from round one becomes the teacher for round two. In the paper, for the one-call program with GPT-3.5, the dev score goes from 24.0% with no compiling, to 44.0% after one round, to 64.7% after two. Look back at the hero: the program code never changed.
The last stage edits the program itself. The paper’s example is an ensemble: bootstrap several copies of one program, run them in parallel, and combine their outputs with a reducing function. The usual function is a majority vote.
Worked example. Seven compiled copies answer a GSM8K question: 18, 18, 14, 18, 26, 18, 14. The vote counts 18 four times, 14 twice and 26 once. The ensemble returns 18. The code is one line: Ensemble(reduce_fn=dspy.majority).compile(bootstrap.programs[:7]).
Voting is not free. It costs seven runs per question. It also does not always help. For the CoT program with GPT-3.5, the ensemble lifts dev accuracy from 80.3% to 88.3%. For the one-call program it goes from 64.7% to 62.7%, a small drop. Chapter 6 reads those rows in full.
So far the model stayed frozen. BootstrapFinetune uses the same demonstrations as training data and updates the model’s weights for each module. Teachers make this powerful. You can compile an expensive program first, then use it as the teacher for a small model. The paper shows one: a compiled RAG program on llama2-13b-chat supervises a finetune of Flan-T5-large, using unlabeled questions. A metric that filters ungrounded answers replaces the missing labels. Chapter 7 gives the result.
Cost check. A compile does not take hours. The paper says even its pricier settings run the program only a few thousand times, for example 10 to 20 trials over 150 to 300 validation examples, and the runs can go in parallel. That is minutes to tens of minutes.
Chapter 6
Read Table 1 row by row, and see which compile steps beat an expert’s hand-written reasoning
You built a machine. Now test it. What result would convince you? The authors chose their test with care. They did not try to beat every record. They asked whether the machine can replace the hand-written prompt: can short programs, compiled, match or beat what experts write, on more than one model?
The task is GSM8K: grade school math word problems, each with one numeric answer. The authors sample 200 questions from the official training set to train, and 300 more to tune on (the dev set). The final test uses the 1,300 official test questions. The metric is simple: does the last number in the model’s output equal the right number?
Two models are used: GPT-3.5, a large proprietary model, and llama2-13b-chat, a smaller open model. Three programs run on each, from Chapters 2 and 3: vanilla (Predict), CoT (ChainOfThought) and reflection (five chains, then a comparison). The compile steps come from Chapter 5. fewshot pastes 8 random training pairs, with the question and answer only. bootstrap is bootstrapping with random search. bootstrap×2 nests it once. +ensemble votes over the top 7 programs. +human CoT uses few-shot examples that include the human-written reasoning from GSM8K itself.
Use the device. Choose a model and a split, and watch the bars.
One bar per row of the table. Choose the model and the split. The small tick on a bar marks the same row on the other split. A dashed stub means the paper prints a dash.
All values are Table 1 of the paper, exact. The paper prints a dash where a row was not run on that split. The Reflection group has four rows because it has no bootstrap×2 or human CoT row.
One detail guards against luck. For the few-shot rows, the authors report the average of 3 to 5 runs, because each run samples different random examples. A single draw could look good or bad by chance. The compiled rows come from a search over many candidates, so they already include that variation.
One. Random examples barely help. Eight random question and answer pairs lift GPT-3.5 on the CoT program from 50.0% to 63.0%. On the Predict program with llama2-13b-chat the same step lowers the score from 7.0% to 4.3%. Examples with no reasoning teach little.
Two. Bootstrapping matches the expert. The hand-written human reasoning chains lift CoT on GPT-3.5 to 78.6% on dev and 72.4% on test. Bootstrapped demonstrations, which no human wrote, reach 80.3% and 72.9%. On llama2-13b-chat the gap is larger: 43.3% against 34.3% on dev. This is hypothesis H1 and H2 in one row. The paper says it “substantiates our hypothesis that DSPy can cut the need for hand-crafted prompts”.
Three. A few more lines of program beat a better prompt. Reflection, only a few lines longer than CoT, wins with a single bootstrap: 83.0% and 44.3% on dev. The authors read that as support for H3: modular programs let you explore designs cheaply.
Four. Bootstrap twice when zero-shot is weak. The Predict program improves from 33.1% (few-shot) to 44.0% (bootstrap) to 64.7% (bootstrap×2) on GPT-3.5. A look at the bootstrapped prompt in Figure 9 explains why. The model learned to write its reasoning inside the answer field. The metric only reads the last number, so that is allowed.
Five. Ensembles help, but not always. CoT on GPT-3.5 rises from 80.3% to 88.3% on dev. Predict on GPT-3.5 falls from 64.7% to 62.7%, and on the test set llama2-13b-chat falls from 36.5% to 34.6%. Voting only helps when the programs make different mistakes.
Here is a check you can do with the table. For GPT-3.5, human CoT drops from 78.6% on dev to 72.4% on test, which is 6.2 points. Bootstrap drops 7.4 points (80.3% to 72.9%). Reflection with bootstrap drops 7.0 points (83.0% to 76.0%). The ensemble drops 6.7 points (88.3% to 81.6%). Every row loses about 6 to 7 points. The dev set was used to choose, so it flatters every row alike. Chapter 5 told you why. The comparisons between rows still hold. Compare rows on the same split.
The caption of Table 1 sums it up: compiling modules, instead of string prompts, improves these models from 4% to 20% accuracy up to 49% to 88% accuracy. The range is the authors’ own summary. For exact numbers, read the rows.
The authors compare with other papers, and they warn the comparisons are informal. A few anchors: Wang et al. report 57% for chain of thought on PaLM 540B, and 74% with self-consistency. The Llama 2 authors report 28.7%, 42.2% and 56.8% for the 13b, 34b and 70b models. The DSPy program on the 13b model is competitive with their 34b result, and uses no human reasoning chains. The GPT-4 report gives 57.1% for GPT-3.5 and 92% for GPT-4, and notes GPT-4 saw part of the GSM8K training set while training.
Chapter 7
Read Table 2, see why the loop beats a single search, and watch a 770 million parameter model learn the whole program
Math problems carry all their facts inside the question. Real questions often do not. “The Victorians was written by an author born in what year?” needs a search, and then a second search that depends on the first. The second case study tests DSPy on exactly this, with HotPotQA, a set of multi-hop questions: each needs facts from two separate documents.
The authors use the open-domain “fullwiki” setting. There is no document given. The program must search a Wikipedia dump (the 2017 abstracts) with a retriever called ColBERTv2. The test set of HotPotQA is hidden, so the official validation set serves as the test, and the authors sample 1,000 questions from it. They split the training set into 70% to train and 30% to tune, keep only the questions marked “hard” (the kind in the official validation and test sets), and sample 200 to train and 300 to tune on.
Two scores appear. Ans is answer exact match: the answer string equals the label. Psg is pair-retrieval accuracy, a measure of whether the search found the pair of passages the question needs.
Four programs compete. vanilla is the one-line Predict from before. CoT RAG is the program from Chapter 3: one search with the original question, then one answer. react is dspy.ReAct("question -> answer", tools=[dspy.Retrieve(k=1)], max_iters=5): an agent that decides when to search, up to 5 times. multihop is BasicMultiHop from Chapter 3: two hops of three passages.
One bar per row. Pick the model, the split and the score. The dashed line marks the compiled T5-Large program, which the paper reports on the dev set only.
Values are Table 2 of the paper. The paper prints a dash where a row was not run. The GPT-3.5 multihop ensemble test value, 45.6, was measured on 50% of the test set because of cost. T5-Large: 39.3 Ans and 46.0 Psg on dev.
A single search is the bottleneck. With bootstrapping, CoT RAG reaches 42.3% Ans on GPT-3.5 dev. Its Psg stays at 36.0% whatever you compile, because it depends on one search with the original question. The compiler can only improve how the program reads passages, not which passages it gets.
The loop fixes the retrieval. The multihop program writes a new query after seeing the first passages. With bootstrapping on GPT-3.5, Psg jumps from 36.0% to 47.0%, and Ans from 42.3% to 48.7%. For llama2-13b-chat, Psg goes from 36.0% to 48.3%.
Compile steps stack. For multihop on GPT-3.5 dev, few-shot gives 36.9%, bootstrap gives 48.7% (+11.8 points) and the ensemble gives 54.7% (+6.0 more). For llama2-13b-chat the same steps give 34.7%, 42.0% and 50.0%. Both models gain 15 to 18 points from compiling alone.
Bootstrapping is not magic. For react on GPT-3.5, one round of bootstrapping scores 31.0%, below the expert-written reasoning (33.0%). A second round, bootstrap×2, scores 39.0% and passes it. Single rounds do not always win. Nesting rescued the agent.
A small model catches up. The paper says compiling makes llama2-13b-chat competitive with GPT-3.5. Check the rows. On dev, compiled llama2-13b-chat multihop (42.0% bootstrap, 50.0% ensemble) beats GPT-3.5 with only few-shot examples (36.9%), and its ensemble beats GPT-3.5 bootstrap (48.7%). On react×2, llama2-13b-chat scores 40.0% against 39.0%.
Figure 11 of the paper shows a prompt for the second-hop query, written by the compiler with llama2-13b-chat. It starts with the instruction “Given the fields `context`, `question`, produce the fields `search query`.” Then it shows two demonstrations. Each has a Context of three numbered passages, a Question, a Reasoning line and a Search Query.
In one, the question asks about the author of a documentary series. The reasoning notes the series was presented by Jeremy Paxman, so the next step is his birth year. The query is “Jeremy Paxman birth year”. A model that reads this example learns the whole move: read the passages, name what is missing, search for exactly that. No person wrote it. It came from a run that ended with a right answer.
The last result uses Chapter 5’s finetuning. The teacher is an ensemble (a union) of two multihop programs on llama2-13b-chat. The student is T5-Large, a model of 770M parameters, about 17 times smaller than the 13B teacher. Training used only 200 questions with labels and 800 without. Yet the compiled T5-Large program reaches 39.3% Ans and 46.0% Psg on dev. The authors note its inference would cost orders of magnitude less than a proprietary model.
Compare it on dev. 39.3% beats the bootstrapped react program on GPT-3.5 (31.0%) and the few-shot multihop program on GPT-3.5 (36.9%). The teacher’s pipeline was copied into a small model. No one wrote a prompt, and no one labeled a search query.
Again the authors line up other results and warn that methods and test samples differ. Chain of thought gets 25.2% EM in Si et al. Self-consistency on PaLM 540B gets 33.8% EM and 44.6% F1. ReAct on PaLM 540B gets 27.4%, and 30.8% with text-davinci-002. Trivedi et al. report 49% on a sample of 500 questions with code-davinci-002. So the best DSPy rows land in the same range as strong published pipelines, using prompts nobody wrote.
Chapter 8
Check the three claims against the evidence, learn how a weak metric spoils a compile, and list what the paper leaves open
You now know the whole machine. Before you build one, ask what the paper proves and what it does not. A good reader checks three things: did each claim get a fair test, what can break in practice, and what did the authors choose not to measure?
Chapter 0 listed three hypotheses. The paper has no separate ablation table. Its ablation is the ladder of compile steps in each table, where each row adds one part. Here is the evidence, row by row.
| Claim | Evidence in the paper | Fair reading |
|---|---|---|
| H1: modules replace prompt strings | Bootstrapped CoT matches or beats human reasoning chains: 80.3% against 78.6% on dev, 72.9% against 72.4% on test (GPT-3.5, GSM8K). | Supported on this task. The test margin is 0.5 points, so treat it as a tie. |
| H2: optimizing adapts to each model | Both models gain a lot from compiling overall, though single steps can lose (few-shot on llama2-13b-chat Predict, 7.0% to 4.3%). llama2-13b-chat gains 9.0 dev points over human CoT (43.3% against 34.3%). | Supported on two models. The paper tests no other family. |
| H3: modularity lets you explore designs | Reflection beats CoT on GSM8K. Multihop beats CoT RAG on HotPotQA, 48.7% against 42.3% Ans on GPT-3.5 dev. | Supported. Note the designs were chosen by the authors, not searched by the system. |
Now compare the ladder on one program, CoT with GPT-3.5 on dev. No compiling scores 50.0%. Random few-shot adds 13.0 points (63.0%). Bootstrapping adds 17.3 more (80.3%). The ensemble adds 8.0 more (88.3%). Together that is 38.3 points. Bootstrapping is the largest single step. This is the closest thing the paper has to an ablation.
A compile can only be as good as its metric. The compiler keeps whatever passes. If the test is loose, bad habits pass too and become demonstrations. This is the main thing that can go wrong in practice. Symptom: the compiled program writes answers that are hedged or made up. Measurement: look at the demonstrations the compile kept. Fix: tighten the metric. The paper gives a fix for RAG: require the answer to appear in a retrieved passage.
Try three metrics on eight toy traces.
Eight runs of a RAG program on training questions. Pick a metric. Green rows pass and become demonstrations. Notice which ones you would not want to teach.
Illustrative toy traces, not from the paper. The first two metrics follow the paper’s answer_exact_match and answer_and_context_match from Section 3.3. The loose metric is our own contrast.
Under exact match, four runs pass. One of them, the 1950 answer, was a guess from memory: it matched but no passage held it. Under the grounded metric that run drops out, so three demonstrations remain, all backed by text. Under the loose metric the hedge “Paris or Lyon” passes, and the model learns to hedge. The paper says such checks can be whole DSPy programs and encourages them.
bool or int were a work in progress. Fields are free text by default.One more fair point. The hardest part of using DSPy is not the library. It is writing a good metric and a good decomposition. The compiler removes prompt writing. It adds metric writing. That is a better trade, because a metric can be tested and a prompt cannot.
If you reproduce the idea on your own task, three checks from the tables tell you whether the machine works. They are rules of thumb from this paper, not laws.
If a check fails, look at the metric and the split before you blame the idea.
Chapter 9
Keep the numbers, the terms, a checklist and the core code on one page, and find where to go next
DSPy says three things. Describe each model call by its inputs and outputs, as a signature. Build the pipeline from modules inside ordinary Python. Then let a compiler find the demonstrations, per model, by running the program and keeping the runs that pass a metric. On two case studies this beat hand-written reasoning, lifted a 13 billion parameter model close to a larger one, and trained a 770 million parameter model to run the whole program.
| What | Number | Where |
|---|---|---|
| GSM8K split | 200 train, 300 dev, 1,300 test | Section 6 |
| HotPotQA split | 200 train, 300 dev, 1,000 test (from the official validation set) | Section 7 |
| Random demonstrations (fewshot) | k = 8 | Section 6 |
| Random search trials, ensemble size | 16 trials by default; top 7 programs vote | Appendix E.2, Section 6 |
| CoT, GPT-3.5, GSM8K dev | 50.0% none, 63.0% fewshot, 80.3% bootstrap, 88.3% ensemble | Table 1 |
| Predict, llama2-13b-chat, GSM8K dev | 7.0% none, 28.0% bootstrap, 37.3% bootstrap×2 | Table 1 |
| Reflection, GPT-3.5 / llama2, GSM8K dev | 83.0% / 44.3% bootstrap; 86.7% / 49.0% ensemble | Table 1 |
| multihop, GPT-3.5, HotPotQA dev Ans | 36.9% fewshot, 48.7% bootstrap, 54.7% ensemble | Table 2 |
| multihop, llama2-13b-chat, dev Ans | 34.7% fewshot, 42.0% bootstrap, 50.0% ensemble | Table 2 |
| Compiled T5-Large (770M) | 39.3% Ans, 46.0% Psg on dev; 200 labeled and 800 unlabeled questions | Section 7 |
| Long strings in LangChain | 50 strings over 1,000 characters; none in DSPy | Appendix B |
| Compile cost | A few thousand program runs: minutes to tens of minutes | Section 6 |
| Term | Meaning |
|---|---|
| Signature | A declaration of a call: input fields, output fields, an optional instruction. |
| Module | A callable that implements a signature, such as Predict or ChainOfThought. |
| Demonstration | An input and output example pasted into a prompt. The main parameter DSPy learns. |
| Trace | The saved inputs and outputs of one module call during a compile run. |
| Metric | A function that scores a final result. It decides which traces count. |
| Teleprompter | An optimizer: program, training set and metric in, better program out. |
| Student and teacher | The program being compiled, and the program whose runs supply the traces. |
| Bootstrap | Collect demonstrations from the program’s own passing runs (rejection sampling). |
| Text transformation graph | A program in which modules call language models, wired with ordinary code. |
forward with plain Python. Count the model calls.The idea fits in about 45 lines. This is our own minimal version, not the library. It has a signature parser, a Predict that builds the prompt and saves traces, and a bootstrap loop. We ran it with a stub model that adds two numbers, and it fills four demonstrations from six training examples.
pythonimport copy, random TRACE = None # set to a list while compiling class Predict: def __init__(self, sig, lm): left, right = sig.split("->") self.ins = [s.strip() for s in left.split(",")] self.outs = [s.strip() for s in right.split(",")] self.lm, self.demos = lm, [] # demos: the parameter we learn def block(self, vals, fields): return "\n".join(f"{k.title()}: {vals[k]}" for k in fields if k in vals) def prompt(self, **kw): head = f"Given the fields {', '.join(self.ins)}, produce the fields {', '.join(self.outs)}." shown = [self.block(d, self.ins + self.outs) for d in self.demos] live = self.block(kw, self.ins) + f"\n{self.outs[0].title()}:" return "\n---\n".join([head] + shown + [live]) def __call__(self, **kw): text = self.lm(self.prompt(**kw)) out, rest = {}, self.outs[0].title() + ":" + text for i, name in enumerate(self.outs): # split the reply at the field labels tag = name.title() + ":" nxt = self.outs[i + 1].title() + ":" if i + 1 < len(self.outs) else None part = rest.split(tag, 1)[1] if nxt and nxt in part: part, rest = part.split(nxt, 1)[0], nxt + part.split(nxt, 1)[1] out[name] = part.strip() if TRACE is not None: TRACE.append((self, kw, out)) return out def bootstrap(program, trainset, metric, max_demos=4): global TRACE student = copy.deepcopy(program) # the copy receives the demos for ex in trainset: TRACE = [] try: pred = program(**ex["inputs"]) finally: traces, TRACE = TRACE, None if metric(ex, pred): # keep the traces of good runs for p, ins, outs in traces: mate = student.preds[program.preds.index(p)] if len(mate.demos) < max_demos: mate.demos.append({**ins, **outs}) if all(len(p.demos) >= max_demos for p in student.preds): break return student
Read it against the chapters. The signature string becomes ins and outs (Chapter 1). demos is the parameter, and prompt assembles the skeleton, the demonstrations and the live inputs (Chapter 2). TRACE is the switch for compile mode. bootstrap runs the program, applies the metric and copies each passing trace into the matching module of the student (Chapter 4). A random-search wrapper would call bootstrap with shuffled data and score each result (Chapter 5).
This reading belongs to the course lecture Context Evolution of MIT MAS.S62. DSPy’s demonstrations are a piece of context that a program learns for itself. The next lecture, LLMs as Optimizers, goes on to systems where a model proposes the changes.
Now press Teach and explain the compile loop from memory: what a signature declares, what Predict saves while compiling, why a passing run supplies the demonstrations, and why the winner of a search scores lower on fresh data. Then go back to the instrument at the top, compile the reflection program, and say which chapter explains each bar.