Skip to main content
skill CX Codex

dspy-evaluation-suite — Claude Code skill: what it does

Tests and benchmarks DSPy modules against evaluation datasets using multi-threaded execution and custom scoring functions.

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

What dspy-evaluation-suite does

This skill automates testing for DSPy pipelines. The Evaluate module runs validation examples across parallel worker threads. Preconfigured patterns cover built-in metrics such as answer_exact_match and the model-based SemanticF1, alongside custom multi-factor scoring functions.

An included EvaluationSuite helper ranks competing module variants and exports evaluation summaries to JSON files. It also supports feedback metrics structured for the GEPA optimizer. The skill targets DSPy version 3.2.1. Tool access is limited to Read, Write, Glob, and Grep.

What it helps with

  • measure DSPy module performance before and after optimization
  • compare multiple program candidates on validation examples
  • run parallel batch evaluations using dspy.evaluate.Evaluate
  • export detailed evaluation metrics to a JSON summary report

Example prompts for the agent

  • Run an evaluation on my DSPy pipeline using devset and answer_exact_match with 8 threads.
  • Create a custom multi-factor metric checking correctness, length, and reasoning presence.
  • Compare two DSPy module variants using EvaluationSuite and save the output to report.json.

How to install dspy-evaluation-suite

1Skills CLI (Vercel)

npx skills add OmidZamani/dspy-skills --skill dspy-evaluation-suite -a claude-code

2Manually: put the files in place

~/.claude/skills/dspy-evaluation-suite/SKILL.md

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

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

Questions about dspy-evaluation-suite

How do I install dspy-evaluation-suite in Claude Code?

Run npx skills add OmidZamani/dspy-skills --skill dspy-evaluation-suite -a claude-code. The skill file will be placed in ~/.claude/skills/dspy-evaluation-suite/SKILL.md.

What does dspy-evaluation-suite do?

It sets up parallel evaluation harnesses for DSPy programs, tracks accuracy across test sets, and compares performance between program iterations.

Which DSPy version does this skill target?

The skill configuration declares compatibility with DSPy 3.2.1.

Source text

SKILL.md · MIT
---
name: dspy-evaluation-suite
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["evaluation"]
requires-extras: []
description: Use for evaluating DSPy programs with Evaluate, answer_exact_match, SemanticF1, custom metrics, baselines, and program comparisons.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep
---

# DSPy Evaluation Suite

## Goal

Systematically evaluate DSPy programs using built-in and custom metrics with parallel execution.

## When to Use

- Measuring program performance before/after optimization
- Comparing different program variants
- Establishing baselines
- Validating production readiness

## Related Skills

- Use with any optimizer: [dspy-bootstrap-fewshot](../dspy-bootstrap-fewshot/SKILL.md), [dspy-miprov2-optimizer](../dspy-miprov2-optimizer/SKILL.md), [dspy-gepa-reflective](../dspy-gepa-reflective/SKILL.md)
- Evaluate RAG pipelines: [dspy-rag-pipeline](../dspy-rag-pipeline/SKILL.md)

## Inputs

| Input | Type | Description |
|-------|------|-------------|
| `program` | `dspy.Module` | Program to evaluate |
| `devset` | `list[dspy.Example]` | Evaluation examples |
| `metric` | `callable` | Scoring function |
| `num_threads` | `int` | Parallel threads |

## Outputs

| Output | Type | Description |
|--------|------|-------------|
| `score` | `float` | Average metric score |
| `results` | `list` | Per-example results |

## Workflow

### Phase 1: Setup Evaluator

```python
from dspy.evaluate import Evaluate

evaluator = Evaluate(
    devset=devset,
    metric=my_metric,
    num_threads=8,
    display_progress=True
)
```

### Phase 2: Run Evaluation

```python
result = evaluator(my_program)
print(f"Score: {result.score:.2f}%")
# Access individual results: (example, prediction, score) tuples
for example, pred, score in result.results[:3]:
    print(f"Example: {example.question[:50]}... Score: {score}")
```

## Built-in Metrics

### answer_exact_match

```python
import dspy

# Normalized, case-insensitive comparison
metric = dspy.evaluate.answer_exact_match
```

### SemanticF1

LLM-based semantic evaluation:

```python
from dspy.evaluate import SemanticF1

semantic = SemanticF1()
score = semantic(example, prediction)
```

## Custom Metrics

### Basic Metric

```python
def exact_match(example, pred, trace=None):
    """Returns bool, int, or float."""
    return example.answer.lower().strip() == pred.answer.lower().strip()
```

### Multi-Factor Metric

```python
def quality_metric(example, pred, trace=None):
    """Score based on multiple factors."""
    score = 0.0
    
    # Correctness (50%)
    if example.answer.lower() in pred.answer.lower():
        score += 0.5
    
    # Conciseness (25%)
    if len(pred.answer.split()) <= 20:
        score += 0.25
    
    # Has reasoning (25%)
    if hasattr(pred, 'reasoning') and pred.reasoning:
        score += 0.25
    
    return score
```

