DSPy

3.1.3 · active · verified Sat Feb 28

Stanford's framework for programming—not prompting—language models. Core primitives: Signatures (typed input/output specs), Modules (dspy.Predict, dspy.ChainOfThought, dspy.ReAct, etc.), and Optimizers (MIPROv2, GEPA, SIMBA, BootstrapFewShot, GRPO). Instead of hand-crafted prompts, you write compositional Python programs and let optimizers automatically tune instructions and few-shot demos against a metric. Supports any LiteLLM-compatible model.

Warnings

Install

Imports

Quickstart

Simple ChainOfThought QA module with DSPy 3.x

import dspy

# Configure LM (uses LiteLLM-style model strings)
dspy.configure(lm=dspy.LM('openai/gpt-4o-mini'))

# Define a Signature
class QA(dspy.Signature):
    """Answer questions with short factual answers."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField(desc='often a few words')

# Define a Module
class CoTQA(dspy.Module):
    def __init__(self):
        self.generate = dspy.ChainOfThought(QA)

    def forward(self, question):
        return self.generate(question=question)

# Run the module
program = CoTQA()
result = program(question='What is the capital of France?')
print(result.answer)

view raw JSON →