Tutorial
Optimise a prompt automatically with DSPy
Write a signature and a metric, run three optimisers on 30 labelled examples, score 20 held-out ones, and see when hand-tuning wins.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
In this tutorial you build a small DSPy program that routes customer support tickets to the right team, measure it on tickets it has never seen, and then let three DSPy optimisers try to improve it. You compare every result on the same 20 held-out tickets. On this task none of the optimisers beats the starting prompt, and working out why is the useful part: you will see what an optimiser can and cannot learn from 30 examples, and when writing the rules down yourself is faster and better.
DSPy describes itself as programming rather than prompting: you declare inputs and outputs, and optimisers write and tune the prompt for a metric you choose. Everything here was run on 25 November 2026 with Python 3.12, DSPy 3.5.0, Optuna 5.1.0 and Ollama 0.40.18 serving llama3.2:3b on a 4-core CPU with no GPU. Your scores will differ a little with a different model or machine; the comparison is what matters.
The pieces DSPy gives you
| Piece | What it is | In this tutorial |
|---|---|---|
| Signature | Typed inputs and outputs, plus a docstring that becomes the instruction | ticket in, category out, one of five teams |
| Module | A strategy for calling the model with a signature | dspy.Predict, a single call |
| Metric | A Python function that scores one prediction | Exact match against the label |
| Optimiser | Rewrites the prompt (examples, instruction or both) to raise the metric on training data | LabeledFewShot, BootstrapFewShot, MIPROv2 |
| Evaluate | Runs a program over a dataset with a metric | Scores on the 20 held-out tickets |
1. Set up the project and the model
Install Ollama if you have not (see run local models with Ollama), then pull the model:
ollama pull llama3.2:3b
Create the project. MIPROv2 needs Optuna, which DSPy ships as an extra:
uv init --bare --python 3.12 ticket-triage
cd ticket-triage
uv add "dspy[optuna]==3.5.0"
A local model keeps the tutorial free and repeatable. To use a hosted model instead, replace the dspy.LM(...) line in step 3, for example with dspy.LM("openai/gpt-5-nano", temperature=1.0, max_tokens=16000) and OPENAI_API_KEY set, as in the DSPy installation guide. GPT-5 models are reasoning models, and DSPy refuses other temperature and max_tokens values for them, so change the whole line, not just the model name. Runs are no longer deterministic at that temperature, so compare scores over two or three runs. An optimiser makes many calls, so check the cost first.
2. Make a labelled dataset
Create tickets.jsonl, 50 tickets with the team that should answer each. The labels follow house rules a model cannot guess: a missing item in a box is delivery, not complaint; “I want my money back” is refund even when the parcel never came; a broken item under warranty is product.
{"text": "My order was meant to arrive Tuesday and the tracking hasn't moved since Saturday", "label": "delivery"}
{"text": "The parcel says delivered but there is nothing at my door", "label": "delivery"}
{"text": "Can I change the delivery address on an order I placed an hour ago?", "label": "delivery"}
{"text": "Do you deliver to Jersey?", "label": "delivery"}
{"text": "The courier left my box in the rain and it's soaked, can I get a replacement sent?", "label": "delivery"}
{"text": "How long does next-day delivery take if I order on a Saturday?", "label": "delivery"}
{"text": "Two items came but the third is missing from the box", "label": "delivery"}
{"text": "The driver said he couldn't find my flat, when will you try again?", "label": "delivery"}
{"text": "It never arrived and I want my money back", "label": "refund"}
{"text": "I returned the jacket two weeks ago and still haven't been paid back", "label": "refund"}
{"text": "You charged me twice for the same order", "label": "refund"}
{"text": "The shoes don't fit, how do I send them back for a refund?", "label": "refund"}
{"text": "I cancelled before it shipped but the money is still gone from my account", "label": "refund"}
{"text": "Can I get a refund on a sale item?", "label": "refund"}
{"text": "The kettle stopped working after a week. I'd like my money back please", "label": "refund"}
{"text": "Where is my refund? You said 5 days and it's been 10", "label": "refund"}
{"text": "Is the blue version of this backpack waterproof?", "label": "product"}
{"text": "Will this charger work with a 2023 laptop?", "label": "product"}
{"text": "What size should I order if I'm usually between a medium and a large?", "label": "product"}
{"text": "Are these headphones noise cancelling?", "label": "product"}
{"text": "When will the green kettle be back in stock?", "label": "product"}
{"text": "Does the desk come assembled?", "label": "product"}
{"text": "The kettle I bought has a crack in it, how do I use the warranty?", "label": "product"}
{"text": "What's the difference between the 2-person and 3-person tent?", "label": "product"}
{"text": "I can't log in, it says my password is wrong", "label": "account"}
{"text": "How do I delete my account and all my data?", "label": "account"}
{"text": "I never got the email to confirm my account", "label": "account"}
{"text": "Please change the email on my account to my work one", "label": "account"}
{"text": "Someone ordered something on my account and it wasn't me", "label": "account"}
{"text": "How do I unsubscribe from your marketing emails?", "label": "account"}
{"text": "The driver was rude to my elderly mother", "label": "complaint"}
{"text": "This is the third time I've contacted you and nobody has replied", "label": "complaint"}
{"text": "Your website kept crashing at checkout and I lost my basket", "label": "complaint"}
{"text": "I'm very unhappy with how your staff spoke to me on the phone", "label": "complaint"}
{"text": "Your returns policy is a joke, I'll never shop here again", "label": "complaint"}
{"text": "Took 40 minutes on hold before anyone answered", "label": "complaint"}
{"text": "My delivery is late again, this keeps happening", "label": "delivery"}
{"text": "The parcel went to my old address even though I updated it", "label": "delivery"}
{"text": "Can I pick up my order from a store instead?", "label": "delivery"}
{"text": "I sent back the wrong-size trousers, has the refund gone through?", "label": "refund"}
{"text": "It arrived broken and I just want the money back", "label": "refund"}
{"text": "Your price dropped the day after I bought it, can I have the difference back?", "label": "refund"}
{"text": "Is this jumper machine washable?", "label": "product"}
{"text": "Do you sell spare parts for the coffee grinder?", "label": "product"}
{"text": "The zip on my new bag broke, is that covered by the guarantee?", "label": "product"}
{"text": "My password reset link has expired", "label": "account"}
{"text": "Can I merge my two accounts?", "label": "account"}
{"text": "The person in your chat kept copying and pasting the same answer", "label": "complaint"}
{"text": "Nobody told me my order was cancelled, I found out when it didn't come", "label": "complaint"}
{"text": "I was promised a call back yesterday and never got one", "label": "complaint"}
3. Write the program, the split and the metric
Create triage.py:
# triage.py: a DSPy program that routes support tickets, plus its data and metric
import json
import random
from pathlib import Path
from typing import Literal
import dspy
Category = Literal["delivery", "refund", "product", "account", "complaint"]
class TriageTicket(dspy.Signature):
"""Route a customer support ticket to the team that should answer it."""
ticket: str = dspy.InputField()
category: Category = dspy.OutputField()
def load_data(seed: int = 7) -> tuple[list[dspy.Example], list[dspy.Example]]:
rows = [json.loads(line) for line in Path("tickets.jsonl").read_text().splitlines()]
random.Random(seed).shuffle(rows)
examples = [dspy.Example(ticket=r["text"], category=r["label"]).with_inputs("ticket") for r in rows]
return examples[:30], examples[30:] # 30 to optimise on, 20 held out
def exact_match(example, prediction, trace=None) -> bool:
return prediction.category == example.category
def configure() -> None:
dspy.configure(lm=dspy.LM("ollama_chat/llama3.2:3b", temperature=0.0, max_tokens=200))
Three decisions here:
- The output is a
Literaltype, so DSPy tells the model the five allowed values and rejects anything else when it parses the reply. - The split is fixed by a seed. The 30 training tickets are all the optimisers may see. The 20 held-out tickets are only for the final score. Shuffle once, then never touch the test set while tuning.
- Temperature is 0, so each prompt gives the same answer every time. That makes runs comparable. DSPy also caches calls, which matters later.
4. Measure the baseline
Create baseline.py:
# baseline.py: score the unoptimised program on the held-out set
import dspy
from triage import TriageTicket, configure, exact_match, load_data
configure()
train, test = load_data()
program = dspy.Predict(TriageTicket)
evaluate = dspy.Evaluate(devset=test, metric=exact_match, num_threads=1, max_errors=len(test))
result = evaluate(program)
print(f"baseline on {len(test)} held-out tickets: {result.score:.1f}%")
for example, prediction, correct in result.results:
category = getattr(prediction, "category", "(no answer)")
if not correct:
print(f" wrong: {example.ticket[:55]!r} -> {category} (want {example.category})")
max_errors=len(test) matters: by default a few unparseable replies stop the whole evaluation. With it set, a reply that cannot be parsed scores zero and the run carries on.
uv run baseline.py
baseline on 20 held-out tickets: 85.0%
wrong: 'Your website kept crashing at checkout and I lost my ba' -> product (want complaint)
wrong: 'My password reset link has expired' -> delivery (want account)
wrong: 'Two items came but the third is missing from the box' -> product (want delivery)
The run took 50 seconds. Seventeen of twenty right from a one-line instruction. Note the sizes: with 20 test tickets, one ticket is 5 percentage points, so a change of one ticket is noise, not progress.
5. Run three optimisers
Create optimise.py. It compiles the same program with the optimiser you name, scores the result on the same held-out tickets, and saves it:
# optimise.py: compile the program on the 30 training tickets, score it on the 20 held out
import sys
import dspy
from triage import TriageTicket, configure, exact_match, load_data
configure()
train, test = load_data()
evaluate = dspy.Evaluate(devset=test, metric=exact_match, num_threads=1, max_errors=len(test))
which = sys.argv[1] if len(sys.argv) > 1 else "bootstrap"
if which == "labeled":
optimiser = dspy.LabeledFewShot(k=8)
compiled = optimiser.compile(dspy.Predict(TriageTicket), trainset=train)
elif which == "mipro":
optimiser = dspy.MIPROv2(metric=exact_match, auto="light", num_threads=1)
compiled = optimiser.compile(dspy.Predict(TriageTicket), trainset=train, seed=7)
else:
optimiser = dspy.BootstrapFewShot(metric=exact_match, max_bootstrapped_demos=4, max_labeled_demos=8)
compiled = optimiser.compile(dspy.Predict(TriageTicket), trainset=train)
result = evaluate(compiled)
print(f"{which} on {len(test)} held-out tickets: {result.score:.1f}%")
print(f"demos in the prompt: {len(compiled.demos)}")
for example, prediction, correct in result.results:
if not correct:
category = getattr(prediction, "category", "(no answer)")
print(f" wrong: {example.ticket[:55]!r} -> {category} (want {example.category})")
compiled.save(f"triage-{which}.json")
What each optimiser does:
LabeledFewShot(k=8)puts eight training tickets, with their labels, in the prompt as examples. It is the baseline the DSPy docs call honest: “ifLabeledFewShotalready gets you where you need to be, heavier optimization is wasted effort” (DSPy: choosing an optimiser).BootstrapFewShotruns the program on training tickets and keeps the runs the metric passes as demonstrations, topped up with labelled examples.MIPROv2(auto="light")also proposes new instructions with the model, then searches combinations of instruction and examples with Optuna, scoring each on part of the training set.
Run them one at a time:
uv run optimise.py labeled
uv run optimise.py bootstrap
uv run optimise.py mipro
Our results, each copied from its run:
labeled on 20 held-out tickets: 85.0%
demos in the prompt: 8
wrong: 'My password reset link has expired' -> complaint (want account)
wrong: "The courier left my box in the rain and it's soaked, ca" -> complaint (want delivery)
wrong: "I returned the jacket two weeks ago and still haven't b" -> complaint (want refund)
Bootstrapped 4 full traces after 4 examples for up to 1 rounds, amounting to 4 attempts.
bootstrap on 20 held-out tickets: 70.0%
demos in the prompt: 8
wrong: "Where is my refund? You said 5 days and it's been 10" -> complaint (want refund)
wrong: 'The parcel went to my old address even though I updated' -> complaint (want delivery)
wrong: 'Two items came but the third is missing from the box' -> complaint (want delivery)
wrong: "The courier left my box in the rain and it's soaked, ca" -> complaint (want delivery)
wrong: "I returned the jacket two weeks ago and still haven't b" -> complaint (want refund)
wrong: 'When will the green kettle be back in stock?' -> delivery (want product)
MIPROv2’s light setting ran 10 trials over 3 instruction candidates and 6 example sets, holding back 24 of the 30 training tickets as its own validation set. It took 395 seconds. The end of its log and the held-out score:
INFO dspy.teleprompt.mipro_optimizer_v2: Returning best identified program with score 91.67!
mipro on 20 held-out tickets: 85.0%
demos in the prompt: 0
wrong: 'Your website kept crashing at checkout and I lost my ba' -> product (want complaint)
wrong: 'My password reset link has expired' -> delivery (want account)
wrong: 'Two items came but the third is missing from the box' -> product (want delivery)
6. Read the results honestly
| Program | Held-out score | Run time |
|---|---|---|
| Baseline, one-line instruction | 85% | 50 s |
LabeledFewShot, 8 examples |
85% | 35 s |
BootstrapFewShot |
70% | 43 s |
MIPROv2, light |
85% | 395 s |
None of the optimisers beat the baseline on unseen tickets, and one made it worse. Three things explain it:
- Examples shifted the model’s bias. With examples in the prompt, the 3B model started labelling anything unhappy as
complaint. A handful of demonstrations taught it the wrong lesson about what matters. - MIPROv2’s 91.67% was on its own validation tickets, drawn from the training set it was tuning on. On the held-out set the chosen program, which was the original instruction with no examples, scored 85% again. A search over many candidates always finds one that looks good on the data it searched; that is why you keep a test set it never sees.
- The errors are about house rules, such as “a missing item is a delivery problem”. Thirty examples, five per team, are not enough for an optimiser to infer rules nobody wrote down.
This matches the DSPy documentation’s own advice that baselines cost almost nothing while search-based optimisers “cost real money”, and that with small evaluation sets example tuning tends to overfit.
7. Write the rules down and compare
If the rules are known, write them into the signature’s docstring. Create handwritten.py:
# handwritten.py: the same program with the team's routing rules written into the instruction
import dspy
from triage import Category, configure, exact_match, load_data
class TriageTicketRules(dspy.Signature):
"""Route a customer support ticket to the team that should answer it.
Rules the support team uses:
- delivery: where an order is, late or missing parcels, missing items, addresses, collection.
- refund: the customer wants money back, or asks where a refund is.
- product: questions about an item, stock, sizes, faults and warranty claims.
- account: logins, passwords, reset links, emails on the account, data deletion.
- complaint: unhappy with how they were treated (staff, waiting, no reply, the website),
not a problem with one order."""
ticket: str = dspy.InputField()
category: Category = dspy.OutputField()
configure()
train, test = load_data()
evaluate = dspy.Evaluate(devset=test, metric=exact_match, num_threads=1, max_errors=len(test))
result = evaluate(dspy.Predict(TriageTicketRules))
print(f"handwritten rules on {len(test)} held-out tickets: {result.score:.1f}%")
for example, prediction, correct in result.results:
if not correct:
category = getattr(prediction, "category", "(no answer)")
print(f" wrong: {example.ticket[:55]!r} -> {category} (want {example.category})")
uv run handwritten.py
handwritten rules on 20 held-out tickets: 95.0%
wrong: 'Your website kept crashing at checkout and I lost my ba' -> refund (want complaint)
Nineteen of twenty, from five lines of rules and no optimiser. Treat that number as optimistic, though. Most of the rules restate the label definitions in step 2, but two phrases do not: “reset links” under account and “the website” under complaint. Both were added after reading the baseline’s wrong answers in step 4, and the reset-link ticket is one of the two the rules fixed. That is tuning on the test set, on a small scale. To trust the score, label a fresh set of tickets the rules have never seen and run handwritten.py on those. The general rule holds: if you write rules by reading test failures, the test score stops meaning anything.
From here the two combine well: keep the handwritten signature, and give an optimiser more data to tune examples on top of it. Compile dspy.Predict(TriageTicketRules) with the same optimise.py choices once you have more labelled tickets, and keep the version only if the held-out score rises by more than a ticket or two.
Pitfalls
A small model fails on format, not on the task. Our first try used llama3.2:1b. It scored 20%, and most “wrong” answers were replies DSPy could not parse (“I cannot fulfill your request”). That measures the output format, not routing. Check what the failures are before you optimise anything, and move to a model that follows the format.
A few parse failures stop the evaluation. Without max_errors, dspy.Evaluate cancels the run after a few exceptions with “Execution cancelled due to errors or interruption.” Set max_errors to the size of the set so failures score zero instead.
MIPROv2 fails with an ImportError. It needs Optuna, which is an optional extra. Install dspy[optuna], as in step 1, rather than plain dspy.
Reruns are instant and identical. DSPy caches model calls on disk, so a second run with the same prompts returns cached answers. That is useful for comparing programs, and misleading if you meant to measure run-to-run variation. Turn the cache off for that, using the cache options in the DSPy docs.
Trusting the optimiser’s own score. The score an optimiser reports is on data it tuned against. Only the held-out score tells you what users will see, and with 20 tickets a 5-point change is one ticket.
Next steps
- Build the habit this tutorial depends on with your first LLM eval, and find the rules worth writing down with error analysis.
- Improve a prompt by hand, with examples and formats, in how to write a good prompt.
- Run the same comparison in CI with promptfoo evals in GitHub Actions.
- Choose the model before you tune the prompt with how to choose an LLM.
Covers
Check your understanding
DSPy prompt optimisation quiz
Signatures, metrics and optimisers, a fixed held-out split, reading small-sample scores, why the optimisers did not win, handwritten rules, and when an optimiser is worth it.
8 questions · pass mark 70%
Review
Related
- Write your first LLM eval
Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.
- Prompting fundamentals: clear tasks, examples and formats
How to write a good prompt: frame the task, say who the output is for, show an example and specify the format, so a model's answers are useful and repeatable.
- Run local models with Ollama
Install Ollama, run an open-weight model on your own machine, call it from scripts over the local API and choose a model size your hardware can handle, offline.
- Few-shot prompting
Including a few input and output examples in the prompt so the model can copy their pattern, format and level of detail.
- Start your evals by reading outputs, not by picking metrics
The fastest way to useful LLM evals is to read real outputs and write down what is wrong. Why error analysis comes before metrics, and how to do it.