DSPy Expert Skill

SkillAI & models

Optimize and build programmatic prompt systems with Stanford DSPy. Signatures, modules (Predict, ChainOfThought, ReAct), optimizer/teleprompter selection, compilation, caching, evaluation. Use when doing programmatic prompt optimization or building compiled prompt programs. Do not use this skill for unrelated requests; route to the nearest named specialist.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the DSPy Expert Skill skill

What this skill tells your AI

The instructions your AI receives, as published by magnus919/agent-skills in dspy/SKILL.md and read by ahel’s review.

DSPy is a compiler for prompt programs, not a chain or RAG framework. You write Python programs with typed signatures and DSPy optimizes the prompts automatically.

⚠️ DSPy is NOT a chain framework. It does not use prompt | model | parser. It does not have LCEL. DSPy operates at a different layer: you define a program with Python control flow and typed signatures, then the compiler optimizes the prompts against a metric. If you reach for DSPy expecting LangChain-style composition, you are reaching for the wrong tool.

Think of it as PyTorch for LMs — you define the architecture, the compiler tunes the weights (prompts).

Core Paradigm

Read this first. It is the most important thing to understand about DSPy.

import dspy

# 1. Configure the LM
lm = dspy.LM("openai/gpt-4o-mini")
dspy.configure(lm=lm)

# 2. Define a signature (input/output schema)
class QASignature(dspy.Signature):
    """Answer questions concisely."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

# 3. Build a program using modules
qa = dspy.ChainOfThought(QASignature)

# 4. Compile against a metric
optimizer = dspy.MIPROv2(metric=dspy.answer_exact_match)
compiled_qa = optimizer.compile(qa, trainset=trainset, num_trials=25)

# 5. Use the compiled program (portable artifact)
answer = compiled_qa(question="What is DSPy?").answer

Core Principles

  1. DSPy is a compiler, not a chain framework. You define the program structure with Python control flow and typed signatures. The compiler optimizes the prompts. This is fundamentally different from LangChain's explicit prompt composition.

  2. Signatures define the task. Input/output field pairs with optional descriptions are the task definition. The syntax is input1, input2 -> output1, output2.

  3. Modules are program components. dspy.Predict (direct), dspy.ChainOfThought (reasoning), dspy.ReAct (tool-use), and custom dspy.Module subclasses. Compose them with Python control flow (if/for/while).

  4. Optimizers tune prompts, not weights. A dozen optimizers (teleprompters) tune instructions, few-shot demos, or both. Selection depends on bottleneck and budget. See the optimizer cheat sheet.

  5. Compile once, serve many. Compilation is expensive ($3-$300+). The output is a portable artifact via program.save(path). Inference is cheap.

  6. Cache aggressively. DSPy caches all LM calls by default. Set DSPY_CACHEDIR for the current client. Disable with dspy.LM(..., cache=False).

Where to Start

You already have...Start here
Nothing — exploring DSPyUnderstand the paradigm (read this page first), then build a simple Predict program
A working prompt you want to optimizePort to a DSPy Signature, add ChainOfThought, compile with BootstrapFewShot
A multi-step pipelineBuild as a custom dspy.Module with Python control flow, compile with MIPROv2
An agent/tool-use taskUse dspy.ReAct with tools, compile with GEPA or AvatarOptimizer
Comparing frameworksSee the Framework Routing Guide

Quick Reference

TaskApproachReference
Basic predictiondspy.Predict(signature)references/core-modules.md
With reasoningdspy.ChainOfThought(signature)references/core-modules.md
With toolsdspy.ReAct(tools=tools)references/agent-patterns.md
Custom programclass MyProgram(dspy.Module)references/program-patterns.md
Quick optimizationdspy.BootstrapFewShot(metric)references/optimizer-guide.md
Full optimizationdspy.MIPROv2(metric, auto="medium")references/optimizer-guide.md
Evaluationdspy.Evaluate(metric=fn, devset=examples)references/evaluation.md
Save/loadprogram.save(path) / program.load(path)references/compilation-guide.md
Retrievaldspy.Retrieve(k=5)references/program-patterns.md

Framework Routing Guide

ScenarioReach forWhy
Prompt optimization / compiled programsDSPyOnly framework that auto-optimizes prompts against a metric
Documents to query / RAGLlamaIndexData ingestion and retrieval are first-class primitives
Chain/agent compositionLangChainLCEL is the cleanest pipe-based composition model
State-machine multi-agentLangGraphGraph topology, subgraphs, human-in-the-loop
Search pipelinesHaystackPipeline model is more mature for search workloads
Role-based teamsCrewAIHigher-level agent abstraction

Reference Files

ReferenceLoad whenFile
Core ModulesBuilding with Predict, ChainOfThought, ReActreferences/core-modules.md
Optimizer GuideChoosing and configuring an optimizerreferences/optimizer-guide.md
Program PatternsRAG, classification, multi-step, tool-usereferences/program-patterns.md
EvaluationMetrics, evaluation loop, dataset creationreferences/evaluation.md
Compilation GuideCaching, cost management, save/loadreferences/compilation-guide.md
Agent PatternsReAct agent, tool-use, AvatarOptimizerreferences/agent-patterns.md
FAQ & TroubleshootingCommon errors and fixesreferences/faq-and-troubleshooting.md
Validation AuditResearch validation of all API claimsreferences/validation-audit.md
Worked RAG ExampleFull RAG compilation with expected outputreferences/example-rag-compilation.md

Template Files

TemplateWhen to useFile
ClassificationText classification with BootstrapFewShottemplates/classification.py
RAG ProgramRAG with ColBERT retrieval and ChainOfThoughttemplates/rag-program.py
Multi-Step ReasoningMulti-step program with tool-usetemplates/multi-step.py

Scripts

ScriptPurposeFile
check-setupVerify DSPy installation and configurationscripts/check-setup.py

Troubleshooting

SymptomLikely causeFixReference
Compilation too slowToo many candidates/threadsReduce num_candidates or use auto="light"references/optimizer-guide.md
Compilation too expensiveNo cachingEnable DSPY_CACHEDIRreferences/compilation-guide.md
Context too longToo many demosReduce max_bootstrapped_demos and max_labeled_demosreferences/faq-and-troubleshooting.md
Low quality after compileWrong optimizer for bottleneckCheck cheat sheet: instructions vs demos vs weightsreferences/optimizer-guide.md
Program is not improvingMetric not discriminatingUse a metric that returns float, not boolreferences/evaluation.md
Sub-module not updating_compiled flag setSet module._compiled = False before recompilingreferences/compilation-guide.md

When NOT to Use DSPy

  • Simple single-prompt application — raw API calls are simpler
  • Need pre-built application modules (PDF Q&A, text-to-SQL) — use LlamaIndex or LangChain
  • One-shot task with no optimization budget — DSPy's compiler overhead won't amortize
  • Real-time latency-critical — compilation happens at development time but adds no inference overhead

Signals

GitHub stars
78
Forks
8
Last commit
Sep 2026
Advanced
Catalog kind
skill
Gateway key
dspy
Source
github.com/magnus919/agent-skills