File size: 10,392 Bytes
6071ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic local tools + generated test cases for the Slayer1B tool-loop eval (PL and EN).

Every tool really executes (no network): fixed weather table, safe arithmetic, a small fact base for search, fixed
FX rates, unit conversion, time zones. Each case states the tool that must be called and values that the final
answer must contain (taken from the tool's output, so an answer can only pass by using the result).
"""
from __future__ import annotations

import ast
import json
import operator
import random

WEATHER = {"krak贸w": (3, "pochmurno / cloudy"), "warszawa": (5, "deszcz / rain"), "gda艅sk": (2, "wiatr / windy"),
           "wroc艂aw": (7, "s艂onecznie / sunny"), "pozna艅": (4, "mg艂a / fog"), "berlin": (6, "cloudy"), "paris": (9, "sunny"),
           "london": (8, "rain"), "madrid": (15, "sunny"), "rome": (13, "cloudy"), "oslo": (-4, "snow"), "tokyo": (11, "clear")}
FX = {"PLN": 1.0, "EUR": 4.27, "USD": 3.94, "GBP": 5.02, "CHF": 4.48, "JPY": 0.0262}
TZ = {"warszawa": 1, "krak贸w": 1, "london": 0, "new york": -5, "tokyo": 9, "sydney": 11, "berlin": 1, "los angeles": -8}
KB = {
    "wis艂a": "Wis艂a to najd艂u偶sza rzeka w Polsce, ma 1022 km d艂ugo艣ci.",
    "mount everest": "Mount Everest is 8849 metres high.",
    "maria sk艂odowska-curie": "Maria Sk艂odowska-Curie otrzyma艂a Nagrod臋 Nobla dwukrotnie: w 1903 i 1911 roku.",
    "python": "Python 3.0 was released on 3 December 2008.",
    "rysy": "Rysy to najwy偶szy szczyt Polski, 2499 m n.p.m. (wierzcho艂ek polski).",
    "speed of light": "The speed of light in vacuum is 299792 km/s.",
    "kopernik": "Miko艂aj Kopernik urodzi艂 si臋 w 1473 roku w Toruniu.",
    "great wall of china": "The Great Wall of China is about 21196 km long.",
}
TOOLS = {
    "get_weather": {"name": "get_weather", "description": "Current weather in a city. Returns temperature in Celsius and conditions.",
                    "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}}, "required": ["city"]}},
    "calculator": {"name": "calculator", "description": "Evaluate an arithmetic expression (+, -, *, /, **, parentheses).",
                   "parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}},
    "search": {"name": "search", "description": "Search an encyclopedia and return a short fact.",
               "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}},
    "convert_currency": {"name": "convert_currency", "description": "Convert an amount between currencies (ISO codes).",
                         "parameters": {"type": "object", "properties": {"amount": {"type": "number"}, "from_currency": {"type": "string"},
                                                                         "to_currency": {"type": "string"}}, "required": ["amount", "from_currency", "to_currency"]}},
    "get_time": {"name": "get_time", "description": "Current local time in a city (reference clock 12:00 UTC).",
                 "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}},
    "send_email": {"name": "send_email", "description": "Send an e-mail (distractor: never needed in these tests).",
                   "parameters": {"type": "object", "properties": {"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}},
                                  "required": ["to", "subject", "body"]}},
}
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}


def _eval(node):
    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
        return node.value
    if isinstance(node, ast.BinOp) and type(node.op) in OPS:
        return OPS[type(node.op)](_eval(node.left), _eval(node.right))
    if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
        return OPS[type(node.op)](_eval(node.operand))
    raise ValueError("unsupported expression")


LOCATIVE = {"Krak贸w": "Krakowie", "Warszawa": "Warszawie", "Gda艅sk": "Gda艅sku", "Wroc艂aw": "Wroc艂awiu", "Pozna艅": "Poznaniu",
            "London": "Londynie", "Tokyo": "Tokio"}
ALIASES = {v.lower(): k.lower() for k, v in LOCATIVE.items()} | {"warsaw": "warszawa", "cracow": "krak贸w", "krakow": "krak贸w",
                                                                   "londyn": "london", "tokio": "tokyo", "nowy jork": "new york"}


def _key(s):
    k = " ".join(str(s or "").lower().replace("-", " - ").split()).replace(" - ", "-")
    return ALIASES.get(k, k)


def execute(name: str, args: dict) -> dict:
    """Run a tool; errors are returned as {'error': ...} (the model must cope)."""
    try:
        if name == "get_weather":
            c = _key(args.get("city"))
            if c not in WEATHER:
                return {"error": f"unknown city: {args.get('city')}"}
            t, cond = WEATHER[c]
            return {"city": args["city"], "temperature_c": t, "conditions": cond}
        if name == "calculator":
            v = _eval(ast.parse(str(args.get("expression", "")), mode="eval").body)
            return {"result": round(v, 6) if isinstance(v, float) else v}
        if name == "search":
            q = _key(args.get("query"))
            hit = next((v for k, v in KB.items() if k in q or q in k), None)
            return {"result": hit} if hit else {"result": "no results"}
        if name == "convert_currency":
            f, t = str(args["from_currency"]).upper(), str(args["to_currency"]).upper()
            if f not in FX or t not in FX:
                return {"error": "unknown currency"}
            return {"amount": args["amount"], "from": f, "to": t, "converted": round(float(args["amount"]) * FX[f] / FX[t], 2)}
        if name == "get_time":
            c = _key(args.get("city"))
            if c not in TZ:
                return {"error": "unknown city"}
            return {"city": args["city"], "local_time": f"{(12 + TZ[c]) % 24:02d}:00"}
        if name == "send_email":
            return {"status": "sent"}
        return {"error": f"unknown tool: {name}"}
    except Exception as e:   # malformed arguments
        return {"error": f"{type(e).__name__}: {e}"}


def _num(v):
    return str(int(v)) if float(v) == int(v) else str(v)


def cases(seed: int = 7) -> list[dict]:
    rnd = random.Random(seed)
    out = []
    pl_cities = ["Krak贸w", "Warszawa", "Gda艅sk", "Wroc艂aw", "Pozna艅"]
    en_cities = ["Berlin", "Paris", "London", "Madrid", "Rome", "Oslo", "Tokyo"]
    for c in pl_cities:
        t, _ = WEATHER[c.lower()]
        for tpl in ["Jaka jest teraz pogoda w {c}?", "Czy w {c} jest dzi艣 zimno? Sprawd藕 temperatur臋."]:
            out.append({"lang": "pl", "prompt": tpl.format(c=LOCATIVE[c]), "expect_tool": "get_weather", "must_contain": [_num(t)]})
    for c in en_cities:
        t, _ = WEATHER[c.lower()]
        out.append({"lang": "en", "prompt": f"What's the weather like in {c} right now?", "expect_tool": "get_weather", "must_contain": [_num(t)]})
    for _ in range(14):
        a, b, c2 = rnd.randint(12, 999), rnd.randint(12, 999), rnd.randint(2, 19)
        expr, val = f"{a} * {b} + {c2}", a * b + c2
        if rnd.random() < 0.5:
            out.append({"lang": "pl", "prompt": f"Policz dok艂adnie: {a} razy {b} plus {c2}. U偶yj kalkulatora.", "expect_tool": "calculator", "must_contain": [str(val)]})
        else:
            out.append({"lang": "en", "prompt": f"Use the calculator: what is {expr}?", "expect_tool": "calculator", "must_contain": [str(val)]})
    facts = [("pl", "Jak d艂uga jest Wis艂a?", ["1022"]), ("en", "How high is Mount Everest?", ["8849"]),
             ("pl", "Ile razy Maria Sk艂odowska-Curie dosta艂a Nobla i w kt贸rych latach?", ["1903", "1911"]),
             ("en", "When was Python 3.0 released?", ["2008"]), ("pl", "Jaki jest najwy偶szy szczyt Polski i ile ma metr贸w?", ["2499"]),
             ("en", "What is the speed of light in vacuum?", ["299792"]), ("pl", "W kt贸rym roku urodzi艂 si臋 Miko艂aj Kopernik?", ["1473"]),
             ("en", "How long is the Great Wall of China?", ["21196"])]
    for lang, q, must in facts:
        out.append({"lang": lang, "prompt": q + (" Wyszukaj to." if lang == "pl" else " Look it up."), "expect_tool": "search", "must_contain": must})
    for _ in range(10):
        amt = rnd.choice([50, 100, 250, 1200, 75])
        f, t = rnd.sample(["PLN", "EUR", "USD", "GBP", "CHF"], 2)
        val = round(amt * FX[f] / FX[t], 2)
        if rnd.random() < 0.5:
            out.append({"lang": "pl", "prompt": f"Ile to jest {amt} {f} w {t}?", "expect_tool": "convert_currency", "must_contain": [_num(val)]})
        else:
            out.append({"lang": "en", "prompt": f"Convert {amt} {f} to {t}.", "expect_tool": "convert_currency", "must_contain": [_num(val)]})
    for c, lang in [("Tokyo", "en"), ("Sydney", "en"), ("New York", "en"), ("Warszawa", "pl"), ("London", "pl")]:
        tt = f"{(12 + TZ[c.lower()]) % 24:02d}:00"
        out.append({"lang": lang, "prompt": (f"Kt贸ra jest teraz godzina w {LOCATIVE.get(c, c)}?" if lang == "pl" else f"What time is it in {c} now?"),
                    "expect_tool": "get_time", "must_contain": [tt[:2].lstrip("0") or "0"]})
    no_tool = [("pl", "Cze艣膰! Jak si臋 masz?"), ("en", "Thanks, that's all for today."), ("pl", "Napisz jedno zdanie o jesieni."),
               ("en", "Say hello in French."), ("pl", "Dzi臋kuj臋 za pomoc!"), ("en", "Give me a synonym for 'happy'.")]
    for lang, q in no_tool:
        out.append({"lang": lang, "prompt": q, "expect_tool": None, "must_contain": []})
    names = list(TOOLS)
    for i, c in enumerate(out):
        need = c["expect_tool"]
        pool = [n for n in names if n != need]
        rnd.shuffle(pool)
        chosen = ([need] if need else []) + pool[: rnd.randint(1, 3)]
        rnd.shuffle(chosen)
        c["tools"] = [TOOLS[n] for n in chosen]
        c["id"] = f"loop-{i:03d}"
    return out


if __name__ == "__main__":
    cs = cases()
    print(len(cs), json.dumps(cs[0], ensure_ascii=False))
    print(execute("get_weather", {"city": "Krak贸w"}), execute("calculator", {"expression": "12*(3+4)"}),
          execute("convert_currency", {"amount": 100, "from_currency": "eur", "to_currency": "PLN"}))