File size: 9,958 Bytes
fb6c876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference tool runtime for models trained on the OPUS-5.5-DATABASE `tools` config.

The same implementations are used (a) to generate the verified OPUS-synth-tools examples
— every tool result in the data is the real output of these functions — and (b) at
inference time, so a fine-tuned model can actually call them:

    from opusdb.agent_tools import TOOL_SPECS, call_tool, parse_tool_calls
    text = model_generate(messages, tools=TOOL_SPECS)
    for call in parse_tool_calls(text):
        result = call_tool(call["name"], call["arguments"])

Tools: calculator, python (subprocess with timeout), date_calc, unit_convert.
"""
import ast
import datetime as dt
import json
import math
import operator
import re
import subprocess
import sys
import tempfile
from fractions import Fraction

TOOL_SPECS = [
    {"type": "function", "function": {
        "name": "calculator",
        "description": "Evaluate an arithmetic expression exactly. Supports + - * / // % **, parentheses and the "
                       "functions sqrt, abs, round, floor, ceil, log, log10, exp, sin, cos, tan, factorial, gcd, "
                       "and the constants pi and e.",
        "parameters": {"type": "object", "properties": {
            "expression": {"type": "string", "description": "e.g. '(1250 * 1.07**3) - 400'"}},
            "required": ["expression"]}}},
    {"type": "function", "function": {
        "name": "python",
        "description": "Run a short Python 3 program and return what it prints (stdout) or the last error line. "
                       "Use print() to return results. Intended for computation only.",
        "parameters": {"type": "object", "properties": {
            "code": {"type": "string", "description": "Python source code"}},
            "required": ["code"]}}},
    {"type": "function", "function": {
        "name": "date_calc",
        "description": "Date arithmetic. operation='add_days' returns date + days; 'diff' returns the number of days "
                       "from date to other_date; 'weekday' returns the weekday name of date. Dates are YYYY-MM-DD.",
        "parameters": {"type": "object", "properties": {
            "operation": {"type": "string", "enum": ["add_days", "diff", "weekday"]},
            "date": {"type": "string"},
            "days": {"type": "integer"},
            "other_date": {"type": "string"}},
            "required": ["operation", "date"]}}},
    {"type": "function", "function": {
        "name": "unit_convert",
        "description": "Convert a value between units of length (mm, cm, m, km, in, ft, yd, mi), mass (mg, g, kg, "
                       "lb, oz), volume (ml, l, gal, cup), time (s, min, h, day, week) or temperature (C, F, K).",
        "parameters": {"type": "object", "properties": {
            "value": {"type": "number"}, "from_unit": {"type": "string"}, "to_unit": {"type": "string"}},
            "required": ["value", "from_unit", "to_unit"]}}},
]
TOOL_NAMES = {t["function"]["name"] for t in TOOL_SPECS}

# ------------------------------------------------------------------ calculator
_BIN = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
        ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow}
_FUNCS = {"sqrt": math.sqrt, "abs": abs, "round": round, "floor": math.floor, "ceil": math.ceil, "log": math.log,
          "log10": math.log10, "exp": math.exp, "sin": math.sin, "cos": math.cos, "tan": math.tan,
          "factorial": math.factorial, "gcd": math.gcd}
_CONSTS = {"pi": math.pi, "e": math.e}


def _calc(node):
    if isinstance(node, ast.Constant) and type(node.value) in (int, float):
        return Fraction(node.value) if isinstance(node.value, int) else Fraction(str(node.value))
    if isinstance(node, ast.Name) and node.id in _CONSTS:
        return _CONSTS[node.id]
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
        v = _calc(node.operand)
        return -v if isinstance(node.op, ast.USub) else v
    if isinstance(node, ast.BinOp) and type(node.op) in _BIN:
        a, b = _calc(node.left), _calc(node.right)
        if isinstance(node.op, ast.Pow):
            if abs(b) > 1000 or (isinstance(a, Fraction) and abs(a) > 10 ** 6 and b > 50):
                raise ValueError("exponent too large")
            if isinstance(b, Fraction) and b.denominator != 1:
                return float(a) ** float(b)
        return _BIN[type(node.op)](a, b)
    if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCS and not node.keywords:
        args = [_calc(a) for a in node.args]
        if node.func.id == "factorial" and (len(args) != 1 or args[0] > 1000):
            raise ValueError("factorial argument too large")
        if node.func.id in ("factorial", "gcd"):
            args = [int(a) for a in args]
        elif node.func.id != "abs" and node.func.id != "round":
            args = [float(a) for a in args]
        return _FUNCS[node.func.id](*args)
    raise ValueError("unsupported expression")


def format_number(v):
    if isinstance(v, Fraction):
        if v.denominator == 1:
            return str(v.numerator)
        v = float(v)
    if isinstance(v, float):
        if math.isinf(v) or math.isnan(v):
            return str(v)
        if v == int(v) and abs(v) < 1e15:
            return str(int(v))
        return f"{v:.10g}"
    return str(v)


def calculator(expression: str):
    if len(expression) > 300:
        return {"error": "expression too long"}
    try:
        tree = ast.parse(expression.replace("^", "**").replace("×", "*").replace("÷", "/"), mode="eval")
        return {"result": format_number(_calc(tree.body))}
    except ZeroDivisionError:
        return {"error": "division by zero"}
    except (ValueError, SyntaxError, TypeError, OverflowError) as exc:
        return {"error": str(exc) or type(exc).__name__}


# ------------------------------------------------------------------ python runner
def python(code: str, timeout: float = 5.0):
    """Runs code in a separate isolated-mode interpreter with a timeout.

    This is NOT a security sandbox: when serving untrusted users, run it inside a container/VM
    without network or credentials.
    """
    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as fh:
        fh.write(code)
        path = fh.name
    try:
        res = subprocess.run([sys.executable, "-I", "-S", path], capture_output=True, text=True, timeout=timeout,
                             cwd=tempfile.gettempdir())
    except subprocess.TimeoutExpired:
        return {"error": f"timeout after {timeout} s"}
    if res.returncode != 0:
        last = res.stderr.strip().splitlines()[-1] if res.stderr.strip() else "error"
        return {"error": last}
    return {"stdout": res.stdout[-4000:]}


# ------------------------------------------------------------------ dates & units
def date_calc(operation: str, date: str, days: int = None, other_date: str = None):
    try:
        d = dt.date.fromisoformat(date)
        if operation == "add_days":
            return {"result": (d + dt.timedelta(days=int(days))).isoformat()}
        if operation == "diff":
            return {"result": (dt.date.fromisoformat(other_date) - d).days}
        if operation == "weekday":
            return {"result": d.strftime("%A")}
        return {"error": f"unknown operation {operation}"}
    except (TypeError, ValueError) as exc:
        return {"error": str(exc)}


_UNITS = {  # factor to SI base of each dimension
    "length": {"mm": 0.001, "cm": 0.01, "m": 1, "km": 1000, "in": 0.0254, "ft": 0.3048, "yd": 0.9144, "mi": 1609.344},
    "mass": {"mg": 1e-6, "g": 0.001, "kg": 1, "lb": 0.45359237, "oz": 0.028349523125},
    "volume": {"ml": 0.001, "l": 1, "gal": 3.785411784, "cup": 0.2365882365},
    "time": {"s": 1, "min": 60, "h": 3600, "day": 86400, "week": 604800},
}


def unit_convert(value, from_unit: str, to_unit: str):
    f, t = from_unit.strip(), to_unit.strip()
    temps = {"C", "F", "K"}
    if f in temps and t in temps:
        c = value if f == "C" else (value - 32) * 5 / 9 if f == "F" else value - 273.15
        out = c if t == "C" else c * 9 / 5 + 32 if t == "F" else c + 273.15
        return {"result": round(out, 6)}
    for table in _UNITS.values():
        if f in table and t in table:
            return {"result": round(value * table[f] / table[t], 6)}
    return {"error": f"cannot convert {from_unit} to {to_unit}"}


IMPL = {"calculator": calculator, "python": python, "date_calc": date_calc, "unit_convert": unit_convert}


def call_tool(name, arguments):
    if name not in IMPL:
        return {"error": f"unknown tool {name}"}
    if isinstance(arguments, str):
        try:
            arguments = json.loads(arguments)
        except ValueError:
            return {"error": "arguments are not valid JSON"}
    try:
        return IMPL[name](**arguments)
    except TypeError as exc:
        return {"error": str(exc)}


# ------------------------------------------------------------------ parsing model output
_TAGGED = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.S)


def parse_tool_calls(text):
    """Extract tool calls from generated text (Hermes/Qwen `<tool_call>{...}</tool_call>` or bare JSON)."""
    calls = []
    blobs = _TAGGED.findall(text)
    if not blobs:
        m = re.search(r"\{.*\}", text, re.S)
        blobs = [m.group(0)] if m else []
    for b in blobs:
        try:
            obj = json.loads(b)
        except ValueError:
            continue
        if isinstance(obj, dict) and "name" in obj:
            args = obj.get("arguments", obj.get("parameters", {}))
            if isinstance(args, str):
                try:
                    args = json.loads(args)
                except ValueError:
                    pass
            calls.append({"name": obj["name"], "arguments": args})
    return calls