Skip to main content
skill CX Codex

dspy-bootstrap-fewshot — Claude Code skill for DSPy optimization

This skill guides BootstrapFewShot setup so a teacher model can generate demonstrations for a DSPy program. Use it when you have labeled examples and want to automate demo selection.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add OmidZamani/dspy-skills --skill dspy-bootstrap-fewshot -a claude-code
Open on GitHub

What dspy-bootstrap-fewshot does

The skill walks through passing a DSPy program, training examples, and a metric to BootstrapFewShot. The optimizer uses a teacher model to produce candidate demonstrations, then compiles them into the program. Its examples cover configuring dspy, checking predictions, and saving the compiled state as JSON.

You need labeled training data and a configured language model; a separate teacher configuration is supported. The guide recommends evaluating on held-out examples. Teacher-model calls have a cost, and results may not generalize to very different inputs, so evaluate the compiled program before using it in a project.

What it helps with

  • select demonstrations for a DSPy program
  • generate examples with a teacher model
  • evaluate an optimized program on held-out data
  • save a compiled program as JSON

Example prompts for the agent

  • Set up BootstrapFewShot for my DSPy program and training set.
  • Show me how to configure a metric and teacher model for DSPy optimization.
  • Add held-out evaluation and save the compiled program.

How to install dspy-bootstrap-fewshot

1Skills CLI (Vercel)

npx skills add OmidZamani/dspy-skills --skill dspy-bootstrap-fewshot -a claude-code

2Manually: put the files in place

~/.claude/skills/dspy-bootstrap-fewshot/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/dspy-bootstrap-fewshot/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about dspy-bootstrap-fewshot

How do I install dspy-bootstrap-fewshot in Claude Code?

Run npx skills add OmidZamani/dspy-skills --skill dspy-bootstrap-fewshot -a claude-code. The skill file is available at ~/.claude/skills/dspy-bootstrap-fewshot/SKILL.md.

What does dspy-bootstrap-fewshot do?

It guides you through using BootstrapFewShot to create teacher-generated demonstrations and compile a DSPy program with selected examples.

What do I need to use this skill?

You need labeled training examples, a DSPy program, and a metric function. You can configure the teacher model separately.

Source text

SKILL.md · MIT
---
name: dspy-bootstrap-fewshot
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["optimizer"]
requires-extras: []
description: Use for BootstrapFewShot, bootstrapped demonstrations, teacher-model demos, and low-data DSPy prompt optimization.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep
---

# DSPy Bootstrap Few-Shot Optimizer

## Goal

Automatically generate and select optimal few-shot demonstrations for your DSPy program using a teacher model.

## When to Use

- You have **10-50 labeled examples**
- Manual example selection is tedious or suboptimal
- You want demonstrations with reasoning traces
- Quick optimization without extensive compute

## Related Skills

- For more data (200+ examples): [dspy-miprov2-optimizer](../dspy-miprov2-optimizer/SKILL.md)
- For agentic systems: [dspy-gepa-reflective](../dspy-gepa-reflective/SKILL.md)
- Measure improvements: [dspy-evaluation-suite](../dspy-evaluation-suite/SKILL.md)

## Inputs

| Input | Type | Description |
|-------|------|-------------|
| `program` | `dspy.Module` | Your DSPy program to optimize |
| `trainset` | `list[dspy.Example]` | Training examples |
| `metric` | `callable` | Evaluation function |
| `metric_threshold` | `float` | Numerical threshold for accepting demos (optional) |
| `max_bootstrapped_demos` | `int` | Max teacher-generated demos (default: 4) |
| `max_labeled_demos` | `int` | Max direct labeled demos (default: 16) |
| `max_rounds` | `int` | Max bootstrapping attempts per example (default: 1) |
| `teacher_settings` | `dict` | Configuration for teacher model (optional) |

## Outputs

| Output | Type | Description |
|--------|------|-------------|
| `compiled_program` | `dspy.Module` | Optimized program with demos |

## Workflow

### Phase 1: Setup

```python
import dspy
from dspy.teleprompt import BootstrapFewShot

# Configure LMs
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
```

### Phase 2: Define Program and Metric

```python
class QA(dspy.Module):
    def __init__(self):
        self.generate = dspy.ChainOfThought("question -> answer")
    
    def forward(self, question):
        return self.generate(question=question)

def validate_answer(example, pred, trace=None):
    return example.answer.lower() in pred.answer.lower()
```

### Phase 3: Compile

