Writeup · Nov 22, 2026 · 12 min read

DSPy Optimizer Patterns: Signatures, MIPRO & Bootstrap Techniques

Writeup

Practical patterns for building optimizable LLM pipelines with DSPy. Covers signatures, modules, teleprompters, evaluation metrics, RAG implementations and production trade-offs with complete Python e

DSPy Optimizer Patterns: Signatures, MIPRO & Bootstrap Techniques

Core Concepts Behind DSPy

DSPy is a programming framework that treats prompts and LLM calls as composable modules rather than handwritten text. Instead of crafting individual prompts manually, developers define the desired input-output behavior through Python classes called signatures. The framework then uses optimizers to automatically improve those prompts or even fine-tune small language models based on a defined metric.

This approach shifts LLM engineering from prompt tweaking to program optimization. A DSPy program is a pipeline of modules that can be compiled against a training set and a metric, producing a version that performs better on held-out examples. The compiler, called a teleprompter, generates demonstrations, refines instructions, and selects effective few-shot examples.

At its foundation, DSPy separates three concerns: the program structure (how modules are wired), the language model being called, and the optimization process. This separation makes it possible to swap models, change optimizers, or modify the metric without rewriting the entire pipeline.

Signatures as Declarative Interfaces

Signatures are the central abstraction. A signature is a Python class that inherits from dspy.Signature and declares input and output fields with docstrings that describe the task.

import dspy

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")

class Classification(dspy.Signature):
    """Classify the sentiment of a customer review."""
    review: str = dspy.InputField()
    sentiment: str = dspy.OutputField(desc="positive, negative, or neutral")

The docstring at the class level acts as the base instruction. Field descriptions further guide the model. When using a predictor, DSPy automatically constructs a prompt that includes the instruction, the field descriptions, and any demonstrations.

Signatures support type hints and can include custom validation logic. They encourage reuse. The same BasicQA signature can be used inside a ChainOfThought module or composed into a larger multi-hop program. This reuse reduces duplication compared to copying prompt text across different parts of an application.

Advanced signatures can define multiple output fields or even structured outputs that the framework will parse. For JSON-like outputs, developers often combine signatures with output parsers provided by the underlying model client.

Predictors, Chains, and Module Composition

The simplest module is dspy.Predict, which takes a signature and calls the language model once. More sophisticated behavior comes from built-in modules such as dspy.ChainOfThought, which appends "Let's think step by step" reasoning to the prompt.

import dspy
from dspy.teleprompt import BootstrapFewShot

lm = dspy.OpenAI(model="gpt-3.5-turbo-instruct", max_tokens=512)
dspy.settings.configure(lm=lm)

qa = dspy.ChainOfThought(BasicQA)

result = qa(question="What is the capital of Japan?")
print(result.answer)
print(result.rationale)

Modules can be composed into larger programs. A common pattern is to create a custom module that inherits from dspy.Module and wires several predictors together.

class RAG(dspy.Module):
    def __init__(self):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=3)
        self.generate = dspy.ChainOfThought("context, question -> answer")
    
    def forward(self, question):
        context = self.retrieve(question).passages
        return self.generate(context=context, question=question)

This RAG class encapsulates both retrieval and generation. Because it inherits from dspy.Module, it can be passed to an optimizer as a complete program. The forward method defines the execution graph.

Composition patterns allow multi-stage reasoning. For example, a program might first generate search queries, retrieve documents for each query, then synthesize an answer. Each stage can use a different signature and different temperature or model.

Evaluation Metrics and the dspy.Evaluate Class

Optimization requires a measurable target. DSPy provides the dspy.Evaluate utility and supports both deterministic metrics and LLM-as-judge metrics.

A simple exact match metric for QA looks like this:

def exact_match(example, pred, trace=None):
    return example.answer.lower() == pred.answer.lower()

evaluator = dspy.Evaluate(
    devset=dev_examples,
    metric=exact_match,
    num_threads=8,
    display_progress=True
)

For more nuanced tasks, developers define custom metrics that return a float between 0 and 1. LLM-based metrics can compare predicted and gold answers using a stronger model such as GPT-4. These metrics are slower and more expensive but often correlate better with human judgment on open-ended tasks.

