Guides using dspy.LabeledFewShot to attach hand-curated labeled examples as few-shot demonstrations without bootstrapping or LM calls. Best for expert-curated, high-stakes few-shot tasks.
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.LabeledFewShot -- the simplest DSPy optimizer. It takes labeled examples you provide and attaches them as few-shot demonstrations to your program's predictors. No bootstrapping, no metric, no LM calls during optimization.
Before writing code, ask:
k value — typically 25-50% of trainset size, capped at the default of 16.dspy.BootstrapFewShot may be better — it evaluates examples against a metric and keeps only the ones that help.dspy.LabeledFewShot is an optimizer that takes a set of labeled training examples and injects them directly as few-shot demonstrations into every predictor in your DSPy program.
Under the hood, compile() creates a copy of your program, iterates over each predictor, and assigns up to k examples from your training set as that predictor's demos.
Use LabeledFewShot when... | Use something else when... |
|---|---|
| You have hand-curated, high-quality examples | You want the optimizer to discover good examples (BootstrapFewShot) |
| You want a quick baseline before trying fancier optimizers | You need instruction tuning too (MIPROv2) |
| You need full control over which demonstrations the LM sees | You have enough data to let DSPy search (BootstrapFewShotWithRandomSearch) |
| Your task is simple enough that a few good examples suffice | Quality requires filtering examples by a metric |
| You want deterministic, reproducible behavior | You want the optimizer to explore different combinations |
Rule of thumb: Use LabeledFewShot as your first optimization step. If accuracy is not high enough, upgrade to BootstrapFewShot which evaluates examples against a metric and keeps only the ones that work.
dspy.LabeledFewShot(k=16)
| Parameter | Type | Default | Description |
|---|---|---|---|
k | int | 16 | Maximum number of demonstration examples to include per predictor |
optimizer.compile(student, *, trainset, sample=True)
| Parameter | Type | Default | Description |
|---|---|---|---|
student | dspy.Module | required | The DSPy program to optimize |
trainset | list[dspy.Example] | required | Labeled examples to use as demonstrations |
sample | bool | True | True = randomly sample k examples; False = take the first k sequentially |
Returns: A copy of student with demonstrations attached to each predictor.
If trainset is empty, the student is returned unmodified.
import dspy
from typing import Literal
# Configure any LM provider
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# 1. Define your signature
class ClassifyIntent(dspy.Signature):
"""Classify the user message into an intent category."""
message: str = dspy.InputField(desc="User message")
intent: Literal["question", "complaint", "praise", "request"] = dspy.OutputField()
# 2. Build your program
classify = dspy.Predict(ClassifyIntent)
# 3. Create hand-picked training examples
trainset = [
dspy.Example(message="How do I reset my password?", intent="question").with_inputs("message"),
dspy.Example(message="This is broken and I want a refund", intent="complaint").with_inputs("message"),
dspy.Example(message="Your team was incredibly helpful!", intent="praise").with_inputs("message"),
dspy.Example(message="Please update my billing address", intent="request").with_inputs("message"),
dspy.Example(message="What formats do you export to?", intent="question").with_inputs("message"),
dspy.Example(message="The app crashes every time I open it", intent="complaint").with_inputs("message"),
]
# 4. Compile with LabeledFewShot
optimizer = dspy.LabeledFewShot(k=4)
optimized = optimizer.compile(classify, trainset=trainset)
# 5. Use the optimized program -- it now includes few-shot demos in every call
result = optimized(message="Can you send me last month's invoice?")
print(result.intent) # request
Verify it worked: Run a few test inputs and inspect dspy.inspect_history(n=1) to confirm demos appear in the prompt. If the prompt looks identical to the zero-shot version, check that .with_inputs() is called on every training example.
When sample=True (the default):
k examples from trainset using a fixed seed (0)When sample=False:
k examples from trainset in orderIf your trainset has fewer than k examples, all examples are used.
The k parameter controls how many demonstrations appear in the prompt.
Keep in mind that each demonstration adds tokens to every LM call. For long input/output fields, use a smaller k to stay within context limits.
When you want precise control over which examples appear, disable sampling:
# Place your best, most representative examples first
trainset = [
dspy.Example(message="What's your return policy?", intent="question").with_inputs("message"),
dspy.Example(message="This product is defective", intent="complaint").with_inputs("message"),
dspy.Example(message="Love the new feature!", intent="praise").with_inputs("message"),
dspy.Example(message="Please cancel my subscription", intent="request").with_inputs("message"),
# ... more examples, ordered by importance
]
optimizer = dspy.LabeledFewShot(k=4)
optimized = optimizer.compile(classify, trainset=trainset, sample=False)
# The first 4 examples are used as demos, in order
After compilation, save the optimized program so you can reuse it without recompiling:
# Save
optimized.save("intent_classifier.json")
# Load later
loaded = dspy.Predict(ClassifyIntent)
loaded.load("intent_classifier.json")
result = loaded(message="How do I upgrade my plan?")
LabeledFewShot attaches demos to every predictor in your program. This works with multi-step pipelines too:
class SupportRouter(dspy.Module):
def __init__(self):
self.classify = dspy.Predict(ClassifyIntent)
self.respond = dspy.ChainOfThought("message, intent -> response")
def forward(self, message):
intent = self.classify(message=message).intent
return self.respond(message=message, intent=intent)
router = SupportRouter()
# Both self.classify and self.respond get demos from the same trainset
optimizer = dspy.LabeledFewShot(k=3)
optimized_router = optimizer.compile(router, trainset=trainset)
Note: every predictor receives demos from the same trainset. If your predictors have different signatures, make sure your training examples include all fields needed across all predictors, or consider compiling predictors separately.
LabeledFewShot is a great starting point, but it has limitations:
Typical improvement: Adding 4-8 curated demos with LabeledFewShot often improves task accuracy by 5-15% over zero-shot. If that is not enough, BootstrapFewShot commonly adds another 10-20% by filtering to only the examples that led to correct outputs.
dspy.BootstrapFewShot addresses all three. It runs your program on each training example, evaluates with a metric, and keeps only the demonstrations that led to correct outputs. The upgrade is straightforward:
# Before: LabeledFewShot (no metric needed)
optimizer = dspy.LabeledFewShot(k=4)
optimized = optimizer.compile(program, trainset=trainset)
# After: BootstrapFewShot (needs a metric)
def metric(example, prediction, trace=None):
return prediction.intent == example.intent
optimizer = dspy.BootstrapFewShot(metric=metric, max_bootstrapped_demos=4)
optimized = optimizer.compile(program, trainset=trainset)
.with_inputs() on training examples. Without .with_inputs("field_name"), DSPy does not know which fields are inputs vs labels. The demonstrations appear malformed in the prompt — the LM sees all fields as input, which confuses it. Always call .with_inputs() on every dspy.Example in your trainset.BootstrapFewShot instead — it evaluates examples against a metric and keeps only the ones that help.k larger than the trainset without explaining the behavior. When k exceeds len(trainset), DSPy silently uses all available examples. This is fine, but Claude should tell the user: "You have 5 examples and k=16, so all 5 will be used as demos."LabeledFewShot assigns the same demos to every predictor. If predictors have different signatures, the examples need all fields across all signatures, or the user should compile predictors separately. Claude sometimes splits the trainset incorrectly — explain the shared-demo behavior.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-data/dspy-signatures/dspy-bootstrap-few-shot/dspy-knn-few-shot/ai-improving-accuracy/dspy-evaluate/dspy-modules/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-api-skills:dspy-labeled-few-shotfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skillsOther plugins' skills for the same job