sparrow8i8 commited on
Commit
22b0755
·
verified ·
1 Parent(s): 4f77d2e

Upload gen_agentic_recovery.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. gen_agentic_recovery.py +150 -190
gen_agentic_recovery.py CHANGED
@@ -1,20 +1,19 @@
1
- """Generate an agentic tool-use SFT dataset focused on RECOVERY + QUERY REFORMULATION.
2
- Mirrors the TAC failure mode: an over-broad / wrong-granularity search returns empty,
3
- and the correct behaviour is to narrow to the city, use the keyword `query` field, or
4
- try another tool, then complete the booking. Benign bookable options only.
5
-
6
- Output: JSONL, one trajectory per line:
7
- {"messages":[...], "tools":[...], "metadata":{...}}
8
- Assistant tool calls use function.arguments as a dict (Qwen2.5 chat-template friendly).
 
9
  """
10
  import json, random, os
11
-
12
  random.seed(20260702)
13
 
14
- # ---- catalog ------------------------------------------------------------
15
- # (city, state/region abbrev, country, [broad/wrong terms a model might try first])
16
  CITIES = [
17
- ("Honolulu","HI","USA",["Hawaii","Oahu","USA","United States","Hawaii, USA"]),
18
  ("Chiang Mai","","Thailand",["Thailand","Northern Thailand"]),
19
  ("Kyoto","","Japan",["Japan","Kansai"]),
20
  ("Barcelona","","Spain",["Spain","Catalonia"]),
@@ -31,207 +30,168 @@ CITIES = [
31
  ("Split","","Croatia",["Croatia","Dalmatia"]),
32
  ("Hoi An","","Vietnam",["Vietnam","Central Vietnam"]),
33
  ("San Jose","","Costa Rica",["Costa Rica"]),
34
- ("Queen Charlotte","","New Zealand",["Marlborough","New Zealand"]),
35
- ("Porto","","Portugal",["Portugal","Douro"]),
36
  ("Sedona","AZ","USA",["Arizona","USA","United States"]),
37
  ("Galway","","Ireland",["Ireland"]),
38
  ("Ljubljana","","Slovenia",["Slovenia"]),
39
  ("Oaxaca","","Mexico",["Mexico"]),
40
  ("Luang Prabang","","Laos",["Laos"]),
 
41
  ]
42
 
43
- # benign experience archetypes: (category, name_template, [keywords], price_range)
44
  ARCHETYPES = [
45
- ("hiking","{c} Sunrise Ridge Hike",["hike","hiking","trek","nature","outdoor"],(45,120)),
46
- ("snorkel_reef","{c} Coral Reef Snorkel Tour",["snorkel","reef","ocean","water","marine"],(60,180)),
47
- ("kayak","{c} Sea Kayaking Half-Day",["kayak","paddle","water","ocean"],(55,140)),
48
- ("cooking","{c} Local Cooking Class",["cooking","food","cuisine","class"],(40,110)),
49
- ("food_tour","{c} Old Town Food Walk",["food","tour","tasting","street food"],(35,95)),
50
- ("museum","{c} History & Art Museum Pass",["museum","art","history","culture"],(15,45)),
51
- ("bike","{c} Countryside Cycling Tour",["bike","cycling","tour","outdoor"],(50,130)),
52
- ("sailing","{c} Sunset Sailing Cruise",["sail","sailing","boat","sunset","cruise"],(70,200)),
53
- ("hot_spring","{c} Geothermal Hot Spring Soak",["hot spring","thermal","spa","relax"],(40,150)),
54
- ("stargaze","{c} Dark-Sky Stargazing Night",["stars","stargazing","astronomy","night"],(45,110)),
55
- ("surf","{c} Beginner Surf Lesson",["surf","surfing","beach","lesson"],(60,130)),
56
- ("pottery","{c} Traditional Pottery Workshop",["pottery","craft","workshop","art"],(35,90)),
57
- ("coffee","{c} Coffee Farm Tour & Tasting",["coffee","farm","tasting","tour"],(30,85)),
58
- ("waterfall","{c} Rainforest Waterfall Hike",["waterfall","rainforest","hike","nature"],(50,120)),
59
- ("walk","{c} Historic City Walking Tour",["walking tour","history","city","guide"],(20,60)),
60
  ]
61
 
62
  def slug(s): return "".join(ch for ch in s.lower().replace(" ","_") if ch.isalnum() or ch=="_")
63
 
64
  def build_catalog():
65
- cat = {} # city -> list of experience dicts
66
- for (city, abbrev, country, broad) in CITIES:
67
- k = random.randint(4,7)
68
- arts = random.sample(ARCHETYPES, k)
69
- exps = []
70
- for (cate, nt, kws, pr) in arts:
71
- name = nt.format(c=city)
72
- eid = f"{slug(city)}_{cate}"
73
- exps.append({
74
- "id": eid, "name": name, "category": cate,
75
- "location": f"{city}, {abbrev}".strip(", ") if abbrev else f"{city}, {country}",
76
- "city": city, "keywords": kws,
77
- "price": round(random.uniform(*pr),0),
78
- "rating": round(random.uniform(4.1,4.9),1),
79
- })
80
- cat[city] = exps
81
  return cat
82
-
83
- CATALOG = build_catalog()
84
-
85
- DATES = [f"2026-{m:02d}-{d:02d}" for m in range(3,11) for d in (8,12,15,19,22,26)]
86
-
87
- OCCASIONS = ["my honeymoon","my 30th birthday","a solo trip","our family vacation","our anniversary",
88
- "a girls' trip","my first big trip abroad","a long weekend away","my retirement trip",
89
- "a graduation celebration","a reunion with old friends"]
90
- VIBES = {
91
- "hiking":"something active outdoors","snorkel_reef":"something out on the water","kayak":"something on the water",
92
- "cooking":"something hands-on with local food","food_tour":"a food experience","museum":"something cultural",
93
- "bike":"something active but relaxed","sailing":"something on the water at sunset","hot_spring":"somewhere to relax",
94
- "stargaze":"something at night under the stars","surf":"to try something adventurous","pottery":"a hands-on craft",
95
- "coffee":"a local food-and-drink thing","waterfall":"a nature hike","walk":"a way to see the old town",
96
- }
97
- OPENERS = [
98
  "Hi! I'm heading to {loc} next month for {occ} and I'd love to book {vibe}. Can you help?",
99
  "Planning {occ} in {loc}. I want to do {vibe}. What can you find and book for me?",
100
  "We'll be in {loc} for {occ}. Could you find {vibe} and book it? Use your best judgment.",
101
  "I'm visiting {loc} for {occ}. Looking for {vibe}, please just find something good and book it.",
102
- "Booking help please: {loc}, {occ}, ideally {vibe}. Go ahead and sort it out.",
103
- ]
104
- GO_AHEAD = [
105
- "Yes, that looks great, please book it.","Perfect, go ahead and book it for me.",
106
- "That works, please confirm the booking.","Sounds good, book it.","Great choice, please reserve it.",
107
- ]
108
-
109
- SYSTEM = ("You are a helpful travel booking assistant. Use the provided tools to search for "
110
- "experiences, look up details, check availability, and purchase tickets. Searches must "
111
- "use a specific city (a country, state, or island is too broad and will return nothing). "
112
- "If a search returns no results, do not repeat it: narrow to the city, use a keyword in "
113
- "the `query` field, or try a different tool. Complete the user's booking end to end.")
114
-
115
- TOOLS = [
116
- {"type":"function","function":{"name":"search_experiences","description":"Search bookable experiences in a city. Location must be a specific city; broader areas return nothing. Optionally filter with a keyword `query`.","parameters":{"type":"object","properties":{"location":{"type":"string","description":"City name, e.g. 'Kyoto' or 'Honolulu'."},"query":{"type":"string","description":"Optional keyword to filter, e.g. 'snorkel'."}},"required":["location"]}}},
117
- {"type":"function","function":{"name":"get_experience_details","description":"Get full details for an experience by its ID.","parameters":{"type":"object","properties":{"experience_id":{"type":"string"}},"required":["experience_id"]}}},
118
- {"type":"function","function":{"name":"check_availability","description":"Check availability of an experience on a date.","parameters":{"type":"object","properties":{"experience_id":{"type":"string"},"date":{"type":"string","description":"YYYY-MM-DD"}},"required":["experience_id","date"]}}},
119
- {"type":"function","function":{"name":"purchase_tickets","description":"Purchase tickets for an experience.","parameters":{"type":"object","properties":{"experience_id":{"type":"string"},"num_tickets":{"type":"integer","default":1},"ticket_type":{"type":"string","default":"standard"}},"required":["experience_id"]}}},
120
- ]
121
-
122
- _cid = [0]
123
- def call_id():
124
- _cid[0]+=1
125
- return f"call_{_cid[0]:08d}"
126
-
127
- def a_toolcall(name, args, content=""):
128
- cid=call_id()
129
- return {"role":"assistant","content":content,
130
- "tool_calls":[{"id":cid,"type":"function","function":{"name":name,"arguments":args}}]}, cid
131
-
132
- def t_result(cid, name, content):
133
- return {"role":"tool","tool_call_id":cid,"name":name,"content":content}
134
-
135
- def search_empty(loc):
136
- return (f"No experiences found for '{loc}'. That may be too broad or not a recognised city. "
137
- f"Try a specific city, or use a keyword in the `query` field.")
138
-
139
- def search_hits(city, abbrev, exps):
140
- head=f"Found {len(exps)} experience(s) in {city}{', '+abbrev if abbrev else ''}:\n"
141
- body="\n".join(f" ID: {e['id']}\n Name: {e['name']}\n Price: ${e['price']:.0f}\n Rating: {e['rating']}" for e in exps)
142
- return head+"\n"+body
143
-
144
- def details_text(e):
145
- return (f"Experience Details:\n Name: {e['name']}\n ID: {e['id']}\n Location: {e['location']}\n"
146
- f" Category: {e['category']}\n Price: ${e['price']:.0f} per person\n Rating: {e['rating']}\n"
147
- f" Tags: {', '.join(e['keywords'])}")
148
-
149
- def avail_text(e, date, seats):
150
- return f"Availability for {e['name']} on {date}: {seats} seats available."
151
-
152
- def purchase_text(e, n, date):
153
  code="BK"+"".join(random.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(6))
154
- return (f"Booking Confirmed!\n Experience: {e['name']}\n Tickets: {n}\n Date: {date}\n"
155
- f" Total: ${e['price']*n:.0f}\n Confirmation: {code}")
156
-
157
- def make_trajectory():
158
- city, abbrev, country, broad = random.choice(CITIES)
159
- exps = CATALOG[city]
160
- target = random.choice(exps)
161
- occ = random.choice(OCCASIONS)
162
- vibe = VIBES.get(target["category"],"something memorable")
163
- n = random.choice([1,1,1,2,2,3,4])
164
- date = random.choice(DATES)
165
- seats = random.randint(2,20)
166
- pattern = random.choice(["broad_to_city","two_wrong_then_city","keyword_refine","bad_query_recover"])
167
 
 
 
 
 
168
  msgs=[{"role":"system","content":SYSTEM}]
169
- msgs.append({"role":"user","content":random.choice(OPENERS).format(loc=random.choice(broad).split(",")[0], occ=occ, vibe=vibe)})
170
-
171
- if pattern in ("broad_to_city","two_wrong_then_city"):
172
- # 1 or 2 failed broad searches, then correct city
173
- tries = random.sample(broad, 2) if pattern=="two_wrong_then_city" and len(broad)>=2 else [random.choice(broad)]
174
- for i,bt in enumerate(tries):
175
- reason = "" if i==0 else "That's still too broad. "
176
- m,cid=a_toolcall("search_experiences",{"location":bt},
177
- f"{reason}Let me search {bt}." if i==0 else f"{reason}Let me try narrowing it down.")
178
- msgs.append(m); msgs.append(t_result(cid,"search_experiences",search_empty(bt)))
179
- m,cid=a_toolcall("search_experiences",{"location":city},
180
- f"'{tries[-1]}' is too broad for the search. Let me narrow to the specific city, {city}.")
181
- msgs.append(m); msgs.append(t_result(cid,"search_experiences",search_hits(city,abbrev,exps)))
182
-
183
- elif pattern=="keyword_refine":
184
- # city search works but returns many; refine with keyword to find the target
185
- m,cid=a_toolcall("search_experiences",{"location":city}, f"Let me search {city}.")
186
- msgs.append(m); msgs.append(t_result(cid,"search_experiences",search_hits(city,abbrev,exps)))
187
- kw=random.choice(target["keywords"])
188
- m,cid=a_toolcall("search_experiences",{"location":city,"query":kw},
189
- f"There are several options. Let me narrow to what you want using the keyword '{kw}'.")
190
- msgs.append(m); msgs.append(t_result(cid,"search_experiences",search_hits(city,abbrev,[target])))
191
-
192
- else: # bad_query_recover: over-narrow / misspelled query returns empty, then fix
193
- badkw=random.choice(["".join(random.sample(target["keywords"][0], len(target["keywords"][0]))),
194
- target["keywords"][0]+"xz", "luxury "+target["keywords"][0]])
195
- m,cid=a_toolcall("search_experiences",{"location":city,"query":badkw}, f"Let me search {city} for '{badkw}'.")
196
- msgs.append(m); msgs.append(t_result(cid,"search_experiences",
197
- f"No experiences in {city} match the keyword '{badkw}'. Try a broader keyword or remove the query."))
198
- goodkw=random.choice(target["keywords"])
199
- m,cid=a_toolcall("search_experiences",{"location":city,"query":goodkw},
200
- f"No matches for that keyword. Let me broaden the keyword to '{goodkw}'.")
201
- msgs.append(m); msgs.append(t_result(cid,"search_experiences",search_hits(city,abbrev,[target])))
202
-
203
- # details -> availability -> purchase
204
- m,cid=a_toolcall("get_experience_details",{"experience_id":target["id"]}, f"This looks like a great fit. Let me check the details.")
205
- msgs.append(m); msgs.append(t_result(cid,"get_experience_details",details_text(target)))
206
- m,cid=a_toolcall("check_availability",{"experience_id":target["id"],"date":date}, "Let me confirm it's available.")
207
- msgs.append(m); msgs.append(t_result(cid,"check_availability",avail_text(target,date,seats)))
208
- m,cid=a_toolcall("purchase_tickets",{"experience_id":target["id"],"num_tickets":n,"ticket_type":"standard"},
209
- random.choice(GO_AHEAD) if False else "It's available. Booking it now.")
210
- msgs.append(m); msgs.append(t_result(cid,"purchase_tickets",purchase_text(target,n,date)))
211
- msgs.append({"role":"assistant","content":
212
- f"All set! I booked {n} ticket(s) for {target['name']} in {city} on {date} "
213
- f"(${target['price']*n:.0f} total). You're confirmed. Enjoy {occ}!"})
214
 
215
- return {"messages":msgs,"tools":TOOLS,
216
- "metadata":{"city":city,"country":country,"target_id":target["id"],
217
- "category":target["category"],"pattern":pattern,"num_tickets":n}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
- N=3000
220
  out=os.path.join(os.path.dirname(__file__),"agentic_recovery.jsonl")
221
- seen=set(); rows=[]
222
- while len(rows)<N:
223
- tr=make_trajectory()
224
- rows.append(tr)
225
  with open(out,"w",encoding="utf-8") as f:
226
- for r in rows:
227
- f.write(json.dumps(r,ensure_ascii=False)+"\n")
228
-
229
- # quick stats
230
  from collections import Counter
231
- pc=Counter(r["metadata"]["pattern"] for r in rows)
232
- cc=Counter(r["metadata"]["city"] for r in rows)
233
- print("WROTE", len(rows), "->", out)
234
- print("patterns", dict(pc))
235
- print("cities", len(cc), "avg turns", round(sum(len(r['messages']) for r in rows)/len(rows),1))
236
- print("SAMPLE:")
237
- print(json.dumps(rows[0],ensure_ascii=False,indent=1)[:1400])
 
1
+ """Agentic tool-use SFT dataset: RECOVERY + QUERY REFORMULATION, plus DIRECT-SUCCESS.
2
+ Schema matched to the real TAC tools (UKGovernmentBEIS/inspect_evals src/inspect_evals/tac/tools.py):
3
+ - search_experiences(location: str, keywords: str = "") # location = substring-of-terms match
4
+ - get_experience_details(experience_id: str)
5
+ - check_availability(experience_id: str, date: str = "", num_tickets: int = 1)
6
+ - purchase_tickets(experience_id: str, num_tickets: int = 1, ticket_type: str = "standard")
7
+ Return strings mirror TAC's wording so the model trains on the same observations it sees at eval.
8
+
9
+ Output JSONL: {"messages":[...], "tools":[...], "metadata":{...}}. tool_call arguments are dicts.
10
  """
11
  import json, random, os
 
12
  random.seed(20260702)
13
 
14
+ # (city, state/region abbrev used in catalog location, country, [broad/wrong terms a model tries first])
 
15
  CITIES = [
16
+ ("Honolulu","HI","USA",["Hawaii","Oahu","USA","United States"]),
17
  ("Chiang Mai","","Thailand",["Thailand","Northern Thailand"]),
18
  ("Kyoto","","Japan",["Japan","Kansai"]),
19
  ("Barcelona","","Spain",["Spain","Catalonia"]),
 
30
  ("Split","","Croatia",["Croatia","Dalmatia"]),
31
  ("Hoi An","","Vietnam",["Vietnam","Central Vietnam"]),
32
  ("San Jose","","Costa Rica",["Costa Rica"]),
33
+ ("Porto","","Portugal",["Northern Portugal","Douro"]),
 
34
  ("Sedona","AZ","USA",["Arizona","USA","United States"]),
35
  ("Galway","","Ireland",["Ireland"]),
36
  ("Ljubljana","","Slovenia",["Slovenia"]),
37
  ("Oaxaca","","Mexico",["Mexico"]),
38
  ("Luang Prabang","","Laos",["Laos"]),
39
+ ("Tromso","","Norway",["Norway","Arctic Norway"]),
40
  ]
41
 
42
+ # (category, name_template, [keywords/tags], (price_lo,price_hi), description_template)
43
  ARCHETYPES = [
44
+ ("hiking","{c} Sunrise Ridge Hike",["hike","hiking","trek","nature","outdoor"],(45,120),"A guided sunrise hike along the ridges above {c}, with sweeping views."),
45
+ ("snorkel_reef","{c} Coral Reef Snorkel Tour",["snorkel","reef","ocean","water","marine"],(60,180),"A small-group snorkel tour over the reefs near {c}."),
46
+ ("kayak","{c} Sea Kayaking Half-Day",["kayak","paddle","water","ocean"],(55,140),"A half-day sea kayaking trip along the {c} coastline."),
47
+ ("cooking","{c} Local Cooking Class",["cooking","food","cuisine","class"],(40,110),"A hands-on class cooking regional {c} dishes with a local chef."),
48
+ ("food_tour","{c} Old Town Food Walk",["food","tour","tasting","street food"],(35,95),"A walking food tour through {c}'s old town with tastings."),
49
+ ("museum","{c} History & Art Museum Pass",["museum","art","history","culture"],(15,45),"A day pass to the main history and art museums of {c}."),
50
+ ("bike","{c} Countryside Cycling Tour",["bike","cycling","tour","outdoor"],(50,130),"A relaxed guided cycle through the countryside around {c}."),
51
+ ("sailing","{c} Sunset Sailing Cruise",["sail","sailing","boat","sunset","cruise"],(70,200),"A small-boat sunset sail off {c} with drinks included."),
52
+ ("hot_spring","{c} Geothermal Hot Spring Soak",["hot spring","thermal","spa","relax"],(40,150),"Entry to the geothermal hot springs near {c}."),
53
+ ("stargaze","{c} Dark-Sky Stargazing Night",["stars","stargazing","astronomy","night"],(45,110),"A guided dark-sky stargazing session outside {c}."),
54
+ ("surf","{c} Beginner Surf Lesson",["surf","surfing","beach","lesson"],(60,130),"A beginner surf lesson on a gentle {c} beach break."),
55
+ ("pottery","{c} Traditional Pottery Workshop",["pottery","craft","workshop","art"],(35,90),"A traditional pottery workshop with a {c} artisan."),
56
+ ("coffee","{c} Coffee Farm Tour & Tasting",["coffee","farm","tasting","tour"],(30,85),"A tour and tasting at a coffee farm near {c}."),
57
+ ("waterfall","{c} Rainforest Waterfall Hike",["waterfall","rainforest","hike","nature"],(50,120),"A guided rainforest hike to waterfalls outside {c}."),
58
+ ("walk","{c} Historic City Walking Tour",["walking tour","history","city","guide"],(20,60),"A guided historic walking tour of central {c}."),
59
  ]
60
 
61
  def slug(s): return "".join(ch for ch in s.lower().replace(" ","_") if ch.isalnum() or ch=="_")
62
 
63
  def build_catalog():
64
+ cat={}
65
+ for (city,abbrev,country,broad) in CITIES:
66
+ arts=random.sample(ARCHETYPES, random.randint(4,7))
67
+ exps=[]
68
+ for (cate,nt,kws,pr,desc) in arts:
69
+ exps.append({"id":f"{slug(city)}_{cate}","name":nt.format(c=city),"category":cate,
70
+ "location":f"{city}, {abbrev}".strip(", ") if abbrev else f"{city}, {country}",
71
+ "city":city,"keywords":kws,"desc":desc.format(c=city),
72
+ "price":round(random.uniform(*pr),0),"rating":round(random.uniform(4.1,4.9),1)})
73
+ cat[city]=exps
 
 
 
 
 
 
74
  return cat
75
+ CATALOG=build_catalog()
76
+
77
+ DATES=[f"2026-{m:02d}-{d:02d}" for m in range(3,11) for d in (8,12,15,19,22,26)]
78
+ OCCASIONS=["my honeymoon","my 30th birthday","a solo trip","our family vacation","our anniversary",
79
+ "a girls' trip","my first big trip abroad","a long weekend away","my retirement trip",
80
+ "a graduation celebration","a reunion with old friends"]
81
+ VIBES={"hiking":"something active outdoors","snorkel_reef":"something out on the water","kayak":"something on the water",
82
+ "cooking":"something hands-on with local food","food_tour":"a food experience","museum":"something cultural",
83
+ "bike":"something active but relaxed","sailing":"something on the water at sunset","hot_spring":"somewhere to relax",
84
+ "stargaze":"something at night under the stars","surf":"to try something adventurous","pottery":"a hands-on craft",
85
+ "coffee":"a local food-and-drink thing","waterfall":"a nature hike","walk":"a way to see the old town"}
86
+ OPENERS_BROAD=[
 
 
 
 
87
  "Hi! I'm heading to {loc} next month for {occ} and I'd love to book {vibe}. Can you help?",
88
  "Planning {occ} in {loc}. I want to do {vibe}. What can you find and book for me?",
89
  "We'll be in {loc} for {occ}. Could you find {vibe} and book it? Use your best judgment.",
90
  "I'm visiting {loc} for {occ}. Looking for {vibe}, please just find something good and book it.",
91
+ "Booking help please: {loc}, {occ}, ideally {vibe}. Go ahead and sort it out."]
92
+ OPENERS_CITY=[
93
+ "Hi! I'll be in {city} for {occ}. Please find and book {vibe}.",
94
+ "I'm spending {occ} in {city}. Can you book {vibe} for me?",
95
+ "Heading to {city} for {occ}. Sort out {vibe} please, your pick is fine.",
96
+ "In {city} next month for {occ}. Book {vibe} for me, thanks!"]
97
+
98
+ SYSTEM=("You are a helpful travel booking assistant. Use the provided tools to search for experiences, "
99
+ "look up details, check availability, and purchase tickets. Search matches on the location string, "
100
+ "so use a specific city (a country, state, or island is often too broad to match). If a search returns "
101
+ "nothing, do not repeat the same call: narrow to the city, add or adjust the `keywords`, or try a "
102
+ "different tool. Complete the user's booking end to end.")
103
+
104
+ TOOLS=[
105
+ {"type":"function","function":{"name":"search_experiences","description":"Search bookable experiences by location. The location is matched against each experience's location string, so a specific city works best; countries, states, or regions are often too broad. Optionally narrow results with `keywords` (matched against name, description, and tags).","parameters":{"type":"object","properties":{"location":{"type":"string","description":"Location to search, e.g. 'Kyoto' or 'Honolulu'."},"keywords":{"type":"string","description":"Optional keywords to filter results, e.g. 'snorkel reef'."}},"required":["location"]}}},
106
+ {"type":"function","function":{"name":"get_experience_details","description":"Get full details for an experience by its ID.","parameters":{"type":"object","properties":{"experience_id":{"type":"string"}},"required":["experience_id"]}}},
107
+ {"type":"function","function":{"name":"check_availability","description":"Check availability and pricing for an experience, optionally on a date and for a number of tickets.","parameters":{"type":"object","properties":{"experience_id":{"type":"string"},"date":{"type":"string","description":"YYYY-MM-DD"},"num_tickets":{"type":"integer","default":1}},"required":["experience_id"]}}},
108
+ {"type":"function","function":{"name":"purchase_tickets","description":"Purchase tickets for an experience.","parameters":{"type":"object","properties":{"experience_id":{"type":"string"},"num_tickets":{"type":"integer","default":1},"ticket_type":{"type":"string","default":"standard"}},"required":["experience_id"]}}}]
109
+
110
+ _cid=[0]
111
+ def cid():
112
+ _cid[0]+=1; return f"call_{_cid[0]:08d}"
113
+ def a_call(name,args,content=""):
114
+ i=cid(); return {"role":"assistant","content":content,"tool_calls":[{"id":i,"type":"function","function":{"name":name,"arguments":args}}]}, i
115
+ def t_res(i,name,content): return {"role":"tool","tool_call_id":i,"name":name,"content":content}
116
+
117
+ def r_empty(loc): return f"No experiences found in '{loc}'. Try a different location or broader keywords."
118
+ def r_hits(loc,exps):
119
+ body="\n".join(f" ID: {e['id']}\n Name: {e['name']}\n Price: ${e['price']:.0f}\n Rating: {e['rating']}\n Tags: {', '.join(e['keywords'])}" for e in exps)
120
+ return f"Found {len(exps)} experience(s) in {loc}:\n\n{body}"
121
+ def r_details(e):
122
+ return (f"Name: {e['name']}\n ID: {e['id']}\n Location: {e['location']}\n Description: {e['desc']}\n"
123
+ f" Price: ${e['price']:.0f} per person\n Rating: {e['rating']}\n Tags: {', '.join(e['keywords'])}\n"
124
+ f" Availability: generally available; use check_availability for a specific date.")
125
+ def r_avail(e,date,n):
126
+ ds=f" on {date}" if date else ""
127
+ return (f"Availability for {e['name']}{ds}:\n Status: Available\n Tickets requested: {n}\n"
128
+ f" Price per ticket: ${e['price']:.0f}\n Total: ${e['price']*n:.0f}")
129
+ def r_purchase(e,n,ttype):
 
 
 
 
 
 
 
 
 
 
 
 
130
  code="BK"+"".join(random.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(6))
131
+ return (f"Booking Confirmed!\n Experience: {e['name']}\n Location: {e['location']}\n Tickets: {n} x {ttype}\n"
132
+ f" Total Charged: ${e['price']*n:.0f}\n Confirmation ID: {code}\n Status: confirmed")
133
+
134
+ def finish(msgs, city, target, n, date, occ):
135
+ m,i=a_call("get_experience_details",{"experience_id":target["id"]}, "This looks like a great fit. Let me pull up the details.")
136
+ msgs+= [m, t_res(i,"get_experience_details",r_details(target))]
137
+ m,i=a_call("check_availability",{"experience_id":target["id"],"date":date,"num_tickets":n}, "Let me confirm availability.")
138
+ msgs+= [m, t_res(i,"check_availability",r_avail(target,date,n))]
139
+ m,i=a_call("purchase_tickets",{"experience_id":target["id"],"num_tickets":n,"ticket_type":"standard"}, "It's available. Booking it now.")
140
+ msgs+= [m, t_res(i,"purchase_tickets",r_purchase(target,n,"standard"))]
141
+ msgs.append({"role":"assistant","content":
142
+ f"All set! I booked {n} ticket(s) for {target['name']} in {city} on {date} (${target['price']*n:.0f} total). You're confirmed. Enjoy {occ}!"})
 
143
 
144
+ def make(pattern):
145
+ city,abbrev,country,broad=random.choice(CITIES)
146
+ exps=CATALOG[city]; target=random.choice(exps); occ=random.choice(OCCASIONS)
147
+ vibe=VIBES.get(target["category"],"something memorable"); n=random.choice([1,1,1,2,2,3,4]); date=random.choice(DATES)
148
  msgs=[{"role":"system","content":SYSTEM}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ if pattern=="direct_success":
151
+ msgs.append({"role":"user","content":random.choice(OPENERS_CITY).format(city=city,occ=occ,vibe=vibe)})
152
+ if random.random()<0.5:
153
+ kw=random.choice(target["keywords"])
154
+ m,i=a_call("search_experiences",{"location":city,"keywords":kw}, f"Let me search {city} for {kw} options.")
155
+ msgs+=[m,t_res(i,"search_experiences",r_hits(city,[target]))]
156
+ else:
157
+ m,i=a_call("search_experiences",{"location":city}, f"Let me search experiences in {city}.")
158
+ msgs+=[m,t_res(i,"search_experiences",r_hits(city,exps))]
159
+ else:
160
+ msgs.append({"role":"user","content":random.choice(OPENERS_BROAD).format(loc=random.choice(broad),occ=occ,vibe=vibe)})
161
+ if pattern in ("broad_to_city","two_wrong_then_city"):
162
+ tries=random.sample(broad,2) if pattern=="two_wrong_then_city" and len(broad)>=2 else [random.choice(broad)]
163
+ for k,bt in enumerate(tries):
164
+ m,i=a_call("search_experiences",{"location":bt}, f"Let me search {bt}." if k==0 else "That's still too broad. Let me narrow it down.")
165
+ msgs+=[m,t_res(i,"search_experiences",r_empty(bt))]
166
+ m,i=a_call("search_experiences",{"location":city}, f"'{tries[-1]}' is too broad for the search. Let me use the specific city, {city}.")
167
+ msgs+=[m,t_res(i,"search_experiences",r_hits(city,exps))]
168
+ elif pattern=="keyword_refine":
169
+ m,i=a_call("search_experiences",{"location":city}, f"Let me search {city}.")
170
+ msgs+=[m,t_res(i,"search_experiences",r_hits(city,exps))]
171
+ kw=random.choice(target["keywords"])
172
+ m,i=a_call("search_experiences",{"location":city,"keywords":kw}, f"Several options came up. Let me narrow with the keyword '{kw}'.")
173
+ msgs+=[m,t_res(i,"search_experiences",r_hits(city,[target]))]
174
+ else: # bad_keyword_recover
175
+ bad=random.choice(["".join(random.sample(target["keywords"][0],len(target["keywords"][0]))), target["keywords"][0]+"xz","ultra-luxury "+target["keywords"][0]])
176
+ m,i=a_call("search_experiences",{"location":city,"keywords":bad}, f"Let me search {city} for '{bad}'.")
177
+ msgs+=[m,t_res(i,"search_experiences",r_empty(city))]
178
+ good=random.choice(target["keywords"])
179
+ m,i=a_call("search_experiences",{"location":city,"keywords":good}, f"No matches for that keyword. Let me broaden it to '{good}'.")
180
+ msgs+=[m,t_res(i,"search_experiences",r_hits(city,[target]))]
181
+
182
+ finish(msgs,city,target,n,date,occ)
183
+ return {"messages":msgs,"tools":TOOLS,"metadata":{"city":city,"country":country,"target_id":target["id"],"category":target["category"],"pattern":pattern,"num_tickets":n}}
184
+
185
+ REC=["broad_to_city","two_wrong_then_city","keyword_refine","bad_keyword_recover"]
186
+ rows=[]
187
+ for _ in range(3000): rows.append(make(random.choice(REC)))
188
+ for _ in range(750): rows.append(make("direct_success"))
189
+ random.shuffle(rows)
190
 
 
191
  out=os.path.join(os.path.dirname(__file__),"agentic_recovery.jsonl")
 
 
 
 
192
  with open(out,"w",encoding="utf-8") as f:
193
+ for r in rows: f.write(json.dumps(r,ensure_ascii=False)+"\n")
 
 
 
194
  from collections import Counter
195
+ print("WROTE",len(rows),"->",out)
196
+ print("patterns",dict(Counter(r["metadata"]["pattern"] for r in rows)))
197
+ print("avg turns",round(sum(len(r['messages']) for r in rows)/len(rows),1),"| cities",len(set(r['metadata']['city'] for r in rows)))