Skip to main content
skill CX Codex

dspy-gepa-reflective — Claude Code skill: GEPA optimization

Guides GEPA optimization of DSPy agents using written feedback and execution traces. Useful for ReAct systems with tools and multi-step workflows.

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

What dspy-gepa-reflective does

This skill walks through applying GEPA to agents and complex DSPy programs. The optimizer uses written feedback about failures and examines execution traces to revise instructions. Its output is a compiled dspy.Module.

The examples cover a feedback metric, a ReAct agent, and calling optimizer.compile with a training set. A GEPA metric takes five arguments and returns a dspy.Prediction containing a score and feedback. Reflection also uses a strong language model.

The skill targets DSPy 3.2.1. GEPA needs a custom feedback metric, and reflection with a strong model can be expensive. The material describes it as less battle-tested than MIPROv2, so teams relying on a more established optimizer should weigh that trade-off.

What it helps with

  • optimize instructions for a tool-using agent
  • give GEPA written explanations of failures
  • inspect traces from multi-step runs
  • compare an agent before and after compilation

Example prompts for the agent

  • Help me optimize my DSPy ReAct agent with GEPA.
  • Write a GEPA metric that returns a score and explains mistakes.
  • Show how to compile an agent from a training set using a strong reflection model.

How to install dspy-gepa-reflective

1Skills CLI (Vercel)

npx skills add OmidZamani/dspy-skills --skill dspy-gepa-reflective -a claude-code

2Manually: put the files in place

~/.claude/skills/dspy-gepa-reflective/SKILL.md

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

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

Questions about dspy-gepa-reflective

How do I install dspy-gepa-reflective in Claude Code?

Run npx skills add OmidZamani/dspy-skills --skill dspy-gepa-reflective -a claude-code. The skill file is placed at ~/.claude/skills/dspy-gepa-reflective/SKILL.md.

What does dspy-gepa-reflective do?

It guides GEPA optimization for DSPy agents and complex programs. The approach uses textual feedback and execution traces to revise instructions.

What does a GEPA metric need to return?

It takes five arguments and returns a dspy.Prediction with a score and textual feedback. A score by itself does not meet the described metric contract.

Source text

SKILL.md · MIT
---
name: dspy-gepa-reflective
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["optimizer", "agent"]
requires-extras: []
description: Use for GEPA reflective optimization, ReAct agent optimization, feedback metrics, LLM reflection, and execution trajectories.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep
---

# DSPy GEPA Optimizer

## Goal

Optimize complex agentic systems using LLM reflection on full execution traces with Pareto-based evolutionary search.

## When to Use

- **Agentic systems** with tool use
- When you have **rich textual feedback** on failures
- Complex multi-step workflows
- Instruction-only optimization needed

## Related Skills

- For non-agentic programs: [dspy-miprov2-optimizer](../dspy-miprov2-optimizer/SKILL.md), [dspy-bootstrap-fewshot](../dspy-bootstrap-fewshot/SKILL.md)
- Measure improvements: [dspy-evaluation-suite](../dspy-evaluation-suite/SKILL.md)

## Inputs

| Input | Type | Description |
|-------|------|-------------|
| `program` | `dspy.Module` | Agent or complex program |
| `trainset` | `list[dspy.Example]` | Training examples |
| `metric` | `callable` | Accepts five arguments and returns `dspy.Prediction(score=..., feedback=...)` |
| `reflection_lm` | `dspy.LM` | Strong LM for reflection (GPT-4) |
| `auto` | `str` | "light", "medium", "heavy" |

## Outputs

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

## Workflow

### Phase 1: Define Feedback Metric

GEPA requires metrics that return *textual feedback*:

```python
def gepa_metric(example, pred, trace=None, pred_name=None, pred_trace=None):
    """Return score and actionable feedback for GEPA reflection."""
    is_correct = example.answer.lower() in pred.answer.lower()
    
    if is_correct:
        feedback = "Correct. The answer accurately addresses the question."
    else:
        feedback = f"Incorrect. Expected '{example.answer}' but got '{pred.answer}'. The model may have misunderstood the question or retrieved irrelevant information."
    
    return dspy.Prediction(score=float(is_correct), feedback=feedback)
```

### Phase 2: Setup Agent

```python
import dspy

def search(query: str) -> list[str]:
    """Search knowledge base for relevant information."""
    rm = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
    results = rm(query, k=3)
    return results if isinstance(results, list) else [results]

def calculate(expression: str) -> float:
    """Safely evaluate mathematical expressions."""
    with dspy.PythonInterpreter() as interp:
        return interp(expression)

agent = dspy.ReAct("question -> answer", tools=[search, calculate])
```

