"""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()