Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FrameworksAI guideAdvanced#frameworks#dspy#prompt-optimization#evals
Frame · ai-engineering / frameworks / 06-dspy-signatures-modules-optimizers.mdGuide 042 / 103

DSPy, signatures, modules and optimizers

DSPy, from Stanford NLP, takes a different stance from every other framework in this track. Instead of writing prompts, you write a program: you declare what goes in and what comes out (a signature), pick a strategy for getting there (a module), and then let an optimizer search for the prompts and few shot examples that score best on your metric. The slogan is "programming, not prompting". As of October 2026 it is on version 3.4.

Why it matters

Hand tuned prompts are fragile. They are tied to one model, they break when you add a field, and nobody remembers why a sentence was added. When you switch from one model family to another, you often start over.

DSPy separates three concerns that prompts mix together:

  • Interface: the signature, for example "question -> answer" or a class with typed fields.
  • Strategy: the module, such as dspy.Predict, dspy.ChainOfThought or the tool using dspy.ReAct.
  • Parameters: the actual instructions and demonstrations. These are learned by an optimizer from a small training set and a metric, not typed by you.

The practical win is that when you change models or requirements, you rerun the optimizer instead of rewriting prompts. It also forces you to have a metric and a dataset, which is good discipline regardless of framework.

How it works

Rendering diagram…

A few terms:

  • Signatures can be inline strings ("article -> claims: list[str]") or classes that subclass dspy.Signature with dspy.InputField and dspy.OutputField. The class docstring becomes the task description. Types are enforced on the outputs.
  • Modules are composable like PyTorch modules. You write a class with sub modules in __init__ and logic in forward.
  • Optimizers (DSPy used to call them teleprompters) include BootstrapFewShot, BootstrapFewShotWithRandomSearch, MIPROv2, GEPA, SIMBA, COPRO, BootstrapFinetune and others. MIPROv2 searches over instructions and demonstrations. GEPA uses a reflection model that reads execution traces and textual feedback from your metric to propose better instructions.

Reference architecture

DSPy fits into a build time and run time split. Optimization is an offline job; the optimized program is a static artifact you load in production.

Rendering diagram…

Code

A support ticket triage program, then optimization with GEPA, following the patterns in the DSPy docs.

from typing import Literal

import dspy

lm = dspy.LM("openai/gpt-5.4-nano")
dspy.configure(lm=lm)


class Triage(dspy.Signature):
    """Classify a support ticket and draft a one line reply."""

    ticket: str = dspy.InputField()
    category: Literal["billing", "bug", "how_to", "other"] = dspy.OutputField()
    reply: str = dspy.OutputField(desc="One polite sentence")


class TriageBot(dspy.Module):
    def __init__(self):
        super().__init__()
        self.classify = dspy.ChainOfThought(Triage)

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


bot = TriageBot()
print(bot(ticket="I was charged twice this month").category)

# A handful of labelled examples (use dozens to hundreds in practice)
train = [
    dspy.Example(ticket="Card charged twice", category="billing").with_inputs("ticket"),
    dspy.Example(ticket="App crashes on login", category="bug").with_inputs("ticket"),
    dspy.Example(ticket="How do I export CSV?", category="how_to").with_inputs("ticket"),
]
val = train  # keep a separate set in real projects


def triage_metric(example, prediction, trace=None, pred_name=None, pred_trace=None):
    ok = example.category == prediction.category
    feedback = None if ok else f"Expected {example.category}, got {prediction.category}"
    return dspy.Prediction(score=float(ok), feedback=feedback)


optimizer = dspy.GEPA(
    metric=triage_metric,
    reflection_lm=dspy.LM("openai/gpt-5.4"),
    auto="light",
)
optimized = optimizer.compile(bot, trainset=train, valset=val)
optimized.save("triage_optimized.json")

# In production
prod_bot = TriageBot()
prod_bot.load("triage_optimized.json")

For tool use, dspy.ReAct("question -> answer", tools=[search, calc]) gives you an agent loop whose instructions can be optimized the same way.

Trade-offs and pitfalls

  • You need a metric and data. This is the price of admission. If you cannot say what "good" means in code, DSPy cannot optimize for it. (That is also a sign you are not ready to ship.)
  • Optimization costs tokens. Optimizers run your program many times. Start with auto="light" budgets, small datasets and cheap task models, and measure the bill.
  • Overfitting is real. Always hold out a validation set. An optimizer will happily memorize a tiny training set.
  • Less direct control over wording. If legal or brand teams must approve exact prompt text, the learned instructions may need review before deployment.
  • Different mental model. Engineers used to prompt editing need time to think in signatures and metrics. Pair it with tracing so people can see the prompts DSPy actually produced.
  • Not an orchestration engine. DSPy does not give you durable state or human approval steps. Use it inside a service or a LangGraph node.

When to pick it: you have a well defined task with labelled examples (classification, extraction, routing, structured generation, RAG answer quality), you switch models often, or you want measurable, repeatable prompt improvement instead of trial and error.

When not to: open ended creative chat with no metric, very early prototypes where requirements change daily, or flows where the hard part is orchestration and approvals rather than prompt quality.

Checklist

  • Write the metric before writing the program.
  • Collect a training set and a separate validation set from real inputs.
  • Use class based signatures with typed outputs for anything structured.
  • Start with a cheap optimizer budget and scale only if scores improve.
  • Save optimized programs as versioned artifacts and load them in production.
  • Re-run optimization when you change the model, and compare scores.
  • Trace optimized programs so you can read the prompts they generate.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.