### Phase 3: Optimize with GEPA

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

optimizer = dspy.GEPA(
    metric=gepa_metric,
    reflection_lm=dspy.LM("openai/gpt-4o"),  # Strong model for reflection
    auto="medium"
)

compiled_agent = optimizer.compile(agent, trainset=trainset)
```

## Production Example

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

logger = logging.getLogger(__name__)

class ResearchAgent(dspy.Module):
    def __init__(self):
        self.react = dspy.ReAct(
            "question -> answer",
            tools=[self.search, self.summarize]
        )
    
    def search(self, query: str) -> list[str]:
        """Search for relevant documents."""
        rm = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
        results = rm(query, k=5)
        return results if isinstance(results, list) else [results]
    
    def summarize(self, text: str) -> str:
        """Summarize long text into key points."""
        summarizer = dspy.Predict("text -> summary")
        return summarizer(text=text).summary
    
    def forward(self, question):
        return self.react(question=question)

def detailed_feedback_metric(example, pred, trace=None, pred_name=None, pred_trace=None):
    """Rich feedback for GEPA reflection."""
    expected = example.answer.lower().strip()
    actual = pred.answer.lower().strip() if pred.answer else ""
    
    # Exact match
    if expected == actual:
        return dspy.Prediction(score=1.0, feedback="Perfect match. Answer is correct and concise.")
    
    # Partial match
    if expected in actual or actual in expected:
        return dspy.Prediction(score=0.7, feedback=f"Partial match. Expected '{example.answer}', got '{pred.answer}'. Answer contains correct info but may be verbose or incomplete.")
    
    # Check for key terms
    expected_terms = set(expected.split())
    actual_terms = set(actual.split())
    overlap = len(expected_terms & actual_terms) / max(len(expected_terms), 1)
    
    if overlap > 0.5:
        return dspy.Prediction(score=0.5, feedback=f"Some overlap. Expected '{example.answer}', got '{pred.answer}'. Key terms present but answer structure differs.")
    
    return dspy.Prediction(score=0.0, feedback=f"Incorrect. Expected '{example.answer}', got '{pred.answer}'. The agent may need better search queries or reasoning.")

def optimize_research_agent(trainset, devset):
    """Full GEPA optimization pipeline."""
    
    dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
    
    agent = ResearchAgent()
    
    # Convert metric for evaluation (just score)
    def eval_metric(example, pred, trace=None):
        return detailed_feedback_metric(example, pred, trace).score
    
    evaluator = Evaluate(devset=devset, num_threads=8, metric=eval_metric)
    baseline = evaluator(agent)
    logger.info(f"Baseline: {baseline:.2%}")
    
    # GEPA optimization
    optimizer = dspy.GEPA(
        metric=detailed_feedback_metric,
        reflection_lm=dspy.LM("openai/gpt-4o"),
        auto="medium"
    )
    
    compiled = optimizer.compile(agent, trainset=trainset)
    optimized = evaluator(compiled)
    logger.info(f"Optimized: {optimized:.2%}")
    
    compiled.save("research_agent_gepa.json")
    return compiled
```

## Metric Contract

GEPA metrics must accept `(gold, pred, trace, pred_name, pred_trace)`. Return `dspy.Prediction(score=..., feedback=...)` when textual feedback is available. Do not pass `enable_tool_optimization`; it is not a DSPy 3.2.1 `GEPA` constructor argument.

## Best Practices

1. **Rich feedback** - More detailed feedback = better reflection
2. **Strong reflection LM** - Use GPT-4 or Claude for reflection
3. **Agentic focus** - Best for ReAct and multi-tool systems
4. **Trace analysis** - GEPA analyzes full execution trajectories

## Limitations

- Requires custom feedback metrics (not just scores)
- Expensive: uses strong LM for reflection
- Newer optimizer, less battle-tested than MIPROv2
- Best for instruction optimization, less for demos

## Official Documentation

- **DSPy Documentation**: [https://dspy.ai/](https://dspy.ai/)
- **DSPy GitHub**: [https://github.com/stanfordnlp/dspy](https://github.com/stanfordnlp/dspy)
- **GEPA Optimizer**: [https://dspy.ai/api/optimizers/GEPA/](https://dspy.ai/api/optimizers/GEPA/)
- **Agents Guide**: [https://dspy.ai/tutorials/agents/](https://dspy.ai/tutorials/agents/)

© OmidZamani · MIT · OmidZamani/dspy-skills

Similar skills

SKILL.md skills catalog →

From the same set23

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-miprov2-optimizer 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. 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-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

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