-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
233 lines (188 loc) · 7.79 KB
/
Copy pathtools.py
File metadata and controls
233 lines (188 loc) · 7.79 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Tools available to the ReAct agent.
Three tools from the paper + a safe calculator:
Search[entity] — fetch the Wikipedia intro paragraph for `entity`
Lookup[keyword] — in the last Search result, find the next sentence
containing `keyword` (like browser Ctrl+F)
Calculate[expr] — safely evaluate an arithmetic expression
Finish[answer] — end the episode and return `answer`
All network calls use the free MediaWiki API (no key required).
"""
from __future__ import annotations
import ast
import math
import operator
import re
import socket
import urllib.error
import urllib.parse
import urllib.request
import json
# ---------------------------------------------------------------------------
# Wikipedia search
# ---------------------------------------------------------------------------
_WIKI_API = "https://en.wikipedia.org/w/api.php"
_SENTENCE_RE = re.compile(r"(?<=[.!?])\s+")
_WIKI_TIMEOUT = int(__import__("os").environ.get("REACT_WIKI_TIMEOUT", "10"))
# Module-level state so Lookup[] can refer to the last Search[] result.
_last_search_sentences: list[str] = []
_lookup_index: int = 0
def _wiki_search(query: str, sentences: int = 5) -> str:
"""Return the first `sentences` sentences of the Wikipedia intro for `query`."""
global _last_search_sentences, _lookup_index
params = urllib.parse.urlencode({
"action": "query",
"prop": "extracts",
"exintro": True,
"explaintext": True,
"redirects": True,
"titles": query,
"format": "json",
})
url = f"{_WIKI_API}?{params}"
try:
req = urllib.request.Request(url, headers={"User-Agent": "react-agent/0.1"})
with urllib.request.urlopen(req, timeout=_WIKI_TIMEOUT) as resp:
data = json.loads(resp.read().decode())
except socket.timeout:
return f"Wikipedia request timed out after {_WIKI_TIMEOUT}s for '{query}'."
except (urllib.error.URLError, json.JSONDecodeError) as exc:
return f"Could not reach Wikipedia: {exc}"
pages = data.get("query", {}).get("pages", {})
page = next(iter(pages.values()))
if "missing" in page:
# Try search-suggest fallback.
return _wiki_search_suggest(query, sentences)
text = page.get("extract", "").strip()
if not text:
return "No extract found for this article."
# Split into sentences for Lookup[].
all_sents = [s.strip() for s in _SENTENCE_RE.split(text) if s.strip()]
_last_search_sentences = all_sents
_lookup_index = 0
snippet = " ".join(all_sents[:sentences])
return snippet or text[:500]
def _wiki_search_suggest(query: str, sentences: int) -> str:
"""OpenSearch fallback: find the closest article title, then fetch it."""
params = urllib.parse.urlencode({
"action": "opensearch",
"search": query,
"limit": 1,
"format": "json",
})
url = f"{_WIKI_API}?{params}"
try:
req = urllib.request.Request(url, headers={"User-Agent": "react-agent/0.1"})
with urllib.request.urlopen(req, timeout=_WIKI_TIMEOUT) as resp:
results = json.loads(resp.read().decode())
if results[1]:
return _wiki_search(results[1][0], sentences)
except Exception:
pass
return f"Could not find a Wikipedia article for '{query}'."
def _wiki_lookup(keyword: str) -> str:
"""Return the next sentence in the last Search result containing `keyword`."""
global _lookup_index
if not _last_search_sentences:
return "No previous Search result to look up in."
keyword_lower = keyword.lower()
for i in range(_lookup_index, len(_last_search_sentences)):
if keyword_lower in _last_search_sentences[i].lower():
_lookup_index = i + 1
return _last_search_sentences[i]
return f"No (more) results for '{keyword}' in the current article."
# ---------------------------------------------------------------------------
# Safe calculator
# ---------------------------------------------------------------------------
_SAFE_OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
ast.Mod: operator.mod,
ast.FloorDiv: operator.floordiv,
}
_SAFE_NAMES = {
"abs": abs, "round": round, "sqrt": math.sqrt,
"pi": math.pi, "e": math.e,
}
def _eval_node(node: ast.AST) -> float:
if isinstance(node, ast.Constant):
if isinstance(node.value, (int, float)):
return float(node.value)
raise ValueError(f"Unsupported constant: {node.value!r}")
if isinstance(node, ast.Name):
if node.id in _SAFE_NAMES:
v = _SAFE_NAMES[node.id]
if callable(v):
raise ValueError(f"'{node.id}' needs arguments")
return float(v) # type: ignore[arg-type]
raise ValueError(f"Unknown name: '{node.id}'")
if isinstance(node, ast.BinOp):
op = _SAFE_OPS.get(type(node.op))
if op is None:
raise ValueError(f"Unsupported operator: {type(node.op).__name__}")
return op(_eval_node(node.left), _eval_node(node.right))
if isinstance(node, ast.UnaryOp):
op = _SAFE_OPS.get(type(node.op))
if op is None:
raise ValueError(f"Unsupported unary op: {type(node.op).__name__}")
return op(_eval_node(node.operand))
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id in _SAFE_NAMES:
fn = _SAFE_NAMES[node.func.id]
if callable(fn):
args = [_eval_node(a) for a in node.args]
return float(fn(*args)) # type: ignore[operator]
raise ValueError(f"Disallowed function call: {ast.dump(node.func)}")
raise ValueError(f"Unsupported AST node: {type(node).__name__}")
def _calculate(expr: str) -> str:
expr = expr.strip().rstrip("=").strip()
# Allow "x,xxx" comma-separated thousands.
expr = expr.replace(",", "")
try:
tree = ast.parse(expr, mode="eval")
result = _eval_node(tree.body)
# Pretty-print: show int if exact, else float.
if result == int(result) and abs(result) < 1e15:
return str(int(result))
return f"{result:.6g}"
except Exception as exc:
return f"Error: {exc}"
# ---------------------------------------------------------------------------
# Public dispatch
# ---------------------------------------------------------------------------
class ToolResult:
def __init__(self, observation: str, done: bool = False, answer: str = ""):
self.observation = observation
self.done = done # True when Finish[] is called
self.answer = answer # Set when done=True
_VALID_TOOLS = ("search", "lookup", "calculate", "finish")
def execute(action_name: str, action_input: str) -> ToolResult:
"""Dispatch an action and return a ToolResult.
Tool names are matched case-insensitively. An empty action_input is
handled gracefully by each tool rather than raising an exception.
"""
name = action_name.strip().lower()
inp = action_input.strip()
if name == "search":
if not inp:
return ToolResult("Search requires a non-empty query.")
obs = _wiki_search(inp)
return ToolResult(obs)
if name == "lookup":
obs = _wiki_lookup(inp)
return ToolResult(obs)
if name == "calculate":
if not inp:
return ToolResult("Calculate requires a non-empty expression.")
obs = _calculate(inp)
return ToolResult(obs)
if name == "finish":
return ToolResult(observation="", done=True, answer=inp)
valid = ", ".join(t.capitalize() for t in _VALID_TOOLS)
return ToolResult(
f"Unknown tool '{action_name}'. Valid tools: {valid}."
)