DSPy prompt optimization works like this: you describe the task as a typed signature, wrap it in a module, write a metric that scores outputs, and let an optimizer (BootstrapFewShot, MIPROv2 or GEPA) search for better instructions and few-shot examples against a small labelled dataset. This tutorial builds a working support-ticket classifier and optimizes it with all three, then evaluates, saves and reloads the result. All code targets DSPy 3.5.0, released on 10 November 2026.

If you're still choosing a framework, our DSPy vs LangChain comparison covers that question. This post assumes you've picked DSPy and want to see optimization working end to end.

What changed in DSPy 3.5 that affects optimization

Most DSPy tutorials online were written for 2.x or early 3.x. Four 3.5 changes matter here, all from the 3.5 upgrade guide:

  • XML is the default adapter. Predictors now use XMLAdapter instead of ChatAdapter, which changes prompts and parsing "even with the same Signature". Programs optimized on 3.4 or earlier need re-evaluating, and probably re-optimizing.
  • model_type="auto" is the default and routes OpenAI and Azure models to the Responses API. Pin model_type="chat" for chat-only proxies.
  • LiteLLM and the OpenAI SDK are optional. DSPy now calls providers through a bundled engine called lm15. Install dspy[litellm] or dspy[openai] only if you need those routes.
  • GEPA graduated from experimental. ChainOfThought now prefers native reasoning, so reasoning may be a dspy.Reasoning object or None rather than a string. That breaks metrics that do string operations on it.

Install with the extra that MIPROv2 needs. MIPROv2 imports Optuna lazily and raises an ImportError telling you to install dspy[optuna]. GEPA's dependency is installed by default on Python versions below 3.15.

python -m venv .venv && source .venv/bin/activate
pip install "dspy[optuna]==3.5.0"
export OPENAI_API_KEY=sk-...

Step 1: signature and module

The example task is support-ticket triage, which has two labelled outputs. That makes it easy to write a deterministic metric. Typed Literal outputs constrain the model to valid labels:

from typing import Literal

import dspy

CATEGORIES = Literal["billing", "bug", "account_access", "feature_request", "other"]


class TriageTicket(dspy.Signature):
    """Classify a customer support ticket for routing."""

    ticket: str = dspy.InputField(desc="Raw ticket text from the customer")
    category: CATEGORIES = dspy.OutputField()
    priority: Literal["low", "medium", "high"] = dspy.OutputField(
        desc="high = customer is blocked or losing money right now"
    )


class Triage(dspy.Module):
    def __init__(self):
        super().__init__()
        self.classify = dspy.Predict(TriageTicket)

    def forward(self, ticket: str):
        return self.classify(ticket=ticket)

The docstring becomes the starting instruction, which is what MIPROv2 and GEPA rewrite. With the 3.5 default adapter, the rendered system prompt lists the fields and asks for <category> and <priority> XML tags. You can see this yourself with dspy.inspect_history(n=1) after any call.

Configure the models once. Keep model names in variables. The optimizers make a lot of calls, so you'll want to swap in cheaper models for experiments:

TASK_MODEL = "openai/gpt-6-luna"      # the model that runs in production
STRONG_MODEL = "openai/gpt-6.1-sol"   # proposes/reflects during optimization

task_lm = dspy.LM(TASK_MODEL)
strong_lm = dspy.LM(STRONG_MODEL)
dspy.configure(lm=task_lm)

Step 2: a small train/val/test split

You don't need thousands of examples; this tutorial uses 80. Use three splits, not two. The optimizer uses train and validation data to make decisions, so only an untouched test set gives you an honest final number. The DSPy GEPA guide recommends the same.

import json
import random


def load_examples(path: str) -> list[dspy.Example]:
    with open(path) as f:
        rows = [json.loads(line) for line in f]
    return [
        dspy.Example(ticket=r["ticket"], category=r["category"], priority=r["priority"])
        .with_inputs("ticket")
        for r in rows
    ]


examples = load_examples("tickets.jsonl")
random.Random(0).shuffle(examples)
trainset, valset, testset = examples[:40], examples[40:60], examples[60:]

.with_inputs("ticket") tells DSPy to pass only the ticket to the program. category and priority stay hidden as labels for the metric.

Step 3: the metric

A DSPy metric receives the gold example, the prediction and an optional trace. The trace argument is how you separate two jobs. During bootstrapping (trace is set), you want a strict pass/fail for deciding whether a generated demo is good enough to keep. During evaluation, you want a graded score:

def triage_metric(example, pred, trace=None):
    category_ok = example.category == pred.category
    priority_ok = example.priority == pred.priority
    if trace is not None:  # bootstrapping: only keep fully correct demos
        return category_ok and priority_ok
    return 0.7 * category_ok + 0.3 * priority_ok

The metric is the real specification of your task. If it rewards the wrong thing, every optimizer will faithfully maximize the wrong thing. For open-ended outputs where exact match doesn't work, the metric can call an LLM judge. Calibrate that judge against human labels first, or you'll be optimizing toward the judge's biases.

Step 4: baseline with dspy.Evaluate

Always measure the unoptimized program first:

