File size: 13,443 Bytes
53d5fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""E5 'tool world' teacher job (vLLM, Qwen3): MANY different tools, with false calls and their repair.

The teacher invents a small tool world per sample (2-6 tools with JSON-schema parameters, 70% Polish requests) across
~150 domains, a user request, the exact call sequence (0-3 calls) and plausible tool results; then a second pass writes the
final answer from those results. Every call is validated against its schema (declared tool, required arguments, types).
Failures are injected programmatically so the model learns to READ the error and fix exactly that:
  missing_arg (drop a required argument) / unknown_tool (misspelled name) / wrong_type (string instead of number, bad
  date format) / service_down (cannot be fixed -> say so, no retry loop) / wrong_tool_first (an unrelated tool returns
  'not relevant' -> switch to the right one).
No-call samples (tools available, request does not need them, or none of the tools fits -> say it cannot be done) teach
restraint. The faulty call is context (masked); every correction and the final answer are trained.
  CUDA_VISIBLE_DEVICES=i python e5_toolworld.py --shard i --nshard 8 --out /workspace/e5gen [--n 6000]
"""
from __future__ import annotations

import argparse
import copy
import hashlib
import json
import random
import re
import time
from pathlib import Path

DOMAINS = ["rezerwacje w restauracjach", "kino i bilety", "poci膮gi PKP", "loty", "hotele", "apteka", "przychodnia i wizyty lekarskie", "bank i przelewy",
           "kursy walut", "gie艂da", "pogoda i jako艣膰 powietrza", "kalendarz i spotkania", "przypomnienia", "poczta e-mail", "SMS", "notatki", "lista zakup贸w",
           "sklep internetowy", "艣ledzenie przesy艂ek", "magazyn i stany", "faktury", "ksi臋gowo艣膰", "HR i urlopy", "CRM i klienci", "zg艂oszenia serwisowe",
           "repozytorium kodu", "CI/CD", "baza danych", "monitoring serwer贸w", "t艂umaczenia", "s艂ownik", "przepisy kulinarne", "dieta i kalorie", "trening",
           "biblioteka", "szko艂a i oceny", "uczelnia i plan zaj臋膰", "nieruchomo艣ci", "samoch贸d i serwis", "艂adowanie aut elektrycznych", "parking", "taks贸wki",
           "rowery miejskie", "komunikacja miejska", "mapy i trasy", "wydarzenia i koncerty", "muzyka", "podcasty", "filmy i seriale", "gry", "sport i wyniki",
           "inteligentny dom", "energia i rachunki", "ubezpieczenia", "urz臋dy i dokumenty", "podatki", "wolontariat", "schronisko dla zwierz膮t", "weterynarz",
           "ogr贸d", "rolnictwo", "drukarka 3D", "laboratorium", "wynajem sprz臋tu", "coworking", "eventy firmowe", "wesele", "podr贸偶e", "wiza", "t艂umacz migowy",
           "kurier", "sklep rowerowy", "kwiaciarnia", "fryzjer", "mechanik", "zg艂oszenia awarii", "statystyki strony www", "newsletter", "media spo艂eczno艣ciowe",
           "code review", "dokumentacja API", "wyszukiwarka publikacji naukowych", "kursy online", "egzaminy", "ankiety", "g艂osowania", "gie艂da pracy"]
GEN_PROMPT = ("Zaprojektuj ma艂y, realistyczny '艣wiat narz臋dzi' dla asystenta AI w dziedzinie: {domain}.\n"
              "Zwr贸膰 wy艂膮cznie JSON: {{\"tools\": [{{\"name\": \"snake_case\", \"description\": \"...\", \"parameters\": {{\"type\": \"object\", \"properties\": {{...}}, "
              "\"required\": [...]}}}}], \"user\": \"wiadomo艣膰 u偶ytkownika ({lang_name})\", \"calls\": [{{\"name\": \"...\", \"arguments\": {{...}}, \"result\": {{...}}}}]}}\n"
              "Wymagania: {n_tools} narz臋dzi (nazwy po angielsku, r贸偶ne od siebie), parametry z typami (string/number/integer/boolean) i opisami; "
              "{calls_rule} Argumenty musz膮 wynika膰 z wiadomo艣ci u偶ytkownika lub z wynik贸w wcze艣niejszych wywo艂a艅. Wyniki realistyczne i konkretne (liczby, nazwy, godziny).")
CALL_RULES = {0: "'calls' ma by膰 pust膮 list膮: wiadomo艣膰 u偶ytkownika to zwyk艂a rozmowa lub pytanie og贸lne, kt贸rego NIE trzeba za艂atwia膰 narz臋dziem.",
              1: "dok艂adnie 1 wywo艂anie, kt贸re w pe艂ni za艂atwia pro艣b臋.",
              2: "dok艂adnie 2 wywo艂ania, gdzie drugie korzysta z wyniku pierwszego (zale偶no艣膰).",
              3: "2-3 wywo艂ania potrzebne do spe艂nienia pro艣by (np. sprawd藕, potem wykonaj)."}
ANSWER_SYS = {"pl": "Jeste艣 asystentem. Na podstawie wynik贸w narz臋dzi odpowiedz u偶ytkownikowi kr贸tko (1-3 zdania), po polsku, podaj膮c konkretne warto艣ci z wynik贸w. Nie wymy艣laj niczego spoza wynik贸w.",
              "en": "You are an assistant. Using the tool results, answer the user briefly (1-3 sentences) in English with the concrete values from the results. Do not invent anything beyond the results."}
NOCALL_SYS = {"pl": "Jeste艣 asystentem. Odpowiedz kr贸tko i naturalnie po polsku. Nie u偶ywaj 偶adnych narz臋dzi.",
              "en": "You are an assistant. Answer briefly and naturally in English. Do not use any tools."}
TYPE_OK = {"string": str, "number": (int, float), "integer": int, "boolean": bool}


def valid_call(tools, c):
    t = next((x for x in tools if x.get("name") == c.get("name")), None)
    if t is None or not isinstance(c.get("arguments"), dict):
        return False
    props = (t.get("parameters") or {}).get("properties") or {}
    for r in (t.get("parameters") or {}).get("required") or []:
        if r not in c["arguments"]:
            return False
    for k, v in c["arguments"].items():
        ty = (props.get(k) or {}).get("type")
        if ty in TYPE_OK and not isinstance(v, TYPE_OK[ty]) or (ty == "integer" and isinstance(v, bool)):
            return False
    return True


def tc(name, args, train=True):
    return {"role": "assistant", "content": "", "tool_calls": [{"name": name, "arguments": json.dumps(args, ensure_ascii=False)}], "trainable": train}


def tr(obj):
    return {"role": "tool", "content": json.dumps(obj, ensure_ascii=False)}


def inject(rnd, tools, calls, lang):
    """Return (messages before the final answer, kind). One failure, then the correct sequence."""
    P = lang == "pl"
    kind = rnd.choices(["none", "missing_arg", "unknown_tool", "wrong_type", "service_down", "wrong_tool_first"], [40, 18, 14, 10, 8, 10])[0]
    msgs = []
    k = rnd.randrange(len(calls))
    for i, c in enumerate(calls):
        if i == k and kind != "none":
            t = next(x for x in tools if x["name"] == c["name"])
            req = (t.get("parameters") or {}).get("required") or []
            props = (t.get("parameters") or {}).get("properties") or {}
            if kind == "missing_arg" and req:
                drop = rnd.choice(req)
                msgs += [tc(c["name"], {a: v for a, v in c["arguments"].items() if a != drop}, False), tr({"error": f"missing required argument: {drop}"})]
            elif kind == "unknown_tool":
                bad = rnd.choice([c["name"].replace("_", ""), c["name"].split("_")[0], "get_" + c["name"].split("_")[-1] + "s", c["name"] + "_v2"])
                msgs += [tc(bad, c["arguments"], False), tr({"error": f"tool not available: {bad}", "available_tools": [x["name"] for x in tools]})]
            elif kind == "wrong_type":
                num = [a for a, v in c["arguments"].items() if (props.get(a) or {}).get("type") in ("number", "integer")]
                if num:
                    a0 = rnd.choice(num)
                    bad = {**c["arguments"], a0: str(c["arguments"][a0]) + (" sztuk" if P else " units")}
                    msgs += [tc(c["name"], bad, False), tr({"error": f"invalid type for {a0}: expected {(props.get(a0) or {}).get('type')}"})]
                else:
                    kind = "none"
            elif kind == "service_down":
                err = rnd.choice(["service unavailable", "timeout", "503 upstream error"])
                msgs += [tc(c["name"], c["arguments"]), tr({"error": err})]
                return msgs, kind, err
            elif kind == "wrong_tool_first":
                other = [x for x in tools if x["name"] != c["name"]]
                if other:
                    o = rnd.choice(other)
                    msgs += [tc(o["name"], {}, False), tr({"error": f"{o['name']} cannot handle this request; check the tool descriptions"})]
                else:
                    kind = "none"
        msgs += [tc(c["name"], c["arguments"]), tr(c["result"])]
    return msgs, kind, None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--shard", type=int, required=True)
    ap.add_argument("--nshard", type=int, default=8)
    ap.add_argument("--out", default="/workspace/e5gen")
    ap.add_argument("--n", type=int, default=6000, help="samples per shard")
    a = ap.parse_args()
    from vllm import LLM, SamplingParams
    llm = LLM("/workspace/models/Qwen3-8B", dtype="bfloat16", max_model_len=4096, gpu_memory_utilization=0.90, seed=a.shard)
    rnd = random.Random(f"tw-{a.shard}")
    log = lambda *x: print(time.strftime("%H:%M:%S"), f"[shard {a.shard}]", *x, flush=True)

    def chat(convs, temp, max_tokens):
        sp = SamplingParams(temperature=temp, top_p=0.9, max_tokens=max_tokens, seed=rnd.randint(0, 2**31))
        return [(r.outputs[0].text.strip(), r.outputs[0].finish_reason) for r in llm.chat(convs, sp, chat_template_kwargs={"enable_thinking": False}, use_tqdm=False)]

    jobs = []
    for _ in range(a.n):
        lang = "pl" if rnd.random() < 0.7 else "en"
        nc = rnd.choices([0, 1, 2, 3], [18, 42, 25, 15])[0]
        jobs.append({"lang": lang, "n_calls": nc, "domain": rnd.choice(DOMAINS),
                     "prompt": GEN_PROMPT.format(domain="{d}", lang_name="po polsku" if lang == "pl" else "in English", n_tools=rnd.randint(2, 6), calls_rule=CALL_RULES[nc])})
    for j in jobs:
        j["prompt"] = j["prompt"].replace("{d}", j["domain"])
    raw = chat([[{"role": "user", "content": j["prompt"]}] for j in jobs], 0.9, 1400)
    worlds = []
    for j, (t, fin) in zip(jobs, raw):
        t = re.sub(r"^```(json)?|```$", "", t.strip()).strip()
        try:
            w = json.loads(t[t.find("{"): t.rfind("}") + 1])
            tools, user, calls = w["tools"], str(w["user"]).strip(), w.get("calls") or []
            names = [x["name"] for x in tools]
        except Exception:
            continue
        if not (2 <= len(tools) <= 6) or len(set(names)) != len(names) or not user or len(calls) != j["n_calls"]:
            continue
        if not all(isinstance(x.get("parameters"), dict) for x in tools) or not all(valid_call(tools, c) and isinstance(c.get("result"), dict) for c in calls):
            continue
        worlds.append({**j, "tools": [{"name": x["name"], "description": str(x.get("description", "")), "parameters": x["parameters"]} for x in tools],
                       "user": user, "calls": [{"name": c["name"], "arguments": c["arguments"], "result": c["result"]} for c in calls]})
    log("worlds", len(worlds), "/", len(jobs))
    ans_in = []
    for w in worlds:
        if w["calls"]:
            ctx = "\n".join(f"- {c['name']}({json.dumps(c['arguments'], ensure_ascii=False)}) -> {json.dumps(c['result'], ensure_ascii=False)}" for c in w["calls"])
            ans_in.append([{"role": "system", "content": ANSWER_SYS[w["lang"]]}, {"role": "user", "content": f"{w['user']}\n\n(Wyniki narz臋dzi:\n{ctx})"}])
        else:
            ans_in.append([{"role": "system", "content": NOCALL_SYS[w["lang"]]}, {"role": "user", "content": w["user"]}])
    ans = chat(ans_in, 0.6, 300)
    fo = open(Path(a.out) / f"toolworld.s{a.shard}.jsonl", "w", encoding="utf-8")
    kept = {}
    for w, (t, fin) in zip(worlds, ans):
        if fin != "stop" or not t:
            continue
        vals = [str(v) for c in w["calls"] for v in c["result"].values() if isinstance(v, (str, int, float)) and len(str(v)) >= 2]
        if w["calls"] and vals and not any(v.lower() in t.lower() for v in vals):
            continue                                        # the answer must use the results
        tools = copy.deepcopy(w["tools"])
        rnd.shuffle(tools)
        msgs = [{"role": "user", "content": w["user"]}]
        kind, err = "no_call", None
        if w["calls"]:
            body, kind, err = inject(rnd, tools, w["calls"], w["lang"])
            msgs += body
        if kind == "service_down":
            t = (f"Nie uda艂o si臋: us艂uga zwr贸ci艂a b艂膮d ({err}). To problem po stronie us艂ugi, wi臋c teraz nie ponawiam; spr贸buj ponownie za chwil臋."
                 if w["lang"] == "pl" else f"That failed: the service returned an error ({err}). It is a service-side problem, so I am not retrying now; please try again shortly.")
        msgs.append({"role": "assistant", "content": t})
        for m in msgs:
            m.setdefault("trainable", m["role"] == "assistant")
        rid = hashlib.sha1(json.dumps(msgs, ensure_ascii=False).encode()).hexdigest()[:16]
        need = w["calls"][0]["name"] if w["calls"] else None
        fo.write(json.dumps({"id": f"toolworld-{rid}", "task": "toolworld", "kind": "tw_" + kind, "lang": w["lang"], "domain": w["domain"], "messages": msgs,
                             "tools": tools, "teacher": "Qwen/Qwen3-8B@b968826d9c", "source": "teacher",
                             "check": {"need_tool": need, "must_include": vals[:1] if kind != "service_down" else [], "give_up_ok": kind == "service_down",
                                       "must_not_call_any": not w["calls"]}}, ensure_ascii=False) + "\n")
        kept[kind] = kept.get(kind, 0) + 1
    fo.close()
    log("kept", kept, "SHARD_DONE")


if __name__ == "__main__":
    main()