-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact_agent.py
More file actions
192 lines (146 loc) · 5.73 KB
/
react_agent.py
File metadata and controls
192 lines (146 loc) · 5.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""Example: ReAct agent with real web search and Temporal durability.
This example demonstrates a DSPy ReAct agent that combines:
- Real web search using Tavily API
- Mathematical computation
- Durable execution with automatic retries and checkpointing
The agent answers complex questions requiring multiple tool calls, with each
tool execution becoming a Temporal activity for fault tolerance.
Usage:
# Start Temporal server first: docker-compose up -d
# Set environment variables:
# export OPENAI_API_KEY=your-key-here
# export TAVILY_API_KEY=your-key-here
# Then run: python examples/react_agent.py
"""
from __future__ import annotations
import asyncio
import os
import uuid
import dspy
from dotenv import load_dotenv
from tavily import TavilyClient
from temporalio import workflow
from temporalio.client import Client
from temporalio.worker import Worker
from dspy_temporal import DSPyPlugin, TemporalModule
from dspy_temporal.sandbox import get_default_sandbox_runner
load_dotenv()
# ============================================================================
# Tool Definitions (standard DSPy functions)
# ============================================================================
def evaluate_math(expression: str) -> str:
"""Safely evaluate a basic math expression."""
import math
allowed_names = {
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"pow": pow,
"sqrt": math.sqrt,
"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"log": math.log,
"log10": math.log10,
"pi": math.pi,
"e": math.e,
}
for char in expression:
if char not in "0123456789+-*/.() ," and not any(name in expression for name in allowed_names):
return f"Error: Invalid character '{char}' in expression"
try:
result = eval(expression, {"__builtins__": {}}, allowed_names) # noqa: S307
except Exception as exc:
print(f"Error: {exc}")
return f"Error: {exc}"
return str(result)
def search_web(query: str) -> str:
"""Search the web using Tavily API.
Args:
query: The search query.
Returns:
Formatted search results with title, content, and source URLs.
"""
api_key = os.getenv("TAVILY_API_KEY")
if not api_key:
return f"[Search failed for '{query}' - TAVILY_API_KEY not set]"
try:
client = TavilyClient(api_key)
response = client.search(query=query, max_results=3)
# Response format: {"results": [{"title": ..., "url": ..., "content": ..., "score": ...}]}
results = response.get("results", [])
if not results:
return f"No results found for '{query}'"
# Format results for the agent
passages = []
for r in results:
title = r.get("title", "")
content = r.get("content", "")
url = r.get("url", "")
passages.append(f"{title}\n{content}\nSource: {url}")
return "\n\n".join(passages)
except Exception as e:
print(f"Tavily error: {e}")
return f"[Search failed for '{query}' - {e}]"
# ============================================================================
# DSPy ReAct Agent
# ============================================================================
react_agent = dspy.ReAct(
"question -> answer",
tools=[evaluate_math, search_web],
)
# TemporalModule automatically wraps the tools as activities
# and exposes them alongside the ReAct LLM calls.
temporal_react = TemporalModule(react_agent, name="react_agent")
# ============================================================================
# Temporal Workflow
# ============================================================================
@workflow.defn
class ReActWorkflow:
"""Temporal workflow that executes the ReAct agent."""
@workflow.run
async def run(self, question: str) -> str:
result = await temporal_react.run(question=question)
return result.answer
# ============================================================================
# Main Execution
# ============================================================================
async def main() -> None:
# Optional: Enable debug logging to see detailed execution traces
# import logging
# logging.basicConfig(level=logging.DEBUG)
# logging.getLogger('dspy_temporal').setLevel(logging.DEBUG)
# Check for required API keys
if not os.environ.get("OPENAI_API_KEY"):
print("ERROR: OPENAI_API_KEY environment variable not set")
print("Please set it: export OPENAI_API_KEY=your-key-here")
return
if not os.environ.get("TAVILY_API_KEY"):
print("ERROR: TAVILY_API_KEY environment variable not set")
print("Please set it: export TAVILY_API_KEY=your-key-here")
return
dspy.configure(lm=dspy.LM("openai/gpt-5-mini"))
temporal_url = os.getenv("TEMPORAL_SERVICE_URL", "localhost:7233")
client = await Client.connect(temporal_url)
async with Worker(
client,
task_queue="react-agent-queue",
workflows=[ReActWorkflow],
plugins=[DSPyPlugin(temporal_react)],
workflow_runner=get_default_sandbox_runner(),
):
print("Worker started. Executing ReAct agent workflow...")
workflow_id = f"react-agent-{uuid.uuid4().hex[:8]}"
result = await client.execute_workflow(
ReActWorkflow.run,
args=[
"What is the current population of Ankara, and how much would it cost to buy a cup of tea for everyone in Ankara?"
],
id=workflow_id,
task_queue="react-agent-queue",
)
print(f"\nAnswer: {result}")
if __name__ == "__main__":
asyncio.run(main())