evaluate = dspy.Evaluate(
    devset=testset, metric=triage_metric, num_threads=8, display_progress=True
)
baseline = evaluate(Triage())
print(f"baseline: {baseline.score:.1f}")

In 3.5, Evaluate returns an EvaluationResult. Its .score is a percentage (for example 79.0, not 0.79), and .results holds (example, prediction, score) tuples. Read the failures in .results before optimizing. Sometimes the fix is a label error in your data, not a better prompt.

Step 5: run an optimizer

Optimizer What it changes Extra LM Budget control Reach for it when
BootstrapFewShot few-shot demos only optional teacher max_bootstrapped_demos, max_labeled_demos first pass, small data, cheapest
MIPROv2 instructions + demos jointly (Bayesian search) prompt_model auto="light"/"medium"/"heavy" you want demos and instructions tuned together
GEPA instructions, by reflecting on failures and text feedback reflection_lm (required) exactly one of auto, max_full_evals, max_metric_calls your metric can explain why an output is wrong

BootstrapFewShot

bootstrap = dspy.BootstrapFewShot(
    metric=triage_metric, max_bootstrapped_demos=4, max_labeled_demos=4
)
fewshot_program = bootstrap.compile(Triage(), trainset=trainset)
print(f"bootstrap: {evaluate(fewshot_program).score:.1f}")

This runs the program over the training set and keeps traces that pass the metric (strict mode, because trace is set) as demonstrations. It is cheap, roughly one pass over the training set, and it is often a surprisingly strong baseline for classification.

MIPROv2

mipro = dspy.MIPROv2(
    metric=triage_metric,
    prompt_model=strong_lm,   # writes instruction candidates
    task_model=task_lm,       # runs the program
    auto="light",
    num_threads=8,
)
mipro_program = mipro.compile(
    Triage(), trainset=trainset, valset=valset,
    max_bootstrapped_demos=3, max_labeled_demos=3,
)

Details from the 3.5 source that affect cost and behaviour:

  • auto="light" uses 6 candidates and caps the validation sample at 100. medium uses 12 and 300, and heavy uses 18 and 1,000.
  • Minibatch evaluation kicks in only when the validation set has more than 50 examples.
  • With this 40/20 split, the light run scheduled 10 trials.
  • If you set auto=None, you must pass both num_candidates and num_trials. Mixing auto with either one raises an error.
  • If you omit valset, MIPROv2 carves 80% of your trainset off for validation.
  • requires_permission_to_run=True now raises an error. The interactive confirmation prompt was removed.

GEPA

GEPA's distinctive feature is that the metric can return text feedback. The reflection LM reads it and rewrites the instruction. The metric signature gains pred_name and pred_trace, and returns dspy.Prediction(score=..., feedback=...):

def triage_feedback(gold, pred, trace=None, pred_name=None, pred_trace=None):
    notes = []
    if pred.category != gold.category:
        notes.append(f"Category should be '{gold.category}', not '{pred.category}'.")
    if pred.priority != gold.priority:
        notes.append(f"Priority should be '{gold.priority}', not '{pred.priority}'. "
                     "High means the customer is blocked or losing money now.")
    score = 0.7 * (pred.category == gold.category) + 0.3 * (pred.priority == gold.priority)
    return dspy.Prediction(score=score, feedback=" ".join(notes) or "Correct.")


gepa = dspy.GEPA(
    metric=triage_feedback,
    reflection_lm=strong_lm,
    auto="light",
    num_threads=8,
    track_stats=True,
)
gepa_program = gepa.compile(Triage(), trainset=trainset, valset=valset)
print(f"gepa: {evaluate(gepa_program).score:.1f}")
print(gepa_program.detailed_results.val_aggregate_scores)

Rules from the GEPA API docs and the source:

  • You must pass reflection_lm (or a custom instruction_proposer).
  • You must pass exactly one budget: auto, max_full_evals or max_metric_calls.
  • If you omit valset, GEPA scores candidates on the trainset. It logs a warning, because that deliberately overfits.
  • The docs advise keeping the valset as small as still represents your traffic. Every candidate is scored on it, so a large valset eats the budget.

On this one-predictor program with 40 training and 20 validation examples, auto="light" budgeted about 460 metric calls, which the log reports as 7.67 full evaluations. Each metric call is a program run, which is one task-LM call here. Reflection calls come on top. That figure is the number to multiply by your per-call cost before you run on a real model.

For a sense of what's possible, the DSPy GEPA getting-started guide reports a haiku program on gpt-5.4-nano climbing from 78.1% to 90.1% with GEPA. That beat unoptimized gpt-5.4 at 82.4%. Those are the project's own numbers on its own task. Your gains depend on your metric and data.

Step 6: save and load the optimized program

Use state-only JSON for production. It is readable, diffable and doesn't involve pickle:

gepa_program.save("triage_gepa.json")

# In the serving process: rebuild the same architecture, then load state
prod = Triage()
prod.load("triage_gepa.json")
print(prod(ticket="Checkout fails for every customer since 9am").priority)

