📄 modules.md

← Vault

DSPy Modules

Complete guide to DSPy's built-in modules for language model programming.

Module Basics

DSPy modules are composable building blocks inspired by PyTorch's NN modules:

Module Selection Guide

TaskModuleReason
----------------------
Simple classificationPredictFast, direct
Math word problemsProgramOfThoughtReliable calculations
Logical reasoningChainOfThoughtBetter with steps
Multi-step researchReActTool usage
High-stakes decisionsMultiChainComparisonSelf-consistency
Structured extractionTypedPredictorType safety
Ambiguous questionsMultiChainComparisonMultiple perspectives

Performance Tips

1. Start with Predict, add reasoning only if needed

2. Use batch processing for multiple inputs

3. Cache predictions for repeated queries

4. Profile token usage with track_usage=True

5. Optimize after prototyping with teleprompters

Common Patterns

Pattern: Retrieval + Generation

`python

class RAG(dspy.Module):

def __init__(self, k=3):

super().__init__()

self.retrieve = dspy.Retrieve(k=k)

self.generate = dspy.ChainOfThought("context, question -> answer")

def forward(self, question):

context = self.retrieve(question).passages

return self.generate(context=context, question=question)

`

Pattern: Verification Loop

`python

class VerifiedQA(dspy.Module):

def __init__(self):

super().__init__()

self.answer = dspy.ChainOfThought("question -> answer")

self.verify = dspy.Predict("question, answer -> is_correct: bool")

def forward(self, question, max_attempts=3):

for _ in range(max_attempts):

answer = self.answer(question=question).answer

is_correct = self.verify(question=question, answer=answer).is_correct

if is_correct:

return dspy.Prediction(answer=answer)

return dspy.Prediction(answer="Unable to verify answer")

`

Pattern: Multi-Turn Dialog

`python

class DialogAgent(dspy.Module):

def __init__(self):

super().__init__()

self.respond = dspy.Predict("history, user_message -> assistant_message")

self.history = []

def forward(self, user_message):

history_str = "\n".join(self.history)

response = self.respond(history=history_str, user_message=user_message)

self.history.append(f"User: {user_message}")

self.history.append(f"Assistant: {response.assistant_message}")

return response

`