The evaluation harness runs the program on a dataset and aggregates the metric. During optimization, this evaluation loop is called repeatedly. Understanding the cost implications is critical: evaluating 500 examples with a 4k context model can consume significant tokens.

Developers should maintain separate dev and test sets. The optimizer uses the dev set for compilation; final reported numbers must come from the untouched test set to avoid overfitting to the metric.

Teleprompters and Optimization Strategies

Teleprompters are DSPy's optimizers. The simplest is LabeledFewShot, which selects random labeled examples to include in the prompt.

BootstrapFewShot is more powerful. It runs the program on training examples, captures traces where the metric passes, and uses those successful traces as demonstrations for future runs. The process is iterative: the current program generates new demonstrations that improve the next version.

from dspy.teleprompt import BootstrapFewShot

optimizer = BootstrapFewShot(
    metric=exact_match,
    max_bootstrapped_demos=4,
    max_labeled_demos=4
)

compiled_rag = optimizer.compile(
    student=RAG(),
    trainset=train_examples
)

The max_bootstrapped_demos parameter controls how many automatically generated examples are kept. Higher numbers increase prompt length and cost but can improve performance up to a saturation point.

MIPRO (Multi-Instruction Prompt Optimizer) is a more recent optimizer that jointly optimizes both the instruction text and the few-shot examples using a Bayesian approach. It runs many parallel trials with different instruction candidates generated by a large teacher model. MIPRO typically requires more compute but often yields stronger results than pure bootstrapping.

Each optimizer has different hyperparameters. BootstrapFewShotWithRandomSearch adds a random search over example combinations. Choosing the right optimizer depends on the task complexity, the size of the training set, and available compute budget.

Building and Optimizing a Retrieval-Augmented Generation Pipeline

A practical RAG implementation in DSPy combines a retriever module with a generation signature. DSPy ships with a simple dspy.Retrieve module that can be backed by any vector store through a custom RM (retrieval model) class.

Here is a more complete example using a ColBERTv2 retriever:

import dspy
from dspy.retrieve import ColBERTv2

colbert = ColBERTv2(url="http://localhost:8899")
dspy.settings.configure(rm=colbert)

class RAGSignature(dspy.Signature):
    """Answer the question based on the provided context."""
    context: list[str] = dspy.InputField(desc="may contain relevant facts")
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

class RAGProgram(dspy.Module):
    def __init__(self):
        self.retrieve = dspy.Retrieve(k=5)
        self.generate = dspy.ChainOfThought(RAGSignature)
    
    def forward(self, question):
        retrieved = self.retrieve(question).passages
        prediction = self.generate(context=retrieved, question=question)
        return dspy.Prediction(answer=prediction.answer, context=retrieved)

After defining the program, compile it against a training set that contains question-answer pairs. During bootstrapping, DSPy will run the retriever, feed results to the generator, and keep only traces where the final answer meets the metric.

One observed pattern is that optimized programs often produce more precise instructions such as "Use only information present in the context. If the context does not contain the answer, respond with 'I don't know'." These instructions emerge automatically from the teacher model during optimization.

After compilation, the resulting program can be saved with compiled_rag.save("rag_program.json") and reloaded in production without re-compiling.

Multi-Hop and Agentic Patterns

DSPy shines for multi-step reasoning. The HotPotQA task, which requires retrieving and combining information from multiple documents, is a canonical example.

A multi-hop program might contain a query generation module, a retrieval module, and a final answer synthesis module. Each hop can be optimized independently or as part of the full program.

ReAct-style agent loops can also be expressed in DSPy by creating a custom module that iterates between a proposal module and an observation module until a stopping condition is met. The optimizer can then improve the stopping criteria and the quality of intermediate proposals.

These agentic patterns trade latency and cost for better reasoning on complex questions. In production, developers often set hard limits on the number of hops or total tokens to control expenses.

Production Deployment Considerations

Once a program is compiled, the demonstrations and refined instructions are baked in. This compiled artifact can be loaded in a FastAPI service or a serverless function. Because the prompts are longer due to few-shot examples, token usage increases compared to zero-shot prompts.

Caching is essential. Identical questions should hit a cache before reaching the LLM. For RAG applications, caching at the retrieval level (by embedding hash) and at the generation level (by full prompt hash) reduces costs significantly.

Monitoring should track both task metrics and operational metrics. Log the input question, retrieved context, generated answer, latency, and token counts. Periodic re-evaluation on a growing golden dataset helps detect regression when underlying models change.

