Skip to main content
skill CX Codex

dspy-miprov2-optimizer — Claude Code skill for DSPy tuning

This skill guides MIPROv2 optimization of DSPy programs, searching for instruction and few-shot demo combinations with Bayesian optimization. Use it to tune a program against training data.

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

What dspy-miprov2-optimizer does

MIPROv2 works in three stages: it generates demonstration candidates, proposes instructions, then searches combinations. The result is an optimized DSPy module. The skill covers setting up the program, metric, and dataset, then evaluating and saving the compiled result with metadata.

The guide recommends 200+ training examples and runs with 40 or more trials. Expect substantial compute use and many LLM calls. Install dspy[optuna]>=3.2.1,<3.3 before running MIPROv2. For smaller datasets, the guide points to a separate skill, dspy-bootstrap-fewshot.

What it helps with

  • tune a DSPy program’s instructions and few-shot demonstrations
  • search for instruction-demo combinations with Bayesian optimization
  • compare a baseline program with its optimized version on a dev set
  • save the compiled module and evaluation metadata

Example prompts for the agent

  • Optimize my DSPy module with MIPROv2 using the training set and exact-match metric.
  • Tune only the DSPy instructions and turn off demonstrations.
  • Compare the baseline agent with the optimized one and save the result to agent_mipro.json.

How to install dspy-miprov2-optimizer

1Skills CLI (Vercel)

npx skills add OmidZamani/dspy-skills --skill dspy-miprov2-optimizer -a claude-code

2Manually: put the files in place

~/.claude/skills/dspy-miprov2-optimizer/SKILL.md

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

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

Questions about dspy-miprov2-optimizer

How do I install dspy-miprov2-optimizer in Claude Code?

Run npx skills add OmidZamani/dspy-skills --skill dspy-miprov2-optimizer -a claude-code. The skill file is installed at ~/.claude/skills/dspy-miprov2-optimizer/SKILL.md.

What does dspy-miprov2-optimizer do?

It guides MIPROv2 optimization of DSPy programs, using Bayesian search to tune instructions and few-shot demonstrations.

What does MIPROv2 need to run?

Install dspy[optuna]>=3.2.1,<3.3 first. The guide recommends at least 200 training examples and notes that optimization makes many LLM calls.

Source text

SKILL.md · MIT
---
name: dspy-miprov2-optimizer
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["optimizer"]
requires-extras: ["dspy[optuna]"]
description: Use for MIPROv2, Bayesian optimization, instruction and demo tuning, and high-performance DSPy program optimization.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep
---

# DSPy MIPROv2 Optimizer

## Goal

Jointly optimize instructions and few-shot demonstrations using Bayesian Optimization for maximum performance.

## When to Use

- You have **200+ training examples**
- You can afford longer optimization runs (40+ trials)
- You need state-of-the-art performance
- Both instructions and demos need tuning

## Related Skills