```python
optimizer = BootstrapFewShot(
    metric=validate_answer,
    max_bootstrapped_demos=4,
    max_labeled_demos=4,
    teacher_settings={'lm': dspy.LM("openai/gpt-4o")}
)

compiled_qa = optimizer.compile(QA(), trainset=trainset)
```

### Phase 4: Use and Save

```python
# Use optimized program
result = compiled_qa(question="What is photosynthesis?")

# Save for production (state-only, recommended)
compiled_qa.save("qa_optimized.json", save_program=False)
```

## Production Example

```python
import dspy
from dspy.teleprompt import BootstrapFewShot
from dspy.evaluate import Evaluate
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ProductionQA(dspy.Module):
    def __init__(self):
        self.cot = dspy.ChainOfThought("question -> answer")
    
    def forward(self, question: str):
        try:
            return self.cot(question=question)
        except Exception as e:
            logger.error(f"Generation failed: {e}")
            return dspy.Prediction(answer="Unable to answer")

def robust_metric(example, pred, trace=None):
    if not pred.answer or pred.answer == "Unable to answer":
        return 0.0
    return float(example.answer.lower() in pred.answer.lower())

def optimize_with_bootstrap(trainset, devset):
    """Full optimization pipeline with validation."""
    
    # Baseline
    baseline = ProductionQA()
    evaluator = Evaluate(devset=devset, metric=robust_metric, num_threads=4)
    baseline_score = evaluator(baseline)
    logger.info(f"Baseline: {baseline_score:.2%}")
    
    # Optimize
    optimizer = BootstrapFewShot(
        metric=robust_metric,
        max_bootstrapped_demos=4,
        max_labeled_demos=4
    )
    
    compiled = optimizer.compile(baseline, trainset=trainset)
    optimized_score = evaluator(compiled)
    logger.info(f"Optimized: {optimized_score:.2%}")
    
    if optimized_score > baseline_score:
        compiled.save("production_qa.json", save_program=False)
        return compiled
    
    logger.warning("Optimization didn't improve; keeping baseline")
    return baseline
```

## Best Practices

1. **Quality over quantity** - 10 excellent examples beat 100 noisy ones
2. **Use stronger teacher** - GPT-4 as teacher for GPT-3.5 student
3. **Validate with held-out set** - Always test on unseen data
4. **Start with 4 demos** - More isn't always better

## Limitations

- Requires labeled training data
- Teacher model costs can add up
- May not generalize to very different inputs
- Limited exploration compared to MIPROv2

## Official Documentation

- **DSPy Documentation**: https://dspy.ai/
- **DSPy GitHub**: https://github.com/stanfordnlp/dspy
- **BootstrapFewShot API**: https://dspy.ai/api/optimizers/BootstrapFewShot/
- **Optimization Guide**: https://dspy.ai/learn/optimization/optimizers/

© OmidZamani · MIT · OmidZamani/dspy-skills

Similar skills

All skills for AI and ML →

From the same set23

dspy-finetune-bootstrap Turns a working DSPy program into fine-tuned weights for a smaller model, cutting inference cost and speeding up responses. CX Codex +1 ★ 124repo stars dspy-evaluation-suite Tests and benchmarks DSPy modules against evaluation datasets using multi-threaded execution and custom scoring functions. CX Codex +1 ★ 124repo stars dspy-embedding-retrieval Build semantic retrieval over an application-owned text corpus with DSPy embeddings, local or hosted models, and optional FAISS indexing. CX Codex +1 ★ 124repo stars dspy-debugging-observability A skill for debugging and monitoring DSPy programs: call history, MLflow tracing, and custom callbacks that track cost and errors. CX Codex +1 ★ 124repo stars dspy-custom-module-design Guides the creation of custom DSPy modules extending dspy.Module with state caching, input validation, and program serialization. CX Codex +1 ★ 124repo stars dspy-better-together A skill that walks you through chaining DSPy prompt and weight optimizers, scoring intermediate programs and keeping the best one. CX Codex +1 ★ 124repo stars dspy-advanced-module-composition Composes complex DSPy programs using module ensembling, MultiChainComparison, sequential pipelines, and fallbacks. Useful for multi-step reasoning architectures. CX Codex +1 ★ 124repo stars dspy-adapters-multimodal This skill guides DSPy adapter choices for structured responses, function calls, and image, audio, or document inputs. Use it when building DSPy-based AI applications. CX Codex +1 ★ 124repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor