DSPy — Program LLMs Instead of Prompting
DSPy is a Python framework for programming language models instead of prompting them. 33.3K+ GitHub stars. Build modular AI systems — classifiers, RAG pipelines, agent loops — and let DSPy optimize pr
Instalación lista para agent
Este activo puede instalarse después de elegir el runtime, revisar el plan y ejecutar el comando correspondiente.
npx -y tokrepo@latest install 88a2e60f-54d1-48cb-9173-23d56a4f3f20 --target codexEjecutar después de confirmar el plan con dry-run.
What it is
DSPy is a Python framework that replaces manual prompt engineering with programmatic modules. Instead of writing fragile prompt strings, you define typed signatures (input/output fields), compose modules into pipelines, and let DSPy optimize the underlying prompts or fine-tuning weights automatically against a metric you specify.
DSPy targets ML engineers and AI application developers building classifiers, RAG pipelines, agent loops, and multi-step reasoning systems. It decouples your application logic from the specific prompt text, making systems portable across models and more robust to model updates.
Why it saves time or tokens
Manual prompt engineering is trial-and-error. DSPy's optimizers (formerly 'teleprompters') search over prompt variations, few-shot example selections, and even fine-tuning data to find the configuration that maximizes your metric. This automated search replaces hours of manual tweaking. Because the optimizer finds efficient prompts, the final system often uses fewer tokens per call than hand-written prompts that include unnecessary instructions.
How to use
- Install DSPy:
pip install dspy - Define a signature:
class QA(dspy.Signature): question = dspy.InputField(); answer = dspy.OutputField() - Create a module, compile it with an optimizer, and run inference
Example
import dspy
lm = dspy.LM('openai/gpt-4o-mini')
dspy.configure(lm=lm)
class Summarize(dspy.Signature):
'''Summarize the document in one paragraph.'''
document = dspy.InputField()
summary = dspy.OutputField()
summarizer = dspy.ChainOfThought(Summarize)
result = summarizer(document='DSPy is a framework for...')
print(result.summary)
This defines a typed summarization module with chain-of-thought reasoning. DSPy generates the actual prompt from the signature and docstring.
| Concept | Purpose |
|---|---|
| Signature | Typed input/output contract |
| Module | Composable building block (ChainOfThought, ReAct) |
| Optimizer | Auto-tunes prompts against a metric |
| Metric | Evaluation function you define |
Related on TokRepo
- AI tools for coding — developer tools for building AI applications
- Prompt library — curated prompts and prompt engineering resources on TokRepo
Common pitfalls
- DSPy optimizers need labeled examples or a reliable metric function; without good evaluation data, optimization produces inconsistent results
- The abstraction hides prompt text, which makes debugging harder; use
dspy.inspect_history()to see what prompts DSPy actually sends - Compiling with a large optimizer on an expensive model can burn significant API credits; start with a small training set and a cheap model
Preguntas frecuentes
LangChain provides building blocks (chains, tools, retrievers) that you wire together with manually written prompts. DSPy replaces the manual prompts with typed signatures and auto-optimizes them. DSPy focuses on making prompts a compiled artifact rather than a hand-written string, while LangChain focuses on the orchestration and integration layer.
DSPy includes BootstrapFewShot (selects few-shot examples), BootstrapFewShotWithRandomSearch (adds random search), MIPRO (multi-instruction proposal optimizer), and others. Each optimizer searches over different prompt configurations to maximize your specified metric. You can also write custom optimizers.
Yes. DSPy supports any model accessible through a supported LM class, including local models via Ollama, vLLM, or Hugging Face Transformers. You configure the model endpoint and DSPy handles prompt formatting. Local models benefit from DSPy optimization just as cloud models do.
A signature is a typed contract defining the inputs and outputs of an AI module. It replaces the prompt template concept. You declare input fields and output fields as Python class attributes with optional descriptions. DSPy compiles these declarations into actual prompts during optimization.
DSPy is used in production by multiple organizations for classification, RAG, and agent workflows. The compiled modules are deterministic given the same optimizer output. However, the API surface is still evolving, so pin your DSPy version and test thoroughly when upgrading.
Referencias (3)
- DSPy GitHub— DSPy is a framework for programming language models
- DSPy Docs— DSPy replaces prompt engineering with typed signatures and optimizers
- Stanford NLP— DSPy originated from Stanford NLP research
Relacionados en TokRepo
Fuente y agradecimientos
Created by Stanford NLP. Licensed under MIT. stanfordnlp/dspy — 33,300+ GitHub stars
Discusión
Activos relacionados
Fooocus — Focus on Prompting and Generating, Not the Tooling
Fooocus is a Stable Diffusion image generator that strips away every dial and toggle. Just type a prompt and get magazine-quality results — opinionated defaults, automatic prompt engineering, and SDXL-grade output with one click.
Structured Outputs — Force LLMs to Return Valid JSON
Complete guide to getting reliable structured JSON from LLMs. Covers OpenAI structured outputs, Claude tool use, Instructor library, and Outlines for guaranteed valid responses.
DSPy — Programming Foundation Models Declaratively
Replace hand-written prompts with modular programs. DSPy compiles declarative AI pipelines into optimized prompts automatically, boosting reliability and performance.
Unsloth — Fine-Tune LLMs 2x Faster with 80% Less Memory
Fine-tune Llama, Mistral, Gemma, and Qwen models 2x faster using 80% less VRAM. Open-source with no accuracy loss. Train on a single GPU what used to need four.