DSPy is a framework that shifts AI development from manual prompt engineering to compiler-driven optimization. It separates the declaration of a task's logic from the optimization of the underlying language model calls. Developers define modules with typed signatures, and DSPy's teleprompter automatically tunes prompts and selects few-shot examples to maximize a user-defined metric.
Glossary
DSPy

What is DSPy?
DSPy is a programming framework that compiles declarative language model calls into optimized pipelines, automatically tuning prompts and fine-tuning weights to maximize a target metric for complex multi-step reasoning tasks.
Unlike static prompt chains, DSPy treats a multi-step pipeline as a differentiable program. The compiler can optimize Chain-of-Thought, ReAct, or custom reasoning graphs by generating and selecting effective instructions. This enables systematic, data-driven improvement of complex architectures without hand-crafting brittle prompt strings.
Core Characteristics of DSPy
DSPy replaces brittle prompt engineering with a systematic compiler that optimizes language model pipelines against a target metric, treating prompts and weights as tunable parameters.
Declarative Signatures
DSPy abstracts the LLM call into a Signature, a declarative specification of input fields and output fields. Instead of writing a prompt, you define the semantic role of the transformation.
- Input/Output Schema: Define fields like
question,context, andanswerwith optional descriptions. - Semantic Roles: The compiler infers the task type (e.g., classification, summarization) from the signature.
- Prompt Agnosticism: You never write a raw prompt string; the compiler generates and optimizes it for you.
Example: qa = dspy.ChainOfThought('context, question -> answer') defines a reasoning step without specifying how to reason.
Teleprompter Optimizers
A Teleprompter is a compiler that tunes the parameters of a DSPy program to maximize a metric. It treats prompt instructions and few-shot examples as trainable parameters.
- BootstrapFewShot: Automatically generates and selects effective few-shot examples from a training set.
- BootstrapFinetune: Distills a large program into a smaller, fine-tuned model for production.
- MIPROv2: A Bayesian optimizer that jointly tunes instructions and few-shot examples across all modules.
Mechanism: The teleprompter runs the program on training data, evaluates outputs against a metric, and iteratively updates the program's internal state.
Composable Modules
DSPy programs are built by composing reusable Modules, which are parameterized layers that abstract prompting techniques. Modules can be nested and chained like neural network layers.
- dspy.ChainOfThought: Implements step-by-step reasoning with an explicit rationale before the answer.
- dspy.ReAct: An agentic module that interleaves thought, action, and observation steps for tool use.
- dspy.MultiChainComparison: Generates multiple reasoning chains and compares them to synthesize a final answer.
- Custom Modules: Subclass
dspy.Moduleto encapsulate complex multi-step logic with internal state.
Metric-Driven Compilation
The DSPy compiler requires a metric function that scores the quality of a program's output against a ground-truth label. This metric is the objective function for all optimization.
- Semantic Metrics: Use
dspy.evaluate.answer_exact_matchfor exact string matching ordspy.evaluate.SemanticF1for meaning-level comparison. - Custom Metrics: Define any Python function that takes
(example, pred, trace)and returns a float score. - Program-Aware: The metric can inspect the full execution trace, not just the final output.
Impact: The metric replaces manual prompt tuning with a principled, reproducible optimization loop.
Language Model Abstraction
DSPy decouples program logic from the underlying model provider through a unified LM interface. Swap between local and remote models without changing program code.
- Provider Agnostic: Supports OpenAI, Anthropic, Cohere, local Hugging Face models, and custom endpoints.
- Configuration: Set
dspy.settings.configure(lm=model, rm=retriever)globally or per-module. - Retrieval Models: A parallel
RMabstraction integrates vector databases and search APIs as retrievable modules.
Benefit: Benchmark the same compiled program across GPT-4, Claude, and Llama 3 to find the optimal cost-performance ratio.
Automatic Prompt Optimization
The core innovation of DSPy is treating prompt engineering as a discrete optimization problem. The compiler searches over the space of possible instructions and demonstrations.
- Instruction Tuning: The optimizer generates and refines natural language instructions for each signature field.
- Few-Shot Selection: It selects the subset of training examples that maximizes validation performance when included as demonstrations.
- Self-Improvement: Programs can be re-compiled as new data arrives, adapting to distribution shifts automatically.
Result: A DSPy program compiled for GPT-3.5 can outperform hand-crafted prompts designed for GPT-4.
DSPy vs. Traditional Prompt Engineering
A feature-level comparison between the DSPy declarative programming framework and manual prompt engineering for optimizing multi-step language model pipelines.
| Feature | DSPy | Manual Prompt Engineering | LangChain/LlamaIndex |
|---|---|---|---|
Optimization Approach | Compiled automatically via teleprompter against a metric | Manual trial-and-error editing of prompt strings | Manual prompt templates with chain orchestration |
Prompt Tuning | Automatic instruction and few-shot example generation | Hand-crafted by developer | Hand-crafted with optional template variables |
Fine-Tuning Support | |||
Metric-Driven | |||
Abstraction Level | Declarative modules (Signature, Module, Optimizer) | String-level manipulation | Imperative chain construction |
Multi-Hop Reasoning Support | Native via compiled sub-question decomposition | Requires manual chain-of-thought prompting | Requires explicit chain construction |
Reproducibility | Deterministic compilation from program definition | Non-deterministic; prompt drift over time | Partially reproducible via chain configs |
Model Portability | Compile once, run on any LM | Prompts often model-specific | Abstracted but prompts remain static |
Frequently Asked Questions
Clear answers to the most common questions about the DSPy programming framework, covering its core abstractions, compilation process, and how it differs from manual prompting.
DSPy is a programming framework that compiles declarative language model calls into optimized pipelines, automatically tuning prompts and fine-tuning weights to maximize a target metric. It works by separating the specification of a task from the optimization of the model's behavior. You define a program using composable modules—like ChainOfThought or ReAct—that declare what the model should do, not how to prompt it. A compiler then takes this program, a training set, and a metric, and automatically generates high-quality few-shot examples, instructions, or weight updates. This replaces brittle, hand-crafted prompt engineering with a systematic, data-driven optimization loop, allowing the same program to be compiled for different language models without manual rewriting.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
DSPy exists within a rich ecosystem of reasoning frameworks and optimization techniques. Explore these related concepts to understand how declarative programming fits into the broader landscape of multi-hop reasoning and agentic architectures.
Chain-of-Thought (CoT) Retrieval
A reasoning paradigm where the model generates intermediate rationales and retrieves supporting evidence for each step. DSPy can automatically optimize CoT prompts by treating the reasoning trace as a tunable parameter, maximizing a target metric like exact match or F1 score without manual prompt engineering.
ReAct (Reasoning and Acting)
A prompting framework that interleaves discrete reasoning traces with tool-use actions. DSPy compiles ReAct pipelines into optimized modules by automatically tuning the few-shot examples and instructions for each reasoning-action step, enabling dynamic planning with external tools like search APIs or calculators.
Self-Consistency
A decoding strategy that samples multiple diverse reasoning paths and selects the final answer via majority voting. DSPy can optimize the temperature and sampling parameters alongside prompt instructions to maximize the marginalization benefit of self-consistency for complex multi-hop questions.
IRCoT (Interleaving Retrieval with Chain-of-Thought)
A method that uses each generated rationale sentence to query a knowledge source, interleaving reasoning with evidence gathering. DSPy treats IRCoT as a compilable program, automatically tuning the retrieval query generation and reasoning steps to improve answer fidelity across multiple hops.
GraphRAG
A retrieval-augmented generation approach using knowledge graphs for community summarization and holistic reasoning. DSPy can compile GraphRAG pipelines by optimizing the entity extraction, community detection, and summarization prompts against a global answer quality metric.
Tool-Augmented Reasoning
An agentic capability where a language model autonomously selects and invokes external tools. DSPy compiles these tool-use signatures into optimized modules by automatically tuning when and how the model should invoke calculators, code interpreters, or APIs to solve sub-tasks.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us