Module 5 · Industrialization
Automatic optimization with DSPy
6 min read
Until now, we have written prompts by hand, then measured. DSPy reverses the approach: you declare what the program must do (its inputs, its outputs, a metric), and an optimizer builds the prompt — examples and sometimes instructions — by maximizing the metric on a training set. This lesson optimizes the clause classifier from lesson 2.2 and takes a close look at what the optimizer produces.
Signature, module, optimizer
DSPy rests on three notions:
| Notion | Role | Here |
|---|---|---|
| Signature | Inputs, typed outputs and a short instruction | A clause → one of the eight types |
| Module | The strategy for calling the model | dspy.Predict (direct answer); dspy.ChainOfThought would add reasoning |
| Optimizer | Builds the prompt by maximizing a metric | BootstrapFewShot: chooses examples |
The signature replaces the hand-written prompt:
ClauseType = Literal["confidentialite", "resiliation", "paiement", "responsabilite", "propriete_intellectuelle",
"force_majeure", "juridiction", "duree"]
class ClassifyClause(dspy.Signature):
"""Classe une clause de contrat dans l'un des huit types."""
clause: str = dspy.InputField(desc="Texte d'une clause de contrat, en français")
clause_type: ClauseType = dspy.OutputField()
The docstring becomes the instruction, the fields become the format, and the Literal type restricts possible values: DSPy generates the prompt, parses the answer and validates it.
The model: local or Claude
DSPy talks to models through LiteLLM. The local model goes through the OpenAI-compatible server from lesson 5.2; Claude, through its identifier:
def local_lm(port: int = 8765) -> dspy.LM:
"""Le modèle local servi par quill.server, vu par DSPy comme un modèle compatible OpenAI."""
return dspy.LM("openai/qwen-local", api_base=f"http://127.0.0.1:{port}/v1", api_key="local",
temperature=0.0, max_tokens=300, cache=False)
def claude_lm(model: str = "anthropic/claude-haiku-5-5") -> dspy.LM:
"""Le même programme sur Claude (ANTHROPIC_API_KEY) : seule la ligne du modèle change."""
return dspy.LM(model, max_tokens=2000)
This is one of DSPy's promises: the program (signature, module, metric) is independent of the model. Switching models means rerunning the optimization, not rewriting prompts.
The metric and the optimization
The metric says what a good answer is; here, the right type:
def metric(example: dspy.Example, prediction, trace=None) -> bool:
return getattr(prediction, "clause_type", None) == example.clause_type
BootstrapFewShot runs the program on the training set, keeps the runs that succeed according to the metric, and inserts them as examples in the prompt:
def optimize(trainset: list[dspy.Example], max_demos: int = 8) -> dspy.Module:
"""BootstrapFewShot : exécute le programme sur l'entraînement, garde comme exemples les traces réussies."""
optimizer = dspy.BootstrapFewShot(metric=metric, max_bootstrapped_demos=4, max_labeled_demos=max_demos)
return optimizer.compile(dspy.Predict(ClassifyClause), trainset=trainset)
The script compares the program before and after optimization, on 80 test clauses written with templates absent from training:
baseline = dspy.Predict(optimize.ClassifyClause)
print(f"Avant optimisation (zéro exemple) : {optimize.evaluate(baseline, testset):.2f}")
start = time.perf_counter()
compiled = optimize.optimize(trainset)
print(f"Optimisation : {time.perf_counter() - start:.0f} s, {len(compiled.demos)} exemples retenus")
print(f"Après optimisation : {optimize.evaluate(compiled, testset):.2f}")
The results, with Qwen2.5-1.5B served locally:
| Program | Accuracy (80 unseen clauses) |
|---|---|
dspy.Predict, no examples | 0.59 |
After BootstrapFewShot (8 examples) | 0.79 |
| Optimization time | 7 seconds |
In 7 seconds, the optimizer gains 20 points: the same order of magnitude as the eight fixed examples chosen by hand in lesson 2.2 (0.61 → 0.80, on another test set). It needed only 5 training clauses to get 4 successful runs, then completed with 4 annotated examples.
What the optimizer produced deserves a read. The prompt sent to the model (shown by dspy.inspect_history) contains:
- a system message generated by DSPy from the signature: the fields, their descriptions, the list of allowed values, and the docstring as the objective;
- the 8 examples, as user/assistant exchanges in the
[[ ## clause ## ]]…[[ ## clause_type ## ]]format.
Its limits show too: the 8 examples cover only 6 types out of 8 (two term examples, two liability examples, none for termination or jurisdiction), and the prompt contains no definition of the types, unlike the hand-written prompt. The optimizer maximized the metric with what it was given; it did not "understand" the task. Adding the definitions to the docstring, or moving to an optimizer that rewrites instructions, are the next leads — to be measured.
DSPy's optimizers
| Optimizer | What it optimizes | Cost |
|---|---|---|
LabeledFewShot | Examples drawn from the annotated set | None |
BootstrapFewShot | Examples from successful runs (with their reasoning, for ChainOfThought) | Low: one pass over training |
BootstrapFewShotWithRandomSearch | Several example sets, the best on a validation set | Medium |
MIPROv2 | Instructions and examples, through Bayesian search | High: hundreds of calls |
GEPA | Instructions, through the model reflecting on its errors | High |
BootstrapFinetune | The weights of a small model, from a large model's traces | A fine-tuning run (Fine-tuning course) |
Start with the cheapest, measure, and move up a notch only if the gain justifies it.
When to use DSPy?
| DSPy is useful when… | A hand-written prompt is enough when… |
|---|---|
| The task has a clear automatic metric | Quality is judged by eye (tone, style) |
| You have dozens to hundreds of annotated examples | You only have a few examples |
| The pipeline has several steps to optimize together | A single call, already good |
| You change models often | The model is fixed for a long time |
And in every case: read the produced prompt. dspy.inspect_history shows what is actually sent to the model. An optimized prompt is still a prompt: it is versioned, reviewed and evaluated like the others (lessons 5.1 and 5.2). The compiled program is saved as a JSON file, which joins the registry.
Key takeaways
- DSPy replaces writing the prompt with a signature, a module and a metric; an optimizer builds the prompt.
- Here,
BootstrapFewShottakes the classifier from 0.59 to 0.79 in 7 seconds — but its examples cover only 6 types out of 8.- The program is model-independent: switching models means rerunning the optimization.
BootstrapFewShotpicks successful examples; MIPROv2 and GEPA also optimize instructions, at a higher cost.- Measure on unseen data, and read the produced prompt with
dspy.inspect_history.
Practice
- Start the local server then
examples/08_dspy.py, and read the prompt printed at the end: which examples were kept? - Replace
dspy.Predictwithdspy.ChainOfThoughtand compare the score and the number of tokens. - Try
MIPROv2withauto="light"and compare the gain with the optimization time.