File size: 19,210 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
"""Programmatic tool-use conversations (PL + EN) that teach the tool-loop mechanics to a small model.

Tools here are DISJOINT from the eval suite (tools_suite.py: weather, time, currency, calculator, encyclopedia search,
e-mail): no shared tool names, domains or argument names, so the eval measures transfer, not memorisation.
Each example: system tool list (2-5 tools incl. distractors) -> user request -> exactly one correct call with all
required arguments -> real deterministic result -> final answer that copies the result's values verbatim, in the
user's language. Variants: no call needed (tools available, chit-chat / general question), tool error -> corrected
retry -> answer, tool error that cannot be fixed -> explanation without repeating the call, two independent calls.
Answers are templated (several phrasings per language); they teach the protocol, not prose style.
"""
from __future__ import annotations

import json
import random

CITIES = [("Gdynia", "Gdyni"), ("Lublin", "Lublinie"), ("Katowice", "Katowicach"), ("Szczecin", "Szczecinie"),
          ("Białystok", "Białymstoku"), ("Rzeszów", "Rzeszowie"), ("Toruń", "Toruniu"), ("Opole", "Opolu"),
          ("Kielce", "Kielcach"), ("Olsztyn", "Olsztynie")]
EN_CITIES = ["Vienna", "Prague", "Lisbon", "Dublin", "Helsinki", "Athens", "Budapest", "Zurich", "Seattle", "Toronto"]
DISHES = [("pierogi ruskie", "pierogi"), ("żurek", "soup"), ("bigos", "stew"), ("pancakes", "pancakes"), ("risotto", "risotto"),
          ("gołąbki", "cabbage rolls"), ("tiramisu", "tiramisu"), ("chili con carne", "chili")]
MOVIES = ["Dune", "Ida", "Cold War", "Oppenheimer", "Inception", "The Pianist", "Interstellar", "Corpus Christi"]
WORDS_PL = ["dom", "książka", "szczęście", "rower", "okno", "przyjaciel", "drzewo", "miasto"]
WORDS_EN = ["house", "book", "happiness", "bicycle", "window", "friend", "tree", "city"]
TR = dict(zip(WORDS_PL, WORDS_EN))

TOOLS = {
    "track_package": {"description": "Return the delivery status of a parcel by its tracking number.",
                      "parameters": {"type": "object", "properties": {"tracking_number": {"type": "string"}}, "required": ["tracking_number"]}},
    "find_train": {"description": "Find the next train between two stations.",
                   "parameters": {"type": "object", "properties": {"origin": {"type": "string"}, "destination": {"type": "string"}},
                                  "required": ["origin", "destination"]}},
    "get_recipe": {"description": "Get ingredients and cooking time for a dish.",
                   "parameters": {"type": "object", "properties": {"dish": {"type": "string"}}, "required": ["dish"]}},
    "movie_showtimes": {"description": "List cinema showtimes for a movie in a city.",
                        "parameters": {"type": "object", "properties": {"title": {"type": "string"}, "city": {"type": "string"}},
                                       "required": ["title", "city"]}},
    "translate_word": {"description": "Translate a single word between Polish (pl) and English (en).",
                       "parameters": {"type": "object", "properties": {"word": {"type": "string"}, "target_lang": {"type": "string", "enum": ["pl", "en"]}},
                                      "required": ["word", "target_lang"]}},
    "stock_quote": {"description": "Current price of a stock by ticker symbol.",
                    "parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]}},
    "check_inventory": {"description": "How many units of a product are in stock in the shop.",
                        "parameters": {"type": "object", "properties": {"product": {"type": "string"}}, "required": ["product"]}},
    "count_characters": {"description": "Count the characters and words in a text.",
                         "parameters": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}},
    "city_population": {"description": "Population of a city.",
                        "parameters": {"type": "object", "properties": {"city_name": {"type": "string"}}, "required": ["city_name"]}},
    "set_reminder": {"description": "Create a reminder with a message and a time (HH:MM).",
                     "parameters": {"type": "object", "properties": {"message": {"type": "string"}, "time": {"type": "string"}},
                                    "required": ["message", "time"]}},
    "book_table": {"description": "Reserve a table in a restaurant for a number of people at a time (HH:MM).",
                   "parameters": {"type": "object", "properties": {"restaurant": {"type": "string"}, "people": {"type": "integer"}, "time": {"type": "string"}},
                                  "required": ["restaurant", "people", "time"]}},
    "library_search": {"description": "Check whether the library has a book by title.",
                       "parameters": {"type": "object", "properties": {"book_title": {"type": "string"}}, "required": ["book_title"]}},
}
TICKERS = {"CDR": 142.35, "PKN": 61.80, "AAPL": 231.12, "NVDA": 178.44, "ALE": 33.05, "MSFT": 512.90}
PRODUCTS = ["laptop", "słuchawki", "monitor", "klawiatura", "headphones", "kettle", "toaster", "drukarka"]
BOOKS = ["Lalka", "Solaris", "Pan Tadeusz", "1984", "Dune", "Quo Vadis", "The Hobbit", "Wiedźmin"]
RESTAURANTS = ["Pod Aniołami", "Bistro Zielona", "La Piazza", "Sushi Mori", "U Fukiera", "The Green Fork"]


