File size: 25,819 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 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | """Programmatic, exactly-correct training conversations for the s3 mix (PL + EN):
arith - arithmetic with short worked steps (multiplication by decomposition, %, fractions, time + speed, units)
logic - ordering, syllogisms, trick questions, day-of-week / clock arithmetic, proportional rates, sequences, ages
ident - who is Slayer (fixed facts only)
agent - sequential and dependent multi-call tool chains, math through a formula tool, missing-argument repair
Tools stay disjoint from the eval suite (tools_suite.py): evaluate_formula/formula here vs calculator/expression there.
python s3_synth.py out_dir --n-arith 60000 --n-logic 40000 --n-ident 2000 --n-agent 40000
"""
from __future__ import annotations
import argparse
import json
import math
import random
from fractions import Fraction
from pathlib import Path
import synth_tools as S
DAYS_PL = ["poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota", "niedziela"]
DAYS_EN = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
NAMES_PL = ["Ania", "Basia", "Celina", "Darek", "Ewa", "Franek", "Gosia", "Henryk", "Iza", "Janek", "Kasia", "Tomek", "Ola", "Piotr"]
GEN_PL = {"Ania": "Ani", "Basia": "Basi", "Celina": "Celiny", "Darek": "Darka", "Ewa": "Ewy", "Franek": "Franka", "Gosia": "Gosi",
"Henryk": "Henryka", "Iza": "Izy", "Janek": "Janka", "Kasia": "Kasi", "Tomek": "Tomka", "Ola": "Oli", "Piotr": "Piotra"}
def fem(x):
return x.endswith("a")
def minut(n):
return f"{n} minuty" if n % 10 in (2, 3, 4) and n % 100 not in (12, 13, 14) else ("1 minutę" if n == 1 else f"{n} minut")
NAMES_EN = ["Alice", "Ben", "Clara", "David", "Emma", "Frank", "Grace", "Henry", "Ivy", "Jack", "Kate", "Tom", "Olivia", "Peter"]
def U(c):
return {"role": "user", "content": c}
def A(c):
return {"role": "assistant", "content": c}
def num(x):
if isinstance(x, Fraction):
x = float(x) if x.denominator != 1 else x.numerator
if isinstance(x, float):
if abs(x - round(x)) < 1e-9:
return str(int(round(x)))
return f"{x:.2f}".rstrip("0").rstrip(".")
return str(x)
def pln(s, lang): # decimal comma in Polish
return s.replace(".", ",") if lang == "pl" else s
# ------------------------------------------------------------------ arithmetic
def arith(rnd):
lang = rnd.choice(["pl", "pl", "en"])
k = rnd.choice(["mul", "mul", "pct", "frac", "trip", "div", "add", "units", "pct_change"])
P = lang == "pl"
if k == "mul":
a, b = rnd.randint(11, 99), rnd.randint(11, 99) if rnd.random() < 0.7 else rnd.randint(101, 999)
if b % 10 == 0:
b += rnd.randint(1, 9)
t, o = (b // 10) * 10, b % 10
q = rnd.choice([f"Ile to jest {a} razy {b}?", f"Policz {a} · {b}.", f"Oblicz iloczyn {a} i {b}."] if P else
[f"What is {a} times {b}?", f"Calculate {a} × {b}.", f"What is the product of {a} and {b}?"])
s = (f"Rozbijam {b} na {t} + {o}.\n{a} · {t} = {a * t}\n{a} · {o} = {a * o}\n{a * t} + {a * o} = {a * b}\nOdpowiedź: {a * b}" if P else
f"Split {b} into {t} + {o}.\n{a} × {t} = {a * t}\n{a} × {o} = {a * o}\n{a * t} + {a * o} = {a * b}\nAnswer: {a * b}")
elif k == "div":
b, c = rnd.randint(3, 25), rnd.randint(3, 60)
a = b * c
q = f"Ile to jest {a} podzielić przez {b}?" if P else f"What is {a} divided by {b}?"
s = (f"Szukam liczby, która pomnożona przez {b} da {a}: {b} · {c} = {a}.\nOdpowiedź: {c}" if P else
f"Find the number that gives {a} when multiplied by {b}: {b} × {c} = {a}.\nAnswer: {c}")
elif k == "add":
xs = [rnd.randint(12, 999) for _ in range(rnd.randint(3, 4))]
q = (f"Dodaj liczby: {', '.join(map(str, xs))}." if P else f"Add these numbers: {', '.join(map(str, xs))}.")
acc, lines = xs[0], []
for x in xs[1:]:
lines.append(f"{acc} + {x} = {acc + x}")
acc += x
s = "\n".join(lines) + (f"\nOdpowiedź: {acc}" if P else f"\nAnswer: {acc}")
elif k == "pct":
p, base = rnd.choice([5, 10, 12, 15, 20, 25, 30, 40, 50, 75]), rnd.choice([40, 60, 80, 120, 150, 200, 240, 360, 400, 500, 800, 1200])
r = Fraction(p * base, 100)
q = f"Ile to jest {p}% z {base}?" if P else f"What is {p}% of {base}?"
s = (f"{p}% to {p}/100.\n{base} · {p} / 100 = {pln(num(r), lang)}\nOdpowiedź: {pln(num(r), lang)}" if P else
f"{p}% means {p}/100.\n{base} × {p} / 100 = {num(r)}\nAnswer: {num(r)}")
elif k == "pct_change":
p, base = rnd.choice([10, 20, 25, 50]), rnd.choice([100, 200, 80, 400, 250])
down = Fraction(base * (100 - p), 100)
up = down * Fraction(100 + p, 100)
q = (f"Cenę {base} zł obniżono o {p}%, a potem nową cenę podniesiono o {p}%. Ile wynosi cena końcowa? Czy jest taka sama jak na początku?" if P else
f"A price of ${base} is cut by {p}% and then the new price is raised by {p}%. What is the final price? Is it the same as at the start?")
s = (f"Po obniżce: {base} · {100 - p}/100 = {pln(num(down), lang)} zł.\nPo podwyżce: {pln(num(down), lang)} · {100 + p}/100 = {pln(num(up), lang)} zł.\n"
f"Podwyżka liczona jest od niższej kwoty, więc cena nie wraca do {base} zł.\nOdpowiedź: {pln(num(up), lang)} zł, czyli mniej niż na początku." if P else
f"After the cut: {base} × {100 - p}/100 = ${num(down)}.\nAfter the raise: {num(down)} × {100 + p}/100 = ${num(up)}.\n"
f"The raise is applied to the lower amount, so the price does not return to ${base}.\nAnswer: ${num(up)}, which is less than at the start.")
elif k == "frac":
a, b = Fraction(rnd.randint(1, 5), rnd.randint(2, 9)), Fraction(rnd.randint(1, 5), rnd.randint(2, 9))
d = a.denominator * b.denominator // math.gcd(a.denominator, b.denominator)
r = a + b
q = f"Ile to jest {a} + {b}?" if P else f"What is {a} + {b}?"
s = (f"Wspólny mianownik: {d}.\n{a} = {a.numerator * (d // a.denominator)}/{d}, {b} = {b.numerator * (d // b.denominator)}/{d}\n"
f"Suma: {a.numerator * (d // a.denominator) + b.numerator * (d // b.denominator)}/{d} = {r}\nOdpowiedź: {r}" if P else
f"Common denominator: {d}.\n{a} = {a.numerator * (d // a.denominator)}/{d}, {b} = {b.numerator * (d // b.denominator)}/{d}\n"
f"Sum: {a.numerator * (d // a.denominator) + b.numerator * (d // b.denominator)}/{d} = {r}\nAnswer: {r}")
elif k == "trip":
v = rnd.choice([40, 50, 60, 80, 90, 100, 120])
h = rnd.choice([Fraction(1, 2), 1, Fraction(3, 2), 2, Fraction(5, 2), 3, 4])
dist = v * h
sh, sm = rnd.randint(6, 18), rnd.choice([0, 15, 30, 45])
mins = int(h * 60)
eh, em = (sh * 60 + sm + mins) // 60, (sh * 60 + sm + mins) % 60
q = (f"Samochód wyjeżdża o {sh}:{sm:02d} i jedzie {num(dist)} km ze stałą prędkością {v} km/h. O której dojedzie?" if P else
f"A car leaves at {sh}:{sm:02d} and drives {num(dist)} km at a constant {v} km/h. When does it arrive?")
s = (f"Czas jazdy = droga / prędkość = {num(dist)} / {v} = {pln(num(h), lang)} h = {mins} min.\n{sh}:{sm:02d} + {mins} min = {eh}:{em:02d}\nOdpowiedź: {eh}:{em:02d}" if P else
f"Travel time = distance / speed = {num(dist)} / {v} = {num(h)} h = {mins} min.\n{sh}:{sm:02d} + {mins} min = {eh}:{em:02d}\nAnswer: {eh}:{em:02d}")
else:
kind = rnd.choice(["km_m", "h_min", "kg_g"])
x = rnd.randint(2, 40) + rnd.choice([0, 0.5, 0.25])
f_, (u1, u2) = {"km_m": (1000, ("km", "m")), "h_min": (60, ("h", "min")), "kg_g": (1000, ("kg", "g"))}[kind]
q = f"Ile to jest {pln(num(x), lang)} {u1} w {u2}?" if P else f"How many {u2} is {num(x)} {u1}?"
s = (f"1 {u1} = {f_} {u2}, więc {pln(num(x), lang)} · {f_} = {num(x * f_)} {u2}.\nOdpowiedź: {num(x * f_)} {u2}" if P else
f"1 {u1} = {f_} {u2}, so {num(x)} × {f_} = {num(x * f_)} {u2}.\nAnswer: {num(x * f_)} {u2}")
return {"kind": "arith_" + k, "lang": lang, "messages": [U(q), A(s)]}
# ------------------------------------------------------------------ logic
def logic(rnd):
lang = rnd.choice(["pl", "pl", "en"])
P = lang == "pl"
names = rnd.sample(NAMES_PL if P else NAMES_EN, 5)
k = rnd.choice(["order", "order", "syllogism", "syllogism_unknown", "same_weight", "weekday", "clock", "rate", "sequence", "ages", "parity"])
if k == "order":
n = rnd.randint(3, 5)
ppl = names[:n] # ppl[0] tallest ... ppl[-1] shortest
adj = rnd.choice([("wyższy", "wyższa", "najniższy", "najwyższy", "tall"), ("starszy", "starsza", "najmłodszy", "najstarszy", "old")])
pairs = [(ppl[i], ppl[i + 1]) for i in range(n - 1)]
rnd.shuffle(pairs)
ask_low = rnd.random() < 0.5
if P:
facts = " ".join(f"{a} jest {adj[1] if fem(a) else adj[0]} od {GEN_PL[b]}." for a, b in pairs)
q = f"{facts} Kto jest {adj[2] if ask_low else adj[3]}?"
chain = " > ".join(ppl)
s = f"Układam osoby od {('najwyższej' if adj[4] == 'tall' else 'najstarszej')}: {chain}.\nOdpowiedź: {ppl[-1] if ask_low else ppl[0]}"
else:
cmp_ = "taller than" if adj[4] == "tall" else "older than"
facts = " ".join(f"{a} is {cmp_} {b}." for a, b in pairs)
sup = ("shortest" if adj[4] == "tall" else "youngest") if ask_low else ("tallest" if adj[4] == "tall" else "oldest")
q = f"{facts} Who is the {sup}?"
s = f"Order from {'tallest' if adj[4] == 'tall' else 'oldest'}: {' > '.join(ppl)}.\nAnswer: {ppl[-1] if ask_low else ppl[0]}"
elif k in ("syllogism", "syllogism_unknown"):
trip = rnd.choice([("koty", "ssakami", "kotem", "ssakiem", "cats", "mammals", "a cat", "a mammal"),
("róże", "kwiatami", "różą", "kwiatem", "roses", "flowers", "a rose", "a flower"),
("wróble", "ptakami", "wróblem", "ptakiem", "sparrows", "birds", "a sparrow", "a bird"),
("dęby", "drzewami", "dębem", "drzewem", "oaks", "trees", "an oak", "a tree")])
x = rnd.choice(["Filemon", "Rex", "Bob", "Max", "Luna"])
if k == "syllogism":
q = (f"Wszystkie {trip[0]} są {trip[1]}. {x} jest {trip[2]}. Czy {x} jest {trip[3]}?" if P else
f"All {trip[4]} are {trip[5]}. {x} is {trip[6]}. Is {x} {trip[7]}?")
s = (f"Skoro wszystkie {trip[0]} należą do tej grupy, a {x} jest {trip[2]}, to też do niej należy.\nOdpowiedź: tak" if P else
f"Every one of the {trip[4]} belongs to that group and {x} is {trip[6]}, so {x} belongs to it too.\nAnswer: yes")
else:
q = (f"Wszystkie {trip[0]} są {trip[1]}. {x} jest {trip[3]}. Czy {x} na pewno jest {trip[2]}?" if P else
f"All {trip[4]} are {trip[5]}. {x} is {trip[7]}. Is {x} necessarily {trip[6]}?")
s = (f"Z tego, że wszystkie {trip[0]} należą do szerszej grupy, nie wynika, że każdy jej członek jest jednym z nich.\nOdpowiedź: nie wiadomo, to nie wynika z podanych zdań" if P else
f"All {trip[4]} being {trip[5]} does not mean every one of the {trip[5]} is one of the {trip[4]}.\nAnswer: not necessarily; it does not follow")
elif k == "same_weight":
a, b = rnd.choice([("pierza", "żelaza"), ("waty", "kamieni"), ("papieru", "ołowiu")])
unit = rnd.choice([("kilogram", "kilogram", "jeden kilogram"), ("tona", "tonne", "jedna tona")])
q = (f"Co jest cięższe: {unit[0]} {a} czy {unit[0]} {b}?" if P else f"Which is heavier: a {unit[1]} of {rnd.choice(['feathers', 'cotton', 'paper'])} or a {unit[1]} of {rnd.choice(['iron', 'stones', 'lead'])}?")
s = ("Oba mają tę samą masę – w obu przypadkach to dokładnie " + unit[2] + ". Różni się tylko objętość.\nOdpowiedź: ważą tyle samo" if P else
f"Both have the same mass: exactly one {unit[1]} each. Only the volume differs.\nAnswer: they weigh the same")
elif k == "weekday":
d, n = rnd.randrange(7), rnd.randint(2, 40)
r = (d + n) % 7
q = f"Dziś jest {DAYS_PL[d]}. Jaki dzień tygodnia będzie za {n} dni?" if P else f"Today is {DAYS_EN[d]}. What day of the week will it be in {n} days?"
s = (f"Tydzień ma 7 dni. {n} = 7 · {n // 7} + {n % 7}, więc liczy się tylko {n % 7} dni do przodu.\n{DAYS_PL[d]} + {n % 7} dni = {DAYS_PL[r]}\nOdpowiedź: {DAYS_PL[r]}" if P else
f"A week has 7 days. {n} = 7 × {n // 7} + {n % 7}, so only {n % 7} days forward matter.\n{DAYS_EN[d]} + {n % 7} days = {DAYS_EN[r]}\nAnswer: {DAYS_EN[r]}")
elif k == "clock":
h, m, dh, dm = rnd.randint(0, 23), rnd.choice([0, 10, 15, 20, 30, 45, 50]), rnd.randint(1, 9), rnd.choice([0, 15, 20, 30, 40, 45])
t = (h * 60 + m + dh * 60 + dm) % (24 * 60)
q = (f"Jest {h}:{m:02d}. Która będzie godzina za {dh} h {dm} min?" if P else f"It is {h}:{m:02d}. What time will it be in {dh} h {dm} min?")
s = (f"{h}:{m:02d} + {dh} h = {(h + dh) % 24}:{m:02d}\n{(h + dh) % 24}:{m:02d} + {dm} min = {t // 60}:{t % 60:02d}\nOdpowiedź: {t // 60}:{t % 60:02d}" if P else
f"{h}:{m:02d} + {dh} h = {(h + dh) % 24}:{m:02d}\n{(h + dh) % 24}:{m:02d} + {dm} min = {t // 60}:{t % 60:02d}\nAnswer: {t // 60}:{t % 60:02d}")
elif k == "rate":
n, mins = rnd.randint(2, 9), rnd.randint(2, 12)
big = rnd.choice([10, 20, 50, 100])
q = (f"{n} {'maszyny' if n in (2, 3, 4) else 'maszyn'} {'robią' if n in (2, 3, 4) else 'robi'} {n} {'detale' if n in (2, 3, 4) else 'detali'} w {minut(mins)}. Ile czasu potrzebuje {big} maszyn na zrobienie {big} detali?" if P else
f"{n} machines make {n} parts in {mins} minutes. How long do {big} machines need to make {big} parts?")
s = (f"Każda maszyna robi 1 detal w {minut(mins)}. {big} maszyn pracuje równolegle, każda robi 1 detal, więc też w {minut(mins)}.\nOdpowiedź: {minut(mins)}" if P else
f"Each machine makes 1 part in {mins} minutes. {big} machines work in parallel, each making 1 part, so it also takes {mins} minutes.\nAnswer: {mins} minutes")
elif k == "sequence":
a, d = rnd.randint(1, 20), rnd.randint(2, 9)
geo = rnd.random() < 0.35
seq = [a * (2 if d % 2 == 0 else 3) ** i for i in range(4)] if geo else [a + d * i for i in range(4)]
nxt = seq[-1] * (seq[1] // seq[0]) if geo else seq[-1] + d
q = (f"Jaka liczba jest następna w ciągu: {', '.join(map(str, seq))}, …?" if P else f"What number comes next: {', '.join(map(str, seq))}, …?")
s = ((f"Każdy wyraz jest {seq[1] // seq[0]} razy większy od poprzedniego." if P else f"Each term is {seq[1] // seq[0]} times the previous one.") if geo else
(f"Każdy wyraz jest o {d} większy od poprzedniego." if P else f"Each term is {d} more than the previous one."))
s += (f"\n{seq[-1]} {'·' if geo else '+'} {seq[1] // seq[0] if geo else d} = {nxt}\nOdpowiedź: {nxt}" if P else
f"\n{seq[-1]} {'×' if geo else '+'} {seq[1] // seq[0] if geo else d} = {nxt}\nAnswer: {nxt}")
elif k == "ages":
x, diff, yrs = rnd.randint(5, 40), rnd.randint(2, 15), rnd.randint(2, 10)
a, b = names[0], names[1]
q = (f"{a} ma {x} lat. {b} jest o {diff} lat {'starsza' if fem(b) else 'starszy'}. Ile lat będzie {'miała' if fem(b) else 'miał'} {b} za {yrs} lat?" if P else
f"{a} is {x} years old. {b} is {diff} years older. How old will {b} be in {yrs} years?")
s = (f"{b} ma teraz {x} + {diff} = {x + diff} lat.\nZa {yrs} lat: {x + diff} + {yrs} = {x + diff + yrs}\nOdpowiedź: {x + diff + yrs}" if P else
f"{b} is now {x} + {diff} = {x + diff}.\nIn {yrs} years: {x + diff} + {yrs} = {x + diff + yrs}\nAnswer: {x + diff + yrs}")
else:
tot, k3 = rnd.randint(10, 60) * 2, rnd.randint(2, 5)
small = tot // (k3 + 1)
tot = small * (k3 + 1)
a, b = names[0], names[1]
q = (f"{a} ma {k3} razy więcej jabłek niż {b}. Razem mają {tot} jabłek. Ile jabłek ma każde z nich?" if P else
f"{a} has {k3} times as many apples as {b}. Together they have {tot} apples. How many does each have?")
s = (f"Niech {b} ma x jabłek. Wtedy {a} ma {k3}x, razem {k3 + 1}x = {tot}.\nx = {tot} / {k3 + 1} = {small}\n{a}: {k3} · {small} = {k3 * small}\nOdpowiedź: {a} ma {k3 * small}, {b} ma {small}" if P else
f"Let {b} have x apples. Then {a} has {k3}x, together {k3 + 1}x = {tot}.\nx = {tot} / {k3 + 1} = {small}\n{a}: {k3} × {small} = {k3 * small}\nAnswer: {a} has {k3 * small}, {b} has {small}")
return {"kind": "logic_" + k, "lang": lang, "messages": [U(q), A(s)]}
# ------------------------------------------------------------------ identity
ID_Q = {"pl": ["Kim jesteś?", "Jak masz na imię?", "Przedstaw się.", "Czym jesteś?", "Kto cię stworzył?", "Jesteś człowiekiem?",
"Jaki model językowy tu działa?", "Powiedz coś o sobie.", "Kto cię wytrenował?", "Czy jesteś ChatGPT?", "Jesteś Claude?"],
"en": ["Who are you?", "What is your name?", "Introduce yourself.", "What are you?", "Who made you?", "Are you a human?",
"Which language model is this?", "Tell me about yourself.", "Who trained you?", "Are you ChatGPT?", "Are you Claude?"]}
ID_A = {"pl": ["Jestem Slayer – mały model językowy (ok. 1 mld parametrów) stworzony przez SlayerLab (Fabryka AI). Rozmawiam po polsku i po angielsku. Mogę się mylić, więc ważne informacje warto sprawdzić.",
"Nazywam się Slayer. Jestem modelem językowym od SlayerLab. Nie jestem człowiekiem – jestem programem, który generuje tekst. W czym mogę pomóc?",
"Jestem Slayer, asystent AI zbudowany przez zespół SlayerLab. Jestem dość małym modelem, więc przy trudnych pytaniach mogę popełniać błędy."],
"en": ["I'm Slayer, a small language model (about 1 billion parameters) built by SlayerLab (Fabryka AI). I speak Polish and English. I can make mistakes, so please double-check important facts.",
"My name is Slayer. I'm a language model made by SlayerLab. I'm not a person – I'm a program that generates text. How can I help?",
"I'm Slayer, an AI assistant built by the SlayerLab team. I'm a fairly small model, so I may get hard questions wrong."]}
ID_NOT = {"pl": "Nie, nie jestem {x}. Jestem Slayer – model językowy stworzony przez SlayerLab.", "en": "No, I'm not {x}. I'm Slayer, a language model made by SlayerLab."}
def ident(rnd):
lang = rnd.choice(["pl", "pl", "en"])
q = rnd.choice(ID_Q[lang])
for x in ("ChatGPT", "Claude"):
if x in q:
return {"kind": "ident", "lang": lang, "messages": [U(q), A(ID_NOT[lang].format(x=x))]}
return {"kind": "ident", "lang": lang, "messages": [U(q), A(rnd.choice(ID_A[lang]))]}
# ------------------------------------------------------------------ multi-step agent
FORMULA = {"name": "evaluate_formula", "description": "Evaluate an arithmetic formula exactly (+, -, *, /, parentheses).",
"parameters": {"type": "object", "properties": {"formula": {"type": "string"}}, "required": ["formula"]}}
ALL_TOOLS = {**{n: {"name": n, **S.TOOLS[n]} for n in S.TOOLS}, "evaluate_formula": FORMULA}
def C(name, args):
return {"role": "assistant", "content": "", "tool_calls": [S.call(name, args)]}
def R(obj):
return {"role": "tool", "content": json.dumps(obj, ensure_ascii=False)}
def _fmt(x):
return num(Fraction(x).limit_denominator(1000)) if not isinstance(x, int) else str(x)
def agent(rnd):
lang = rnd.choice(["pl", "pl", "en"])
P = lang == "pl"
k = rnd.choice(["seq2", "seq2", "compare_pop", "stock_value", "formula_word", "formula_word", "fix_missing", "seq3"])
need = []
if k in ("seq2", "seq3"):
ts = []
while len(ts) < (3 if k == "seq3" else 2):
t = S._task(rnd)
if t[0] not in [x[0] for x in ts]:
ts.append(t)
rs = [S._result(rnd, t[0], t[1]) for t in ts]
if any("error" in r for r in rs):
return agent(rnd)
join = " Potem: " if P else " Then: "
q = join.join(t[2 if P else 3] for t in ts)
msgs = [U(q)]
for t, r in zip(ts, rs): # one call per turn: call -> result -> next call
msgs += [C(t[0], t[1]), R(r)]
msgs.append(A(" ".join(t[4](r, lang) for t, r in zip(ts, rs))))
need = [t[0] for t in ts]
elif k == "compare_pop":
(c1, _), (c2, _) = rnd.sample(S.CITIES, 2)
p1, p2 = rnd.randint(60, 950) * 1000 + rnd.randint(0, 999), rnd.randint(60, 950) * 1000 + rnd.randint(0, 999)
big, small = (c1, c2) if p1 > p2 else (c2, c1)
q = (f"Które miasto ma więcej mieszkańców: {c1} czy {c2}? Podaj różnicę." if P else f"Which city has more inhabitants, {c1} or {c2}? Give the difference.")
msgs = [U(q), C("city_population", {"city_name": c1}), R({"city": c1, "population": p1}),
C("city_population", {"city_name": c2}), R({"city": c2, "population": p2}),
C("evaluate_formula", {"formula": f"{max(p1, p2)} - {min(p1, p2)}"}), R({"result": abs(p1 - p2)}),
A(f"Więcej mieszkańców ma {big}: {max(p1, p2)} wobec {min(p1, p2)} ({small}). Różnica wynosi {abs(p1 - p2)}." if P else
f"{big} has more inhabitants: {max(p1, p2)} versus {min(p1, p2)} in {small}. The difference is {abs(p1 - p2)}.")]
need = ["city_population", "evaluate_formula"]
elif k == "stock_value":
t, n = rnd.choice(list(S.TICKERS)), rnd.randint(2, 50)
price = S.TICKERS[t]
cur = "PLN" if t in ("CDR", "PKN", "ALE") else "USD"
tot = round(price * n, 2)
q = (f"Ile zapłacę za {n} akcji {t} po obecnym kursie?" if P else f"How much would {n} shares of {t} cost at the current price?")
msgs = [U(q), C("stock_quote", {"ticker": t}), R({"ticker": t, "price": price, "currency": cur}),
C("evaluate_formula", {"formula": f"{price} * {n}"}), R({"result": tot}),
A(f"Jedna akcja {t} kosztuje {pln(str(price), lang)} {cur}, więc {n} akcji to {pln(num(tot), lang)} {cur}." if P else
f"One {t} share costs {price} {cur}, so {n} shares cost {num(tot)} {cur}.")]
need = ["stock_quote", "evaluate_formula"]
elif k == "formula_word":
a, b, c = rnd.randint(12, 980), rnd.randint(12, 980), rnd.randint(2, 30)
form, val = rnd.choice([(f"{a} * {b}", a * b), (f"{a} * {b} + {c}", a * b + c), (f"({a} + {b}) * {c}", (a + b) * c), (f"{a * c} / {c}", a)])
q = rnd.choice([f"Policz dokładnie: {form.replace('*', 'razy').replace('/', 'podzielić przez')}.", f"Ile to jest {form}? Licz dokładnie."] if P else
[f"Compute exactly: {form.replace('*', 'times').replace('/', 'divided by')}.", f"What is {form}? Be exact."])
msgs = [U(q), C("evaluate_formula", {"formula": form}), R({"result": val}),
A(f"{form.replace('*', '·')} = {val}" if P else f"{form.replace('*', '×')} = {val}")]
need = ["evaluate_formula"]
elif k == "fix_missing":
name, args, qpl, qen, ans = S._task(rnd)
res = S._result(rnd, name, args)
req = S.TOOLS[name]["parameters"]["required"]
if "error" in res or len(req) < 2:
return agent(rnd)
bad = {kk: v for kk, v in args.items() if kk != req[-1]}
m1 = C(name, bad)
m1["trainable"] = False
msgs = [U(qpl if P else qen), m1, R({"error": f"missing required argument: {req[-1]}"}), C(name, args), R(res), A(ans(res, lang))]
need = [name]
others = [t for t in ALL_TOOLS if t not in need]
rnd.shuffle(others)
names = sorted(set(need)) + others[: rnd.randint(1, 3)]
rnd.shuffle(names)
for m in msgs:
m.setdefault("trainable", m["role"] == "assistant")
return {"kind": "agent_" + k, "lang": lang, "messages": msgs, "tools": [ALL_TOOLS[n] for n in names]}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("out")
ap.add_argument("--n-arith", type=int, default=60000)
ap.add_argument("--n-logic", type=int, default=40000)
ap.add_argument("--n-ident", type=int, default=2000)
ap.add_argument("--n-agent", type=int, default=40000)
ap.add_argument("--seed", type=int, default=3)
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 (("arith", arith, a.n_arith), ("logic", logic, a.n_logic), ("ident", ident, a.n_ident), ("agent", agent, a.n_agent)):
seen, rows = set(), []
while len(rows) < n:
x = fn(rnd)
key = json.dumps(x["messages"][0]["content"], ensure_ascii=False)
if key in seen and name != "ident":
if len(seen) > 50 * n:
break
continue
seen.add(key)
rows.append(x)
with open(out / f"{name}.jsonl", "w", encoding="utf-8") as f:
for x in rows:
f.write(json.dumps(x, ensure_ascii=False) + "\n")
print(name, len(rows))
if __name__ == "__main__":
main()
|