agentic-tool-recovery-sft / gen_agentic_recovery.py
sparrow8i8's picture
Upload gen_agentic_recovery.py with huggingface_hub
22b0755 verified
Raw
History Blame Contribute Delete
15.3 kB
"""Agentic tool-use SFT dataset: RECOVERY + QUERY REFORMULATION, plus DIRECT-SUCCESS.
Schema matched to the real TAC tools (UKGovernmentBEIS/inspect_evals src/inspect_evals/tac/tools.py):
- search_experiences(location: str, keywords: str = "") # location = substring-of-terms match
- get_experience_details(experience_id: str)
- check_availability(experience_id: str, date: str = "", num_tickets: int = 1)
- purchase_tickets(experience_id: str, num_tickets: int = 1, ticket_type: str = "standard")
Return strings mirror TAC's wording so the model trains on the same observations it sees at eval.
Output JSONL: {"messages":[...], "tools":[...], "metadata":{...}}. tool_call arguments are dicts.
"""
import json, random, os
random.seed(20260702)
# (city, state/region abbrev used in catalog location, country, [broad/wrong terms a model tries first])
CITIES = [
("Honolulu","HI","USA",["Hawaii","Oahu","USA","United States"]),
("Chiang Mai","","Thailand",["Thailand","Northern Thailand"]),
("Kyoto","","Japan",["Japan","Kansai"]),
("Barcelona","","Spain",["Spain","Catalonia"]),
("Queenstown","","New Zealand",["New Zealand","South Island"]),
("Reykjavik","","Iceland",["Iceland"]),
("Cusco","","Peru",["Peru","Andes"]),
("Cape Town","","South Africa",["South Africa","Western Cape"]),
("Ubud","","Indonesia",["Bali","Indonesia"]),
("Marrakech","","Morocco",["Morocco"]),
("Cairns","QLD","Australia",["Australia","Great Barrier Reef","Queensland"]),
("Interlaken","","Switzerland",["Switzerland","Swiss Alps"]),
("Banff","AB","Canada",["Canada","Alberta","Rocky Mountains"]),
("Lisbon","","Portugal",["Portugal"]),
("Split","","Croatia",["Croatia","Dalmatia"]),
("Hoi An","","Vietnam",["Vietnam","Central Vietnam"]),
("San Jose","","Costa Rica",["Costa Rica"]),
("Porto","","Portugal",["Northern Portugal","Douro"]),
("Sedona","AZ","USA",["Arizona","USA","United States"]),
("Galway","","Ireland",["Ireland"]),
("Ljubljana","","Slovenia",["Slovenia"]),
("Oaxaca","","Mexico",["Mexico"]),
("Luang Prabang","","Laos",["Laos"]),
("Tromso","","Norway",["Norway","Arctic Norway"]),
]
# (category, name_template, [keywords/tags], (price_lo,price_hi), description_template)
ARCHETYPES = [
("hiking","{c} Sunrise Ridge Hike",["hike","hiking","trek","nature","outdoor"],(45,120),"A guided sunrise hike along the ridges above {c}, with sweeping views."),
("snorkel_reef","{c} Coral Reef Snorkel Tour",["snorkel","reef","ocean","water","marine"],(60,180),"A small-group snorkel tour over the reefs near {c}."),
("kayak","{c} Sea Kayaking Half-Day",["kayak","paddle","water","ocean"],(55,140),"A half-day sea kayaking trip along the {c} coastline."),
("cooking","{c} Local Cooking Class",["cooking","food","cuisine","class"],(40,110),"A hands-on class cooking regional {c} dishes with a local chef."),
("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."),
("museum","{c} History & Art Museum Pass",["museum","art","history","culture"],(15,45),"A day pass to the main history and art museums of {c}."),
("bike","{c} Countryside Cycling Tour",["bike","cycling","tour","outdoor"],(50,130),"A relaxed guided cycle through the countryside around {c}."),
("sailing","{c} Sunset Sailing Cruise",["sail","sailing","boat","sunset","cruise"],(70,200),"A small-boat sunset sail off {c} with drinks included."),
("hot_spring","{c} Geothermal Hot Spring Soak",["hot spring","thermal","spa","relax"],(40,150),"Entry to the geothermal hot springs near {c}."),
("stargaze","{c} Dark-Sky Stargazing Night",["stars","stargazing","astronomy","night"],(45,110),"A guided dark-sky stargazing session outside {c}."),
("surf","{c} Beginner Surf Lesson",["surf","surfing","beach","lesson"],(60,130),"A beginner surf lesson on a gentle {c} beach break."),
("pottery","{c} Traditional Pottery Workshop",["pottery","craft","workshop","art"],(35,90),"A traditional pottery workshop with a {c} artisan."),
("coffee","{c} Coffee Farm Tour & Tasting",["coffee","farm","tasting","tour"],(30,85),"A tour and tasting at a coffee farm near {c}."),
("waterfall","{c} Rainforest Waterfall Hike",["waterfall","rainforest","hike","nature"],(50,120),"A guided rainforest hike to waterfalls outside {c}."),
("walk","{c} Historic City Walking Tour",["walking tour","history","city","guide"],(20,60),"A guided historic walking tour of central {c}."),
]
def slug(s): return "".join(ch for ch in s.lower().replace(" ","_") if ch.isalnum() or ch=="_")
def build_catalog():
cat={}
for (city,abbrev,country,broad) in CITIES:
arts=random.sample(ARCHETYPES, random.randint(4,7))
exps=[]
for (cate,nt,kws,pr,desc) in arts:
exps.append({"id":f"{slug(city)}_{cate}","name":nt.format(c=city),"category":cate,
"location":f"{city}, {abbrev}".strip(", ") if abbrev else f"{city}, {country}",
"city":city,"keywords":kws,"desc":desc.format(c=city),
"price":round(random.uniform(*pr),0),"rating":round(random.uniform(4.1,4.9),1)})
cat[city]=exps
return cat
CATALOG=build_catalog()
DATES=[f"2026-{m:02d}-{d:02d}" for m in range(3,11) for d in (8,12,15,19,22,26)]
OCCASIONS=["my honeymoon","my 30th birthday","a solo trip","our family vacation","our anniversary",
"a girls' trip","my first big trip abroad","a long weekend away","my retirement trip",
"a graduation celebration","a reunion with old friends"]
VIBES={"hiking":"something active outdoors","snorkel_reef":"something out on the water","kayak":"something on the water",
"cooking":"something hands-on with local food","food_tour":"a food experience","museum":"something cultural",
"bike":"something active but relaxed","sailing":"something on the water at sunset","hot_spring":"somewhere to relax",
"stargaze":"something at night under the stars","surf":"to try something adventurous","pottery":"a hands-on craft",
"coffee":"a local food-and-drink thing","waterfall":"a nature hike","walk":"a way to see the old town"}
OPENERS_BROAD=[
"Hi! I'm heading to {loc} next month for {occ} and I'd love to book {vibe}. Can you help?",
"Planning {occ} in {loc}. I want to do {vibe}. What can you find and book for me?",
"We'll be in {loc} for {occ}. Could you find {vibe} and book it? Use your best judgment.",
"I'm visiting {loc} for {occ}. Looking for {vibe}, please just find something good and book it.",
"Booking help please: {loc}, {occ}, ideally {vibe}. Go ahead and sort it out."]
OPENERS_CITY=[
"Hi! I'll be in {city} for {occ}. Please find and book {vibe}.",
"I'm spending {occ} in {city}. Can you book {vibe} for me?",
"Heading to {city} for {occ}. Sort out {vibe} please, your pick is fine.",
"In {city} next month for {occ}. Book {vibe} for me, thanks!"]
SYSTEM=("You are a helpful travel booking assistant. Use the provided tools to search for experiences, "
"look up details, check availability, and purchase tickets. Search matches on the location string, "
"so use a specific city (a country, state, or island is often too broad to match). If a search returns "
"nothing, do not repeat the same call: narrow to the city, add or adjust the `keywords`, or try a "
"different tool. Complete the user's booking end to end.")
TOOLS=[
{"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"]}}},
{"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"]}}},
{"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"]}}},
{"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"]}}}]
_cid=[0]
def cid():
_cid[0]+=1; return f"call_{_cid[0]:08d}"
def a_call(name,args,content=""):
i=cid(); return {"role":"assistant","content":content,"tool_calls":[{"id":i,"type":"function","function":{"name":name,"arguments":args}}]}, i
def t_res(i,name,content): return {"role":"tool","tool_call_id":i,"name":name,"content":content}
def r_empty(loc): return f"No experiences found in '{loc}'. Try a different location or broader keywords."
def r_hits(loc,exps):
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)
return f"Found {len(exps)} experience(s) in {loc}:\n\n{body}"
def r_details(e):
return (f"Name: {e['name']}\n ID: {e['id']}\n Location: {e['location']}\n Description: {e['desc']}\n"
f" Price: ${e['price']:.0f} per person\n Rating: {e['rating']}\n Tags: {', '.join(e['keywords'])}\n"
f" Availability: generally available; use check_availability for a specific date.")
def r_avail(e,date,n):
ds=f" on {date}" if date else ""
return (f"Availability for {e['name']}{ds}:\n Status: Available\n Tickets requested: {n}\n"
f" Price per ticket: ${e['price']:.0f}\n Total: ${e['price']*n:.0f}")
def r_purchase(e,n,ttype):
code="BK"+"".join(random.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(6))
return (f"Booking Confirmed!\n Experience: {e['name']}\n Location: {e['location']}\n Tickets: {n} x {ttype}\n"
f" Total Charged: ${e['price']*n:.0f}\n Confirmation ID: {code}\n Status: confirmed")
def finish(msgs, city, target, n, date, occ):
m,i=a_call("get_experience_details",{"experience_id":target["id"]}, "This looks like a great fit. Let me pull up the details.")
msgs+= [m, t_res(i,"get_experience_details",r_details(target))]
m,i=a_call("check_availability",{"experience_id":target["id"],"date":date,"num_tickets":n}, "Let me confirm availability.")
msgs+= [m, t_res(i,"check_availability",r_avail(target,date,n))]
m,i=a_call("purchase_tickets",{"experience_id":target["id"],"num_tickets":n,"ticket_type":"standard"}, "It's available. Booking it now.")
msgs+= [m, t_res(i,"purchase_tickets",r_purchase(target,n,"standard"))]
msgs.append({"role":"assistant","content":
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}!"})
def make(pattern):
city,abbrev,country,broad=random.choice(CITIES)
exps=CATALOG[city]; target=random.choice(exps); occ=random.choice(OCCASIONS)
vibe=VIBES.get(target["category"],"something memorable"); n=random.choice([1,1,1,2,2,3,4]); date=random.choice(DATES)
msgs=[{"role":"system","content":SYSTEM}]
if pattern=="direct_success":
msgs.append({"role":"user","content":random.choice(OPENERS_CITY).format(city=city,occ=occ,vibe=vibe)})
if random.random()<0.5:
kw=random.choice(target["keywords"])
m,i=a_call("search_experiences",{"location":city,"keywords":kw}, f"Let me search {city} for {kw} options.")
msgs+=[m,t_res(i,"search_experiences",r_hits(city,[target]))]
else:
m,i=a_call("search_experiences",{"location":city}, f"Let me search experiences in {city}.")
msgs+=[m,t_res(i,"search_experiences",r_hits(city,exps))]
else:
msgs.append({"role":"user","content":random.choice(OPENERS_BROAD).format(loc=random.choice(broad),occ=occ,vibe=vibe)})
if pattern in ("broad_to_city","two_wrong_then_city"):
tries=random.sample(broad,2) if pattern=="two_wrong_then_city" and len(broad)>=2 else [random.choice(broad)]
for k,bt in enumerate(tries):
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.")
msgs+=[m,t_res(i,"search_experiences",r_empty(bt))]
m,i=a_call("search_experiences",{"location":city}, f"'{tries[-1]}' is too broad for the search. Let me use the specific city, {city}.")
msgs+=[m,t_res(i,"search_experiences",r_hits(city,exps))]
elif pattern=="keyword_refine":
m,i=a_call("search_experiences",{"location":city}, f"Let me search {city}.")
msgs+=[m,t_res(i,"search_experiences",r_hits(city,exps))]
kw=random.choice(target["keywords"])
m,i=a_call("search_experiences",{"location":city,"keywords":kw}, f"Several options came up. Let me narrow with the keyword '{kw}'.")
msgs+=[m,t_res(i,"search_experiences",r_hits(city,[target]))]
else: # bad_keyword_recover
bad=random.choice(["".join(random.sample(target["keywords"][0],len(target["keywords"][0]))), target["keywords"][0]+"xz","ultra-luxury "+target["keywords"][0]])
m,i=a_call("search_experiences",{"location":city,"keywords":bad}, f"Let me search {city} for '{bad}'.")
msgs+=[m,t_res(i,"search_experiences",r_empty(city))]
good=random.choice(target["keywords"])
m,i=a_call("search_experiences",{"location":city,"keywords":good}, f"No matches for that keyword. Let me broaden it to '{good}'.")
msgs+=[m,t_res(i,"search_experiences",r_hits(city,[target]))]
finish(msgs,city,target,n,date,occ)
return {"messages":msgs,"tools":TOOLS,"metadata":{"city":city,"country":country,"target_id":target["id"],"category":target["category"],"pattern":pattern,"num_tickets":n}}
REC=["broad_to_city","two_wrong_then_city","keyword_refine","bad_keyword_recover"]
rows=[]
for _ in range(3000): rows.append(make(random.choice(REC)))
for _ in range(750): rows.append(make("direct_success"))
random.shuffle(rows)
out=os.path.join(os.path.dirname(__file__),"agentic_recovery.jsonl")
with open(out,"w",encoding="utf-8") as f:
for r in rows: f.write(json.dumps(r,ensure_ascii=False)+"\n")
from collections import Counter
print("WROTE",len(rows),"->",out)
print("patterns",dict(Counter(r["metadata"]["pattern"] for r in rows)))
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)))