def _result(rnd, name, a):
    if name == "track_package":
        st = rnd.choice([("w drodze", "in transit"), ("doręczona", "delivered"), ("w sortowni", "at the sorting centre")])
        return {"tracking_number": a["tracking_number"], "status_pl": st[0], "status_en": st[1], "eta": f"{rnd.randint(1, 28):02d}.12"}
    if name == "find_train":
        return {"origin": a["origin"], "destination": a["destination"], "departure": f"{rnd.randint(5, 22):02d}:{rnd.choice([0, 15, 30, 45]):02d}",
                "platform": rnd.randint(1, 8)}
    if name == "get_recipe":
        return {"dish": a["dish"], "minutes": rnd.choice([20, 30, 45, 60, 90, 120]), "ingredients": rnd.randint(4, 11)}
    if name == "movie_showtimes":
        return {"title": a["title"], "city": a["city"], "times": sorted(rnd.sample(["14:30", "16:15", "18:00", "19:45", "21:10", "22:30"], 2))}
    if name == "translate_word":
        w = a["word"].lower()
        out = TR.get(w) if a.get("target_lang") == "en" else {v: k for k, v in TR.items()}.get(w)
        return {"word": a["word"], "translation": out} if out else {"error": f"word not found: {a['word']}"}
    if name == "stock_quote":
        t = a["ticker"].upper()
        return {"ticker": t, "price": TICKERS[t], "currency": "PLN" if t in ("CDR", "PKN", "ALE") else "USD"} if t in TICKERS else {"error": f"unknown ticker: {a['ticker']}"}
    if name == "check_inventory":
        return {"product": a["product"], "units": rnd.choice([0, 2, 5, 12, 37])}
    if name == "count_characters":
        return {"characters": len(a["text"]), "words": len(a["text"].split())}
    if name == "city_population":
        return {"city": a["city_name"], "population": rnd.randint(60, 950) * 1000 + rnd.randint(0, 999)}
    if name == "set_reminder":
        return {"status": "created", "time": a["time"]}
    if name == "book_table":
        return {"status": "confirmed", "restaurant": a["restaurant"], "people": a["people"], "time": a["time"], "booking_id": f"R{rnd.randint(1000, 9999)}"}
    if name == "library_search":
        return {"book_title": a["book_title"], "available": rnd.random() < 0.6, "copies": rnd.randint(0, 3)}
    raise KeyError(name)


