File size: 10,645 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 | """Programmatic E5 data (exact, no teacher): repairing tool calls from the error message, and reading documents.
repair_* the first call is wrong, the tool's error says why, the next call fixes exactly that, then the answer:
missing argument / unknown tool name (pick one from the list) / invalid value format / document not found
(pick from 'available') / section not found (read the whole file) / no results (rephrase once) /
unrecoverable service error (say so honestly, no retry loop)
docs_* list_docs -> read_doc(name[, section]) -> answer that uses the document's content; read once, reuse later
The faulty first call is context (not trained); every correction and the final answer are trained.
Tools: synth_tools.py (disjoint from the 0/1 eval) + doc tools + web_search (offline-style results).
python e5_synth.py out_dir --n-repair 12000 --n-docs 6000
"""
from __future__ import annotations
import argparse
import json
import random
from pathlib import Path
import doc_tools as D
import synth_tools as S
WEB = {"name": "web_search", "description": "Search the web. Returns the top results: title, url and a short snippet.",
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}
ALL = {**{n: {"name": n, **S.TOOLS[n]} for n in S.TOOLS}, **D.TOOLS, "web_search": WEB}
def U(c):
return {"role": "user", "content": c}
def A(c):
return {"role": "assistant", "content": c}
def C(name, args, train=True):
return {"role": "assistant", "content": "", "tool_calls": [S.call(name, args)], "trainable": train}
def R(obj):
return {"role": "tool", "content": json.dumps(obj, ensure_ascii=False)}
def toolset(rnd, need):
others = [t for t in ALL if t not in need]
rnd.shuffle(others)
names = sorted(set(need)) + others[: rnd.randint(1, 3)]
rnd.shuffle(names)
return [ALL[n] for n in names]
def repair(rnd):
lang = rnd.choice(["pl", "pl", "en"])
P = lang == "pl"
k = rnd.choice(["missing", "missing", "unknown_tool", "bad_value", "no_results", "service"])
name, args, qpl, qen, ans = S._task(rnd)
if k == "bad_value" and name not in ("set_reminder", "book_table"):
k = "missing"
q = qpl if P else qen
res = S._result(rnd, name, args)
if "error" in res:
return repair(rnd)
req = S.TOOLS[name]["parameters"]["required"]
if k == "missing":
drop = rnd.choice(req)
bad = {a: v for a, v in args.items() if a != drop}
msgs = [U(q), C(name, bad, False), R({"error": f"missing required argument: {drop}"}), C(name, args), R(res), A(ans(res, lang))]
need = [name]
elif k == "unknown_tool":
fake = rnd.choice([name.split("_")[0], name.replace("_", ""), "lookup", "get_info", "check_" + name.split("_")[-1]])
if fake == name:
fake = "lookup"
msgs = [U(q), C(fake, args, False), R({"error": f"tool not available: {fake}"}), C(name, args), R(res), A(ans(res, lang))]
need = [name]
elif k == "bad_value" and name in ("set_reminder", "book_table"):
badt = rnd.choice(["o 18", "6pm", "18.30", "wieczorem"])
bad = {**args, "time": badt}
msgs = [U(q), C(name, bad, False), R({"error": "invalid value for time: expected HH:MM"}), C(name, args), R(res), A(ans(res, lang))]
need = [name]
elif k == "no_results":
topic = rnd.choice(["SlayerLab", "Fabryka AI", "Slayer1B", "Bielik", "PLLuM", "Kraków Lajkonik", "Toruń piernik"])
q1, q2 = topic.split()[0].lower(), f"{topic} " + rnd.choice(["Hugging Face", "organizacja", "projekt", "official site", "wikipedia"])
url = f"https://example.org/{topic.replace(' ', '_')}"
hit = {"title": f"{topic} — opis" if P else f"{topic} — overview", "url": url, "domain": "example.org",
"snippet": f"{topic}: " + ("informacje o projekcie i zespole." if P else "information about the project and the team.")}
q = (f"Wyszukaj w internecie, czym jest {topic}." if P else f"Search the web: what is {topic}?")
msgs = [U(q), C("web_search", {"query": q1}, False), R({"query": q1, "results": [], "note": "no results"}),
C("web_search", {"query": q2}), R({"query": q2, "results": [hit]}),
A((f"Znalazłem: {hit['snippet']} Źródło: {url}" if P else f"Found it: {hit['snippet']} Source: {url}"))]
need = ["web_search"]
else:
err = rnd.choice(["service unavailable", "timeout", "rate limit exceeded"])
msgs = [U(q), C(name, args), R({"error": err}),
A((f"Nie udało się: narzędzie {name} zwróciło błąd ({err}). To błąd po stronie usługi, więc nie ponawiam teraz w kółko; spróbuj za chwilę."
if P else f"That did not work: the {name} tool returned an error ({err}). It is a service-side problem, so I am not retrying in a loop; please try again shortly."))]
need = [name]
final = msgs[-1]["content"]
return {"kind": "repair_" + k, "lang": lang, "messages": msgs, "tools": toolset(rnd, need),
"check": {"need_tool": need[0], "must_include": [w.strip(".,") for w in final.split() if any(c.isdigit() for c in w)][:2], "give_up_ok": k == "service"}}
DOC_FACTS = {
"pl": [("cennik.md", "## Cennik\n- Konsultacja: 150 zł za godzinę\n- Pakiet 5 godzin: 600 zł\n- Dojazd poza miasto: 2 zł/km", "Ile kosztuje pakiet 5 godzin?", "600 zł"),
("regulamin.md", "## Zwroty\nTowar można zwrócić w ciągu 21 dni od odbioru.\n## Reklamacje\nReklamacje rozpatrujemy w 10 dni roboczych.", "Ile mam dni na zwrot towaru?", "21 dni"),
("zespol.md", "## Zespół\n- Marta Nowak – kierowniczka projektu\n- Jan Wiśniewski – backend\n- Ola Zając – testy", "Kto odpowiada za testy?", "Ola Zając"),
("api.md", "## Autoryzacja\nNagłówek: X-Api-Key.\n## Format daty\nDaty zawsze w formacie RRRR-MM-DD.\n## Limit\n100 zapytań na minutę.", "Jaki jest limit zapytań do API?", "100 zapytań na minutę")],
"en": [("pricing.md", "## Pricing\n- Basic plan: $12 per month\n- Team plan: $49 per month (up to 10 users)", "How much is the team plan?", "$49"),
("handbook.md", "## Working hours\nCore hours are 10:00-15:00 CET.\n## Holidays\nEveryone gets 26 days of paid leave.", "How many days of paid leave do we get?", "26 days"),
("release.md", "## Release process\n1. Tag the commit as vX.Y.Z\n2. Run the smoke tests\n3. Publish the changelog", "What is the second step of a release?", "Run the smoke tests")]}
def docs_example(rnd):
lang = rnd.choice(["pl", "pl", "en"])
P = lang == "pl"
fname, body, q, a = rnd.choice(DOC_FACTS[lang])
# vary the facts so the model has to read, not memorise
if any(ch.isdigit() for ch in a):
import re
nums = re.findall(r"\d+", a)
new = str(int(nums[0]) + rnd.choice([-7, -3, 2, 5, 11, 30]) if int(nums[0]) > 12 else int(nums[0]) + rnd.randint(1, 9))
body, a = body.replace(nums[0], new, 1) if nums[0] in body else body, a.replace(nums[0], new, 1)
docs = {"SLAYER.md": ("# SLAYER.md\n## Użytkownik\nOdpowiadaj krótko, po polsku.\n## Dokumenty\nSzczegóły firmy są w osobnych plikach w docs/." if P else
"# SLAYER.md\n## User\nAnswer briefly, in English.\n## Documents\nCompany details live in separate files in docs/."), fname: body}
k = rnd.choice(["list_then_read", "list_then_read", "wrong_name", "section", "missing_section", "no_name"])
if k == "no_name": # the E4 failure seen in the chat: read_doc without its required name
bad = rnd.choice([{}, {"section": "name"}, {"section": "Użytkownik" if P else "User"}])
msgs = [U(q), C("read_doc", bad, False), R(D.execute("read_doc", bad, docs)), C("read_doc", {"name": "SLAYER.md"}), R(D.execute("read_doc", {"name": "SLAYER.md"}, docs))]
else:
msgs = [U(q), C("read_doc", {"name": "SLAYER.md"}), R(D.execute("read_doc", {"name": "SLAYER.md"}, docs))]
if k in ("list_then_read", "no_name"):
msgs += [C("list_docs", {}), R(D.execute("list_docs", {}, docs)), C("read_doc", {"name": fname}), R(D.execute("read_doc", {"name": fname}, docs))]
elif k == "wrong_name":
wrong = fname.replace(".md", "") + rnd.choice(["s.md", ".txt", "_v2.md"])
msgs += [C("read_doc", {"name": wrong}, False), R(D.execute("read_doc", {"name": wrong}, docs)), C("read_doc", {"name": fname}), R(D.execute("read_doc", {"name": fname}, docs))]
elif k == "section":
sec = D.sections(body)
h = next((x for x in sec if any(w in x.lower() for w in q.lower().split())), list(sec)[0])
msgs += [C("list_docs", {}), R(D.execute("list_docs", {}, docs)), C("read_doc", {"name": fname, "section": h}), R(D.execute("read_doc", {"name": fname, "section": h}, docs))]
else:
msgs += [C("read_doc", {"name": fname, "section": "FAQ"}, False), R(D.execute("read_doc", {"name": fname, "section": "FAQ"}, docs)),
C("read_doc", {"name": fname}), R(D.execute("read_doc", {"name": fname}, docs))]
msgs.append(A((f"Według pliku {fname}: {a}." if P else f"According to {fname}: {a}.")))
if rnd.random() < 0.4: # follow-up in the same conversation: reuse what was read, no new calls
msgs += [U("Dzięki!" if P else "Thanks!"), A("Proszę bardzo." if P else "You're welcome.")]
return {"kind": "docs_" + k, "lang": lang, "messages": msgs, "tools": toolset(rnd, ["read_doc", "list_docs"]),
"docs": docs, "check": {"need_tool": "read_doc", "first_read": "SLAYER.md", "must_include": [a]}}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("out")
ap.add_argument("--n-repair", type=int, default=12000)
ap.add_argument("--n-docs", type=int, default=3000)
ap.add_argument("--seed", type=int, default=5)
a = ap.parse_args()
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
rnd = random.Random(a.seed)
for name, fn, n in (("repair", repair, a.n_repair), ("docs", docs_example, a.n_docs)):
with open(out / f"{name}.jsonl", "w", encoding="utf-8") as f:
for _ in range(n):
x = fn(rnd)
for m in x["messages"]:
m.setdefault("trainable", m["role"] == "assistant")
f.write(json.dumps(x, ensure_ascii=False) + "\n")
print(name, n)
if __name__ == "__main__":
main()
|