DSPy Explained: Programming Language Models Instead of Prompting
DSPy replaces hand-written prompts with programs. Signatures declare the task, modules compose the pipeline, and optimizers tune the prompts automatically.
By Galactic News Editorial · Published 2026-11-19T01:44:57+00:00 · Updated 2026-11-19T01:44:57+00:00
DSPy Explained: Programming Language Models Instead of Prompting
DSPy is a Python framework for building language-model programs. Instead of writing prompts by hand and tuning them through trial and error, you declare what the model should do, compose those declarations into a pipeline, and let DSPy find the best prompts for you. The tagline is "programming, not prompting" language models. This explainer covers how it works, when it helps, and how to write your first program.
What DSPy is
DSPy stands for Declarative Self-improving Python. It comes from the Stanford NLP group, led by researcher Omar Khattab. The core paper, "DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines", was published in October 2023 and appeared at ICLR 2024. The framework grew out of earlier Stanford work on compound language-model systems, including ColBERT-QA and Baleen. An earlier version was called DSP. The rename to DSPy came with the paper in October 2023.
The problem DSPy attacks is familiar to anyone who has built with language models. Prompts are fragile strings. A small wording change can swing results. Moving to a new model means re-tuning every prompt. DSPy treats prompts the way PyTorch treats neural networks: they become compiled artifacts, generated from higher-level code rather than written by hand. You write the program. The framework writes the prompts.
DSPy explained: signatures declare the task
The first core idea is the signature. A signature is a typed declaration of what a language-model call should do. It names the inputs and the outputs, not the prompt text. Here is the canonical example from the official documentation:
class BasicQA(dspy.Signature):
"""Answer questions with short factoid answers."""
question: str = dspy.InputField()
answer: str = dspy.OutputField(desc="often between 1 and 5 words")
The signature says the task takes a question and returns a short answer. It says nothing about how to phrase the request to the model. DSPy compiles the signature into an effective prompt at run time. Change the model, and the same signature still works, because the prompt is generated for the model you configured. You can also write a signature as a short string, such as "question -> answer", for simple cases.
Modules: composable building blocks
The second core idea is the module. Modules are composable building blocks with learnable parameters, inspired by PyTorch's nn.Module. Each module is a strategy for calling a language model against a signature. The main ones are:
- dspy.Predict — the simplest module. It makes one direct call to the model for the signature.
- dspy.ChainOfThought — asks the model to reason step by step before answering. Wrapping a signature in ChainOfThought is often the first improvement you try.
- dspy.ReAct — runs a reasoning-and-action loop, letting the model call tools while it works.
- dspy.Retrieve — fetches context documents from a retriever, such as ColBERTv2, for retrieval-augmented generation.
- dspy.ProgramOfThought — has the model write and run code for tasks that need exact computation.
- dspy.RLM — runs sandboxed Python reasoning, with optional tools.
- dspy.Parallel — runs several predictions at once across threads.
You compose modules into a program with a forward method, just as you compose layers in PyTorch. A question-answering pipeline might retrieve passages with dspy.Retrieve, then answer with dspy.ChainOfThought. Each step is a module with its own signature. The program is ordinary Python code, so you can test it, version it and reuse it.
Optimizers: the compiler that tunes your prompts
The third core idea is the optimizer, originally called a teleprompter. You provide a small training set and a metric, a function that scores whether an output is good. The optimizer then searches for better instructions and few-shot examples, and compiles them into your program. The main optimizers are:
| Optimizer | What it does | When to use it |
|---|---|---|
| LabeledFewShot | Adds labeled examples to the prompt | Quick baseline, almost no cost |
| BootstrapFewShot | Generates demonstrations from your training set using the model itself | Cheap, strong default for most programs |
| BootstrapFewShotWithRandomSearch | Tries random subsets of demonstrations | When you want a better set than one pass finds |
| MIPROv2 | Jointly tunes instructions and examples with Bayesian optimization | Demanding programs where quality matters most |
| COPRO | Proposes and refines instructions iteratively | Instruction-only tuning |
| SIMBA | Improves prompts in mini-batches | Large programs and long optimization runs |
| BootstrapFinetune | Compiles a fine-tuned model instead of prompts | When prompt tuning is not enough |
A newer optimizer, GEPA, uses reflective prompt evolution and was presented at ICLR 2026. It reflects on the model's own errors to propose better instructions. The official documentation also reports a striking result: on a labeling task, GPT-4o-mini's accuracy rose from 66 percent to 87 percent just by running an optimizer over the same code, with no prompt rewriting by hand.
Metrics are the other half of the system. A metric is a function that returns a number or a boolean for a prediction. It can be exact-match scoring, a parsed answer check, or a language model acting as a judge. DSPy ships an evaluation helper, dspy.evaluate.Evaluate, that runs your program over a development set and reports the metric. Save a compiled program with .save() and load it back with .load() when you need it again.
Your first DSPy program, step by step
- Install the package. Run
pip install dspy. DSPy needs Python 3.9 or later. - Configure a language model. DSPy uses LiteLLM under the hood, so most providers work with the same syntax. For OpenAI, set your API key and call
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini")). Local models work too, through Ollama. - Write a signature. Declare the inputs and outputs of your task, as in the BasicQA example above.
- Pick a module. Start with
dspy.ChainOfThought(BasicQA)for any task that benefits from step-by-step reasoning. - Build a small training set. Collect a few dozen examples with known answers. DSPy represents them as dspy.Example objects.
- Define a metric. Write a function that scores a prediction against the known answer. Exact match works for factoid answers.
- Compile with an optimizer. Run
dspy.BootstrapFewShot(metric=your_metric).compile(program, trainset=trainset). The optimizer returns a compiled program with better prompts baked in. - Evaluate before you ship. Run the compiled program over a held-out development set with dspy.evaluate.Evaluate. Compare the score with the uncompiled version. If the score did not improve, try MIPROv2.
DSPy vs manual prompting
| Aspect | Manual prompting | DSPy |
|---|---|---|
| What you write | Prompt strings | Signatures and modules |
| How prompts improve | Hand editing and re-testing | Optimizers search automatically |
| Switching models | Re-tune every prompt | Same program, new model |
| Evaluation | Ad hoc, by eye | Metrics and development sets built in |
| Learning curve | Low to start | Higher, but the program is reusable |
| Best for | One-off calls and prototypes | Pipelines you will run and improve over time |
When DSPy pays off, and when it does not
DSPy pays off when you run the same task many times and care about quality. Classification, extraction, multi-step question answering and retrieval pipelines are the sweet spot. If you have labeled examples and a metric you trust, the optimizer will usually beat hand-written prompts, and the gain compounds as you add data.
It does not pay off for one-off calls, where writing a prompt is faster than building a program. It also does not help when you cannot define a metric. If you cannot score an output automatically, the optimizer has nothing to optimize. Creative writing and open-ended chat are poor fits for the same reason. Start with a task that has right answers, measure the baseline, and only then invest in optimization.
Bottom line
DSPy changes the unit of work from the prompt to the program. Signatures declare what each step does. Modules compose those steps into pipelines. Optimizers tune the prompts behind them, using your data and your metric. The result is a system that survives a model change and improves as you add examples. If you build language-model features that need to keep working, that is a better foundation than a folder full of prompt strings.