DSPy Explained: Optimizing Prompts Programmatically Instead of by Hand

DSPy replaces hand-written prompts with declarative signatures, composable modules and optimizers that compile prompts against a metric. Learn how it works.

By Galactic News Editorial · Published 2026-11-27T17:05:50+00:00 · Updated 2026-11-27T17:05:50+00:00

DSPy declarative prompt optimization explained for ML engineers

DSPy Explained: Optimizing Prompts Programmatically Instead of by Hand

Prompt engineering breaks at scale. A prompt that works for one model fails on the next. A few-shot example that helps one task hurts another. Every change means another round of hand editing and retesting. DSPy takes a different path. It treats prompts as parameters that a compiler optimises against a metric, the way a compiler optimises code. This guide explains how DSPy declarative prompt optimization works, when it helps, and how to start.

What DSPy is

DSPy stands for Declarative Self-improving Python. It is an open-source, MIT-licensed framework from Stanford NLP for programming language models instead of hand-writing prompts. The project lives at github.com/stanfordnlp/dspy, with documentation at dspy.ai. The foundational paper, published at ICLR 2024, is titled "DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines."

The core idea is simple. Instead of writing a prompt string, you declare what a task should do. Instead of tuning that string by hand, you run an optimizer that searches for the best prompt and the best few-shot examples for your metric. The framework's own summary says it best: DSPy is the framework for programming, rather than prompting, language models.

DSPy grew out of the earlier Demonstrate-Search-Predict framework from Stanford NLP. It is the second iteration of that idea, generalised into a full programming model for language model pipelines.

The three building blocks of DSPy declarative prompt optimization

DSPy has three core abstractions: signatures, modules and optimizers. They work together, and each one replaces a piece of manual prompt work.

Signatures are typed input-output contracts. A signature says which named fields go in and which come out, with descriptions for each. Write it as a string, such as "context, question -> answer", or as a Python class with typed fields. The signature says nothing about the prompt text. It is the contract between your code and the model, much like a function signature in a typed language.

Modules wrap a signature with a prompting strategy. They replace hand-written techniques with composable code. The built-in modules include Predict for direct completion, ChainOfThought for step-by-step reasoning, ReAct for interleaving reasoning with tool calls, and ProgramOfThought for generating and running code. You compose modules into a program, the way you compose layers in a neural network. Swap a module and the whole pipeline changes, without rewriting the downstream code.

Optimizers, historically called teleprompters, compile a program. An optimizer takes your program, a metric and a training set, and returns a new program with tuned instructions and few-shot examples. The compiled program is the output. You deploy it, and you recompile when the model or the task changes.

How the optimizers work

Different optimizers fit different budgets. BootstrapFewShot is the simplest. It runs the program on the training set, keeps the outputs that score well, and uses them as few-shot examples. It works well on small datasets.

BootstrapFewShotWithRandomSearch goes further. It explores many candidate sets of examples and keeps the ones that score best. It suits medium datasets where a single pass leaves performance on the table.

MIPROv2 is the most powerful optimizer in DSPy. It jointly optimises instructions and demonstrations. It works in three phases: an LLM proposes candidate instruction strings, each candidate is evaluated against a validation set using the quality metric, and a Bayesian surrogate model selects the most promising configurations for the next round. The loop repeats until the compiled program converges.

GEPA is a newer reflective optimizer. It uses the model's own reflections on failures to propose better instructions. BetterTogether combines prompt search with model fine-tuning, optimising both at once.

The paper's case studies show why this matters. Within minutes of compiling, a few lines of DSPy allowed GPT-3.5 and llama2-13b-chat to self-bootstrap pipelines that outperformed standard few-shot prompting, generally by over 25% and 65% respectively. Programs compiled to small open models like a 770M-parameter T5 were competitive with approaches that relied on expert-written prompt chains for proprietary GPT-3.5.

A minimal DSPy program, step by step

A first program takes about ten lines. Follow these steps.

  1. Install DSPy. Run pip install dspy. The framework needs Python 3.10 or later.
  2. Configure a language model. Point DSPy at a model with dspy.configure. The same code runs against different providers by changing one model string.
  3. Declare a signature. Write the task as input and output fields, for example a question going in and an answer coming out.
  4. Pick a module. Wrap the signature in ChainOfThought if the task needs reasoning, or Predict if it does not.
  5. Define a metric. Write a small function that scores an output against the expected answer. The metric is the target the optimizer aims at.
  6. Compile. Call an optimizer such as MIPROv2 with the program, the metric and a training set. Save the compiled program and deploy it.

The compiled program is a saved artifact with frozen prompts and examples. That is the point. The prompt becomes a versioned, testable output of a repeatable process, not a string pasted into code and forgotten.

When DSPy helps, and when it does not

DSPy helps most when you have a clear metric and labelled examples. Classification, extraction, retrieval QA and multi-step agent pipelines all fit. If you can score an output, the optimizer can improve it. It also helps when prompts must survive a model change. Recompile against the new model instead of rewriting every prompt by hand.

It helps less when the task has no measurable target. Open-ended creative writing and subjective style work have no metric to optimise against. It also adds overhead for a one-off call. A single prompt in a script does not need a compiler. DSPy earns its keep on pipelines that run repeatedly, change often, or must hit a quality bar.

There is also a cost to watch. Optimizers make many model calls during compilation. A MIPROv2 run over a large training set is not free. Budget for it, and keep the training set small enough to iterate quickly.

Bottom line

DSPy replaces hand-tuned prompt strings with a program, a metric and a compiler. You declare the task, pick a module, and let the optimizer find the prompt that scores best. For teams running language model pipelines in production, that turns prompt tuning from an art into a repeatable process. Start with one pipeline, one metric and BootstrapFewShot. Move to MIPROv2 when the dataset and the stakes justify it.