- For limited data (10-50 examples): [dspy-bootstrap-fewshot](../dspy-bootstrap-fewshot/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` | Program to optimize |
| `trainset` | `list[dspy.Example]` | 200+ training examples |
| `metric` | `callable` | Evaluation function |
| `auto` | `str` | "light", "medium", or "heavy" |
| `num_trials` | `int` | Optimization trials (40+) |

## Outputs

| Output | Type | Description |
|--------|------|-------------|
| `compiled_program` | `dspy.Module` | Fully optimized program |

## Workflow

Install the optional Optuna dependency before using MIPROv2:

```bash
pip install -U "dspy[optuna]>=3.2.1,<3.3"
```

### Three-Stage Process

1. **Bootstrap** - Generate candidate demonstrations
2. **Propose** - Create grounded instruction candidates
3. **Search** - Bayesian optimization over combinations

### Phase 1: Setup

```python
import dspy
from dspy.teleprompt import MIPROv2

lm = dspy.LM('openai/gpt-4o-mini')
dspy.configure(lm=lm)
```

### Phase 2: Define Program

```python
class RAGAgent(dspy.Module):
    def __init__(self):
        self.retrieve = dspy.Retrieve(k=3)
        self.generate = dspy.ChainOfThought("context, question -> answer")
    
    def forward(self, question):
        context = self.retrieve(question).passages
        return self.generate(context=context, question=question)
```

### Phase 3: Optimize

```python
from dspy.teleprompt import MIPROv2

optimizer = MIPROv2(
    metric=dspy.evaluate.answer_exact_match,
    auto="medium",  # Balanced optimization
    num_threads=24
)

compiled = optimizer.compile(RAGAgent(), trainset=trainset)
```

## Auto Presets

| Preset | Trials | Use Case |
|--------|--------|----------|
| `"light"` | ~10 | Quick iteration |
| `"medium"` | ~40 | Production optimization |
| `"heavy"` | ~100+ | Maximum performance |

## Production Example

```python
import dspy
from dspy.teleprompt import MIPROv2
from dspy.evaluate import Evaluate
import json
import logging

logger = logging.getLogger(__name__)

class ReActAgent(dspy.Module):
    def __init__(self, tools):
        self.react = dspy.ReAct("question -> answer", tools=tools)
    
    def forward(self, question):
        return self.react(question=question)

def search_tool(query: str) -> list[str]:
    """Search knowledge base."""
    results = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')(query, k=3)
    return [r['long_text'] for r in results]

def optimize_agent(trainset, devset):
    """Full MIPROv2 optimization pipeline."""
    
    agent = ReActAgent(tools=[search_tool])
    
    # Baseline evaluation
    evaluator = Evaluate(
        devset=devset,
        metric=dspy.evaluate.answer_exact_match,
        num_threads=8
    )
    baseline = evaluator(agent)
    logger.info(f"Baseline: {baseline:.2%}")
    
    # MIPROv2 optimization
    optimizer = MIPROv2(
        metric=dspy.evaluate.answer_exact_match,
        auto="medium",
        num_threads=24,
        # Custom settings
        num_candidates=15,
        max_bootstrapped_demos=4,
        max_labeled_demos=8
    )
    
    compiled = optimizer.compile(agent, trainset=trainset)
    optimized = evaluator(compiled)
    logger.info(f"Optimized: {optimized:.2%}")
    
    # Save with metadata
    compiled.save("agent_mipro.json")
    
    metadata = {
        "baseline_score": baseline,
        "optimized_score": optimized,
        "improvement": optimized - baseline,
        "num_train": len(trainset),
        "num_dev": len(devset)
    }
    
    with open("optimization_metadata.json", "w") as f:
        json.dump(metadata, f, indent=2)
    
    return compiled, metadata
```

## Instruction-Only Mode

```python
from dspy.teleprompt import MIPROv2

# Disable demos for pure instruction optimization
optimizer = MIPROv2(
    metric=metric,
    auto="medium",
    max_bootstrapped_demos=0,
    max_labeled_demos=0
)
```

## Best Practices

1. **Data quantity matters** - 200+ examples for best results
2. **Use auto presets** - Start with "medium", adjust based on results
3. **Parallel threads** - Use `num_threads=24` or higher if available
4. **Monitor costs** - Track API usage during optimization
5. **Save intermediate** - Bayesian search saves progress

## Limitations

- High computational cost (many LLM calls)
- Requires substantial training data
- Optimization time: hours for "heavy" preset
- Memory intensive for large candidate sets

## Official Documentation

- **DSPy Documentation**: https://dspy.ai/
- **DSPy GitHub**: https://github.com/stanfordnlp/dspy
- **MIPROv2 API**: https://dspy.ai/api/optimizers/MIPROv2/
- **Optimizers 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-production-deployment Prepares DSPy 3.2.1 pipelines for production by configuring safe caching, state-only JSON persistence, async calls, and output streaming. CX Codex +1 ★ 124repo stars dspy-output-refinement-constraints This skill shows how to validate DSPy outputs, refine them with dspy.Refine, and choose among candidates with dspy.BestOfN. Use it when generated results must meet format or content rules. CX Codex +1 ★ 124repo stars dspy-optimizer-selection Helps you pick a DSPy optimizer that fits your data and budget, from LabeledFewShot up to GEPA and BetterTogether. Useful when you don't know where to start compiling. CX Codex +1 ★ 124repo stars dspy-optimize-anything Guides AI agents through GEPA reflective evolutionary search for code, prompts, configs, and text artifacts using diagnostic feedback. CX Codex +1 ★ 124repo stars dspy-mcp-tool-integration A skill that walks through wiring an MCP server into DSPy: turning its tools into dspy.Tool and calling them from an async agent. CX Codex +1 ★ 124repo stars dspy-haystack-integration Optimizes Haystack pipeline prompts using DSPy few-shot compilers. Connects Haystack retrievers into DSPy modules for data-driven prompt tuning. CX Codex +1 ★ 124repo stars dspy-gepa-reflective Guides GEPA optimization of DSPy agents using written feedback and execution traces. Useful for ReAct systems with tools and multi-step workflows. CX Codex +1 ★ 124repo stars 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

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