Contents
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:
Create a complex prompt
Test and tune it
breaks the prompt
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.
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.
# 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: ParisThis 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.
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.
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 accurateWhat happened during compilation?
Krok 1
RAG pipeline on the training data.It analyzed errors.
automatically generated few-shot examples
generate_answer based on successful and failed attempts.The result was a new “compiled” pipeline with optimized prompts built in.
Why is this revolutionary?
Abstraction from a specific LLM:
Performance:
Modularity:
dspy.ChainOfThought, dspy.ReAct and dspy.MultiChainComparison.Reproducibility:
Data-driven approach:
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.