Wraps any DSPy module to run it N times and return the highest-scoring output via dspy.BestOfN. Useful when output quality varies and you want to sample multiple completions to pick the best.
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 using DSPy's BestOfN module to run a program multiple times and keep the highest-scoring result. This is rejection sampling -- generate N candidates, score each one, return the winner.
If the user has not already answered these, ask before writing BestOfN code:
dspy.Module — Predict, ChainOfThought, ReAct, a custom class, etc.)reward_fn — a function that scores each output without human judgment. If the user has no scoring idea, suggest simple heuristics (length check, regex match, test execution) before reaching for an LM judge.temperature=1.0 means N full LM calls. Help the user pick N that fits their constraints.dspy.BestOfN wraps any DSPy module and calls it up to N times with temperature=1.0 (each attempt uses a different rollout ID to get diverse outputs). A reward function scores every result, and BestOfN returns the single best prediction.
If any attempt hits a score threshold you set, execution stops early -- no need to burn through all N attempts when you already have a great result.
Your module ──> Run N times ──> Score each with reward_fn ──> Return best
Do not use BestOfN when:
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# 1. Define your module
qa = dspy.ChainOfThought("question -> answer")
# 2. Define a reward function
def short_answer(args, pred):
"""Prefer concise single-word answers."""
return 1.0 if len(pred.answer.split()) == 1 else 0.0
# 3. Wrap with BestOfN
best_qa = dspy.BestOfN(
module=qa,
N=3,
reward_fn=short_answer,
threshold=1.0,
)
# 4. Call it like any module
result = best_qa(question="What is the capital of Belgium?")
print(result.answer)
dspy.BestOfN(
module, # Any dspy.Module to run repeatedly
N, # Number of attempts (int)
reward_fn, # Scoring function: (args_dict, prediction) -> float
threshold, # Early-stop threshold: stop as soon as a score >= threshold
fail_count=None, # Max failures before raising an error (defaults to N)
)
| Parameter | Type | Description |
|---|---|---|
module | dspy.Module | The module to run N times |
N | int | Maximum number of attempts |
reward_fn | Callable[[dict, Prediction], float] | Scores each prediction; higher is better |
threshold | float | If any attempt scores >= this value, return immediately |
fail_count | int | None | How many attempts can fail (raise exceptions) before BestOfN itself raises. Defaults to N (all can fail before error) |
The reward function is the core of BestOfN. It receives two arguments:
def reward_fn(args: dict, prediction: dspy.Prediction) -> float:
# args: the keyword arguments you passed to the BestOfN call
# prediction: the output from one attempt of the wrapped module
# Return: a scalar score (higher = better)
...
Key differences from a dspy.Evaluate metric:
(args_dict, prediction) not (example, prediction, trace)args contains only the inputs you passed, not expected outputsBinary pass/fail:
def passes_tests(args, pred):
"""Score 1.0 if generated code passes all tests, 0.0 otherwise."""
try:
exec(pred.code)
return 1.0
except Exception:
return 0.0
Graded score:
def quality_score(args, pred):
"""Score summaries on length and keyword coverage."""
score = 0.0
# Prefer summaries under 100 words
if len(pred.summary.split()) <= 100:
score += 0.5
# Reward covering key topics
keywords = ["revenue", "growth", "forecast"]
covered = sum(1 for kw in keywords if kw in pred.summary.lower())
score += 0.5 * (covered / len(keywords))
return score
Using an LM as judge inside the reward:
class JudgeQuality(dspy.Signature):
"""Rate the answer quality from 0.0 to 1.0."""
question: str = dspy.InputField()
answer: str = dspy.InputField()
score: float = dspy.OutputField(desc="Quality score from 0.0 to 1.0")
judge = dspy.Predict(JudgeQuality)
def llm_reward(args, pred):
result = judge(question=args["question"], answer=pred.answer)
return result.score
Note: Using an LM as judge inside the reward function costs additional tokens per attempt. Reserve this for cases where programmatic scoring isn't feasible.
| N | Trade-off |
|---|---|
| 2-3 | Low cost, modest quality gain. Good starting point. |
| 5 | Solid improvement for tasks with high variance. Sweet spot for most uses. |
| 10+ | Diminishing returns unless your metric is very selective (e.g., <10% pass rate). |
Rule of thumb: if your base module succeeds ~50% of the time, N=3 gives you a ~87.5% chance of at least one success. If it succeeds ~20% of the time, you need N=8 for ~83%.
The math: probability of at least one success in N tries = 1 - (1 - p)^N where p is the single-attempt success rate.
temperature=1.0 and a unique rollout ID for each attemptdspy.Predictionthreshold, return immediately (early stopping)fail_count, raise an exceptionThe unique rollout IDs ensure the LM produces diverse outputs even with the same input. Temperature is fixed at 1.0 to maximize diversity.
BestOfN multiplies your token usage by up to N times (fewer if early stopping kicks in). Budget accordingly:
| Base cost per call | N | Max cost |
|---|---|---|
| $0.01 | 3 | $0.03 |
| $0.01 | 5 | $0.05 |
| $0.01 | 10 | $0.10 |
Ways to manage cost:
Both BestOfN and dspy.MultiChainComparison aim to pick the best output from multiple candidates, but they work differently:
| BestOfN | MultiChainComparison | |
|---|---|---|
| Selection method | Your reward function scores each candidate | An LM reads all candidates and picks the best |
| Metric required | Yes -- you must provide a reward_fn | No -- the LM decides what "best" means |
| Token cost | N calls to your module (+ reward fn) | Multiple chain calls + one comparison call |
| Best when | You have a clear, automatable scoring criterion | Quality is subjective or hard to score programmatically |
| Optimizable | The wrapped module can be optimized | The comparison module can be optimized |
Use BestOfN when you can write a reward function. Use MultiChainComparison when you want the LM to judge quality using its own understanding.
BestOfN works well as a complement to DSPy optimizers. Optimize your module first, then wrap the optimized version with BestOfN for an additional quality boost:
# Optimize the base module
optimizer = dspy.BootstrapFewShot(metric=metric, max_bootstrapped_demos=4)
optimized_qa = optimizer.compile(qa, trainset=trainset)
# Wrap the optimized module with BestOfN
best_qa = dspy.BestOfN(
module=optimized_qa,
N=3,
reward_fn=my_reward,
threshold=1.0,
)
This stacks two quality improvements: better prompts from the optimizer, and rejection sampling from BestOfN.
(example, prediction, trace=None) signature. BestOfN reward functions take (args_dict, prediction), not the (example, prediction, trace) signature used by dspy.Evaluate metrics. The args dict contains only the inputs you passed to the call, not labeled examples with gold outputs.threshold to enable early stopping. Without a meaningful threshold, BestOfN always runs all N attempts even when the first one is perfect. Set threshold to a value that represents "good enough" (e.g., 1.0 for binary pass/fail, 0.9 for graded metrics) to save tokens on easy inputs.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-multi-chain-comparison/dspy-refine/dspy-evaluate/ai-improving-accuracy/ai-making-consistent/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
/dspy-api-skills:dspy-best-of-nfrom 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-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-bootstrap-finetuneGenerates training data from a teacher model and fine-tunes student model weights using dspy.BootstrapFinetune. Use when you need maximum quality from a smaller/cheaper model — distilling GPT-4 quality into a cheaper model, generating training data from a strong teacher to fine-tune a weak student, reducing inference costs by replacing an expensive model with a fine-tuned small one, or building a production model that is fast and cheap. Related - ai-fine-tuning, ai-cutting-costs, dspy-better-together. Also used for model distillation with DSPy, teacher-student training, fine-tune small model from GPT-4 outputs, reduce API costs with fine-tuning, generate training data then fine-tune, cheap model same quality, distill large model into small model, fine-tune Llama from GPT-4, production model training, move from API to self-hosted model.Other plugins' skills for the same job