def _task(rnd):
    """(tool, args, prompt_pl, prompt_en, answer_fn(result, lang) -> str)"""
    k = rnd.choice(list(TOOLS))
    if k == "track_package":
        n = f"PL{rnd.randint(10**8, 10**9 - 1)}"
        return k, {"tracking_number": n}, f"Gdzie jest moja paczka {n}?", f"Where is my parcel {n}?", \
            lambda r, l: (f"Paczka {r['tracking_number']} ma status: {r['status_pl']}. Przewidywana dostawa: {r['eta']}." if l == "pl"
                          else f"Parcel {r['tracking_number']} is {r['status_en']}. Expected delivery: {r['eta']}.")
    if k == "find_train":
        (a, _), (b, _) = rnd.sample(CITIES, 2)
        return k, {"origin": a, "destination": b}, f"Kiedy jest najbliższy pociąg na trasie {a} – {b}?", f"When is the next train from {a} to {b}?", \
            lambda r, l: (f"Najbliższy pociąg na trasie {r['origin']} – {r['destination']} odjeżdża o {r['departure']} z peronu {r['platform']}." if l == "pl"
                          else f"The next train from {r['origin']} to {r['destination']} leaves at {r['departure']} from platform {r['platform']}.")
    if k == "get_recipe":
        d = rnd.choice(DISHES)[0]
        return k, {"dish": d}, f"Ile czasu zajmuje przygotowanie dania „{d}”?", f"How long does it take to make {d}?", \
            lambda r, l: (f"Przygotowanie dania „{r['dish']}” zajmuje około {r['minutes']} minut i wymaga {r['ingredients']} składników." if l == "pl"
                          else f"Making {r['dish']} takes about {r['minutes']} minutes and needs {r['ingredients']} ingredients.")
    if k == "movie_showtimes":
        m, (c, loc) = rnd.choice(MOVIES), rnd.choice(CITIES)
        return k, {"title": m, "city": c}, f"O której grają film „{m}” w {loc}?", f"What time is {m} showing in {c}?", \
            lambda r, l: (f"Film „{r['title']}” w mieście {r['city']} grają o {r['times'][0]} i {r['times'][1]}." if l == "pl"
                          else f"{r['title']} is showing in {r['city']} at {r['times'][0]} and {r['times'][1]}.")
    if k == "translate_word":
        if rnd.random() < 0.5:
            w = rnd.choice(WORDS_PL)
            return k, {"word": w, "target_lang": "en"}, f"Jak jest po angielsku „{w}”?", f"What is the English word for the Polish '{w}'?", \
                lambda r, l: (f"„{r['word']}” po angielsku to „{r['translation']}”." if l == "pl" else f"'{r['word']}' in English is '{r['translation']}'.")
        w = rnd.choice(WORDS_EN)
        return k, {"word": w, "target_lang": "pl"}, f"Jak przetłumaczyć „{w}” na polski?", f"How do you say '{w}' in Polish?", \
            lambda r, l: (f"„{r['word']}” po polsku to „{r['translation']}”." if l == "pl" else f"'{r['word']}' in Polish is '{r['translation']}'.")
    if k == "stock_quote":
        t = rnd.choice(list(TICKERS))
        return k, {"ticker": t}, f"Ile kosztuje teraz akcja {t}?", f"What is the current price of {t}?", \
            lambda r, l: (f"Akcja {r['ticker']} kosztuje teraz {r['price']} {r['currency']}." if l == "pl" else f"{r['ticker']} is trading at {r['price']} {r['currency']}.")
    if k == "check_inventory":
        p = rnd.choice(PRODUCTS)
        return k, {"product": p}, f"Czy produkt „{p}” jest dostępny na stanie?", f"Do you have any {p} in stock?", \
            lambda r, l: ((f"Tak, mamy {r['units']} szt. produktu „{r['product']}”." if r["units"] else f"Niestety, produktu „{r['product']}” nie ma teraz na stanie (0 szt.).")
                          if l == "pl" else (f"Yes, there are {r['units']} units of {r['product']} in stock." if r["units"] else f"Sorry, {r['product']} is out of stock (0 units)."))
    if k == "count_characters":
        txt = rnd.choice(["Ala ma kota", "Litwo, ojczyzno moja", "The quick brown fox", "Szybki brązowy lis skacze", "Hello world again"])
        return k, {"text": txt}, f"Policz znaki i słowa w tekście: „{txt}”.", f"Count the characters and words in: '{txt}'.", \
            lambda r, l: (f"Tekst ma {r['characters']} znaków i {r['words']} słów." if l == "pl" else f"The text has {r['characters']} characters and {r['words']} words.")
    if k == "city_population":
        c, loc = rnd.choice(CITIES)
        return k, {"city_name": c}, f"Ilu mieszkańców ma miasto {c}?", f"What is the population of {c}?", \
            lambda r, l: (f"Miasto {r['city']} ma {r['population']} mieszkańców." if l == "pl" else f"{r['city']} has a population of {r['population']}.")
    if k == "set_reminder":
        t = f"{rnd.randint(6, 22):02d}:{rnd.choice([0, 30]):02d}"
        msg = rnd.choice([("zadzwonić do mamy", "call mom"), ("wziąć leki", "take the medicine"), ("kupić mleko", "buy milk")])
        return k, {"message": msg[0], "time": t}, f"Przypomnij mi o {t}, żeby {msg[0]}.", f"Remind me at {t} to {msg[1]}.", \
            lambda r, l: (f"Gotowe, przypomnienie ustawione na {r['time']}." if l == "pl" else f"Done, the reminder is set for {r['time']}.")
    if k == "book_table":
        res, n, t = rnd.choice(RESTAURANTS), rnd.randint(2, 8), f"{rnd.randint(12, 21)}:{rnd.choice(['00', '30'])}"
        return k, {"restaurant": res, "people": n, "time": t}, f"Zarezerwuj stolik w restauracji „{res}” dla {osob(n)} na {t}.", f"Book a table at {res} for {n} people at {t}.", \
            lambda r, l: (f"Zarezerwowane: restauracja „{r['restaurant']}”, {osob(r['people'])}, godz. {r['time']}. Numer rezerwacji: {r['booking_id']}." if l == "pl"
                          else f"Booked: {r['restaurant']}, {r['people']} people at {r['time']}. Booking number: {r['booking_id']}.")
    b = rnd.choice(BOOKS)
    return "library_search", {"book_title": b}, f"Czy w bibliotece jest książka „{b}”?", f"Does the library have '{b}'?", \
        lambda r, l: ((f"Tak, książka „{r['book_title']}” jest dostępna ({r['copies']} egz.)." if r["available"] else f"Niestety, książka „{r['book_title']}” jest teraz niedostępna.")
                      if l == "pl" else (f"Yes, '{r['book_title']}' is available ({r['copies']} copies)." if r["available"] else f"Sorry, '{r['book_title']}' is not available right now."))


