Automatic prompt optimization (DSPy)

In one sentence

Stop hand-tuning prompts: define the task, an eval set and a metric, and let an optimizer search instructions and few-shot examples that maximize the metric. Prompts become learned parameters you recompile per model.

Analogy: Hyperparameter search instead of tweaking a learning rate by hand: you define the objective and the search space, the machine runs the trials. Without a held-out set, you just overfit faster.

The optimizer searches prompts against your metric on train/validation data; only an untouched test set decides whether the compiled prompt ships.

How it works

  • In DSPy you write a program: signatures declare inputs and outputs, modules pick a strategy like ChainOfThought.
  • Optimizers tune each module: BootstrapFewShot keeps traces that pass the metric as demos; MIPROv2 also proposes instructions.
  • Other approaches: OPRO has an LLM propose prompts from scored ones; TextGrad backpropagates critiques as textual gradients.
  • Non-negotiable: train and validation splits, an untouched test set, and a metric you trust.
  • When you swap models, recompile: in the example, one run replaced a week of prompt rewrites.

Check yourself

Answer to mark it learned; your answers aren't scored.

After running MIPROv2 on 300 labeled tickets, a teammate reports 97% accuracy, up from 78%, measured on those same 300 tickets. What do you do before shipping?

Go deeper

Full explanation

Hand-written prompts are tuned by feel on a few examples and break when you swap models. Automatic prompt optimization treats the prompt as a learnable parameter: given labeled examples and a metric, an optimizer proposes prompts, scores them and keeps the best.

DSPy (Stanford) is the main framework. You write a program, not a prompt:

  • Signatures declare inputs and outputs: question, context -> answer.
  • Modules pick a strategy (Predict, ChainOfThought, ReAct) and compose like PyTorch layers.
  • Optimizers tune the prompts of every module against your metric:
    • BootstrapFewShot runs the program on training data and keeps traces that pass the metric as few-shot demos.
    • MIPROv2 also proposes instructions and searches instruction × demo combinations with Bayesian optimization.
    • GEPA reflects on failed traces in natural language to rewrite instructions.

Other approaches: OPRO (Google DeepMind) has an LLM propose new prompts from a history of scored ones; TextGrad backpropagates LLM-written critiques as "textual gradients" through a pipeline.

The non-negotiables: train and validation splits plus an untouched test set, and a metric you trust (exact match, F1, or a validated LLM-as-a-judge). No eval set, no optimization (Eval-driven development).

The payoff: when the model changes, you recompile instead of rewriting prompts by hand.

Code Compile a ticket router with DSPy MIPROv2
pythonCompile a ticket router with DSPy MIPROv2
import dspy

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))  # any LiteLLM model id

class Triage(dspy.Signature):
    """Route a support ticket to the right queue."""
    ticket: str = dspy.InputField()
    queue: str = dspy.OutputField(desc="one of: billing, bug, account, other")

program = dspy.ChainOfThought(Triage)   # the program; prompts are its parameters

def metric(example, pred, trace=None):
    return example.queue == pred.queue.strip().lower()

def to_examples(rows):
    return [dspy.Example(ticket=t, queue=q).with_inputs("ticket") for t, q in rows]

trainset = to_examples(load_split("train"))  # ~300 labeled tickets
testset = to_examples(load_split("test"))    # never shown to the optimizer

# Proposes instructions, bootstraps demos, searches combinations
optimizer = dspy.MIPROv2(metric=metric, auto="light")
compiled = optimizer.compile(program, trainset=trainset)

evaluate = dspy.Evaluate(devset=testset, metric=metric, num_threads=8)
print("baseline:", evaluate(program))
print("compiled:", evaluate(compiled))   # judge only on held-out data

compiled.save("triage_v3.json")   # learned prompt = versioned artifact
Real example

A team routes support tickets into 6 queues with a hand-written prompt: ~78% accuracy on a 400-ticket held-out set. They wrap it as a DSPy ChainOfThought signature and run MIPROv2 (light) on 300 labeled tickets. The compiled program, a new instruction plus 4 bootstrapped demos, scores ~86% on the same held-out set. Six months later they move to a cheaper model: recompiling takes one run instead of a week of prompt rewrites, and lands at ~84%.

Trade-offs +4 · −3

+ You gain

  • Replaces guesswork with a measured search against your own metric.
  • Portable: swap the model and recompile instead of rewriting prompts.
  • Tunes every stage of a multi-step pipeline jointly, which humans rarely manage.
  • Bootstrapped demos come from your own data, so few-shot examples match real inputs.

− You pay

  • Useless without a labeled eval set and a metric you trust; building those is the real work.
  • Optimized prompts can be opaque or odd, which makes review and debugging harder.
  • Each run costs hundreds to thousands of LLM calls and must be repeated on model changes.

Use it when

You have ≥50 labeled examples and an automatic metric, plus a multi-stage pipeline, frequent model swaps or a plateau after hand-tuning. Classification, extraction, routing and RAG answering fit well.

Avoid it when

No eval set or no reliable metric (open-ended creative writing), one-off prompts, or gaps that need new knowledge or behavior only better retrieval or fine-tuning can add.

Numbers to know 4
  • OPRO: optimized prompts beat human-written ones by up to 8% on GSM8K and up to 50% on Big-Bench Hard tasks.
  • OPRO's top GSM8K instruction for PaLM 2-L, "Take a deep breath and work on this problem step-by-step": 80.2% vs 71.8% for "Let's think step by step".
  • MIPRO: beat baseline optimizers on 5 of 7 multi-stage programs with Llama-3-8B, by up to 13% accuracy.
  • TextGrad: lifted GPT-4o zero-shot accuracy on Google-Proof QA from 51% to 55%.
Common pitfalls 4
  • Reporting the score on the data you optimized on; confirm on an untouched test split.
  • A gameable metric, such as a judge that likes length, gets optimized into verbose wrong outputs.
  • Shipping the compiled prompt unread: check the demos for leaked labels, PII or test items.
  • Assuming the result is model-independent: it is tuned to one model, so re-optimize when you switch.
Interview questions 2

Answer out loud first, then reveal.

When would you reach for DSPy instead of hand-writing prompts?Show answer

When three things hold: I have at least ~50–100 labeled examples, a metric I trust that runs automatically, and either a multi-stage pipeline or frequent model swaps. Then hand-tuning is the expensive, unreproducible option. I'd start with BootstrapFewShot, which is cheap and often captures much of the gain through good demos, then try MIPROv2. I'd skip it for open-ended generation without a reliable metric, or when the real gap is missing knowledge: optimization can't add facts the model doesn't have.

How do you avoid overfitting during prompt optimization?Show answer

With the same discipline as ML. Three splits: train for bootstrapping demos, validation for selecting candidates, and a test set the optimizer never sees, used once to report. The data has to be large and representative enough; with 30 examples a 3-point gain is noise. I check the metric can't be gamed, read the winning prompt and demos for leaked labels, and gate promotion on the same CI evals as any prompt change, with the compiled artifact versioned and traced like code.