DSPy is a framework for building language-model systems with declarative task signatures and reusable modules. A signature describes input and output fields; a module supplies a strategy, while DSPy generates the model-facing prompt instead of requiring hand-written prompt text. section 6.5 section 6.6.3
The workflow shifts effort from writing prompts to specifying a program, examples, and a measurable quality metric. This suits tasks such as classification, extraction, and RAG when behavior can be evaluated repeatedly. Results depend on representative examples and a useful metric. section 10.3.7
Listing 6.5 Python script using different prompting strategies (CoT and ReAct) with DSPy
import dspy
class MathQA(dspy.Signature): #1
question: str = dspy.InputField(desc="a short math word problem")
answer: str = dspy.OutputField(desc="the final numeric answer only")
def safe_calculator(expression: str) -> str: #2
"""Evaluate an arithmetic expression and return the result."""
# Restricted evaluation of +, -, *, /, parentheses, and the
# functions sqrt, ceil, and floor
...
cot_math_solver = dspy.ChainOfThought(MathQA) #3
react_math_agent = dspy.ReAct(signature=MathQA,
tools=[safe_calculator], max_iters=5) #4
The math-tutor implementation uses one signature with two modules: ChainOfThought for stepwise reasoning and ReAct for calculator use. Choose based on whether a task can rely on internal reasoning or needs tools, verification, or iterative refinement. section 6.6.3
Listing 10.7 Defining and optimizing a predictor in DSPy
class ActionPlan(dspy.Signature):
"""Turn a request into a compact action plan."""
request: str = dspy.InputField(desc="short project request")
summary: str = dspy.OutputField(desc="one-sentence summary")
owner: str = dspy.OutputField(desc="best owner or team")
# The optimizer rewrites the prompt from examples and a metric
planner = dspy.Predict(ActionPlan)
optimizer = dspy.BootstrapFewShot(metric=owner_matches)
optimized_planner = optimizer.compile(planner, trainset=trainset)
The action-planning example shows the optimization loop: define fields in a signature, create a predictor, then compile it with training examples and an owner-matching metric. section 10.3.7



