Aleksander22's picture
Slayer1B 1.10 Instruct 30.11 (SFT)
53d5fc6 verified
Raw History Blame Contribute Delete
13.4 kB
"""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()