{"id":"431d2d62-016b-4a74-8963-bd30acf7bebd","shortId":"nBgy9C","kind":"skill","title":"dspy-react-agent-builder","tagline":"This skill should be used when the user asks to \"create a ReAct agent\", \"build an agent with tools\", \"implement tool-calling agent\", \"use dspy.ReAct\", mentions \"agent with tools\", \"reasoning and acting\", \"multi-step agent\", \"agent optimization with GEPA\", or needs to build produc","description":"# DSPy ReAct Agent Builder\n\n## Goal\n\nBuild production-quality ReAct agents that use tools to solve complex multi-step tasks with reasoning, acting, and error handling.\n\n## When to Use\n\n- Multi-step tasks requiring tool use\n- Search + reasoning workflows\n- Complex question answering with external data\n- Tasks needing calculation, retrieval, or API calls\n\n## Related Skills\n\n- Optimize agents: [dspy-gepa-reflective](../dspy-gepa-reflective/SKILL.md)\n- Define signatures: [dspy-signature-designer](../dspy-signature-designer/SKILL.md)\n- Evaluate performance: [dspy-evaluation-suite](../dspy-evaluation-suite/SKILL.md)\n\n## Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `signature` | `str` | Task signature (e.g., \"question -> answer\") |\n| `tools` | `list[callable]` | Available tools/functions |\n| `max_iters` | `int` | Max reasoning steps (default: 20) |\n\n## Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `agent` | `dspy.ReAct` | Configured ReAct agent |\n\n## Workflow\n\n### Phase 1: Define Tools\n\nTools are Python functions with clear docstrings. The agent uses docstrings to understand tool capabilities:\n\n```python\nimport dspy\n\ndef search(query: str) -> list[str]:\n    \"\"\"Search knowledge base for relevant information.\n\n    Args:\n        query: Search query string\n\n    Returns:\n        List of relevant text passages\n    \"\"\"\n    retriever = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')\n    results = retriever(query, k=3)\n    return [r['text'] for r in results]\n\ndef calculate(expression: str) -> float:\n    \"\"\"Safely evaluate mathematical expressions.\n\n    Args:\n        expression: Math expression (e.g., \"2 + 2\", \"sqrt(16)\")\n\n    Returns:\n        Numerical result\n    \"\"\"\n    try:\n        interpreter = dspy.PythonInterpreter()\n        return interpreter.execute(expression)\n    except Exception as e:\n        return f\"Error: {e}\"\n```\n\n### Phase 2: Create ReAct Agent\n\n```python\n# Configure LM\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n# Create agent\nagent = dspy.ReAct(\n    signature=\"question -> answer\",\n    tools=[search, calculate],\n    max_iters=5\n)\n\n# Use agent\nresult = agent(question=\"What is the population of Paris plus 1000?\")\nprint(result.answer)\n```\n\n### Phase 3: Production Agent with Error Handling\n\n```python\nimport dspy\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nclass ResearchAgent(dspy.Module):\n    \"\"\"Production agent with error handling and logging.\"\"\"\n\n    def __init__(self, max_iters: int = 5):\n        self.max_iters = max_iters\n        self.agent = dspy.ReAct(\n            signature=\"question -> answer\",\n            tools=[self.search, self.calculate, self.summarize],\n            max_iters=max_iters\n        )\n\n    def search(self, query: str) -> list[str]:\n        \"\"\"Search for relevant documents.\"\"\"\n        try:\n            retriever = dspy.ColBERTv2(\n                url='http://20.102.90.50:2017/wiki17_abstracts'\n            )\n            results = retriever(query, k=5)\n            return [r['text'] for r in results]\n        except Exception as e:\n            logger.error(f\"Search failed: {e}\")\n            return [f\"Search unavailable: {e}\"]\n\n    def calculate(self, expression: str) -> str:\n        \"\"\"Evaluate mathematical expressions safely.\"\"\"\n        try:\n            interpreter = dspy.PythonInterpreter()\n            result = interpreter.execute(expression)\n            return str(result)\n        except Exception as e:\n            logger.error(f\"Calculation failed: {e}\")\n            return f\"Error: {e}\"\n\n    def summarize(self, text: str) -> str:\n        \"\"\"Summarize long text into key points.\"\"\"\n        try:\n            summarizer = dspy.Predict(\"text -> summary: str\")\n            return summarizer(text=text[:1000]).summary\n        except Exception as e:\n            logger.error(f\"Summarization failed: {e}\")\n            return \"Summarization unavailable\"\n\n    def forward(self, question: str) -> dspy.Prediction:\n        \"\"\"Execute agent with error handling.\"\"\"\n        try:\n            return self.agent(question=question)\n        except Exception as e:\n            logger.error(f\"Agent failed: {e}\")\n            return dspy.Prediction(answer=f\"Error: {e}\")\n\n# Usage\nagent = ResearchAgent(max_iters=6)\nresponse = agent(question=\"What is the capital of France and its population?\")\nprint(response.answer)\n```\n\n### Phase 4: Optimize with GEPA\n\nReAct agents benefit from reflective optimization:\n\n```python\nfrom dspy.evaluate import Evaluate\n\ndef feedback_metric(example, pred, trace=None, pred_name=None, pred_trace=None):\n    \"\"\"Provide textual feedback for GEPA.\"\"\"\n    is_correct = example.answer.lower() in pred.answer.lower()\n    score = 1.0 if is_correct else 0.0\n    feedback = \"Correct.\" if is_correct else f\"Expected '{example.answer}'. Check tool selection.\"\n    return dspy.Prediction(score=score, feedback=feedback)\n\n# Optimize agent\noptimizer = dspy.GEPA(\n    metric=feedback_metric,\n    reflection_lm=dspy.LM(\"openai/gpt-4o\"),\n    auto=\"medium\",\n    enable_tool_optimization=True  # Also optimize tool docstrings\n)\n\ncompiled = optimizer.compile(agent, trainset=trainset)\ncompiled.save(\"research_agent_optimized.json\", save_program=False)\n```\n\n## Best Practices\n\n1. **Clear tool docstrings** - Agent relies on docstrings to understand tool capabilities\n2. **Error handling** - All tools should handle failures gracefully and return error messages\n3. **Tool independence** - Test each tool separately before adding to agent\n4. **Logging** - Track tool calls and agent reasoning for debugging\n5. **Limit iterations** - Set reasonable `max_iters` to prevent infinite loops (default is 20, but 5-10 often sufficient for simpler tasks)\n\n## Limitations\n\n- ReAct works best with 3-7 tools; too many tools confuse the agent\n- Not all LMs support tool calling equally well (GPT-4 > GPT-3.5)\n- Agent may call tools unnecessarily or miss necessary calls\n- Requires GEPA optimization for production quality\n- Tool execution is sequential, not parallelized\n\n## Official Documentation\n\n- **DSPy Documentation**: https://dspy.ai/\n- **DSPy GitHub**: https://github.com/stanfordnlp/dspy\n- **ReAct Module**: https://dspy.ai/api/modules/ReAct/\n- **Agents Tutorial**: https://dspy.ai/tutorials/agents/","tags":["dspy","react","agent","builder","skills","omidzamani","agent-skills","claude-code","claude-skills","llm","prompt-optimization","rag"],"capabilities":["skill","source-omidzamani","skill-dspy-react-agent-builder","topic-agent-skills","topic-claude-code","topic-claude-skills","topic-dspy","topic-llm","topic-prompt-optimization","topic-rag"],"categories":["dspy-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/OmidZamani/dspy-skills/dspy-react-agent-builder","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add OmidZamani/dspy-skills","source_repo":"https://github.com/OmidZamani/dspy-skills","install_from":"skills.sh"}},"qualityScore":"0.487","qualityRationale":"deterministic score 0.49 from registry signals: · indexed on github topic:agent-skills · 74 github stars · SKILL.md body (6,249 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-05-02T06:55:44.791Z","embedding":null,"createdAt":"2026-04-18T22:14:17.289Z","updatedAt":"2026-05-02T06:55:44.791Z","lastSeenAt":"2026-05-02T06:55:44.791Z","tsv":"'-10':669 '-3.5':700 '-4':698 '-7':681 '/api/modules/react/':736 '/dspy-evaluation-suite/skill.md':127 '/dspy-gepa-reflective/skill.md':113 '/dspy-signature-designer/skill.md':120 '/stanfordnlp/dspy':731 '/tutorials/agents/':741 '0.0':555 '1':163,607 '1.0':550 '1000':296,445 '16':241 '2':238,239,260,619 '20':151,666 '20.102.90.50':210,363 '2017/wiki17_abstracts':211,364 '3':216,300,632,680 '4':511,643 '5':283,330,369,653,668 '6':495 'act':38,75 'ad':640 'agent':4,19,22,29,33,42,43,54,62,108,156,160,174,263,272,273,285,287,302,318,466,481,491,497,516,575,597,611,642,649,688,701,737 'also':591 'answer':94,138,277,339,486 'api':103 'arg':196,233 'ask':14 'auto':585 'avail':142 'base':192 'benefit':517 'best':605,678 'build':20,50,57 'builder':5,55 'calcul':100,225,280,392,416 'call':28,104,647,694,703,709 'callabl':141 'capabl':180,618 'capit':502 'check':565 'class':314 'clear':171,608 'compil':595 'compiled.save':600 'complex':68,92 'configur':158,265 'confus':686 'correct':545,553,557,560 'creat':16,261,271 'data':97 'debug':652 'def':184,224,324,348,391,423,459,526 'default':150,664 'defin':114,164 'descript':131,155 'design':119 'docstr':172,176,594,610,614 'document':358,723,725 'dspi':2,52,110,117,124,183,308,724,727 'dspy-evaluation-suit':123 'dspy-gepa-reflect':109 'dspy-react-agent-build':1 'dspy-signature-design':116 'dspy.ai':726,735,740 'dspy.ai/api/modules/react/':734 'dspy.ai/tutorials/agents/':739 'dspy.colbertv2':208,361 'dspy.configure':267 'dspy.evaluate':523 'dspy.gepa':577 'dspy.lm':269,583 'dspy.module':316 'dspy.predict':437 'dspy.prediction':464,485,569 'dspy.pythoninterpreter':247,403 'dspy.react':31,157,274,336 'e':254,258,380,385,390,413,418,422,450,455,478,483,489 'e.g':136,237 'els':554,561 'enabl':587 'equal':695 'error':77,257,304,320,421,468,488,620,630 'evalu':121,125,230,397,525 'exampl':529 'example.answer':564 'example.answer.lower':546 'except':251,252,377,378,410,411,447,448,475,476 'execut':465,717 'expect':563 'express':226,232,234,236,250,394,399,406 'extern':96 'f':256,382,387,415,420,452,480,487,562 'fail':384,417,454,482 'failur':626 'fals':604 'feedback':527,541,556,572,573,579 'float':228 'forward':460 'franc':504 'function':169 'gepa':46,111,514,543,711 'github':728 'github.com':730 'github.com/stanfordnlp/dspy':729 'goal':56 'gpt':697,699 'grace':627 'handl':78,305,321,469,621,625 'implement':25 'import':182,307,309,524 'independ':634 'infinit':662 'inform':195 'init':325 'input':128,129 'int':146,329 'interpret':246,402 'interpreter.execute':249,405 'iter':145,282,328,332,334,345,347,494,655,659 'k':215,368 'key':433 'knowledg':191 'limit':654,675 'list':140,188,202,353 'lm':266,268,582 'lms':691 'log':310,323,644 'logger':311 'logger.error':381,414,451,479 'logging.getlogger':312 'long':430 'loop':663 'mani':684 'math':235 'mathemat':231,398 'max':144,147,281,327,333,344,346,493,658 'may':702 'medium':586 'mention':32 'messag':631 'metric':528,578,580 'miss':707 'modul':733 'multi':40,70,83 'multi-step':39,69,82 'name':313,534 'necessari':708 'need':48,99 'none':532,535,538 'numer':243 'offici':722 'often':670 'openai/gpt-4o':584 'openai/gpt-4o-mini':270 'optim':44,107,512,520,574,576,589,592,712 'optimizer.compile':596 'output':152,153 'parallel':721 'pari':294 'passag':206 'perform':122 'phase':162,259,299,510 'plus':295 'point':434 'popul':292,507 'practic':606 'pred':530,533,536 'pred.answer.lower':548 'prevent':661 'print':297,508 'produc':51 'product':59,301,317,714 'production-qu':58 'program':603 'provid':539 'python':168,181,264,306,521 'qualiti':60,715 'queri':186,197,199,214,351,367 'question':93,137,276,288,338,462,473,474,498 'r':218,221,371,374 'react':3,18,53,61,159,262,515,676,732 'reason':36,74,90,148,650,657 'reflect':112,519,581 'relat':105 'relev':194,204,357 'reli':612 'requir':86,710 'research_agent_optimized.json':601 'researchag':315,492 'respons':496 'response.answer':509 'result':212,223,244,286,365,376,404,409 'result.answer':298 'retriev':101,207,213,360,366 'return':201,217,242,248,255,370,386,407,419,441,456,471,484,568,629 'safe':229,400 'save':602 'score':549,570,571 'search':89,185,190,198,279,349,355,383,388 'select':567 'self':326,350,393,425,461 'self.agent':335,472 'self.calculate':342 'self.max':331 'self.search':341 'self.summarize':343 'separ':638 'sequenti':719 'set':656 'signatur':115,118,132,135,275,337 'simpler':673 'skill':7,106 'skill-dspy-react-agent-builder' 'solv':67 'source-omidzamani' 'sqrt':240 'step':41,71,84,149 'str':133,187,189,227,352,354,395,396,408,427,428,440,463 'string':200 'suffici':671 'suit':126 'summar':424,429,436,442,453,457 'summari':439,446 'support':692 'task':72,85,98,134,674 'test':635 'text':205,219,372,426,431,438,443,444 'textual':540 'tool':24,27,35,65,87,139,165,166,179,278,340,566,588,593,609,617,623,633,637,646,682,685,693,704,716 'tool-cal':26 'tools/functions':143 'topic-agent-skills' 'topic-claude-code' 'topic-claude-skills' 'topic-dspy' 'topic-llm' 'topic-prompt-optimization' 'topic-rag' 'trace':531,537 'track':645 'trainset':598,599 'tri':245,359,401,435,470 'true':590 'tutori':738 'type':130,154 'unavail':389,458 'understand':178,616 'unnecessarili':705 'url':209,362 'usag':490 'use':10,30,64,81,88,175,284 'user':13 'well':696 'work':677 'workflow':91,161","prices":[{"id":"a1414b4b-4ee6-4647-8b2e-4f0db369a9cd","listingId":"431d2d62-016b-4a74-8963-bd30acf7bebd","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"OmidZamani","category":"dspy-skills","install_from":"skills.sh"},"createdAt":"2026-04-18T22:14:17.289Z"}],"sources":[{"listingId":"431d2d62-016b-4a74-8963-bd30acf7bebd","source":"github","sourceId":"OmidZamani/dspy-skills/dspy-react-agent-builder","sourceUrl":"https://github.com/OmidZamani/dspy-skills/tree/master/skills/dspy-react-agent-builder","isPrimary":false,"firstSeenAt":"2026-04-18T22:14:17.289Z","lastSeenAt":"2026-05-02T06:55:44.791Z"}],"details":{"listingId":"431d2d62-016b-4a74-8963-bd30acf7bebd","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"OmidZamani","slug":"dspy-react-agent-builder","github":{"repo":"OmidZamani/dspy-skills","stars":74,"topics":["agent-skills","claude-code","claude-skills","dspy","llm","prompt-optimization","rag"],"license":"mit","html_url":"https://github.com/OmidZamani/dspy-skills","pushed_at":"2026-02-21T12:49:43Z","description":"Collection of Claude Skills for DSPy framework - program language models, optimize prompts, and build RAG pipelines systematically","skill_md_sha":"b709ed383e03e6efb64c0b2cb645b7f3229483bd","skill_md_path":"skills/dspy-react-agent-builder/SKILL.md","default_branch":"master","skill_tree_url":"https://github.com/OmidZamani/dspy-skills/tree/master/skills/dspy-react-agent-builder"},"layout":"multi","source":"github","category":"dspy-skills","frontmatter":{"name":"dspy-react-agent-builder","description":"This skill should be used when the user asks to \"create a ReAct agent\", \"build an agent with tools\", \"implement tool-calling agent\", \"use dspy.ReAct\", mentions \"agent with tools\", \"reasoning and acting\", \"multi-step agent\", \"agent optimization with GEPA\", or needs to build production agents that use tools to solve complex tasks."},"skills_sh_url":"https://skills.sh/OmidZamani/dspy-skills/dspy-react-agent-builder"},"updatedAt":"2026-05-02T06:55:44.791Z"}}