Skip to main content
skill CX Codex

dspy-react-agent-builder — Claude Code skill: build ReAct agents

This skill guides you through building DSPy ReAct agents that call tools to handle multi-step tasks. Use it for workflows involving retrieval, calculations, or answers based on external data.

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

What dspy-react-agent-builder does

The skill shows how to define a task signature and provide Python functions as tools. It builds the agent with dspy.ReAct; function docstrings describe what each tool can do. The examples add error handling and logging, and use max_iters to cap the agent’s reasoning steps.

GEPA can optimize an agent against a training set and feedback metric. Tool calls run sequentially, not in parallel. The guidance recommends 3–7 tools, since larger sets can confuse the agent, and notes that language models differ in their support for tool calling. Examples use DSPy, dspy.PythonInterpreter, and dspy.ColBERTv2.

What it helps with

  • build a ReAct agent that searches documents
  • add calculation tools to a multi-step workflow
  • handle failures during tool calls
  • optimize an agent with GEPA and a training set

Example prompts for the agent

  • Build a DSPy ReAct agent that searches documents and answers a question.
  • Add a calculation tool and error handling to my agent.
  • Set up GEPA to optimize this ReAct agent using a training set and feedback metric.

How to install dspy-react-agent-builder

1Skills CLI (Vercel)

npx skills add OmidZamani/dspy-skills --skill dspy-react-agent-builder -a claude-code

2Manually: put the files in place

~/.claude/skills/dspy-react-agent-builder/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/dspy-react-agent-builder/

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

Questions about dspy-react-agent-builder

How do I install dspy-react-agent-builder in Claude Code?

Run npx skills add OmidZamani/dspy-skills --skill dspy-react-agent-builder -a claude-code. The skill file is at ~/.claude/skills/dspy-react-agent-builder/SKILL.md.

What does dspy-react-agent-builder do?

It guides you in setting up a dspy.ReAct agent that uses supplied tools for multi-step tasks. It also covers error handling and GEPA optimization.

How many tools should a ReAct agent use?

The skill recommends 3–7 tools; a larger set can confuse the agent. Tool calls run sequentially rather than in parallel.

Source text

SKILL.md · MIT
---
name: dspy-react-agent-builder
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["agent", "reasoning"]
requires-extras: []
description: Use for ReAct agents, tool-calling agents, dspy.ReAct, multi-step reasoning and acting, and GEPA agent optimization.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep
---

# DSPy ReAct Agent Builder

## Goal

Build production-quality ReAct agents that use tools to solve complex multi-step tasks with reasoning, acting, and error handling.

## When to Use

- Multi-step tasks requiring tool use
- Search + reasoning workflows
- Complex question answering with external data
- Tasks needing calculation, retrieval, or API calls

## Related Skills

- Optimize agents: [dspy-gepa-reflective](../dspy-gepa-reflective/SKILL.md)
- Connect MCP tools: [dspy-mcp-tool-integration](../dspy-mcp-tool-integration/SKILL.md)
- Configure native tool calling: [dspy-adapters-multimodal](../dspy-adapters-multimodal/SKILL.md)
- Define signatures: [dspy-signature-designer](../dspy-signature-designer/SKILL.md)
- Evaluate performance: [dspy-evaluation-suite](../dspy-evaluation-suite/SKILL.md)

## Inputs

| Input | Type | Description |
|-------|------|-------------|
| `signature` | `str` | Task signature (e.g., "question -> answer") |
| `tools` | `list[callable]` | Available tools/functions |
| `max_iters` | `int` | Max reasoning steps (default: 20) |

## Outputs

| Output | Type | Description |
|--------|------|-------------|
| `agent` | `dspy.ReAct` | Configured ReAct agent |

## Workflow

### Phase 1: Define Tools

Tools are Python functions with clear docstrings. The agent uses docstrings to understand tool capabilities:

```python
import dspy

def search(query: str) -> list[str]:
    """Search knowledge base for relevant information.

    Args:
        query: Search query string

    Returns:
        List of relevant text passages
    """
    retriever = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
    results = retriever(query, k=3)
    return [r['text'] for r in results]

def calculate(expression: str) -> float:
    """Safely evaluate mathematical expressions.

    Args:
        expression: Math expression (e.g., "2 + 2", "sqrt(16)")

    Returns:
        Numerical result
    """
    try:
        with dspy.PythonInterpreter() as interpreter:
            return interpreter.execute(expression)
    except Exception as e:
        return f"Error: {e}"
```

### Phase 2: Create ReAct Agent

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

# Create agent
agent = dspy.ReAct(
    signature="question -> answer",
    tools=[search, calculate],
    max_iters=5
)

# Use agent
result = agent(question="What is the population of Paris plus 1000?")
print(result.answer)
```

### Phase 3: Production Agent with Error Handling

```python
import dspy
import logging

