Guides joint prompt and weight optimization using dspy.BetterTogether for maximum accuracy. Use after prompt-only optimization plateaus — chains instruction tuning with fine-tuning in alternating rounds for compounding gains.
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.BetterTogether to get the best possible quality by combining prompt optimization and model fine-tuning in alternating rounds. Each round builds on the improvements from the previous one, creating compounding gains that beat either approach alone.
Before generating code, confirm:
/ai-improving-accuracy first — BetterTogether is only worth it after individual optimizers plateau./ai-improving-accuracy instead."p -> w -> p" is hours to half a day.BetterTogether is a DSPy optimizer that alternates between prompt optimization (instructions, few-shot examples) and weight optimization (fine-tuning). Instead of running these independently, it chains them so each phase builds on the previous one's improvements:
Research shows this consistently outperforms either approach alone, with 5-78% gains over individual techniques (arXiv 2407.10930v2). A Databricks case study on IE Bench showed GEPA alone +2.1 points, fine-tuning alone +1.9 points, but combined they achieved +4.8 points over baseline.
/ai-improving-accuracy)/ai-improving-accuracygpt-4o-mini/gpt-4o, or local models)Before starting, confirm:
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# Define your program
class Classify(dspy.Signature):
"""Classify the support ticket into a category."""
text: str = dspy.InputField()
category: str = dspy.OutputField()
program = dspy.ChainOfThought(Classify)
# IMPORTANT: All predictors must have explicit LMs assigned
program.set_lm(lm)
# Define your metric
def metric(example, prediction, trace=None):
return prediction.category.strip().lower() == example.category.strip().lower()
# Prepare data
trainset = [dspy.Example(text=x["text"], category=x["category"]).with_inputs("text") for x in data]
valset = trainset[800:900]
trainset = trainset[:800]
# Run BetterTogether with defaults
optimizer = dspy.BetterTogether(metric=metric)
compiled = optimizer.compile(program, trainset=trainset, valset=valset)
By default, BetterTogether uses:
p: BootstrapFewShotWithRandomSearch for prompt optimizationw: BootstrapFinetune for weight optimization"p -> w -> p" (prompts, then weights, then prompts again)BetterTogether executes a strategy string that defines the order of optimization phases:
"p -> w -> p"
| | |
| | +-- Re-optimize prompts for the fine-tuned model
| +------- Fine-tune weights using the optimized prompts
+------------ Optimize prompts first (instructions + few-shot)
At each step:
After all steps, BetterTogether returns the best-scoring candidate across all phases (ties broken by earlier position).
Pass your own optimizers as keyword arguments. The keys become identifiers in the strategy string:
optimizer = dspy.BetterTogether(
metric=metric,
p=dspy.GEPA(metric=metric, auto="medium"),
w=dspy.BootstrapFinetune(metric=metric),
)
program.set_lm(lm)
compiled = optimizer.compile(
program,
trainset=trainset,
valset=valset,
strategy="p -> w -> p",
)
You can use any DSPy Teleprompter as an optimizer. Common choices:
| Key | Optimizer | Best for |
|---|---|---|
p | GEPA | Instruction tuning, fewer examples |
p | MIPROv2 | Best general prompt optimization |
p | BootstrapFewShotWithRandomSearch | Fast prompt optimization (default) |
w | BootstrapFinetune | Weight optimization (default) |
BetterTogether(metric, **optimizers)| Parameter | Type | Description |
|---|---|---|
metric | Callable | Evaluation function (example, prediction, trace=None) -> numeric |
**optimizers | keyword args | Custom optimizers. Keys become strategy identifiers (e.g., p=GEPA(...), w=BootstrapFinetune(...)) |
optimizer.compile(student, *, trainset, ...)| Parameter | Type | Default | Description |
|---|---|---|---|
student | Module | required | Program to optimize. All predictors must have LMs via set_lm() |
trainset | list[Example] | required | Training examples |
valset | list[Example] | None | Validation set. If None, splits from trainset |
valset_ratio | float | 0.1 | Fraction of trainset to use as valset when valset=None |
strategy | str | "p -> w -> p" | Optimizer execution order using keys from constructor |
teacher | Module or list[Module] | None | Optional teacher program(s) for distillation |
num_threads | int | None | Parallel threads for evaluation |
shuffle_trainset_between_steps | bool | True | Shuffle trainset before each step |
seed | int | None | Random seed for reproducibility |
optimizer_compile_args | dict | None | Per-optimizer custom compile arguments |
The compiled program has two extra attributes:
candidate_programs: List of dicts with 'program', 'score', 'strategy' keys, sorted by score descendingflag_compilation_error_occurred: Boolean indicating if any step failed| Strategy | Rounds | Use case |
|---|---|---|
"p -> w -> p" | 3 | Default. Best balance of quality and cost |
"p -> w" | 2 | Simpler, cheaper. Good starting point |
"w -> p" | 2 | When your model needs weight tuning first |
"p -> w -> p -> w" | 4 | Maximum quality, highest cost |
BetterTogether runs multiple optimization rounds, so it costs more than individual optimizers:
| Strategy | Approximate cost | Time |
|---|---|---|
"p -> w" | 1x prompt opt + 1x fine-tune | Hours |
"p -> w -> p" (default) | 2x prompt opt + 1x fine-tune | Hours to half a day |
"p -> w -> p -> w" | 2x prompt opt + 2x fine-tune | Half a day to a day |
Fine-tuning is the expensive part. Each fine-tuning round involves:
"p -> w" to see if two rounds are enoughoptimizer_compile_args to limit individual optimizer budgets| Approach | Data needed | Quality | Cost | When to use |
|---|---|---|---|---|
| MIPROv2 alone | 200+ | Good | Low | First optimization attempt |
| BootstrapFinetune alone | 500+ | Better | Medium | When prompts hit a ceiling |
| BetterTogether | 500+ | Best | High | When you need maximum quality |
Rule of thumb: Try MIPROv2 first. If you're still short of your quality target, try BootstrapFinetune. If you need more, use BetterTogether.
set_lm(). Global dspy.configure(lm=...) is not enough for BetterTogether.program = dspy.ChainOfThought(MySignature)
program.set_lm(lm) # Required
Fine-tunable model: The weight optimizer needs a model that supports fine-tuning (OpenAI, Databricks, or local models with GPU).
Validation data: Provide either an explicit valset or set valset_ratio > 0. Without validation data, BetterTogether returns the latest program instead of the best one.
Strategy keys must match: Keys in the strategy string must match the keyword argument names from the constructor.
After compilation, examine all candidate programs:
compiled = optimizer.compile(program, trainset=trainset, valset=valset)
# See all candidates ranked by score
for candidate in compiled.candidate_programs:
print(f"Strategy step: {candidate['strategy']}, Score: {candidate['score']:.1f}%")
# Check if any errors occurred
if compiled.flag_compilation_error_occurred:
print("Warning: one or more optimization steps failed")
BetterTogether has built-in resilience. If any optimization step fails:
flag_compilation_error_occurred = True on the resultAlways check this flag in production workflows.
set_lm() and relies on global dspy.configure(). BetterTogether requires every predictor to have an explicit LM assignment via program.set_lm(lm). Without it, the weight optimizer cannot identify which model to fine-tune and raises an error. Always call set_lm() on the program before compile().valset (or valset_ratio > 0), BetterTogether returns the latest program instead of the best-scoring one across all phases. Always provide a valset or leave valset_ratio=0.1 so the optimizer can select the best candidate.valset overlaps with trainset, the optimizer selects based on inflated scores. Use a held-out split or let BetterTogether auto-split via valset_ratio.flag_compilation_error_occurred after compile. If a fine-tuning step fails silently (API timeout, quota exceeded), BetterTogether returns the best program found before the failure. Always check compiled.flag_compilation_error_occurred and inspect compiled.candidate_programs to verify which steps completed.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/ai-fine-tuning/ai-improving-accuracy/dspy-evaluate/dspy-data/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, prompt-optimization, fine-tuning, accuracy, hybrid-optimization
/dspy-api-skills:dspy-better-togetherfrom 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-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