The JSON contains the optimized instructions and demos per predictor, so open it in a JSON formatter and review it like any other code change. Whole-program saving (save("dir/", save_program=True)) uses cloudpickle. In 3.5, loading it requires an explicit opt-in. Calling dspy.load("dir/") without the flag raises ValueError: Loading with pickle is not allowed, so you must write:

loaded = dspy.load("triage_gepa_program/", allow_pickle=True)  # trusted files only

The saving tutorial says that from 3.0 onward, saved programs are meant to stay loadable across 3.x releases. The 3.5 adapter change still means a program optimized on 3.4 will produce different prompts on 3.5, so re-evaluate after upgrading.

Cost: what an optimization run really spends

  • Count calls before running. BootstrapFewShot makes about one pass over the trainset. MIPROv2 runs the program over the validation set (or minibatches of it) for each trial, plus proposal calls to prompt_model. GEPA logs its metric-call budget up front.
  • Use a cheap task model and a strong proposer. Only the proposer or reflection model needs to be strong, and it is called far less often than the task model.
  • Check spend afterwards. Every dspy.LM keeps a history in which each entry has a cost field. Run sum(e["cost"] or 0 for e in task_lm.history) and do the same for strong_lm. In 3.5 an unknown cost is None, not zero, so a total of 0 can mean "not priced", not "free". dspy.configure(track_usage=True) adds per-prediction token usage via pred.get_lm_usage().
  • Rely on the cache, carefully. dspy.LM caches by default (cache=True), so re-running an identical evaluation is cheap. The 3.5 upgrade guide warns that old cache entries miss under the new cache format, so your first 3.5 run pays full price.
  • Watch hidden retries. In 3.5, num_retries=0 disables LM retries but not adapter fallback. After a parse failure, the Chat and XML adapters can make an extra JSON-format call. To prevent that, configure the adapter explicitly, for example dspy.configure(adapter=dspy.XMLAdapter(use_native_function_calling=True, use_json_adapter_fallback=False)).

When optimization isn't worth it

  • You can't write a metric. Without a score that tracks quality, optimizers have nothing to climb. Fix that first.
  • The baseline already meets the bar. If the test score clears your requirement, optimization only adds artifacts to maintain.
  • Your data is tiny or unrepresentative. Optimizing against 15 hand-picked examples mostly fits those 15 examples.
  • The task changes weekly. Every change to the label set or output format means re-optimizing. Keep it in the backlog until things settle.
  • The failure isn't a prompt problem. Bad retrieval, missing context or a model that's too weak won't be fixed by better wording. Read .results first.

DSPy vs LangGraph: different layers

The "DSPy vs LangGraph" search is a category error worth clearing up. LangGraph orchestrates control flow: stateful graphs, branches, retries, human-in-the-loop steps. DSPy optimizes what happens inside an LM call: instructions, demos and output parsing. They compose well. A DSPy program, loaded from its saved JSON, can be the function behind one LangGraph node. If durable orchestration is your real problem, see LangGraph vs Temporal. For broader evaluation tooling, see our LLM evaluation frameworks guide.

I ran every snippet in this post on DSPy 3.5.0 against a scripted stand-in LM (DSPy's DummyLM with a custom responder), so the scores it produced are meaningless. The API calls, budgets and save/load behaviour described above come from those runs.

Frequently Asked Questions

Which DSPy optimizer should I start with?

Start with BootstrapFewShot. It is cheap and gives you a second data point beyond the baseline. Move to MIPROv2 with auto="light" when you want instructions and demos tuned together. Use GEPA when your metric can explain why an output failed, because that text feedback is what GEPA learns from.

How much data does DSPy prompt optimization need?

There is no hard minimum, but you need enough examples that the validation score means something, and a separate test set. A few dozen labelled examples per split is a reasonable start for a classifier. Add more where the model fails. MIPROv2 needs at least two training examples if you don't pass a valset, and GEPA warns if you omit the valset.

Do optimized DSPy programs transfer to a different model?

Not reliably. The optimized instructions and demos are tuned for the task model used during optimization. The DSPy docs note that the same program optimizes differently on different models. Re-run the optimizer, or at least dspy.Evaluate, when you switch models or upgrade DSPy across the 3.5 adapter change.

Why does my old DSPy program score differently after upgrading to 3.5?

DSPy 3.5 switched the default adapter to XMLAdapter, changed ChainOfThought to prefer native reasoning, and routes OpenAI models to the Responses API by default. All of these change the prompt the model sees. The upgrade guide says to re-evaluate optimized programs. Pin dspy.ChatAdapter() if you need the old field format while you re-optimize.

Is DSPy a replacement for LangGraph or LangChain?

No. DSPy focuses on programming and optimizing LM calls against a metric. LangGraph handles stateful orchestration. You can use DSPy modules inside a LangGraph or LangChain application, or on their own.

Bottom Line

DSPy prompt optimization is worth it when you have a metric you trust and a test set the optimizer never sees. Start with a baseline, try BootstrapFewShot, then use MIPROv2 or GEPA with a budget you've estimated from their logs. On 3.5 specifically, install dspy[optuna] for MIPROv2, re-evaluate anything optimized before the XML adapter switch, and pass allow_pickle=True explicitly if you load whole-program saves. Ship the state-only JSON and review it like code.