Wraps any DSPy module with iterative self-improvement: scores each attempt with a reward function, generates feedback on failures, and retries until a quality threshold is met. Use for self-critique, iterative revision, or multi-draft generation.
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.
Before writing code, clarify:
dspy.BestOfN instead.Migrating from dspy.Assert / dspy.Suggest? Both were removed in DSPy 3.x.
dspy.Refineis their replacement and handles feedback-driven retries natively — no custom retry loop needed.
Use dspy.Refine when:
Do not use Refine when:
dspy.ChainOfThought insteaddspy.Predict calldspy.BestOfNThree things are needed: a module to wrap, a reward function, and a threshold.
import dspy
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini")) # or "anthropic/claude-sonnet-4-5-20250929", etc.
# 1. Define the module to refine
qa = dspy.ChainOfThought("question -> answer")
# 2. Define a reward function
# Takes (args_dict, prediction) -> float
def concise_answer(args, pred):
"""Reward one-word answers."""
return 1.0 if len(pred.answer.split()) == 1 else 0.0
# 3. Wrap with Refine
refined_qa = dspy.Refine(
module=qa,
N=3,
reward_fn=concise_answer,
threshold=1.0,
)
# Use it -- same interface as the wrapped module
result = refined_qa(question="What is the capital of Belgium?")
print(result.answer) # "Brussels"
dspy.Refine(
module, # dspy.Module -- required
N, # int -- required, max attempts
reward_fn, # Callable[[dict, Prediction], float] -- required
threshold, # float -- required, target reward score
fail_count=None, # int | None -- max failures before error (defaults to N)
)
| Parameter | Type | Default | Description |
|---|---|---|---|
module | dspy.Module | required | The module whose outputs you want to refine |
N | int | required | Maximum number of attempts. Each attempt uses temperature=1.0 with a different rollout ID |
reward_fn | Callable[[dict, Prediction], float] | required | Scores a prediction. Receives (args, pred) where args is the input kwargs dict and pred is the module's output. Returns a float |
threshold | float | required | Target score. Refine returns immediately when an attempt meets or exceeds this value |
fail_count | int | None | None (→ N) | Maximum allowed failures before raising an error |
The reward function is the core of Refine. It receives two arguments:
args -- a dict of the inputs passed to the module (e.g., {"question": "What is..."})pred -- the module's prediction object (access fields like pred.answer, pred.reasoning)It must return a float. Higher is better.
def valid_json(args, pred):
"""Accept only valid JSON outputs."""
import json
try:
json.loads(pred.output)
return 1.0
except (json.JSONDecodeError, TypeError):
return 0.0
Return partial scores to help Refine pick the best attempt even when none fully succeed:
def quality_score(args, pred):
"""Score answer quality on multiple criteria."""
score = 0.0
answer = pred.answer
# Criterion 1: not empty
if answer.strip():
score += 0.3
# Criterion 2: reasonable length (20-200 words)
word_count = len(answer.split())
if 20 <= word_count <= 200:
score += 0.4
# Criterion 3: addresses the question
if args["question"].split()[0].lower() in answer.lower():
score += 0.3
return score
import re
def valid_email_extraction(args, pred):
"""Reward valid email addresses extracted from text."""
emails = pred.emails if isinstance(pred.emails, list) else []
if not emails:
return 0.0
email_pattern = r'^[\w.-]+@[\w.-]+\.\w+$'
valid_count = sum(1 for e in emails if re.match(email_pattern, e))
return valid_count / len(emails)
Each attempt runs the wrapped module at temperature=1.0 with a different rollout ID, producing diverse outputs. Refine's selection logic:
reward_fnthreshold, return immediatelyChoosing N:
| N value | Use case | Cost |
|---|---|---|
| 2-3 | Format validation, simple constraints | Low overhead |
| 3-5 | Quality criteria, multi-factor scoring | Moderate |
| 5-10 | High-stakes outputs, strict requirements | Higher cost, better results |
The sweet spot for most use cases is N=3 to N=5. Beyond 5, diminishing returns are common unless the reward function is very specific.
In practice, Refine with N=3 and a graduated reward function typically moves a pipeline from a 40-60% baseline pass rate (outputs meeting your quality bar on the first try) to 75-90%. The exact gain depends on how achievable the threshold is and how much the feedback mechanism can guide the LM toward improvement.
What makes Refine different from random retries is feedback generation. When an attempt fails to meet the threshold:
This means later attempts are informed by earlier failures. Attempt 3 knows what went wrong in attempts 1 and 2.
You do not write the feedback logic -- Refine handles it automatically based on your reward function's scores.
Both modules run a wrapped module multiple times and select the best output, but they work differently:
| Aspect | dspy.Refine | dspy.BestOfN |
|---|---|---|
| Feedback | Generates feedback from failures, improving subsequent attempts | No feedback -- each attempt is independent |
| Attempts | Sequential (each informed by previous) | Independent (can be parallel) |
| Early stopping | Returns on first success meeting threshold | Also returns on first success meeting threshold |
| Best for | Iterative improvement, complex quality criteria | Sampling diversity, simple pass/fail |
| Cost pattern | Often fewer calls (feedback improves later attempts) | All attempts independent, no learning between them |
Use Refine when the LM can improve with feedback -- writing tasks, format compliance, multi-criteria quality.
Use BestOfN when attempts are independent and feedback would not help -- creative generation, sampling diverse options, simple binary checks.
Refine works with any dspy.Module, not just built-in ones:
class Summarizer(dspy.Module):
def __init__(self):
self.summarize = dspy.ChainOfThought("article -> summary")
def forward(self, article):
return self.summarize(article=article)
def good_summary(args, pred):
"""Score summary quality."""
summary = pred.summary
article = args["article"]
score = 0.0
# Shorter than original
if len(summary) < len(article) * 0.3:
score += 0.5
# At least 2 sentences
if summary.count('.') >= 2:
score += 0.5
return score
refined_summarizer = dspy.Refine(
module=Summarizer(),
N=3,
reward_fn=good_summary,
threshold=0.8,
)
result = refined_summarizer(article="Long article text here...")
print(result.summary)
dspy.Predict does not expose a reasoning field. Use dspy.ChainOfThought as the inner module so the feedback loop has reasoning to critique and improve.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-best-of-n/dspy-chain-of-thought/ai-checking-outputs/ai-improving-accuracy/ai-writing-content/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
/dspy-api-skills:dspy-refinefrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 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.Other plugins' skills for the same job