DSPy: compiling declarative LM calls into self-improving pipelines
arXiv ↗PDF ↗Paper ↗Website ↗Code ↗
Read first: Demonstrate-Search-Predict (DSP): composing retrieval and LMs
TL;DR. DSPy treats an LM pipeline like a neural network:
- Modules (
Predict,ChainOfThought,ReAct, …) have declarative signatures likequestion -> answer. - The program is ordinary Python control flow.
- An optimizer (first called a teleprompter) tunes each module’s prompt, demonstrations or weights to maximise a metric on the final output.
Why it matters now. “Programs with learnable prompts” is the standard framing for compound AI systems, and later work optimizes against the same abstraction: MIPROv2, BetterTogether, GEPA. For search, a multi-hop RAG pipeline becomes ten lines of code plus an optimizer.
One compilation, traced
Section titled “One compilation, traced”An illustrative run of BootstrapFewShot on a two-hop program (generate_query twice, then answer), with the three data roles kept apart:
| Data | Used for | Touched by the optimizer? |
|---|---|---|
| trainset (question, answer) | running the teacher program to bootstrap demonstrations | yes |
| valset | scoring and choosing among candidate demo sets (random-search variants) | yes, for selection only |
| test set | the reported number | no |
- Run the teacher on a training example. Question: Which country is the birthplace of the director of film X?
generate_query(hop 1) writes director of film X; the retriever returns a passage naming director D.generate_query(hop 2) writes D birthplace; the retriever returns D’s biography.answeroutputs the country. - Score the final output. The metric compares the answer with the gold label. Only the final answer is labelled; neither query is.
- Extract demonstrations. Because the run passed, each module’s own input and output are saved as a demo for that module: hop-1 query, hop-2 query and the answer step each get one example. A failed run contributes nothing.
- Repeat until enough demos, then (in the random-search variant) build several candidate demo sets and keep the one that scores best on the valset.
- Report on the test set, which neither bootstrapping nor selection saw.
This is why bootstrapped demos can teach query writing without query labels (the mechanism question below), and why most compile cost is validation (the derive question). The twice-bootstrapping result is in Table 2’s ReAct rows (HotPotQA dev answer EM): the second round runs BootstrapFewShotWithRandomSearch starting from the round-1 bootstrapped program, and moves GPT-3.5 from 31.0 to 39.0. (For HotPotQA the paper uses the training set itself, not dev, for selection, so the train/selection split above is the general pattern, not that exact setup.) These are the paper’s historical teleprompters; the current library’s optimizers (MIPROv2, GEPA) run the same train-then-select pattern with different search procedures.
Limitations and open questions
Section titled “Limitations and open questions”- Optimization costs many LM calls, and results vary with the training split and the metric.
- The metric is everything: a weak metric gives brittle programs.
- When should you optimize prompts and when weights? See BetterTogether and GEPA vs. GRPO.
Hands-on
Section titled “Hands-on”- dspy.ai tutorials: build a multi-hop RAG program with a ColBERTv2 retriever and compile it with
BootstrapFewShot, thenMIPROv2.
Connections
Section titled “Connections”- Before: DSP, Baleen, ReAct.
- After: DSPy Assertions, MIPROv2, BetterTogether, GEPA, STORM (built with DSPy), Recursive Language Models.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Derive / compute
You compile a DSPy BasicMultiHop program (two query generators and one answer module: 3 LM calls and 2 retrievals per run) with BootstrapFewShotWithRandomSearch. It runs 16 candidate trials; each bootstraps up to 4 successful traces from a shuffled trainset and is then scored on 300 validation examples. If the teacher succeeds on 40% of training examples, estimate the program runs, LM calls and retrievals. Which phase dominates, and how would you cut it?
What a strong answer covers
- Bootstrapping per trial needs about 4 / 0.4 = 10 training runs, because it stops once it has enough successes. Validation per trial is 300 runs. Total ≈ 16 × 310 = 4,960 program runs.
- LM calls ≈ 4,960 × 3 ≈ 14,900 and retrievals ≈ 4,960 × 2 ≈ 9,900. This matches the paper's estimate of a few thousand program runs (10–20 trials over 150–300 validation examples).
- Validation is about 97% of the cost, so bootstrapping is cheap and selection is expensive.
- Each successful trace gives one demo to each of the 3 predictors, so 4 traces yield 12 demos with no hand-labelled queries.
- To cut cost: use a smaller validation set or minibatch scoring with occasional full evaluation (as MIPROv2 does), run fewer trials, cache repeated calls, and stop weak candidates early.
- Mechanism
On HotPotQA with GPT-3.5, the multihop program goes from 38.3 to 47.0 passage accuracy when labelled question–answer demos are replaced by bootstrapped demos, even though neither setting has labels for search queries. What does a bootstrapped demonstration carry that a labelled pair does not, and when can it teach the wrong behaviour?
What a strong answer covers
- A labelled pair shows only the question and the final answer, so the query-generation modules never see an example of a good search query.
- A bootstrapped trace stores each predictor's own inputs and outputs from a run that passed the metric, so every module gets in-context examples of its own step, including first- and second-hop queries.
- The metric acts as weak supervision for intermediate steps: queries that led to a correct answer are kept, others are dropped.
- Risk: a run can pass with a useless intermediate step (the answer came from memory, or matched by luck), teaching bad queries. DSPy Assertions later added backtracking in the teacher for this reason.
- The metric receives the trace, so it can be tightened, for example by also requiring the retrieved passages to contain the gold titles.
- What if…
In the DSPy paper's ReAct rows on HotPotQA, one round of bootstrapping gives 31.0 with GPT-3.5, below the 33.0 from human-written reasoning demos, while two rounds give 39.0. For llama2-13b the same rows read 24.7 and 40.0. Why does a second round help so much, and what controls would you add before trusting the result?
What a strong answer covers
- Round 1 is limited by a weak zero-shot teacher: few, mostly easy, examples succeed, so the demo pool is small and biased.
- Round 2 uses the compiled round-1 program as teacher; it solves more and harder examples, so the demos are more numerous and diverse. This is self-training, close to STaR's iterate-on-own-successes loop.
- Human ReAct demos are fixed and written in a style the model did not produce; bootstrapped traces are in-distribution for the student.
- Controls: match total compute (round 2 runs the pipeline twice as often), report variance across seeds, and test whether a third round keeps improving or saturates.
- Both rounds select on the same validation set, so confirm the gain on held-out test data to rule out overfitting to the selection set.
- Design
A biomedical group gives you 50 labelled question–answer pairs and a 5M-abstract corpus and wants a DSPy multi-hop RAG system. Design the program, the metric and the data splits for compilation, and say what you would do if the zero-shot program answers only 5% of training questions correctly.
What a strong answer covers
- Program: a few explicit modules with clear signatures (a query generator per hop, an answer module with citations), starting close to BasicMultiHop.
- Metric: answer match plus a trace-level check (retrieved or cited abstracts contain the answer), because an answer-only metric admits lucky traces.
- Splits: for example 20 train and 30 validation, plus a separate held-out test set. With so little data, report confidence intervals and avoid repeated winner-picking on the same 30.
- At 5% zero-shot success, 20 training questions give about one trace. Options: bootstrap with a stronger teacher LM, add a few hand-written demos, or relax the metric for intermediate steps.
- Use unlabelled questions: the paper's T5-Large result used 200 labelled and 800 unlabelled examples with a teacher ensemble, so unlabelled data can widen the bootstrap pool.
- Critique
DSPy reports that compiled pipelines beat both standard few-shot prompting and pipelines with expert-created demonstrations, and that compiling lifts simple GSM8K programs on GPT-3.5 from 33% to 82%. Critique what this comparison does and does not show, and propose an experiment that could falsify the claim that the programming model is what matters.
What a strong answer covers
- Baselines get no validation-driven search; compilation spends thousands of program runs selecting on a validation set, so part of the gain is bought with search budget.
- Small splits (200 train, 300 dev for GSM8K and HotPotQA) and selection on dev make overfitting and noise plausible.
- Expert demonstrations were not tuned to the specific LM, while bootstrapped demos are, so the comparison favours LM-adaptive prompts by design.
- Falsifier: give a human prompt engineer, or random search over hand-written prompts, the same number of validation evaluations. If they match the compiled program, the gain comes from search and validation, not from the DSPy abstractions.
- Also test transfer: re-evaluate a program compiled for one LM on a different LM to see how much is overfitting to the student.
- Research idea
DSPy optimizes prompts and demonstrations while the retriever stays frozen. Pitch a thesis-chapter-sized project that uses DSPy traces to train the retriever as well. State the hypothesis, the training signal, the evaluation, and the main risk.
What a strong answer covers
- Hypothesis: successful traces reveal which generated queries and passages led to correct answers, giving retriever training data without relevance judgments.
- Signal: (generated query, passage used in the answer) pairs from passing traces as positives, and passages from failing traces as hard negatives; train ColBERT or a dense retriever contrastively or by distilling from the reader.
- Loop: optimize prompts with the retriever fixed, retrain the retriever on the new traces, and repeat, which is the retriever analogue of BetterTogether's prompt–weight alternation.
- Evaluation: gold supporting-document recall and BEIR-style out-of-domain retrieval, plus end-to-end QA at matched compute.
- Risk: a feedback loop in which the retriever learns to return what the current LM already uses, while answer-correct traces can still contain irrelevant passages.