NO_TOOL = {"pl": [("Cześć!", "Cześć! W czym mogę pomóc?"), ("Dzięki, to wszystko.", "Nie ma za co! Miłego dnia."),
                  ("Jak się masz?", "Dziękuję, dobrze! Czym mogę dziś pomóc?"), ("Co to jest fotosynteza w jednym zdaniu?",
                  "Fotosynteza to proces, w którym rośliny wytwarzają cukry z dwutlenku węgla i wody, korzystając z energii światła."),
                  ("Podaj synonim słowa „szybki”.", "Synonimem słowa „szybki” jest „prędki”."), ("Kim był Fryderyk Chopin?", "Fryderyk Chopin był polskim kompozytorem i pianistą epoki romantyzmu.")],
           "en": [("Hi there!", "Hello! How can I help you today?"), ("Thanks, that's all.", "You're welcome! Have a great day."),
                  ("What is 2 + 2?", "2 + 2 = 4."), ("Give me a synonym for 'big'.", "A synonym for 'big' is 'large'."),
                  ("Who wrote Romeo and Juliet?", "Romeo and Juliet was written by William Shakespeare."), ("Tell me a fun fact.", "Octopuses have three hearts.")]}


def osob(n):
    return f"{n} osoby" if n % 10 in (2, 3, 4) and n % 100 not in (12, 13, 14) else f"{n} osób"


def call(name, args):
    return {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}


