Guides building multi-step DSPy programs as composable, optimizable modules using dspy.Module and forward(). Covers nesting, sub-module discovery by optimizers, and structuring RAG or classification pipelines.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Guide the user through structuring DSPy programs as reusable, composable modules. A dspy.Module is the building block for all DSPy programs -- like PyTorch's nn.Module but for language model pipelines.
Ask before writing any code:
self. attributes is critical)async def forward() and acall — impacts design from the start)Then build or explain the pattern that fits.
dspy.Module is the building block for multi-step DSPy programs. Declare sub-modules in __init__ as self. attributes, wire them together with Python logic in forward(). DSPy optimizers automatically discover and tune all sub-modules in the tree.
Modules are composable. A module can use other custom modules as sub-modules:
class Summarizer(dspy.Module):
def __init__(self):
self.summarize = dspy.ChainOfThought("text -> summary")
def forward(self, text):
return self.summarize(text=text)
class AnalyzeAndSummarize(dspy.Module):
def __init__(self):
self.classify = dspy.Predict("text -> category")
self.summarizer = Summarizer() # nested custom module
self.respond = dspy.ChainOfThought("category, summary -> response")
def forward(self, text):
category = self.classify(text=text).category
summary = self.summarizer(text=text).summary
return self.respond(category=category, summary=summary)
DSPy optimizers traverse the full module tree. When you optimize AnalyzeAndSummarize, the inner Summarizer's prompts get optimized too.
Use print() to inspect all sub-modules and their signatures:
pipeline = AnalyzeAndSummarize()
print(pipeline)
Output shows the module tree:
AnalyzeAndSummarize(
classify = Predict(text -> category)
summarizer = Summarizer(
summarize = ChainOfThought(text -> summary)
)
respond = ChainOfThought(category, summary -> response)
)
This is useful for verifying your module hierarchy and debugging which sub-modules exist.
After optimization, save the learned state (few-shot demos, instructions) and reload it later:
# Save after optimization
optimized_program = optimizer.compile(my_program, trainset=trainset)
optimized_program.save("my_program.json")
# Load into a fresh instance
loaded = MyProgram()
loaded.load("my_program.json")
# Use the loaded program -- it has the optimized prompts
result = loaded(question="What is DSPy?")
What gets saved:
Predict modules trackWhat does not get saved:
forward() -- that's your codeBootstrapFinetune)dspy.configure() before loadingUse dspy.Refine to enforce quality constraints on outputs through a reward function. This replaces the older dspy.Assert/dspy.Suggest pattern:
class SafeQA(dspy.Module):
def __init__(self):
self.generate = dspy.ChainOfThought("question -> answer")
def forward(self, question):
return self.generate(question=question)
def answer_reward(args, pred):
"""Score answer quality. Returns float between 0.0 and 1.0."""
score = 0.0
# Hard requirement -- must provide a substantive answer
if pred.answer.strip() and pred.answer != "I don't know":
score += 0.6
# Quality preference -- at least 10 words
if len(pred.answer.split()) >= 10:
score += 0.4
return score
# Wrap with Refine to retry until quality threshold is met
validated_qa = dspy.Refine(
module=SafeQA(),
N=3,
reward_fn=answer_reward,
threshold=0.6, # must at least pass the hard requirement
)
dspy.Refine -- wraps a module, scores each attempt with a reward function, and retries until the threshold is met (up to N attempts). Use for requirements that must be met.dspy.BestOfN -- similar to Refine but without cross-attempt feedback; use when attempts are independent.For detailed Refine patterns and examples, see /dspy-refine and /dspy-best-of-n.
Route to different sub-modules based on intermediate results:
class ConditionalPipeline(dspy.Module):
def __init__(self):
self.classify = dspy.Predict("text -> category")
self.simple_handler = dspy.Predict("text -> response")
self.complex_handler = dspy.ChainOfThought("text -> response")
def forward(self, text):
category = self.classify(text=text).category
if category in ("simple", "faq"):
return self.simple_handler(text=text)
else:
return self.complex_handler(text=text)
Process a list of items or iterate until a condition is met:
class BatchProcessor(dspy.Module):
def __init__(self):
self.process_item = dspy.ChainOfThought("item -> result")
def forward(self, items: list[str]):
results = []
for item in items:
result = self.process_item(item=item)
results.append(result.result)
return dspy.Prediction(results=results)
Keep improving until quality is sufficient:
class Refiner(dspy.Module):
def __init__(self, max_rounds=3):
self.draft = dspy.ChainOfThought("task -> output")
self.critique = dspy.ChainOfThought("task, output -> feedback, is_good: bool")
self.revise = dspy.ChainOfThought("task, output, feedback -> output")
self.max_rounds = max_rounds
def forward(self, task):
result = self.draft(task=task)
for _ in range(self.max_rounds):
check = self.critique(task=task, output=result.output)
if check.is_good:
break
result = self.revise(
task=task,
output=result.output,
feedback=check.feedback,
)
return result
Wrap sub-module calls to handle failures gracefully:
class ResilientModule(dspy.Module):
def __init__(self):
self.primary = dspy.ChainOfThought("question -> answer")
self.fallback = dspy.Predict("question -> answer")
def forward(self, question):
try:
return self.primary(question=question)
except Exception:
return self.fallback(question=question)
Use dspy.Prediction to return structured results from forward():
class MultiOutput(dspy.Module):
def __init__(self):
self.analyze = dspy.ChainOfThought("text -> sentiment, topics: list[str]")
self.summarize = dspy.ChainOfThought("text -> summary")
def forward(self, text):
analysis = self.analyze(text=text)
summary = self.summarize(text=text)
return dspy.Prediction(
sentiment=analysis.sentiment,
topics=analysis.topics,
summary=summary.summary,
)
Assign cheaper models to simpler steps:
expensive_lm = dspy.LM("openai/gpt-4o") # or "anthropic/claude-sonnet-4-5-20250929", etc.
cheap_lm = dspy.LM("openai/gpt-4o-mini") # or any smaller model
pipeline = MyProgram()
pipeline.classify.set_lm(cheap_lm)
pipeline.generate.set_lm(expensive_lm)
Use batch() to process multiple examples in parallel:
pipeline = MyProgram()
examples = [dspy.Example(question=q).with_inputs("question") for q in questions]
results = pipeline.batch(examples, num_threads=4, timeout=120)
Skip the class if you only need a single LM call and will never optimize or save it — call dspy.Predict or dspy.ChainOfThought directly:
# Fine for one-off scripts and notebooks
predict = dspy.ChainOfThought("question -> answer")
result = predict(question="What is DSPy?")
Wrap in a Module when you need any of: re-use across the codebase, DSPy optimizer traversal, save()/load() state, batch() parallelism, or programmatic inspection via named_predictors().
| Pattern | Use when | Key property |
|---|---|---|
| Sequential steps | Each step's output feeds the next | Simplest; fully optimizable |
| Conditional routing | Different paths based on intermediate result | Cheap classifier directs to specialized handler |
| Loop / retry | Quality check drives iteration count | max_rounds param prevents infinite loops |
dspy.Refine wrapper | Retry is boilerplate — just need a reward function | Delegates retry logic to DSPy |
| Nested modules | Reusable sub-pipeline across multiple parent modules | Optimizers traverse nested trees automatically |
# Check module tree before optimizing -- catch missing self. attributes early
print(pipeline)
# Confirm all Predict instances are discoverable
print(pipeline.named_predictors()) # should list every sub-module
# Smoke-test on one example before running batch
result = pipeline(**example.inputs())
assert hasattr(result, "answer"), "forward() must return a Prediction with expected fields"
self. attributes. Optimizers discover sub-modules by traversing self. attributes in __init__. A Predict stored in a local variable or a plain list is invisible to optimization. Use a dict assigned to self. — DSPy traverses dicts for parameters.dspy.configure() inside forward(). Configure once at startup. Calling it per-forward adds overhead and causes unexpected behavior during optimization.forward() args differently from training example fields. When an optimizer traces your module, it passes inputs from training examples to forward(). Mismatched argument names cause silent failures. Use the same field names as your dspy.Example inputs.forward() method. Every dspy.Module subclass must implement forward(). Without it, calling the module raises an error.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-signatures/dspy-predict/dspy-chain-of-thought/ai-building-pipelines/ai-improving-accuracy/ai-do if you do not have it — it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/dspy-api-skills:dspy-modulesfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest.Other plugins' skills for the same job