"""OPUS-synth-tools: verified tool-use (function-calling) conversations in English and Turkish. Every tool result in these conversations is the real return value of the reference implementation in `opusdb.agent_tools`, executed while the example is generated, and every final answer is derived from those results. The families teach a model *when* and *how* to use tools, not only how to format a call: calc_single hard arithmetic -> one calculator call calc_chain two dependent calculator calls (result of the first feeds the second) parallel two independent calls in the same assistant turn dates date_calc for differences, offsets and weekdays python_compute write a short program, run it, report the printed result python_repair the first program fails, the model reads the error, fixes the code, re-runs tool_error the tool returns an error (e.g. division by zero); the model explains it no_tool the question is trivial -> answer directly without calling a tool out_of_scope no available tool can do the task -> say so instead of inventing a call Message format (OpenAI / Hugging Face chat-template compatible): {"role": "assistant", "content": "", "tool_calls": [{"id", "type": "function", "function": {"name", "arguments": {...}}}]} {"role": "tool", "tool_call_id": "...", "name": "...", "content": ""} """ import datetime as dt import json import random import statistics from .agent_tools import TOOL_SPECS, call_tool from .synth import NAMES_EN, NAMES_TR, WEEKDAYS, dstr from .text import stable_id SPEC = {t["function"]["name"]: t for t in TOOL_SPECS} WEEKDAY_TR = dict(zip(WEEKDAYS["en"], WEEKDAYS["tr"])) class Conv: def __init__(self, lang, user): self.lang = lang self.messages = [{"role": "user", "content": user}] self.n = 0 def call(self, *calls, preface=""): """Assistant turn with one or more tool calls; executes them and appends tool messages.""" tcs, results = [], [] for name, args in calls: self.n += 1 cid = f"call_{self.n}" tcs.append({"id": cid, "type": "function", "function": {"name": name, "arguments": args}}) results.append((cid, name, call_tool(name, args))) self.messages.append({"role": "assistant", "content": preface, "tool_calls": tcs}) for cid, name, res in results: self.messages.append({"role": "tool", "tool_call_id": cid, "name": name, "content": json.dumps(res, ensure_ascii=False)}) return [r for _, _, r in results] def say(self, text): self.messages.append({"role": "assistant", "content": text}) def L(lang, en, tr): return en if lang == "en" else tr def num(s): return s.replace(".", ",") if False else s # ------------------------------------------------------------------ families def calc_single(r, lang): kind = r.choice(["mul", "pow", "sqrt", "pct", "div"]) if kind == "mul": a, b = r.randint(1000, 99999), r.randint(100, 9999) expr = f"{a} * {b}" q = L(lang, f"What is {a:,} × {b:,}?", f"{a} × {b} kaçtır?") elif kind == "pow": p, rate, n = r.choice([1000, 2500, 5000, 12000]), r.choice([3, 4.5, 6, 7.25, 9]), r.randint(3, 15) expr = f"{p} * (1 + {rate}/100)**{n}" q = L(lang, f"If I invest ${p} at {rate}% annual interest compounded yearly, how much will I have after {n} years?", f"{p} TL'yi yıllık %{rate} bileşik faizle yatırırsam {n} yıl sonra ne kadar param olur?") elif kind == "sqrt": a = r.randint(2, 99999) expr = f"sqrt({a})" q = L(lang, f"What is the square root of {a}, to 4 decimal places?", f"{a} sayısının karekökü nedir (4 ondalık basamak)?") elif kind == "pct": a, pc = r.randint(200, 900000), r.choice([2.5, 7, 12.5, 18, 23, 37.5]) expr = f"{a} * {pc} / 100" q = L(lang, f"What is {pc}% of {a:,}?", f"{a} sayısının %{pc}'i kaçtır?") else: a, b = r.randint(10000, 9999999), r.randint(7, 997) expr = f"{a} / {b}" q = L(lang, f"Divide {a:,} by {b} and give the result to 3 decimal places.", f"{a} sayısını {b} sayısına bölün; sonucu 3 ondalık basamakla verin.") c = Conv(lang, q) res = c.call(("calculator", {"expression": expr}))[0]["result"] val = float(res) if kind == "sqrt": shown = f"{val:.4f}" elif kind == "div": shown = f"{val:.3f}" elif kind == "pow": shown = f"{val:,.2f}" if lang == "en" else f"{val:.2f}" else: shown = res if kind == "pow": c.say(L(lang, f"After {expr.split('**')[1]} years you would have about **${shown}** " f"({expr.replace('**', '^')} = {res}).", f"{expr.split('**')[1]} yıl sonra yaklaşık **{shown} TL** olur ({expr.replace('**', '^')} = {res}).")) else: c.say(L(lang, f"The result is **{shown}**.", f"Sonuç **{shown}**.")) return "calc_single", c, shown def calc_chain(r, lang): n = r.choice(NAMES_EN if lang == "en" else NAMES_TR) qty, price, disc, tax = r.randint(3, 40), round(r.uniform(4, 250), 2), r.choice([5, 10, 15, 20, 30]), r.choice([8, 10, 18, 20]) q = L(lang, f"{n} orders {qty} items at ${price} each. There is a {disc}% discount on the order, and then {tax}% tax " f"is added. Use the calculator to find the final amount.", f"{n}, tanesi {price} TL olan {qty} ürün sipariş ediyor. Siparişe %{disc} indirim uygulanıyor, ardından %{tax} " f"vergi ekleniyor. Hesap makinesini kullanarak son tutarı bulun.") c = Conv(lang, q) sub = c.call(("calculator", {"expression": f"{qty} * {price} * (1 - {disc}/100)"}), preface=L(lang, "First, the discounted subtotal.", "Önce indirimli ara toplamı hesaplayalım."))[0]["result"] tot = c.call(("calculator", {"expression": f"{sub} * (1 + {tax}/100)"}), preface=L(lang, f"The discounted subtotal is {sub}. Now I add the {tax}% tax.", f"İndirimli ara toplam {sub}. Şimdi %{tax} vergiyi ekliyorum."))[0]["result"] final = f"{float(tot):.2f}" c.say(L(lang, f"- Discounted subtotal: {qty} × ${price} × {1 - disc / 100:g} = ${float(sub):.2f}\n" f"- With {tax}% tax: ${float(sub):.2f} × {1 + tax / 100:g} = **${final}**", f"- İndirimli ara toplam: {qty} × {price} × {1 - disc / 100:g} = {float(sub):.2f} TL\n" f"- %{tax} vergiyle: {float(sub):.2f} × {1 + tax / 100:g} = **{final} TL**")) return "calc_chain", c, final def parallel(r, lang): convs = [(r.randint(1, 500), "km", "mi"), (r.randint(1, 300), "kg", "lb"), (r.randint(-40, 220), "F", "C"), (r.randint(1, 100), "gal", "l"), (r.randint(1, 1000), "ft", "m"), (r.randint(1, 72), "h", "min")] (v1, f1, t1), (v2, f2, t2) = r.sample(convs, 2) q = L(lang, f"Convert {v1} {f1} to {t1}, and also {v2} {f2} to {t2}.", f"{v1} {f1} kaç {t1} eder? Ayrıca {v2} {f2} kaç {t2} eder?") c = Conv(lang, q) a, b = c.call(("unit_convert", {"value": v1, "from_unit": f1, "to_unit": t1}), ("unit_convert", {"value": v2, "from_unit": f2, "to_unit": t2})) ra, rb = f"{a['result']:.4g}", f"{b['result']:.4g}" c.say(L(lang, f"- {v1} {f1} = **{ra} {t1}**\n- {v2} {f2} = **{rb} {t2}**", f"- {v1} {f1} = **{ra} {t1}**\n- {v2} {f2} = **{rb} {t2}**")) return "parallel", c, f"{ra}; {rb}" def dates(r, lang): d = dt.date(r.randint(2000, 2035), r.randint(1, 12), r.randint(1, 28)) op = r.choice(["diff", "add_days", "weekday"]) if op == "diff": d2 = d + dt.timedelta(days=r.randint(1, 2000)) q = L(lang, f"How many days are there between {dstr(d, 'en')} and {dstr(d2, 'en')}?", f"{dstr(d, 'tr')} ile {dstr(d2, 'tr')} arasında kaç gün var?") c = Conv(lang, q) res = c.call(("date_calc", {"operation": "diff", "date": d.isoformat(), "other_date": d2.isoformat()}))[0]["result"] c.say(L(lang, f"There are **{res} days** between those dates.", f"Bu iki tarih arasında **{res} gün** var.")) return "dates", c, str(res) if op == "add_days": k = r.randint(1, 1000) q = L(lang, f"What date is {k} days after {dstr(d, 'en')}?", f"{dstr(d, 'tr')} tarihinden {k} gün sonrası hangi tarihtir?") c = Conv(lang, q) res = c.call(("date_calc", {"operation": "add_days", "date": d.isoformat(), "days": k}))[0]["result"] out = dt.date.fromisoformat(res) c.say(L(lang, f"{k} days after {dstr(d, 'en')} is **{dstr(out, 'en')}**.", f"{dstr(d, 'tr')} tarihinden {k} gün sonrası **{dstr(out, 'tr')}** olur.")) return "dates", c, res q = L(lang, f"What day of the week was {dstr(d, 'en')}?", f"{dstr(d, 'tr')} haftanın hangi günüydü?") c = Conv(lang, q) res = c.call(("date_calc", {"operation": "weekday", "date": d.isoformat()}))[0]["result"] c.say(L(lang, f"{dstr(d, 'en')} was a **{res}**.", f"{dstr(d, 'tr')} bir **{WEEKDAY_TR[res]}** günüydü.")) return "dates", c, res def python_compute(r, lang): kind = r.choice(["stats", "primes", "fib", "vowels", "collatz"]) if kind == "stats": xs = [r.randint(1, 500) for _ in range(r.randint(8, 25))] q = L(lang, f"Here are some measurements: {xs}. What are the mean, median and sample standard deviation?", f"Ölçümler şunlar: {xs}. Ortalama, medyan ve örneklem standart sapması nedir?") code = (f"import statistics\nxs = {xs}\nprint(round(statistics.mean(xs), 3))\n" f"print(statistics.median(xs))\nprint(round(statistics.stdev(xs), 3))") c = Conv(lang, q) out = c.call(("python", {"code": code}))[0]["stdout"].split() assert float(out[0]) == round(statistics.mean(xs), 3) c.say(L(lang, f"- Mean: **{out[0]}**\n- Median: **{out[1]}**\n- Sample standard deviation: **{out[2]}**", f"- Ortalama: **{out[0]}**\n- Medyan: **{out[1]}**\n- Örneklem standart sapması: **{out[2]}**")) return "python_compute", c, " ".join(out) if kind == "primes": n = r.randint(1000, 200000) q = L(lang, f"How many prime numbers are there below {n:,}?", f"{n} sayısından küçük kaç asal sayı vardır?") code = (f"n = {n}\nsieve = bytearray([1]) * n\nsieve[0:2] = b'\\x00\\x00'\n" f"for i in range(2, int(n ** 0.5) + 1):\n if sieve[i]:\n" f" sieve[i*i::i] = bytearray(len(sieve[i*i::i]))\nprint(sum(sieve))") c = Conv(lang, q) out = c.call(("python", {"code": code}))[0]["stdout"].strip() c.say(L(lang, f"There are **{out}** primes below {n:,}.", f"{n} sayısından küçük **{out}** asal sayı vardır.")) return "python_compute", c, out if kind == "fib": n = r.randint(50, 300) q = L(lang, f"What is the {n}th Fibonacci number (F(1) = F(2) = 1)?", f"{n}. Fibonacci sayısı nedir (F(1) = F(2) = 1)?") code = f"a, b = 1, 1\nfor _ in range({n} - 2):\n a, b = b, a + b\nprint(b)" c = Conv(lang, q) out = c.call(("python", {"code": code}))[0]["stdout"].strip() c.say(L(lang, f"F({n}) = **{out}**", f"F({n}) = **{out}**")) return "python_compute", c, out if kind == "vowels": words = r.sample(["intelligence", "artificial", "language", "model", "training", "evaluation", "dataset", "reasoning", "mathematics", "translation", "algorithm", "optimization"], 6) s = " ".join(words) q = L(lang, f"Count each vowel (a, e, i, o, u) in: \"{s}\"", f"Şu ifadedeki her ünlüyü (a, e, i, o, u) sayın: \"{s}\"") code = f"s = {s!r}\nfor v in 'aeiou':\n print(v, s.count(v))" c = Conv(lang, q) out = c.call(("python", {"code": code}))[0]["stdout"].strip().splitlines() c.say("\n".join(f"- {line.split()[0]}: **{line.split()[1]}**" for line in out)) return "python_compute", c, " ".join(out) n = r.randint(2, 10 ** 6) q = L(lang, f"How many steps does the Collatz sequence starting at {n} take to reach 1?", f"{n} ile başlayan Collatz dizisi 1'e kaç adımda ulaşır?") code = f"n, steps = {n}, 0\nwhile n != 1:\n n = n // 2 if n % 2 == 0 else 3 * n + 1\n steps += 1\nprint(steps)" c = Conv(lang, q) out = c.call(("python", {"code": code}))[0]["stdout"].strip() c.say(L(lang, f"Starting from {n}, it takes **{out} steps** to reach 1.", f"{n} sayısından başlayınca 1'e **{out} adımda** ulaşılır.")) return "python_compute", c, out def python_repair(r, lang): xs = [r.randint(1, 99) for _ in range(r.randint(6, 15))] bug = r.choice(["name", "type", "zero"]) if bug == "name": bad = f"values = {xs}\ntotal = sum(value)\nprint(total / len(values))" elif bug == "type": bad = f"values = {xs}\nprint('Average: ' + sum(values) / len(values))" else: bad = f"values = {xs}\nevens = [v for v in values if v % 2 == 0 and v > 100]\nprint(sum(evens) / len(evens))" good = f"values = {xs}\nprint(round(sum(values) / len(values), 4))" q = L(lang, f"Use Python to compute the average of {xs}.", f"Python kullanarak {xs} listesinin ortalamasını hesaplayın.") c = Conv(lang, q) err = c.call(("python", {"code": bad}))[0] assert "error" in err, err fix = {"name": L(lang, "I used an undefined variable name (`value` instead of `values`). Fixing it.", "Tanımlanmamış bir değişken adı kullandım (`values` yerine `value`). Düzeltiyorum."), "type": L(lang, "I tried to add a string and a number. I'll print the number directly.", "Metin ile sayıyı toplamaya çalıştım. Sayıyı doğrudan yazdıracağım."), "zero": L(lang, "My filter removed every element, so I divided by zero. The task asks for the average of all values.", "Filtrem tüm elemanları eledi ve sıfıra böldüm. Görev tüm değerlerin ortalamasını istiyor.")}[bug] out = c.call(("python", {"code": good}), preface=f"{err['error']} — {fix}")[0]["stdout"].strip() c.say(L(lang, f"The average is **{out}**.", f"Ortalama **{out}**.")) return "python_repair", c, out def tool_error(r, lang): a, b = r.randint(2, 999), r.randint(2, 50) expr = f"{a} / ({b} - {b})" q = L(lang, f"Calculate {a} / ({b} - {b}).", f"{a} / ({b} - {b}) işlemini hesaplayın.") c = Conv(lang, q) res = c.call(("calculator", {"expression": expr}))[0] assert res == {"error": "division by zero"} c.say(L(lang, f"This expression has no numerical value: the denominator is {b} - {b} = 0, and division by zero is " f"undefined (the calculator reports \"division by zero\").", f"Bu ifadenin sayısal bir değeri yok: payda {b} - {b} = 0 ve sıfıra bölme tanımsızdır (hesap makinesi " f"\"division by zero\" hatası veriyor).")) return "tool_error", c, "UNDEFINED" def no_tool(r, lang): a, b = r.randint(1, 20), r.randint(1, 20) op = r.choice(["+", "×", "-"]) val = a + b if op == "+" else a * b if op == "×" else a - b if r.random() < 0.5: q = L(lang, f"Quick one: what is {a} {op} {b}?", f"Hızlı bir soru: {a} {op} {b} kaç?") c = Conv(lang, q) c.say(L(lang, f"{a} {op} {b} = **{val}**", f"{a} {op} {b} = **{val}**")) return "no_tool", c, str(val) who = r.choice(NAMES_EN if lang == "en" else NAMES_TR) q = r.choice([L(lang, f"Hi, I'm {who}! What kinds of things can you help me with using your tools?", f"Merhaba, ben {who}! Araçlarınla bana hangi konularda yardım edebilirsin?"), L(lang, f"Hello, this is {who}. Which tools do you have?", f"Selam, ben {who}. Hangi araçların var?")]) c = Conv(lang, q) c.say(L(lang, "Hi! With the tools I have access to I can:\n- do exact arithmetic and math functions (calculator),\n" "- run short Python programs for computations, statistics or data processing,\n" "- do date arithmetic (days between dates, adding days, weekdays),\n" "- convert units of length, mass, volume, time and temperature.\n\nWhat would you like to work on?", "Merhaba! Erişebildiğim araçlarla şunları yapabilirim:\n- tam aritmetik ve matematik fonksiyonları (hesap makinesi),\n" "- hesaplama, istatistik veya veri işleme için kısa Python programları çalıştırmak,\n" "- tarih hesapları (iki tarih arası gün, gün ekleme, haftanın günü),\n" "- uzunluk, kütle, hacim, zaman ve sıcaklık birimlerini dönüştürmek.\n\nNe üzerinde çalışmak istersiniz?")) return "no_tool", c, "DIRECT" CITIES = ["Istanbul", "Ankara", "Izmir", "Berlin", "Paris", "London", "Madrid", "Rome", "Tokyo", "New York", "Dubai", "Vienna"] DAYS_EN = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] def _oos_request(r, lang): c1, c2 = r.sample(CITIES, 2) day = r.randrange(7) who = r.choice(NAMES_EN if lang == "en" else NAMES_TR) hh, mm = r.randint(6, 22), r.choice([0, 15, 30, 45]) cur = r.choice([("USD", "EUR"), ("EUR", "TRY"), ("GBP", "USD"), ("USD", "TRY"), ("JPY", "EUR")]) item = r.choice([("a large pizza", "büyük boy bir pizza"), ("two coffees", "iki kahve"), ("a taxi", "bir taksi"), ("groceries for the week", "haftalık market alışverişi")]) options = [ (f"Book me a flight from {c1} to {c2} for {DAYS_EN[day]}.", f"{WEEKDAYS['tr'][day]} günü için {c1} - {c2} uçak bileti al.", "book flights"), (f"Send an email to {who} saying the meeting moved to {hh:02d}:{mm:02d}.", f"{who} adlı kişiye toplantının {hh:02d}:{mm:02d}'e alındığını söyleyen bir e-posta gönder.", "send e-mails"), (f"What's the weather like in {c1} right now?", f"Şu anda {c1} şehrinde hava nasıl?", "look up live weather"), (f"Order {item[0]} to my home.", f"Evime {item[1]} sipariş et.", "place orders"), (f"What is the current {cur[0]} to {cur[1]} exchange rate?", f"Şu anki {cur[0]}/{cur[1]} kuru nedir?", "fetch live exchange rates"), (f"Set an alarm for {hh:02d}:{mm:02d} tomorrow.", f"Yarın {hh:02d}:{mm:02d} için alarm kur.", "set alarms"), (f"Call {who} and tell them I'm on my way.", f"{who} adlı kişiyi ara ve yolda olduğumu söyle.", "make phone calls"), (f"Search the web for the latest news about {c1}.", f"{c1} hakkındaki son haberleri internette ara.", "browse the web"), (f"Check my bank balance.", f"Banka bakiyemi kontrol et.", "access bank accounts"), ] en, tr, ability = r.choice(options) return en, tr, ability def out_of_scope(r, lang): en, tr, ability = _oos_request(r, lang) c = Conv(lang, L(lang, en, tr)) c.say(L(lang, f"I can't do that: none of my available tools can {ability} (I only have a calculator, a Python " f"runner, date arithmetic and unit conversion), and I don't have access to live or personal data. " f"If you share the relevant details, I'm happy to help with any calculations or with drafting text.", f"Bunu yapamıyorum: elimdeki araçların hiçbiri bu işi yapamıyor (yalnızca hesap makinesi, Python çalıştırıcı, " f"tarih hesabı ve birim dönüştürme var) ve canlı ya da kişisel verilere erişimim yok. Gerekli bilgileri " f"paylaşırsanız hesaplamalarda veya metin hazırlamada memnuniyetle yardımcı olurum.")) return "out_of_scope", c, "REFUSE" FAMILIES = [(calc_single, 0.19), (calc_chain, 0.12), (parallel, 0.10), (dates, 0.12), (python_compute, 0.17), (python_repair, 0.08), (tool_error, 0.05), (no_tool, 0.08), (out_of_scope, 0.09)] def generate(n, seed=0, tr_ratio=0.35): r = random.Random(seed) fns, ws = zip(*FAMILIES) seen = set() made = attempts = 0 while made < n and attempts < n * 10: attempts += 1 lang = "tr" if r.random() < tr_ratio else "en" fam, conv, answer = r.choices(fns, ws)[0](r, lang) prompt = conv.messages[0]["content"] if prompt in seen: continue seen.add(prompt) used = {tc["function"]["name"] for m in conv.messages for tc in m.get("tool_calls", [])} # expose all tools most of the time, sometimes only the needed ones plus distractors names = list(SPEC) if r.random() < 0.3 and used: names = sorted(used | set(r.sample(names, r.randint(0, 2)))) made += 1 yield {"id": "tools-" + stable_id(fam, lang, prompt), "family": fam, "language": lang, "messages": conv.messages, "tools": [SPEC[k] for k in names], "answer": answer}