-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
56 lines (51 loc) · 1.43 KB
/
tools.py
File metadata and controls
56 lines (51 loc) · 1.43 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
import re
import sympy as sp
from decimal import Decimal
from typing import Dict, Callable
class Tool:
def __init__(self, name: str, schema: dict, func: Callable[[dict], dict]):
self.name = name
self.schema = schema
self.call = func
def _safe_calc(args: dict) -> dict:
expr = args["expression"]
if re.search(r"[^\d+\-*/().^ ]", expr):
return {"error": "Illegal characters in expression"}
try:
val = Decimal(str(sp.sympify(expr).evalf()))
return {"result": str(val)}
except Exception as e:
return {"error": str(e)}
def _reverse_string(args: dict) -> dict:
return {"result": args["text"][::-1]}
def _word_count(args: dict) -> dict:
return {"result": len(args["text"].split())}
TOOLS: Dict[str, Tool] = {
"calculator": Tool(
"calculator",
{
"type": "object",
"properties": {"expression": {"type": "string"}},
"required": ["expression"],
},
_safe_calc,
),
"reverse_string": Tool(
"reverse_string",
{
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
},
_reverse_string,
),
"word_count": Tool(
"word_count",
{
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
},
_word_count,
),
}