Model swapping is straightforward. A program optimized on GPT-3.5 can often be used with Claude or a local model, although performance varies. Some teams compile once with a strong teacher model and deploy with a cheaper student model.

Versioning compiled programs is important. Store the training set version, optimizer hyperparameters, and metric definition alongside the compiled artifact. This enables reproducible optimization runs weeks later.

Cost and Performance Trade-offs

Optimization is not free. A typical BootstrapFewShot run on 200 training examples with GPT-3.5 can cost between a few dollars and tens of dollars depending on context length and number of trials. MIPRO generally costs more because it explores a larger search space.

The benefit appears when the optimized program is used thousands of times. For high-volume applications, the improved accuracy and reduced need for manual prompt iteration easily justify the upfront cost.

Simpler tasks may not need optimization. If a zero-shot prompt already achieves 92% on the metric, adding few-shot examples may only yield marginal gains at the expense of higher latency and cost per request.

Interpretability decreases with automatic optimization. The generated instructions can be verbose or use unexpected phrasing. Teams that require explainability sometimes add a human review step for the compiled prompts before deploying them.

Overfitting to the metric is a real risk. Using an LLM judge as the metric can lead to prompt hacking where the program learns to exploit weaknesses in the judge rather than genuinely improve. Regular human spot checks on evaluation outputs are necessary.

Integration Patterns with Existing Tools

DSPy works alongside vector databases, embedding models, and orchestration frameworks. The dspy.Retrieve class can be subclassed to call Pinecone, Weaviate, or PostgreSQL with pgvector. The only requirement is implementing a forward method that accepts a query and returns a list of passages.

For embedding-based retrieval, many teams continue to use the same embedding model they already operate in production. DSPy does not dictate the embedding layer; it only consumes the retrieved text.

Logging and observability integrate naturally. Wrapping the DSPy module calls with OpenTelemetry spans allows tracing the full execution graph including retrieval and multiple LLM calls. Each module can emit its own span with input and output fields.

When deploying to production, teams often compile the program in a CI pipeline that runs nightly against an expanded training set. The compiled artifact is then published as a package or stored in object storage for services to download on startup.

Common Pitfalls and Debugging Techniques

One frequent issue is insufficient training data. DSPy works best with at least 50-100 high-quality labeled examples. Synthetic data generated by a larger model can bootstrap the process but should be validated by humans.

Trace inspection is the primary debugging tool. The dspy.settings.configure flag trace can be enabled to capture full LLM calls. Examining failed traces reveals whether the retriever returned irrelevant passages or the generator ignored relevant information.

Hyperparameter sensitivity is another concern. Changing max_bootstrapped_demos from 3 to 8 can swing accuracy by 10-15 percentage points on some tasks. Systematic ablation studies are recommended before locking in a configuration.

Token limits become problematic with long contexts. When using ChainOfThought inside a multi-hop program, intermediate reasoning can push the total prompt over the model's context window. Pruning retrieved passages by relevance score or using a summarization module helps manage context length.

When DSPy Makes Sense for Startups and Small Teams

Small teams benefit from DSPy when they have repeatable LLM tasks with measurable success criteria. Customer support triage, structured data extraction from documents, and synthetic dataset generation are strong candidates.

If the product relies on a single prompt that rarely changes, manual engineering may remain simpler. The framework shines when multiple prompts interact inside a pipeline and manual coordination becomes error-prone.

The learning curve is moderate for developers already comfortable with Python and prompt engineering. The main mental shift is from thinking in natural language prompts to thinking in composable modules and metrics.

Because compiled programs are portable, a startup can prototype with expensive models and later optimize for cheaper inference endpoints without changing application code. This flexibility supports iterative product development while controlling infrastructure costs.

Future directions for the framework include tighter integration with fine-tuning loops and support for multimodal signatures. The core pattern of declarative modules plus automatic optimization is likely to influence how production LLM applications are built in the coming years.

By treating prompts as optimizable code rather than static text, DSPy offers a systematic path toward more reliable LLM systems. The patterns described here—careful signature design, metric-driven evaluation, iterative bootstrapping, and disciplined production deployment—provide a foundation that teams can adapt to their specific domains and constraints.

Keep reading

Related Research