logger = logging.getLogger(__name__)

class ResearchAgent(dspy.Module):
    """Production agent with error handling and logging."""

    def __init__(self, max_iters: int = 5):
        self.max_iters = max_iters
        self.agent = dspy.ReAct(
            signature="question -> answer",
            tools=[self.search, self.calculate, self.summarize],
            max_iters=max_iters
        )

    def search(self, query: str) -> list[str]:
        """Search for relevant documents."""
        try:
            retriever = dspy.ColBERTv2(
                url='http://20.102.90.50:2017/wiki17_abstracts'
            )
            results = retriever(query, k=5)
            return [r['text'] for r in results]
        except Exception as e:
            logger.error(f"Search failed: {e}")
            return [f"Search unavailable: {e}"]

    def calculate(self, expression: str) -> str:
        """Evaluate mathematical expressions safely."""
        try:
            with dspy.PythonInterpreter() as interpreter:
                return str(interpreter.execute(expression))
        except Exception as e:
            logger.error(f"Calculation failed: {e}")
            return f"Error: {e}"

    def summarize(self, text: str) -> str:
        """Summarize long text into key points."""
        try:
            summarizer = dspy.Predict("text -> summary: str")
            return summarizer(text=text[:1000]).summary
        except Exception as e:
            logger.error(f"Summarization failed: {e}")
            return "Summarization unavailable"

    def forward(self, question: str) -> dspy.Prediction:
        """Execute agent with error handling."""
        try:
            return self.agent(question=question)
        except Exception as e:
            logger.error(f"Agent failed: {e}")
            return dspy.Prediction(answer=f"Error: {e}")

# Usage
agent = ResearchAgent(max_iters=6)
response = agent(question="What is the capital of France and its population?")
print(response.answer)
```

### Phase 4: Optimize with GEPA

ReAct agents benefit from reflective optimization:

```python
from dspy.evaluate import Evaluate

def feedback_metric(example, pred, trace=None, pred_name=None, pred_trace=None):
    """Provide textual feedback for GEPA."""
    is_correct = example.answer.lower() in pred.answer.lower()
    score = 1.0 if is_correct else 0.0
    feedback = "Correct." if is_correct else f"Expected '{example.answer}'. Check tool selection."
    return dspy.Prediction(score=score, feedback=feedback)

# Optimize agent
optimizer = dspy.GEPA(
    metric=feedback_metric,
    reflection_lm=dspy.LM("openai/gpt-4o"),
    auto="medium"
)

compiled = optimizer.compile(agent, trainset=trainset)
compiled.save("research_agent_optimized.json", save_program=False)
```

## Best Practices

1. **Clear tool docstrings** - Agent relies on docstrings to understand tool capabilities
2. **Error handling** - All tools should handle failures gracefully and return error messages
3. **Tool independence** - Test each tool separately before adding to agent
4. **Logging** - Track tool calls and agent reasoning for debugging
5. **Limit iterations** - Set reasonable `max_iters` to prevent infinite loops (default is 20, but 5-10 often sufficient for simpler tasks)

## Limitations

- ReAct works best with 3-7 tools; too many tools confuse the agent
- Not all LMs support tool calling equally well (GPT-4 > GPT-3.5)
- Agent may call tools unnecessarily or miss necessary calls
- GEPA can improve production quality when a representative trainset and feedback metric are available
- Tool execution is sequential, not parallelized

## Official Documentation

- **DSPy Documentation**: https://dspy.ai/
- **DSPy GitHub**: https://github.com/stanfordnlp/dspy
- **ReAct Module**: https://dspy.ai/api/modules/ReAct/
- **Agents Tutorial**: https://dspy.ai/tutorials/agents/

© OmidZamani · MIT · OmidZamani/dspy-skills

Similar skills

SKILL.md skills catalog →

From the same set23

skill-perfection Audits and patches skill markdown files in a single pass against official documentation. Useful when preparing an agent skill for release. CX Codex +1 ★ 124repo stars dspy-simba-optimizer This skill guides SIMBA optimization for DSPy programs, using numeric scores to refine prompts and demonstrations. Use it when you can measure task quality with a metric. CX Codex +1 ★ 124repo stars dspy-signature-designer Turns a task description into a typed DSPy signature with declared inputs and outputs. Useful when model replies must fit a fixed schema. CX Codex +1 ★ 124repo stars dspy-reasoning-modules Guides configuration of DSPy 3.2.1 reasoning modules including RLM, ProgramOfThought, CodeAct, and Parallel. Useful for sandboxed code and long documents. CX Codex +1 ★ 124repo stars dspy-rag-pipeline Builds retrieval-augmented generation pipelines powered by ColBERTv2 that can be systematically optimized. Use when questions require searching across your own document corpus and grounding answers in retrieved facts. CX Codex +1 ★ 124repo stars 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

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