Provides DSPy utility functions for cache control, debugging with inspect_history, saving/loading optimized programs, and runtime validation with Refine/BestOfN. Useful for production DSPy workflows.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Guide the user through DSPy's utility functions -- controlling caching, debugging calls, persisting optimized programs, and enforcing runtime constraints with reward functions.
Looking for streaming, async, or MCP? These have dedicated skills now:
- Streaming tokens to a UI -- see
/dspy-streaming- Async execution and FastAPI -- see
/dspy-async- MCP server integration -- see
/dspy-mcp
Ask the user before diving in:
Then jump to the relevant section below.
DSPy caches LM responses by default to reduce costs and speed up development. Use dspy.configure_cache to control this globally.
# Disable all caching (disk and memory)
dspy.configure_cache(enable_disk_cache=False, enable_memory_cache=False)
# Disable only disk cache (keep memory cache for speed)
dspy.configure_cache(enable_disk_cache=False)
# Re-enable both caches
dspy.configure_cache(enable_disk_cache=True, enable_memory_cache=True)
# DSPy 3.2+ - harden the on-disk cache against untrusted pickle payloads
dspy.configure_cache(restrict_pickle=True)
You can also control caching per LM instance:
# This LM never caches
lm_no_cache = dspy.LM("openai/gpt-4o-mini", cache=False)
# This LM caches (default)
lm_cached = dspy.LM("openai/gpt-4o-mini", cache=True)
Cache is stored locally on disk. Identical calls (same prompt, parameters, model) return cached results with no API call.
When NOT to disable caching: During optimization runs -- optimizers rely heavily on cache to avoid redundant LM calls. Disabling cache globally during optimization dramatically increases cost and time.
dspy.inspect_history shows the raw prompts and responses from recent LM calls. This is the single most useful debugging tool in DSPy.
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
classify = dspy.Predict("text -> label")
classify(text="Great product!")
# See what was actually sent to and received from the LM
dspy.inspect_history(n=1) # Show last 1 call
dspy.inspect_history(n=3) # Show last 3 calls
dspy.inspect_history(n=1) to see the last LM callFor more detailed tracing, configure DSPy with an empty trace list:
dspy.configure(lm=lm, trace=[])
You can also print a module to see its structure:
print(my_program) # Shows module tree with all sub-modules and signatures
After optimizing a DSPy program, save its learned state (few-shot demos, instructions) for production use.
# After optimization
optimized = optimizer.compile(my_program, trainset=trainset)
# Save learned state only (default -- class definition must exist at load time)
optimized.save("optimized_program.json")
# Save entire program including class definition (load without recreating the class)
optimized.save("optimized_program_dir", save_program=True)
# Option A: load state into a fresh instance of the same class
program = MyProgram()
program.load("optimized_program.json")
# Option B: load an entire saved program (only when saved with save_program=True)
program = dspy.load("optimized_program_dir")
# Use it
result = program(question="What is DSPy?")
dspy.Predict modulesforward() -- that's your code, it must exist at load timeBootstrapFinetune)dspy.configure() before loadingUse save(save_program=True) to include the class definition. Then dspy.load() reconstructs the program without needing the class imported.
import dspy
class MyPipeline(dspy.Module):
def __init__(self):
self.classify = dspy.Predict("text -> category")
self.respond = dspy.ChainOfThought("text, category -> response")
def forward(self, text):
cat = self.classify(text=text)
return self.respond(text=text, category=cat.category)
# --- Optimization (run once) ---
# optimizer = dspy.MIPROv2(metric=metric, auto="medium")
# optimized = optimizer.compile(MyPipeline(), trainset=trainset)
# optimized.save("pipeline_v1.json")
# --- Production (run on every request) ---
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
pipeline = MyPipeline()
pipeline.load("pipeline_v1.json")
result = pipeline(text="How do I reset my password?")
Use dspy.Refine to wrap any module and retry until a reward function returns a score meeting a threshold. This replaced dspy.Assert/dspy.Suggest in DSPy 3.x:
import dspy
qa = dspy.ChainOfThought("question -> answer")
def answer_reward(args, pred):
"""Score answer quality. Returns 0.0-1.0."""
if not pred.answer.strip():
return 0.0
if len(pred.answer.split()) < 5:
return 0.5 # soft penalty for short answers
return 1.0
validated_qa = dspy.Refine(
module=qa,
N=3,
reward_fn=answer_reward,
threshold=1.0,
)
result = validated_qa(question="What is DSPy?")
| Approach | How it works | Use when |
|---|---|---|
dspy.Refine | Retries with feedback from the reward function until threshold met or N attempts exhausted | Later attempts can improve based on earlier failures |
dspy.BestOfN | Runs N independent attempts, returns the best-scoring one | Attempts are independent; cross-attempt feedback would not help |
Both require threshold (no default -- must be explicit). Both accept fail_count (how many failures allowed before raising; defaults to N).
For detailed patterns and examples, see /dspy-refine and /dspy-best-of-n.
save() does not persist forward() logic -- only learned state (demos, instructions) is saved. The class definition must exist in your production code at load time.dspy.configure() before load() -- loading a saved program before configuring the LM causes silent failures where the program runs but uses no LM (or the wrong one).inspect_history shows cached calls too -- after a cache hit, inspect_history still shows the call, but the prompt may look different from what was originally sent. Disable cache if you need exact prompt inspection.enable_disk_cache=False, enable_memory_cache=False during optimization dramatically increases cost and time -- only disable cache for specific inference calls, not globally.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-streaming/dspy-async/dspy-mcp/dspy-lm -- Configure language models, per-LM caching, inspect_history on LM instances/dspy-modules -- Build composable programs with dspy.Module, save/load patterns/ai-tracing-requests -- Production observability and tracing for DSPy programs/dspy-refine -- Refine patterns, reward functions, and iterative improvement/dspy-best-of-n -- BestOfN for independent sampling without cross-attempt feedback/ai-serving-apis -- Serve DSPy programs as web APIs/ai-do if you do not have it -- it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest./dspy-asyncUse when you need to run DSPy modules asynchronously — FastAPI endpoints, concurrent LM calls, non-blocking execution, or integrating DSPy into async web frameworks. Common scenarios - serving DSPy behind FastAPI or Starlette, running multiple LM calls concurrently with asyncio.gather, non-blocking batch processing, combining async with streaming, or building async agent loops. Related - ai-serving-apis, dspy-parallel, dspy-streaming, dspy-utils. Also used for aforward, acall, async DSPy, await dspy, FastAPI with DSPy async, concurrent DSPy calls, asyncio with DSPy, non-blocking DSPy, async batch processing, semaphore concurrency limit, asyncio.gather DSPy, async web framework DSPy, Starlette DSPy, aiohttp DSPy./dspy-best-of-nRuns any DSPy module N times and returns the highest-scoring output via a reward function using dspy.BestOfN. Use when output quality varies across runs and you want to sample multiple completions and pick the best — trading latency for reliability on high-stakes outputs. Common scenarios - generating multiple candidate answers and picking the highest-scoring one, improving reliability on high-stakes classification, reducing variance in creative generation, getting better summaries by sampling several and selecting the best, or trading latency for quality on critical decisions. Related - ai-improving-accuracy, ai-making-consistent, dspy-refine. Also used for sample multiple completions, pick the best of several LLM outputs, majority voting for LLM, self-consistency decoding, reduce LLM output variance, generate and select pattern, best candidate selection, how to make AI more reliable by trying multiple times, brute force better quality, retry and pick best, dspy.BestOfN, quality vs latency tradeoff, n=5 completions pick best./dspy-better-togetherJointly optimize prompts and model weights using dspy.BetterTogether for maximum accuracy. Use when you have already tried prompt-only optimization and want the next level — jointly tuning prompts and model weights for maximum quality. Common scenarios - you have maxed out prompt optimization and need the next level, combining instruction tuning with weight tuning for maximum quality, making a small model match a large model through joint optimization, or squeezing the last few percent of accuracy. Related - ai-fine-tuning, ai-improving-accuracy, ai-cutting-costs. Also used for dspy.BetterTogether, joint prompt and weight optimization, beyond prompt engineering, combine fine-tuning with prompt optimization, maximum possible quality from DSPy, hybrid optimization strategy, prompt optimization hit a ceiling, fine-tune and optimize prompts at the same time, advanced DSPy optimization, best possible accuracy, what to try after MIPROv2, next level AI quality./dspy-bootstrap-few-shotAutomatically generate and select few-shot demonstrations for a DSPy program from labeled data using dspy.BootstrapFewShot - the simplest and fastest optimizer. Use when you have 50+ labeled examples and want a quick accuracy boost as your first optimization step. Common scenarios - your first optimization attempt on a new DSPy program, adding few-shot examples automatically from labeled data, quick accuracy boost before trying heavier optimizers, bootstrapping demonstrations from a teacher model, or getting started with DSPy optimization. Related - ai-improving-accuracy, dspy-labeled-few-shot. Also used for dspy.BootstrapFewShot, simplest DSPy optimizer, first optimizer to try, automatic few-shot example selection, bootstrap demonstrations from labels, quick optimization baseline, add examples to prompt automatically, teacher bootstrapping, labeled data to few-shot demos, starting point for DSPy optimization, easy accuracy improvement, how to optimize DSPy program for the first time./dspy-api-skills:dspy-utilsfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skillsOther plugins' skills for the same job