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 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:

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:

OptimizerWhat it doesWhen to use it
LabeledFewShotAdds labeled examples to the promptQuick baseline, almost no cost
BootstrapFewShotGenerates demonstrations from your training set using the model itselfCheap, strong default for most programs
BootstrapFewShotWithRandomSearchTries random subsets of demonstrationsWhen you want a better set than one pass finds
MIPROv2Jointly tunes instructions and examples with Bayesian optimizationDemanding programs where quality matters most
COPROProposes and refines instructions iterativelyInstruction-only tuning
SIMBAImproves prompts in mini-batchesLarge programs and long optimization runs
BootstrapFinetuneCompiles a fine-tuned model instead of promptsWhen 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

  1. Install the package. Run pip install dspy. DSPy needs Python 3.9 or later.
  2. 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.
  3. Write a signature. Declare the inputs and outputs of your task, as in the BasicQA example above.
  4. Pick a module. Start with dspy.ChainOfThought(BasicQA) for any task that benefits from step-by-step reasoning.
  5. Build a small training set. Collect a few dozen examples with known answers. DSPy represents them as dspy.Example objects.
  6. Define a metric. Write a function that scores a prediction against the known answer. Exact match works for factoid answers.
  7. 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.
  8. 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

AspectManual promptingDSPy
What you writePrompt stringsSignatures and modules
How prompts improveHand editing and re-testingOptimizers search automatically
Switching modelsRe-tune every promptSame program, new model
EvaluationAd hoc, by eyeMetrics and development sets built in
Learning curveLow to startHigher, but the program is reusable
Best forOne-off calls and prototypesPipelines 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.