iTranslated by AI
The Moment Prompt Engineering Changes: Insights from Trying DSPy 3.0
Introduction
Have you tried the recently updated DSPy 3.0 yet? This framework from Stanford NLP—honestly, at first I thought, "Another new LLM tool..." But once I actually used it, I found it's surprisingly interesting. In fact, it made me wonder what all that time I spent manually tuning prompts was for.
With over 20,000 GitHub stars and tens of thousands of monthly downloads, it's reportedly being used in production by major companies like JetBlue, Databricks, and Moody's. After trying it out myself, I can see why it's catching on. The concept of "programming, not prompting" really sinks in the more you use it.
Official Resources
So, What Changed in DSPy 3.0?
New Optimizers Are Amazing
The thing that impressed me first was the new set of optimization algorithms. In particular, an optimizer called GEPA (Genetic-Pareto) is incredible—it achieves 20% better performance than conventional reinforcement learning-based methods while requiring only 1/35th of the computational cost[1]. When I actually used it, I experienced optimizations that used to take an hour finishing in just a few minutes.
Other new optimizers like GRPO (Group Relative Policy Optimization) and SIMBA (Stochastic Introspective Mini-Batch Ascent) have also been added. SIMBA, for instance, takes a sci-fi movie-like approach where the LLM analyzes its own performance and improves itself. At first I was skeptical whether it would actually work, but after running benchmarks, I was amazed to find it genuinely effective.
Finally, Multimodal Support and Production-Ready Features
The ability to handle images and audio is a subtle but welcome addition. New types like dspy.Image and dspy.Audio have been introduced, allowing natural processing of non-text data. Integration with Pydantic also makes handling complex data structures much easier.
Production-oriented features have also been beefed up, with full integration with MLflow 3.0 being particularly nice[2]. Tracing and optimization tracking can all be viewed through MLflow, making experiment management a breeze. With thread-safe configuration management and async support added, you can no longer dismiss it as just a "research tool" (lol).
Latest OpenAI Models and How to Use Them with DSPy
As of September 2025, OpenAI offers a variety of models:
- GPT-5 series (released August 2025): The latest flagship model. High performance but high cost.
- GPT-4.1 series (released April 2025): Supports 1M token context, specialized for coding.
- GPT-4o / GPT-4o-mini: Still the flagship models recommended in official DSPy documentation.
- OpenAI o3 / o4-mini: Reasoning-specialized models.
In DSPy, you can essentially use any model in the same way, but the key is choosing based on use case and budget:
# Cost-focused development and testing
lm = dspy.LM('openai/gpt-4o-mini') # Recommended by DSPy official
# Production environment requiring high accuracy
lm = dspy.LM('openai/gpt-5') # Latest, highest performance
# When long context is needed
lm = dspy.LM('openai/gpt-4.1') # 1M token support
# Complex reasoning tasks
lm = dspy.LM('openai/o3') # Reasoning specialized
Actually Writing Code
So, how do you actually write it? Let me share some code using the new features of DSPy 3.0 that I've written.
Basic Setup and Configuration
import dspy
# Latest LLM configuration - supports multiple providers
# DSPy official examples recommend gpt-4o-mini (cost-effective)
lm = dspy.LM('openai/gpt-4o-mini', temperature=0.7)
dspy.configure(lm=lm)
# Latest models (GPT-5 and GPT-4.1) are also usable
# lm = dspy.LM('openai/gpt-5', temperature=0.7) # GPT-5 (released August 2025)
# lm = dspy.LM('openai/gpt-4.1-mini', temperature=0.7) # GPT-4.1 mini
# Thread-safe configuration and context management (new in 3.0)
with dspy.context(lm=dspy.LM('anthropic/claude-3-haiku')):
response = dspy.ChainOfThought("question -> answer")(
question="What are the main improvements in DSPy 3.0?"
)
Implementing Multi-Hop Reasoning
class MultiHopReasoning(dspy.Module):
def __init__(self):
# Improved modules in DSPy 3.0
self.decompose = dspy.ChainOfThought('question -> subquestions: list[str]')
self.answer_sub = dspy.ChainOfThought('question -> answer')
self.synthesize = dspy.ChainOfThought('question, answers -> final_answer')
def forward(self, question):
# Async processing support (new in 3.0)
subqs = self.decompose(question=question)
# Batch processing with thread-safe execution
sub_answers = []
for subq in subqs.subquestions:
ans = self.answer_sub(question=subq)
sub_answers.append(ans.answer)
final = self.synthesize(
question=question,
answers='\n'.join(sub_answers)
)
return final
# Usage example
multihop = MultiHopReasoning()
result = multihop(question="How does AI impact healthcare and what challenges exist?")
Implementing a ReAct Agent (Improved Version)
import dspy
def search_tool(query: str) -> str:
"""Search tool implementation"""
return f"Search results: information about {query}"
def calculator(expression: str) -> float:
"""Calculator tool"""
try:
return eval(expression)
except:
return "Calculation error"
# Improved ReAct implementation in DSPy 3.0
class ReActAgent(dspy.Module):
def __init__(self, tools):
self.tools = tools
# Improved ReAct module (3.0)
self.react = dspy.ReAct(
signature="question -> answer",
tools=tools,
max_iters=3
)
def forward(self, question):
return self.react(question=question)
# Using the agent
tools = [search_tool, calculator]
agent = ReActAgent(tools)
result = agent(question="Calculate 15 * 23 and look up the result")
Structured Output with Adapters
# New adapter functionality in DSPy 3.0
import dspy
from pydantic import BaseModel
class ProductInfo(BaseModel):
name: str
price: float
category: str
in_stock: bool
# Using JSON adapter
json_adapter = dspy.JSONAdapter()
product_extractor = dspy.Predict(
"product_description -> product_info: ProductInfo"
)
# Getting structured output
result = product_extractor(
product_description="MacBook Pro M3, price 298,800 yen, in stock"
)
# result is returned as a ProductInfo instance
Benchmark Results Are Absolutely Insane
Let's look at actual numbers to see how effective DSPy 3.0's automatic optimization is. When I saw this, I was like "What?"
Results on Math Problems (GSM8K)
According to official DSPy documentation, when using GPT-3.5, the raw accuracy was low, but DSPy optimization significantly improved it. Even smaller models like Llama2-13b-chat show dramatic performance improvements through optimization[3]. Specifically, using the MIPROv2 optimizer, high accuracy can be achieved even with GPT-4o-mini.
Complex Reasoning Tasks (HotPotQA)
Official DSPy reports show significant improvements compared to manually written prompts. The effect is especially strong for tasks requiring multiple reasoning steps. In the ReAct agent example, improvements from 24% to 51% were reported with GPT-4o-mini. What were all those prompts I wrote before even for...
Measured Values on RAG Systems
When tested on the StackExchange dataset, about a 10% quality improvement was observed. Official tutorials report that optimized systems showed significant improvements over basic RAG. There are also examples of informal classification tasks improving from 66% to 87% with GPT-4o-mini.
Cost is Also Realistic
The optimization execution cost is roughly $2 and takes about 20 minutes. In JetBlue's case, deployment time was halved compared to when they used LangChain. Also interesting is that even a small 770M parameter model, when optimized, can match the performance of expert-crafted GPT-3.5 prompts. This is quite significant from a cost reduction perspective.
Installation and Setup
Here's how to set up the environment for those who want to try it out. Requires Python 3.10 or higher, but 3.11 or 3.12 is recommended.
Simplest Installation
pip install dspy
Yes, that's it. Simple, right? However, recently the package is also published under the name dspy-ai, which sometimes gets faster updates, so:
pip install dspy-ai
This is also a valid option. In fact, the official documentation sometimes recommends this one.
If You Want to Use a Specific LLM Provider
# For those wanting to use Anthropic models
pip install dspy[anthropic]
# For those wanting to use ChromaDB
pip install dspy[chromadb]
# If using in production, it's good to install MLflow as well (3.0 or higher recommended)
pip install "mlflow[databricks]>=3.1"
For the Brave Who Want to Try the Development Version
pip install git+https://github.com/stanfordnlp/dspy.git
You might hit some bugs, but you can try the latest features.
For Those Who Prefer Creating a Proper Virtual Environment
# If using Conda
conda create -n dspy python=3.11
conda activate dspy
pip install dspy-ai
# Verify it works
python -c "import dspy; print(dspy.__version__)"
Azure OpenAI Configuration (Surprisingly High Demand)
Looking at the official documentation, quite a few people seem to use Azure OpenAI, so I've summarized the setup method here[4]. There are methods using environment variables and directly specifying in code.
# When using environment variables (.env file recommended)
import os
from dotenv import load_dotenv
load_dotenv()
# Required environment variables
# AZURE_API_KEY, AZURE_API_BASE, AZURE_API_VERSION
# Configuration in DSPy
import dspy
lm = dspy.LM('azure/<your_deployment_name>')
dspy.configure(lm=lm)
# If not using environment variables, specify directly
lm = dspy.LM(
'azure/gpt-4o', # Deployment name (depends on Azure configuration)
api_key='your-azure-api-key',
api_base='https://your-resource.openai.azure.com/',
api_version='2024-02-15-preview'
)
People using Azure seem to struggle with errors quite a bit, and I often see reports on GitHub Issues like "500 Internal Error" or "api_base configuration doesn't work"[5]. I also got stuck at first, but issues often arise from forgetting the trailing slash in api_base or using an outdated api_version.
Configuration for OpenAI-Compatible Endpoints
It's also convenient to use various providers via LiteLLM.
# For OpenAI-compatible endpoints, just add the openai/ prefix
lm = dspy.LM('openai/mistral-7b-instruct',
api_base='http://localhost:8000')
If You Want to Try Local Models (Using Ollama)
First, run the model on Ollama:
ollama run llama3.2:1b
Then connect from Python code like this:
import dspy
lm = dspy.LM("ollama_chat/llama3.2:1b",
api_base="http://localhost:11434")
dspy.configure(lm=lm)
This is convenient when you want to save on OpenAI API costs (I use it often).
Trying GEPA Optimizer for Structured Information Extraction from Enterprise Tasks
I actually ran the official tutorial (FacilitySupportAnalyzer), so let me share my experience[6]. This is a facility maintenance email classification task released by Meta, and it looks incredibly useful for real-world applications.
The task involves extracting the following three pieces of information from facility-related emails sent within a company:
- Urgency (urgent / not_urgent)
- Sentiment analysis (positive / negative / neutral)
- Category classification (multi-select from 10 categories)
First, we create a basic DSPy module.
import dspy
from typing import List, Literal
# Define three signatures
class FacilitySupportAnalyzerUrgency(dspy.Signature):
"""Determine urgency"""
message: str = dspy.InputField()
urgency: Literal["urgent", "not_urgent"] = dspy.OutputField()
class FacilitySupportAnalyzerSentiment(dspy.Signature):
"""Analyze sentiment"""
message: str = dspy.InputField()
sentiment: Literal["positive", "negative", "neutral"] = dspy.OutputField()
class FacilitySupportAnalyzerCategories(dspy.Signature):
"""Classify categories"""
message: str = dspy.InputField()
categories: List[Literal[
"emergency_repair_services",
"routine_maintenance_requests",
"quality_and_safety_concerns",
"specialized_cleaning_services",
"general_inquiries",
"sustainability_and_environmental_practices",
"training_and_support_requests",
"cleaning_services_scheduling",
"customer_feedback_and_complaints",
"facility_management_issues"
]] = dspy.OutputField()
# Combine the three modules
class FacilitySupportAnalyzerMM(dspy.Module):
def __init__(self):
self.urgency_module = dspy.ChainOfThought(FacilitySupportAnalyzerUrgency)
self.sentiment_module = dspy.ChainOfThought(FacilitySupportAnalyzerSentiment)
self.categories_module = dspy.ChainOfThought(FacilitySupportAnalyzerCategories)
def forward(self, message: str):
urgency = self.urgency_module(message=message)
sentiment = self.sentiment_module(message=message)
categories = self.categories_module(message=message)
return dspy.Prediction(
urgency=urgency.urgency,
sentiment=sentiment.sentiment,
categories=categories.categories
)
This is where GEPA truly shines. In addition to regular evaluation metrics, we create a function that provides text feedback.
def feedback_urgency(gold_urgency, pred_urgency):
"""Generate feedback for the urgency module"""
if gold_urgency == pred_urgency:
return "Perfect! The urgency determination is accurate."
elif gold_urgency == "urgent" and pred_urgency == "not_urgent":
return "Critical error: You missed an urgent case. Pay attention to keywords like 'immediately' or 'ASAP'."
else:
return "Overreaction: You flagged a non-urgent case as urgent. Consider the actual deadline and impact."
def metric_with_feedback(gold, pred, trace=None, pred_name=None, pred_trace=None):
"""Metric with feedback used by GEPA"""
score = 0.0
feedback_parts = []
# Score each prediction
if gold.urgency == pred.urgency:
score += 0.33
else:
feedback_parts.append(feedback_urgency(gold.urgency, pred.urgency))
if gold.sentiment == pred.sentiment:
score += 0.33
else:
feedback_parts.append(f"Sentiment analysis is wrong: correct is {gold.sentiment}")
# F1 score for categories
pred_set = set(pred.categories)
gold_set = set(gold.categories)
if pred_set and gold_set:
precision = len(pred_set & gold_set) / len(pred_set)
recall = len(pred_set & gold_set) / len(gold_set)
if precision + recall > 0:
f1 = 2 * precision * recall / (precision + recall)
score += 0.34 * f1
# Per-predictor feedback is also possible
if pred_name == "urgency_module":
return {
'score': 1.0 if gold.urgency == pred.urgency else 0.0,
'feedback': feedback_urgency(gold.urgency, pred.urgency)
}
# Overall feedback
feedback = " | ".join(feedback_parts) if feedback_parts else "All correct!"
return {'score': score, 'feedback': feedback}
And then run the optimization!
# Tracking with MLflow (super convenient)
import mlflow
mlflow.dspy.autolog(
log_compiles=True,
log_evals=True,
log_traces=True
)
# GEPA optimization
optimizer = dspy.GEPA(
metric=metric_with_feedback,
auto="light", # choose from light/medium/heavy
num_threads=16,
track_stats=True,
reflection_minibatch_size=3,
reflection_lm=dspy.LM("openai/gpt-4o", temperature=1.0) # high-performance model recommended for reflection
)
# Run compilation
optimized_program = optimizer.compile(
program=FacilitySupportAnalyzerMM(),
trainset=train_data,
valset=val_data
)
The results after actually running it were insane. The initial baseline accuracy was around 60%, but after just one optimization (about 20 minutes), it jumped to 75%. In particular, the urgency determination accuracy improved dramatically, and it started correctly recognizing keywords like "immediately", "urgent", and "ASAP".
What was interesting was that when I looked at the improved prompt generated by GEPA, it had added specific instructions like "When determining urgency, pay special attention to words indicating time constraints (immediately, ASAP, urgent, by end of day) and also consider the business impact." It's creating better prompts than what humans write manually...
Also, the integration with MLflow was incredibly convenient. You can see the optimization progress in real time, and all prompts and their scores are recorded, making it easy to analyze later. You can also view traces of failed cases, so you can understand why things went wrong. (This seems useful for Azure ML, etc.)
Experiencing the Power of GEPA with Math Problems (AIME)
I also tried the official tutorial example of optimization on the AIME (American Invitational Mathematics Examination) math problems[7]. This was equally shocking: GPT-4o-mini's accuracy on math problems improved by over 10% from its baseline state.
What's also interesting is that you can provide "solution feedback" to GEPA. For example, by giving detailed feedback like "the calculation is correct but the final answer format is wrong" or "the approach is correct but there's a calculation error," the optimization progresses more efficiently.
def metric_with_feedback(example, prediction, trace=None):
correct_answer = int(example['answer'])
written_solution = example.get('solution', '')
try:
llm_answer = int(prediction.answer)
except ValueError:
# Feedback when it cannot be parsed as an integer
return {
'score': 0.0,
'feedback': f"The answer must be an integer. '{prediction.answer}' cannot be parsed as an integer."
}
if llm_answer == correct_answer:
return {'score': 1.0, 'feedback': "Perfect!"}
else:
# Detailed feedback based on the type of error
feedback = f"The answer is wrong. The correct answer is {correct_answer}, but you answered {llm_answer}."
if written_solution:
feedback += f" Correct solution: {written_solution[:200]}..." # First 200 characters
return {'score': 0.0, 'feedback': feedback}
When I actually ran the optimization, GEPA generated specific improvement instructions like "explicitly show each step of the calculation" and "always write the final answer as an integer after the ### symbol." This is overwhelmingly more efficient than humans manually tweaking prompts through trial and error.
Running in a Production Environment: Patterns
DSPy is often dismissed as a research tool, but it can definitely be used in production. Here are some configurations I've actually tried.
Wrapping with FastAPI for a Quick API
The simplest way is to wrap it with FastAPI. You can write it like this:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import dspy
# Initialize DSPy
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
qa_module = dspy.ChainOfThought('question -> answer')
app = FastAPI(title="DSPy QA API")
class QuestionRequest(BaseModel):
question: str
context: str = ""
class AnswerResponse(BaseModel):
answer: str
reasoning: str = ""
@app.post("/predict", response_model=AnswerResponse)
async def predict(request: QuestionRequest):
try:
# Async execution (new DSPy 3.0 feature)
async_qa = dspy.asyncify(qa_module)
result = await async_qa(question=request.question)
return AnswerResponse(
answer=result.answer,
reasoning=getattr(result, 'reasoning', '')
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
For Those Who Want Proper Experiment Management with MLflow
If you want to manage experiments properly, the integration with MLflow is recommended. It is fully supported from DSPy 3.0.
import mlflow
import mlflow.dspy
# Configure MLflow tracking
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("dspy-qa-system")
# Enable automatic log recording (new DSPy 3.0 feature)
mlflow.dspy.autolog()
with mlflow.start_run():
# Optimize the model
optimized_module = optimizer.compile(qa_module, trainset=train_data)
# Save and log the model
mlflow.dspy.log_model(
dspy_model=optimized_module,
artifact_path="model",
input_example={"question": "Sample question"},
)
# Record metrics
mlflow.log_metric("accuracy", 0.87)
mlflow.log_metric("optimization_time", 1200) # seconds
For more detailed usage, refer to the Azure Databricks documentation.
Practical Usage in Production
Here are some tips I learned from actually running it in production that aren't in the official documentation.
Caching Strategy is Crucial
DSPy caches LLM call results by default. This is good, but using the same cache for experiments and production can lead to chaos.
# Change rollout_id for each experiment
# This creates separate cache spaces
result_v1 = program(question="test", rollout_id="experiment_v1")
result_v2 = program(question="test", rollout_id="experiment_v2")
# In production, disabling caching is also an option
lm = dspy.LM("gpt-4o-mini", cache=False)
# Or, increase temperature to ensure diversity
lm = dspy.LM("gpt-4o-mini", temperature=0.7, rollout_id=f"prod_{timestamp}")
About rollout_id
The rollout_id parameter introduced in DSPy 3.0 separates the cache by namespace. Even with the same input, using a different rollout_id treats it as a separate cache entry.
Error Retry and Fallback
In production environments, API calls can sometimes fail, so retry handling is essential.
import time
from typing import Optional
class RobustQAModule(dspy.Module):
def __init__(self, fallback_lm: Optional[dspy.LM] = None):
self.primary = dspy.ChainOfThought('question -> answer')
self.fallback_lm = fallback_lm
def forward(self, question: str, max_retries: int = 3):
for attempt in range(max_retries):
try:
return self.primary(question=question)
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # exponential backoff
elif self.fallback_lm:
# Use fallback LM
with dspy.context(lm=self.fallback_lm):
return self.primary(question=question)
else:
raise
Metric Monitoring and Alerts
Integrate with MLflow to continuously monitor performance metrics.
import mlflow
from datetime import datetime
class MonitoredQASystem:
def __init__(self, module, threshold=0.8):
self.module = module
self.threshold = threshold
mlflow.set_experiment("production_qa_system")
def process(self, question: str):
with mlflow.start_run():
start_time = time.time()
# Run prediction
result = self.module(question=question)
# Record latency
latency = time.time() - start_time
mlflow.log_metric("latency", latency)
# Record confidence score if available
if hasattr(result, 'confidence'):
mlflow.log_metric("confidence", result.confidence)
# Low confidence alert
if result.confidence < self.threshold:
self.send_alert(f"Low confidence: {result.confidence}")
return result
def send_alert(self, message: str):
# Notify via Slack/Email/PagerDuty, etc.
print(f"⚠️ Alert: {message}")
A/B Testing and Canary Deployment
A method for gradually rolling out new prompts or optimized modules.
import random
import hashlib
class ABTestingModule(dspy.Module):
def __init__(self, module_a, module_b, split_ratio=0.5):
self.module_a = module_a # current version
self.module_b = module_b # new version
self.split_ratio = split_ratio
def forward(self, question: str, user_id: Optional[str] = None):
# Maintain consistency based on user ID
if user_id:
hash_val = int(hashlib.md5(user_id.encode()).hexdigest(), 16)
use_b = (hash_val % 100) < (self.split_ratio * 100)
else:
use_b = random.random() < self.split_ratio
# Record metrics
variant = "B" if use_b else "A"
mlflow.log_param("variant", variant)
if use_b:
return self.module_b(question=question)
else:
return self.module_a(question=question)
How Does It Compare to Other Frameworks?
DSPy vs LangChain
Here's a comparison, including my personal impressions:
| Item | DSPy 3.0 | LangChain |
|---|---|---|
| Basic Philosophy | Programming language models | Orchestrating LLM workflows |
| Approach | Declarative, self-optimizing | Imperative, manual prompt tuning |
| Community | Growing (16k stars) | Massive (90k+ stars) |
| Prompt Optimization | Fully automated | Relies on human effort |
| Learning Curve | Tough at first, easier later | Easy at first, hell later |
| Best Suited For | Complex multi-step reasoning | Rapid prototyping |
LangChain has a larger community and is easier to get started with. However, for building complex production systems, DSPy's automatic optimization is a real lifesaver.
For a more detailed comparison, check out Qdrant's blog post.
DSPy vs Guidance/LMQL
Guidance and LMQL excel at structuring single LLM calls cleanly. DSPy, on the other hand, is strong at optimizing the entire multi-stage pipeline. The use cases differ, so you could even combine them.
DSPy's Unique Strengths
I believe DSPy's biggest strength is its adaptability to model changes. When you want to switch from GPT-4 to Claude 3, LangChain would require rewriting all the prompts, but with DSPy you just recompile. Actually trying this is quite impressive.
Also, since it's developed by a research institution (Stanford NLP), it continuously implements the latest paper-based methods. DSPy is the only framework that allows you to use cutting-edge optimizers like GEPA.
Where Is It Actually Being Used?
I looked up the companies adopting it as of September 2025 from official documentation and community information. I was surprised to find that many major companies are using it.
Tech Companies
JetBlue uses it for their chatbots and reported significant performance improvements after switching from LangChain. Databricks utilizes it for classification tasks and RAG[8]. Other adopters include Replit (code generation) and VMware (RAG optimization).
Finance & Insurance
Moody's uses it for financial workflow optimization, and RadiantLogic uses it for an AI assistant with multi-module routing functions. Financial institutions are often seen as cautious, but they're surprisingly forward-thinking.
E-commerce
Zoro UK uses it to normalize product attributes from over 300 suppliers. Sephora also seems to use it for some agent-related tasks, but details are not public.
Healthcare
STChealth uses it for entity resolution and can output human-readable justifications. Salomatic uses it to enrich medical reports. It's starting to be used in healthcare as well.
Academic Research Results Are Impressive
Stanford's STORM project, which automatically generates Wikipedia-style articles, has exceeded 10,000 stars on GitHub. The WangLab at the University of Toronto won the MEDIQA medical QA competition by a 20-point margin over the runner-up.
UMD's suicide detection system performed 40% better than a prompt that experts spent 20 hours creating. That was quite shocking.
Best Practices I Learned from Using It
Recommended Project Structure
After creating several projects, I found this structure to be the most maintainable.
project/
├── src/
│ ├── modules/ # DSPy modules go here
│ │ ├── signatures.py # Group signature definitions
│ │ └── pipelines.py # Pipeline implementations
│ ├── optimizers/ # If you create custom optimizers
│ └── evaluation/ # Evaluation metrics
├── data/ # Training data
├── experiments/ # Results of optimization experiments
├── configs/ # Configuration files (YAML recommended)
└── tests/ # Write tests
Implement Proper Error Handling
The assertion feature introduced in DSPy 3.0 is incredibly useful. You can use it like this:
class ValidatedQA(dspy.Module):
def __init__(self):
super().__init__()
self.generate_answer = dspy.ChainOfThought('question -> answer')
def forward(self, question):
response = self.generate_answer(question=question)
# DSPy 3.0 assertion feature
dspy.Suggest(
len(response.answer.split()) >= 3,
"Answer must be at least 3 words long"
)
dspy.Assert(
response.answer.strip() != "",
"Answer cannot be empty"
)
return response
Choosing an Optimizer Based on Data Size
I was really confused about this at first, so here's my personal usage guide.
# When data is scarce (less than 50 examples)
# → Use BootstrapFewShot
optimizer = dspy.BootstrapFewShot(
metric=answer_match,
max_bootstrapped_demos=4,
max_labeled_demos=4
)
# Medium-sized data (50 to 500 examples)
# → Combine with RandomSearch
optimizer = dspy.BootstrapFewShotWithRandomSearch(
metric=answer_match,
max_bootstrapped_demos=8,
num_candidate_programs=10
)
# When you have a lot of data or want to optimize instructions
# → Use MIPROv2
optimizer = dspy.MIPROv2(
metric=answer_match,
auto="medium", # Choose from light, medium, heavy
num_threads=4
)
# When you want the absolute best performance (time is not an issue)
# → Use GEPA (new 3.0 feature)
optimizer = dspy.GEPA(
metric=answer_match,
breadth=10,
depth=3
)
Honestly, if you're unsure, just use GEPA and you'll get good results (lol).
For more details on choosing an optimizer, refer to the official documentation.
Performance Tuning Tips
Here are some techniques that helped when running in production.
# When you want to batch process asynchronously
import asyncio
async def process_batch(questions):
"""Process multiple questions concurrently"""
tasks = []
for question in questions:
# Async support from 3.0!
async_module = dspy.asyncify(qa_module)
tasks.append(async_module(question=question))
results = await asyncio.gather(*tasks)
return results
# Using cache wisely (subtly important)
# Change rollout_id per experiment to separate caches
prediction = program(
question="test",
rollout_id="experiment_v2" # Changing this creates a separate cache
)
Asynchronous processing is especially effective when there are many API calls. It can reduce the time to process 10 questions to 1/10 (obviously, but still).
Suitability of DSPy
Cases where DSPy is advantageous
Based on my actual use, I found DSPy to be overwhelmingly advantageous in these cases:
- Complex multi-step reasoning: Multiple steps like RAG → reasoning → summarization
- High-volume routine tasks: Processing a large number of similar tasks
- Frequent model switching: Frequently switching between GPT-4 → Claude → Gemini
- Accuracy is paramount: Prioritizing accuracy even if development time is longer
- Long-term maintenance required: When prompt maintainability is important
Cases where DSPy is not suitable
Conversely, in these cases, it's better to just use LangChain:
- Simple one-off tasks: Just summarization or simple classification
- Prototyping stage: When you want to make something work quickly
- Creative tasks: Writing poetry, story generation, etc.
- No training data: Optimization requires at least 20-50 examples
- Entire team is new to LLMs: The learning curve is relatively steep
Looking forward to future developments
Future plans mentioned by the development team
Looking at the official roadmap[9], several interesting features are planned.
First, a human-in-the-loop feedback feature. Once implemented, it will be easier to incorporate human feedback, making it much more practical. Also, improvements to optimize efficiently with minimal training data are underway. They are targeting a further 20% improvement over current optimizers – and it's already amazing.
Benchmark systematization is also progressing, which should make it clearer when to use which optimizer.
Market position
It's starting to be used widely from academic research to enterprise production environments, effectively bridging the gap between a "research tool" and a "production-ready platform." Whether it will grow as explosively as LangChain remains to be seen, but it is certainly carving out an important position.
What I think after using it for 3 months
It's been three months since I seriously started using DSPy. At first, I thought, "Do I have to learn another new framework?" but now it's an indispensable tool. (Though I still feel I haven't mastered it fully and there are parts I don't understand...)
Especially with the advent of the GEPA optimizer, the concept of prompt engineering has fundamentally changed. Prompt creation, which was once a "craft," has become data-driven "engineering." I miss the days when I manually wrote "think step by step"...
However, it's not a silver bullet. For simple tasks, LangChain is faster, and the training cost for team members cannot be ignored. But for running complex AI systems in production, DSPy's automatic optimization is truly valuable.
Also, the community is still small, which is a challenge. Searching on Stack Overflow yields little information, and there's even less in Japanese. But conversely, starting now might give you a first-mover advantage.
Finally: Now is the chance to start
DSPy 3.0 indeed has a steep learning curve. But once you understand it, your prompt engineering productivity will dramatically increase. Especially for those building production systems in companies, it's worth the investment.
The official documentation is getting better, and innovative features like GEPA are being added. Integration with Azure OpenAI has also improved, making it easier for enterprise users.
Personally, I predict that automatic optimization frameworks like DSPy will become standard within the next year. The era of manually writing prompts may soon be over.
If you're interested, try the official tutorial first. You'll definitely get hooked.
Reference Links
Official Resources
Tutorials & Learning Resources
Technical Papers & References
Comparison & Explanatory Articles
OpenAI Model Related
Happy DSPying! 🚀
Disclaimer
This article is for informational purposes only and is based on information as of November 2025. The accuracy and completeness of the content are not guaranteed and may contain errors. Please check the official documentation for the latest information. Use the code samples in this article at your own risk. Manage sensitive information such as API keys appropriately, and exercise sufficient caution regarding security when using them in public environments. The author assumes no responsibility for any damages (including service interruption, data loss, business loss, etc.) arising from the use of the content of this article. Please use all products and services listed in this article in accordance with each company's terms of service.
Discussion