Quick Start (5 min): Your First DSPy Program
Manual prompt engineering breaks under the slightest pressure. You can spend 40 hours tweaking adjectives, punctuation, and system prompt delimiters. Yet the moment you switch from GPT-4o to Claude 3.5 Sonnet or an 8B local model, accuracy often drops by 15% to 30%. DSPy discards prompt templates altogether. Instead, it lets you compose declarative Python modules that compile directly against target language models.
You can get a working pipeline running in under three minutes. Start by spinning up a clean virtual environment and installing the core libraries:
pip install dspy-ai python-dotenv
Next, wire up your model backend and specify a task signature. A signature specifies input and output fields as typed contracts. It completely separates your pipeline logic from raw string formatting:
import os
import dspy
# Configure language model backend
lm = dspy.LM('openai/gpt-4o-mini', api_key=os.getenv('OPENAI_API_KEY'))
dspy.configure(lm=lm)
# Step 1: Define the task signature
class TechnicalSummarizer(dspy.Signature):
"""Summarize complex technical logs or stack traces into actionable fixes."""
raw_log = dspy.InputField(desc="Unformatted runtime logs or error traces")
root_cause = dspy.OutputField(desc="Concise explanation of the underlying failure")
fix_action = dspy.OutputField(desc="Prescriptive steps or terminal commands to resolve it")
# Step 2: Wrap inside a predictor module
summarizer = dspy.Predict(TechnicalSummarizer)
# Step 3: Run inference
sample_log = """
2026-11-20T10:14:02Z ERROR [worker-pod-4b] psycopg2.OperationalError:
FATAL: remaining connection slots are reserved for non-replication superuser connections
"""
response = summarizer(raw_log=sample_log)
print("Root Cause:", response.root_cause)
print("Action:", response.fix_action)
Under the hood, DSPy renders the prompt, queries the API, and validates the output schema. You get clean object attributes directly. Forget about writing brittle regex parsers or debugging broken JSON responses.
Deep Dive: Core Mechanics and Declarative Modules
Building real applications requires mastering three fundamentals: Signatures, Modules, and Teleprompters (Optimizers).
Signatures vs. Traditional Prompt Templates
Conventional LLM frameworks rely on sprawling f-strings or Jinja templates. Rename a single variable in that setup, and downstream parsers immediately choke. DSPy signatures prevent that failure mode by providing explicit, typed contracts:
# Inline shorthand signature
classify_sentiment = dspy.Predict("sentence -> sentiment: bool")
# Class-based custom signature for complex schemas
class BugReportTriage(dspy.Signature):
issue_title = dspy.InputField()
reproduction_steps = dspy.InputField()
component = dspy.OutputField(desc="Subsystem name e.g., auth, database, frontend")
severity_score = dspy.OutputField(desc="Integer scale from 1 (trivial) to 5 (outage)")
Predict vs. ChainOfThought Modules
Predictors execute your signatures. While dspy.Predict performs direct single-turn transformations, dspy.ChainOfThought automatically adds internal reasoning steps before generating the final fields. You never have to modify the underlying signature:
class SQLDebugger(dspy.Module):
def __init__(self):
super().__init__()
# Injects reasoning step automatically
self.debugger = dspy.ChainOfThought("schema, query, error_message -> fixed_query")
def forward(self, schema, query, error_message):
return self.debugger(
schema=schema,
query=query,
error_message=error_message
)
Advanced Usage: Automated Prompt Optimization with Teleprompters
This is where DSPy transforms your development workflow. Rather than manually testing 50 prompt variants in a spreadsheet, DSPy optimizers (historically called teleprompters) search the space for you. They systematically discover optimal few-shot demonstrations, instruction prefixes, and reasoning paths across your validation data.
Defining the Metric and Dataset
Optimizers need two things: representative training samples and a quantitative evaluation metric. Here is how to construct a scoring function for triaging support tickets:
# Build a tiny training set of labeled gold examples
trainset = [
dspy.Example(
ticket="Cannot connect to replica database on port 5433",
category="Infrastructure",
urgency="High"
).with_inputs("ticket"),
dspy.Example(
ticket="Typo in footer link on billing settings page",
category="UI/UX",
urgency="Low"
).with_inputs("ticket"),
dspy.Example(
ticket="Stripe webhook signature validation failing intermittently",
category="Billing-API",
urgency="High"
).with_inputs("ticket"),
]
# Define the evaluation metric
def ticket_accuracy(example, prediction, trace=None):
category_match = example.category.lower() == prediction.category.strip().lower()
urgency_match = example.urgency.lower() == prediction.urgency.strip().lower()
return category_match and urgency_match
Compiling with BootstrapFewShot
The compiler runs candidate examples through your pipeline. It records successful runs that pass your metric, extracts effective reasoning steps, and synthesizes them into an optimized program:
from dspy.teleprompt import BootstrapFewShot
class TicketClassifier(dspy.Module):
def __init__(self):
super().__init__()
self.triage = dspy.ChainOfThought("ticket -> category, urgency")
def forward(self, ticket):
return self.triage(ticket=ticket)
# Configure the teleprompter
teleprompter = BootstrapFewShot(
metric=ticket_accuracy,
max_bootstrapped_demos=2,
max_labeled_demos=2
)
# Compile (tune) the pipeline
uncompiled_program = TicketClassifier()
compiled_program = teleprompter.compile(student=uncompiled_program, trainset=trainset)
# Save the compiled parameters for deployment
compiled_program.save("ticket_classifier_compiled.json")
# Test on unseen inputs
test_ticket = "Worker node out of memory; pod evicted during nightly batch processing"
result = compiled_program(ticket=test_ticket)
print(f"Predicted Category: {result.category}")
print(f"Predicted Urgency: {result.urgency}")
Practical Tips for Production Workflows
- Version control compiled JSON artifacts: Stop hardcoding prompt strings into application repositories. Treat compiled output files from
compiled_program.save()like model checkpoints. Track them in Git alongside test suites. If accuracy regresses, rollback takes seconds. - Dual-model compilation: Use an advanced teacher model like GPT-4o or Claude 3.5 Sonnet to synthesize reasoning traces during optimization. Then compile those demonstrations into a smaller student model like Llama 3.1 8B or GPT-4o-mini. This gives you frontier-grade accuracy while slashing inference costs by over 70%.
- Design continuous metrics: Binary 0/1 metrics work for basic label classification. For long-form text or multi-field extraction, use composite scores. Blending token overlap (F1) with schema validation and embedding distance gives the optimizer a smoother gradient to navigate.
- Inspect raw calls during development: Debugging unexpected model responses is straightforward. Run
lm.inspect_history(n=1)right after execution to see the exact payload sent over HTTP. It prints the exact delimiters and prompt injections generated by the compiler.