### GEPA-Compatible Metric

```python
def feedback_metric(example, pred, trace=None, pred_name=None, pred_trace=None):
    """Return a GEPA-compatible score and textual feedback."""
    correct = example.answer.lower() in pred.answer.lower()
    
    if correct:
        return dspy.Prediction(score=1.0, feedback="Correct answer provided.")
    else:
        return dspy.Prediction(
            score=0.0,
            feedback=f"Expected '{example.answer}', got '{pred.answer}'"
        )
```

## Production Example

```python
import dspy
from dspy.evaluate import Evaluate, SemanticF1
import json
import logging
from typing import Optional
from dataclasses import dataclass

logger = logging.getLogger(__name__)

@dataclass
class EvaluationResult:
    score: float
    num_examples: int
    correct: int
    incorrect: int
    errors: int

def comprehensive_metric(example, pred, trace=None) -> float:
    """Multi-dimensional evaluation metric."""
    scores = []
    
    # 1. Correctness
    if hasattr(example, 'answer') and hasattr(pred, 'answer'):
        correct = example.answer.lower().strip() in pred.answer.lower().strip()
        scores.append(1.0 if correct else 0.0)
    
    # 2. Completeness (answer not empty or error)
    if hasattr(pred, 'answer'):
        complete = len(pred.answer.strip()) > 0 and "error" not in pred.answer.lower()
        scores.append(1.0 if complete else 0.0)
    
    # 3. Reasoning quality (if available)
    if hasattr(pred, 'reasoning'):
        has_reasoning = len(str(pred.reasoning)) > 20
        scores.append(1.0 if has_reasoning else 0.5)
    
    return sum(scores) / len(scores) if scores else 0.0

class EvaluationSuite:
    def __init__(self, devset, num_threads=8):
        self.devset = devset
        self.num_threads = num_threads
    
    def evaluate(self, program, metric=None) -> EvaluationResult:
        """Run full evaluation with detailed results."""
        metric = metric or comprehensive_metric

        evaluator = Evaluate(
            devset=self.devset,
            metric=metric,
            num_threads=self.num_threads,
            display_progress=True
        )

        eval_result = evaluator(program)

        # Extract individual scores from results
        scores = [score for example, pred, score in eval_result.results]
        correct = sum(1 for s in scores if s >= 0.5)
        errors = sum(1 for s in scores if s == 0)

        return EvaluationResult(
            score=eval_result.score,
            num_examples=len(self.devset),
            correct=correct,
            incorrect=len(self.devset) - correct - errors,
            errors=errors
        )
    
    def compare(self, programs: dict, metric=None) -> dict:
        """Compare multiple programs."""
        results = {}
        
        for name, program in programs.items():
            logger.info(f"Evaluating: {name}")
            results[name] = self.evaluate(program, metric)
        
        # Rank by score
        ranked = sorted(results.items(), key=lambda x: x[1].score, reverse=True)
        
        print("\n=== Comparison Results ===")
        for rank, (name, result) in enumerate(ranked, 1):
            print(f"{rank}. {name}: {result.score:.2%}")
        
        return results
    
    def export_report(self, program, output_path: str, metric=None):
        """Export detailed evaluation report."""
        result = self.evaluate(program, metric)
        
        report = {
            "summary": {
                "score": result.score,
                "total": result.num_examples,
                "correct": result.correct,
                "accuracy": result.correct / result.num_examples
            },
            "config": {
                "num_threads": self.num_threads,
                "num_examples": len(self.devset)
            }
        }
        
        with open(output_path, 'w') as f:
            json.dump(report, f, indent=2)
        
        logger.info(f"Report saved to {output_path}")
        return report

# Usage
suite = EvaluationSuite(devset, num_threads=8)

# Single evaluation
result = suite.evaluate(my_program)
print(f"Score: {result.score:.2%}")

# Compare variants
results = suite.compare({
    "baseline": baseline_program,
    "optimized": optimized_program,
    "finetuned": finetuned_program
})
```

## Best Practices

1. **Hold out test data** - Never optimize on evaluation set
2. **Multiple metrics** - Combine correctness, quality, efficiency
3. **Statistical significance** - Use enough examples (100+)
4. **Track over time** - Version control evaluation results

## Limitations

- Metrics are task-specific; no universal measure
- SemanticF1 requires LLM calls (cost)
- Parallel evaluation can hit rate limits
- Edge cases may not be captured

## Official Documentation

- **DSPy Documentation**: https://dspy.ai/
- **DSPy GitHub**: https://github.com/stanfordnlp/dspy
- **Evaluation API**: https://dspy.ai/api/evaluation/
- **Metrics Guide**: https://dspy.ai/learn/evaluation/metrics/

© OmidZamani · MIT · OmidZamani/dspy-skills

Similar skills

All skills for AI and ML →

From the same set23

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 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-bootstrap-fewshot 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. 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