Contents
DSPy: Programming LLM Pipelines with Python

DSPy: When Writing Prompts Becomes Programming

In the rapidly changing world of large language models (LLMs), prompt engineering has become a key skill. But what if the days of manually tuning brittle prompts are numbered? Enter DSPy, a framework that treats an LLM pipeline like a software program.

DSPy, short for Declarative Self-improving Language Programs, is a Python library from Stanford NLP that lets you define, optimize and compose LLM-powered modules programmatically. Rather than writing long, complex prompts, define the structure of a task and let DSPy find how best to perform it.

The problem: traditional prompts are brittle

Imagine building a question-answering system. A traditional approach might be:

1

Create a complex prompt

with instructions, few-shot examples and output formatting.
2

Test and tune it

manually for different cases.
3

breaks the prompt

Discover that —say GPT-3.5 to Llama 3—or making a small data change .
4

Start again.

This cycle is inefficient, hard to scale and feels more like art than engineering.

Example: a manually created prompt

Answer the question based on the provided context.
Context: The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It is named after the engineer Gustave Eiffel, whose company designed and built the tower.
Question: Who designed the Eiffel Tower?
Answer: The Eiffel Tower was designed by Gustave Eiffel's company.
---
Context: The Great Wall of China is a series of fortifications that were built across the historical northern borders of ancient Chinese states and Imperial China as protection against various nomadic groups from the Eurasian Steppe.
Question: Why was the Great Wall of China built?
Answer: The Great Wall of China was built to protect against nomadic groups.
---
Context: {provided_context}
Question: {provided_question}
Answer:

This is rigid. If the question or context format changes, it may fail.

The solution: programmatic composition with DSPy

DSPy changes the approach. Rather than a monolithic prompt, define small reusable modules called signatures.

1. Signature: an atomic pipeline block

A signature declaratively describes the LLM's task, defining input and output fields.

python
import dspy

class BasicQA(dspy.Signature):
    """Answer questions based on context."""
    context = dspy.InputField(desc="may contain relevant facts")
    question = dspy.InputField()
    answer = dspy.OutputField(desc="often between 1 and 5 words")

What happened? We defined BasicQA inheriting from dspy.Signature. context and question are inputs; answer is output. The desc attributes are hints to the LLM about each field.

2. Modules: combining signatures

DSPy provides predefined modules for signatures. The simplest is dspy.Predict.

python
# Configure your LLM (e.g. OpenAI, Llama)
openai = dspy.OpenAI(model='gpt-3.5-turbo')
dspy.settings.configure(lm=openai)

# Create a prediction module
qa_predictor = dspy.Predict(BasicQA)

# Run prediction
result = qa_predictor(context="The capital of France is Paris.", question="What is the capital of France?")
print(result.answer) # Output: Paris

This is only the beginning. The real power comes from composition and optimization.

3. Composition: building complex pipelines

Consider a more complex RAG system. Traditionally it might be one huge prompt; with DSPy, we compose modules.

python
class RAG(dspy.Module):
    def __init__(self, num_passages=3):
        super().__init__()
        # 1. Retriever to find relevant documents
        self.retrieve = dspy.Retrieve(k=num_passages)
        # 2. Answer generator
        self.generate_answer = dspy.ChainOfThought(BasicQA)

    def forward(self, question):
        # Retrieve relevant contexts
        context = self.retrieve(question).passages
        # Generate an answer based on contexts
        prediction = self.generate_answer(context=context, question=question)
        return dspy.Prediction(context=context, answer=prediction.answer)

What happened? We created a RAG module, used dspy.Retrieve for retrieval (for example from a vector database) and dspy.ChainOfThought to generate an answer. In forward, we defined the flow: question → retrieve → generate_answer → prediction.

The magic: teleprompters and optimization

Here is the best part: DSPy can optimize your pipeline for you. The process is called compilation.

The compiler, called a Teleprompter, takes the pipeline and a few training examples, then automatically generates and tests different prompts for each module.

python
from dspy.teleprompt import BootstrapFewShot

# 1. Prepare a few examples (question, answer)
trainset = [
    dspy.Example(question="What is the capital of Slovakia?", answer="Bratislava").with_inputs("question"),
    dspy.Example(question="Who wrote Hamlet?", answer="William Shakespeare").with_inputs("question"),
]

# 2. Create an optimizer (Teleprompter)
# BootstrapFewShot creates few-shot examples for each step
teleprompter = BootstrapFewShot(metric=dspy.evaluate.answer_exact_match)

# 3. Run compilation
compiled_rag = teleprompter.compile(RAG(), trainset=trainset)

# 4. Use the optimized pipeline
prediction = compiled_rag(question="What is the highest mountain on Earth?")
print(prediction.answer) # The output will probably be more accurate

What happened during compilation?

1

Krok 1

DSPy ran the RAG pipeline on the training data.
2

It analyzed errors.

3

automatically generated few-shot examples

It for generate_answer based on successful and failed attempts.
4

The result was a new “compiled” pipeline with optimized prompts built in.

Why is this revolutionary?

1

Abstraction from a specific LLM:

Define the pipeline independently of a model; switch to a better one and recompile.
2

Performance:

Optimized pipelines can achieve significantly better results than manually tuned prompts.
3

Modularity:

Swap and combine modules such as dspy.ChainOfThought, dspy.ReAct and dspy.MultiChainComparison.
4

Reproducibility:

Version structured code rather than brittle prompts.
5

Data-driven approach:

Pipeline quality depends on data quality rather than prompt “magic”.

Conclusion

DSPy shifts the work from “prompt engineering” to “LLM programming”. It is a powerful tool for building robust, scalable and effective LLM applications. If you are tired of endless prompt tuning and want to approach LLMs like a software engineer, DSPy offers a way forward.

All articles