def example(rnd):
    lang = rnd.choice(["pl", "pl", "en"])            # Polish-weighted: the admitted tool data is English only
    kind = rnd.choices(["single", "no_tool", "error_fix", "error_stop", "double"], weights=[60, 15, 10, 5, 10])[0]
    tools_needed, msgs = [], []
    if kind == "no_tool":
        q, a = rnd.choice(NO_TOOL[lang])
        msgs = [{"role": "user", "content": q}, {"role": "assistant", "content": a}]
    elif kind == "double":
        t1, t2 = _task(rnd), _task(rnd)
        while t2[0] == t1[0]:
            t2 = _task(rnd)
        q = f"{t1[2 if lang == 'pl' else 3]} {'A także:' if lang == 'pl' else 'Also:'} {t2[2 if lang == 'pl' else 3]}"
        r1, r2 = _result(rnd, t1[0], t1[1]), _result(rnd, t2[0], t2[1])
        if "error" in r1 or "error" in r2:
            return example(rnd)
        msgs = [{"role": "user", "content": q},
                {"role": "assistant", "content": "", "tool_calls": [call(t1[0], t1[1]), call(t2[0], t2[1])]},
                {"role": "tool", "content": json.dumps(r1, ensure_ascii=False)}, {"role": "tool", "content": json.dumps(r2, ensure_ascii=False)},
                {"role": "assistant", "content": t1[4](r1, lang) + " " + t2[4](r2, lang)}]
        tools_needed = [t1[0], t2[0]]
    else:
        name, args, qpl, qen, ans = _task(rnd)
        q = qpl if lang == "pl" else qen
        res = _result(rnd, name, args)
        if "error" in res:
            return example(rnd)
        tools_needed = [name]
        if kind == "single":
            msgs = [{"role": "user", "content": q}, {"role": "assistant", "content": "", "tool_calls": [call(name, args)]},
                    {"role": "tool", "content": json.dumps(res, ensure_ascii=False)}, {"role": "assistant", "content": ans(res, lang)}]
        elif kind == "error_fix":       # first call misses a required argument -> error -> fixed call -> answer
            req = TOOLS[name]["parameters"]["required"]
            bad = {k: v for k, v in args.items() if k != req[-1]}
            err = {"error": f"missing required argument: {req[-1]}"}
            msgs = [{"role": "user", "content": q}, {"role": "assistant", "content": "", "tool_calls": [call(name, bad)]},
                    {"role": "tool", "content": json.dumps(err)}, {"role": "assistant", "content": "", "tool_calls": [call(name, args)]},
                    {"role": "tool", "content": json.dumps(res, ensure_ascii=False)}, {"role": "assistant", "content": ans(res, lang)}]
        else:                            # service error that cannot be fixed by the model -> explain, do not repeat
            err = {"error": rnd.choice(["service unavailable", "timeout", "rate limit exceeded"])}
            msgs = [{"role": "user", "content": q}, {"role": "assistant", "content": "", "tool_calls": [call(name, args)]},
                    {"role": "tool", "content": json.dumps(err)},
                    {"role": "assistant", "content": (f"Przepraszam, narzędzie {name} zwróciło błąd ({err['error']}). Spróbuj ponownie za chwilę." if lang == "pl"
                                                      else f"Sorry, the {name} tool returned an error ({err['error']}). Please try again in a moment.")}]
    others = [t for t in TOOLS if t not in tools_needed]
    rnd.shuffle(others)
    names = tools_needed + others[: rnd.randint(1, 3)] if tools_needed else others[: rnd.randint(2, 4)]
    rnd.shuffle(names)
    tools = [{"name": n, "description": TOOLS[n]["description"], "parameters": TOOLS[n]["parameters"]} for n in names]
    for m in msgs:
        m.setdefault("trainable", m["role"] == "assistant")
        if m["role"] == "assistant" and m.get("tool_calls") and kind == "error_fix" and m is msgs[1]:
            m["trainable"] = False       # the faulty first call is context, never a target
    return {"kind": kind, "lang": lang, "messages": msgs, "tools": tools}


def generate(n, seed=20261125):
    rnd = random.Random(seed)
    return [example(rnd) for _ in range(n)]


if __name__ == "__main__":
    import collections
    xs = generate(2000)
    print(collections.Counter((x["kind"], x["lang"]) for x in xs))
    print(json.dumps(xs[3], ensure_ascii=False, indent=1)[:1500])