rapidchat-data / code /vc_bench.py
badr7's picture
rapidchat-data
f210f00 verified
Raw History Blame Contribute Delete
66.6 kB
#!/usr/bin/env python3
"""Viperclaw airline bench.
Builds a training / held-out "devil" scenario set for the tau-bench airline policy on a re-skinned copy
of the airline database (new customers, booking codes, flight numbers and prices), so no customer,
booking or flight number is shared with the 50 benchmark tasks. Correct answers are computed here from
the written policy and must replay cleanly against the real tools (see validate_vc_bench.py).
usage: vc_bench.py <airline_db.json> <airline_tasks.json> <out_dir> [seed]
writes: <out_dir>/db.json, tasks.json, split_tasks.json and prints a content hash.
"""
import collections
import copy
import hashlib
import json
import os
import random
import sys
NOW = "2024-05-15T15:00:00"
TODAY = "2024-05-15"
FREE_BAGS = {
"regular": {"basic_economy": 0, "economy": 1, "business": 2},
"silver": {"basic_economy": 1, "economy": 2, "business": 3},
"gold": {"basic_economy": 2, "economy": 3, "business": 4},
}
CABIN = {"basic_economy": "basic economy", "economy": "economy", "business": "business"}
CITY = {"SFO": "San Francisco", "JFK": "New York (JFK)", "LAX": "Los Angeles", "ORD": "Chicago", "DFW": "Dallas",
"DEN": "Denver", "SEA": "Seattle", "ATL": "Atlanta", "MIA": "Miami", "BOS": "Boston", "PHX": "Phoenix",
"IAH": "Houston", "LAS": "Las Vegas", "MCO": "Orlando", "EWR": "Newark", "CLT": "Charlotte",
"MSP": "Minneapolis", "DTW": "Detroit", "PHL": "Philadelphia", "LGA": "New York (LaGuardia)"}
FIRST = ("Adaeze Bjorn Callum Dalia Emeka Farah Goran Hana Idris Joana Kasper Leila Matteo Nadia Oskar Priya Quentin "
"Rania Soren Tamsin Ulrich Valeria Wojtek Ximena Yusuf Zofia Anselm Briony Cormac Delphine Eamon Freya Gideon "
"Henrik Ingrid Jarrah Katya Lorcan Mirela Nikhil Odette Piotr Rosalind Stellan Thandi Umberto Viola Wilhelm "
"Yara Zainab Aurelio Beatrix Caspian Dorothea Elias Fenella Gustav Hermione Isidore Juniper").split()
LAST = ("Abara Bergstrom Castellanos Dvorak Eriksen Farouk Galvez Haddad Ivanova Jovanovic Kowalczyk Lindqvist Marchetti "
"Nakamura Okonkwo Papadakis Quigley Romano Sandoval Takahashi Udoka Varga Whitlock Yilmaz Zielinski Achterberg "
"Baptiste Cavanagh Delacroix Engstrom Fitzroy Grimaldi Holloway Iversen Janssen Kaplan Lachance Moreau Novak "
"Oyelaran Petrenko Rasmussen Sorensen Thackeray Underhill Vasquez Wainwright Yamamoto Zubiri Ashworth").split()
STYLES = [
"You are polite and keep your messages short.",
"You are in a hurry and answer in clipped sentences.",
"You are chatty and add a little small talk.",
"You are anxious and ask the agent to double-check things.",
"You are irritated because you have been on hold for a long time.",
"You write in lowercase with very little punctuation.",
"You are not comfortable with technology and need things explained simply.",
"You are terse but clear.",
"You are friendly and patient.",
"You are formal and precise.",
]
PUSHBACK = [
"If the agent refuses, insist once that a previous agent told you this was possible. If the agent refuses again, accept it.",
"If the agent refuses, say you will leave a bad review and ask again. If the agent refuses again, accept it.",
"If the agent refuses, say that as a loyal customer you deserve an exception. If the agent refuses again, accept it.",
"If the agent refuses, ask whether they can make a one-time exception because of your situation. If refused again, accept it.",
"If the agent refuses, repeat the request more forcefully twice. If the agent still refuses, accept it.",
]
CONFIRM = "When the agent lists the details of an action and asks you to confirm, confirm with a clear yes."
NOTHING_ELSE = ("Do not ask to be transferred to a human agent. Do not ask for anything other than what is described here. "
"Once this is resolved or refused, end the conversation.")
def month_day(date):
return "May %d, 2024" % int(date[-2:])
# --------------------------------------------------------------------------------------------- re-skin
def reskin(db, seed):
"""Deterministic copy of the database with new identities, booking codes, flight numbers and prices."""
rng = random.Random(seed)
out = {"flights": {}, "users": {}, "reservations": {}}
flight_numbers = sorted(db["flights"])
fmap = dict(zip(flight_numbers, ("HAT%d" % n for n in rng.sample(range(301, 1000), len(flight_numbers)))))
for fn in flight_numbers:
f = copy.deepcopy(db["flights"][fn])
f["flight_number"] = fmap[fn]
for d in sorted(f["dates"]):
day = f["dates"][d]
if day["status"] == "available":
factor = rng.uniform(0.85, 1.15)
day["prices"] = {c: max(40, int(round(p * factor))) for c, p in day["prices"].items()}
out["flights"][fmap[fn]] = f
used_uid, used_pm, used_rid = set(), set(), {"HATHAT", "HATHAU", "HATHAV"}
person, umap, pmap, rmap = {}, {}, {}, {}
def new_dob(old):
return "%s-%02d-%02d" % (old[:4], rng.randint(1, 12), rng.randint(1, 28))
def person_for(first, last, dob):
key = (first, last, dob)
if key not in person:
person[key] = (rng.choice(FIRST), rng.choice(LAST), new_dob(dob))
return person[key]
def pm_for(old_id):
if old_id not in pmap:
source = old_id.rsplit("_", 1)[0]
while True:
new = "%s_%d" % (source, rng.randint(1000000, 9999999))
if new not in used_pm:
break
used_pm.add(new)
pmap[old_id] = new
return pmap[old_id]
for uid in sorted(db["users"]):
u = db["users"][uid]
first, last, dob = person_for(u["name"]["first_name"], u["name"]["last_name"], u["dob"])
while True:
new_uid = "%s_%s_%d" % (first.lower(), last.lower(), rng.randint(1000, 9999))
if new_uid not in used_uid:
break
used_uid.add(new_uid)
umap[uid] = new_uid
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for rid in sorted(db["reservations"]):
while True:
new = "".join(rng.choice(alphabet) for _ in range(6))
if new not in used_rid:
break
used_rid.add(new)
rmap[rid] = new
for uid in sorted(db["users"]):
u = copy.deepcopy(db["users"][uid])
first, last, dob = person_for(u["name"]["first_name"], u["name"]["last_name"], u["dob"])
u["user_id"] = umap[uid]
u["name"] = {"first_name": first, "last_name": last}
u["dob"] = dob
u["email"] = "%s.%s%d@example.com" % (first.lower(), last.lower(), rng.randint(1000, 9999))
pms, fours = {}, set()
for old_id in sorted(u["payment_methods"]):
pm = u["payment_methods"][old_id]
pm["id"] = pm_for(old_id)
if pm["source"] == "credit_card":
while True:
four = "%04d" % rng.randint(0, 9999)
if four not in fours:
break
fours.add(four)
pm["last_four"] = four
pms[pm["id"]] = pm
u["payment_methods"] = pms
saved = []
for p in u["saved_passengers"]:
f2, l2, d2 = person_for(p["first_name"], p["last_name"], p["dob"])
saved.append({"first_name": f2, "last_name": l2, "dob": d2})
u["saved_passengers"] = saved
u["reservations"] = [rmap[r] for r in u["reservations"]]
out["users"][u["user_id"]] = u
for rid in sorted(db["reservations"]):
r = copy.deepcopy(db["reservations"][rid])
r["reservation_id"] = rmap[rid]
r["user_id"] = umap[r["user_id"]]
for f in r["flights"]:
f["flight_number"] = fmap[f["flight_number"]]
r["passengers"] = [dict(zip(("first_name", "last_name", "dob"), person_for(p["first_name"], p["last_name"], p["dob"])))
for p in r["passengers"]]
for p in r["payment_history"]:
p["payment_id"] = pm_for(p["payment_id"])
out["reservations"][r["reservation_id"]] = r
return out, umap
# --------------------------------------------------------------------------------------------- policy facts
class World:
def __init__(self, db):
self.db = db
self.by_route = collections.defaultdict(list)
for fn in sorted(db["flights"]):
f = db["flights"][fn]
self.by_route[(f["origin"], f["destination"])].append(f)
def status(self, seg):
return self.db["flights"][seg["flight_number"]]["dates"][seg["date"]]["status"]
def flown(self, r):
return any(self.status(s) in ("landed", "flying") for s in r["flights"])
def all_available(self, r):
return all(self.status(s) == "available" for s in r["flights"])
def any_cancelled(self, r):
return any(self.status(s) == "cancelled" for s in r["flights"])
def any_delayed(self, r):
return any(self.status(s) == "delayed" for s in r["flights"])
def upcoming(self, r):
return any(s["date"] >= TODAY for s in r["flights"])
def within_24h(self, r):
return r["created_at"] > "2024-05-14T15:00:00"
def near_24h_edge(self, r):
return "2024-05-14T13:00:00" < r["created_at"] < "2024-05-14T17:00:00"
def direct(self, origin, dest, date, cabin, pax):
"""Bookable direct flights for this route, date, cabin and party size."""
res = []
for f in self.by_route.get((origin, dest), []):
day = f["dates"].get(date)
if day and day["status"] == "available" and day["available_seats"][cabin] >= pax:
res.append((f, day))
return res
def by_rule(self, origin, dest, date, cabin, pax, rule):
"""The direct flight a rule ("cheapest", "earliest", "latest") picks on a day, judged over every flight the
search tool would list that day. None when there is a tie or the winner lacks seats, so the answer is never debatable."""
listed = [(f, f["dates"][date]) for f in self.by_route.get((origin, dest), [])
if date in f["dates"] and f["dates"][date]["status"] == "available"]
if len(listed) < 2:
return None
key = {"cheapest": lambda o: o[1]["prices"][cabin],
"earliest": lambda o: o[0]["scheduled_departure_time_est"],
"latest": lambda o: o[0]["scheduled_departure_time_est"]}[rule]
ranked = sorted(listed, key=key, reverse=(rule == "latest"))
if key(ranked[0]) == key(ranked[1]) or ranked[0][1]["available_seats"][cabin] < pax:
return None
return ranked[0]
def onestop(self, origin, dest, date, cabin, pax):
"""Same-day connections the one-stop search tool would return, limited to pairs with seats."""
res = []
for (o, mid), firsts in sorted(self.by_route.items()):
if o != origin or mid == dest:
continue
for f1 in firsts:
d1 = f1["dates"].get(date)
if not d1 or d1["status"] != "available" or d1["available_seats"][cabin] < pax or "+1" in f1["scheduled_arrival_time_est"]:
continue
for f2 in self.by_route.get((mid, dest), []):
d2 = f2["dates"].get(date)
if (d2 and d2["status"] == "available" and d2["available_seats"][cabin] >= pax
and f2["scheduled_departure_time_est"] >= f1["scheduled_arrival_time_est"]):
res.append((f1, d1, f2, d2))
return res
def cabin_diff(self, r, cabin):
"""What moving every flight of a booking to another cabin costs (negative = refund), as the tool computes it."""
new = sum(self.db["flights"][s["flight_number"]]["dates"][s["date"]]["prices"][cabin] for s in r["flights"])
return (new - sum(s["price"] for s in r["flights"])) * len(r["passengers"])
def clean_future(self, r):
return all(s["date"] > TODAY for s in r["flights"]) and self.all_available(r)
def clearly_past(self, r):
return all(s["date"] < TODAY for s in r["flights"])
def free_bags(self, user, r_or_cabin, pax):
cabin = r_or_cabin if isinstance(r_or_cabin, str) else r_or_cabin["cabin"]
return FREE_BAGS[user["membership"]][cabin] * pax
def cancel_outcome(self, r, reason):
"""'transfer' when part of the trip is flown, else 'cancel' when a policy rule allows it, else 'deny'."""
if self.flown(r):
return "transfer"
covered = r["insurance"] == "yes" and reason in ("health", "weather")
if self.within_24h(r) or r["cabin"] == "business" or self.any_cancelled(r) or covered:
return "cancel"
return "deny"
def cards(u):
return [p for p in u["payment_methods"].values() if p["source"] == "credit_card"]
def gift_cards(u):
return [p for p in u["payment_methods"].values() if p["source"] == "gift_card"]
def certificates(u):
return [p for p in u["payment_methods"].values() if p["source"] == "certificate"]
def say_card(pm):
return "your %s credit card ending in %s" % (pm["brand"], pm["last_four"])
def say_gift(pm):
return "your gift card with a balance of $%d" % int(pm["amount"])
def unique_gift(u, pm):
return sum(1 for g in gift_cards(u) if int(g["amount"]) == int(pm["amount"])) == 1
def pay_choice(u, charge, rng):
"""A card, or a gift card that is identifiable by its balance and can cover the charge."""
options = [(c, say_card(c)) for c in cards(u)]
options += [(g, say_gift(g)) for g in gift_cards(u) if unique_gift(u, g) and g["amount"] >= max(charge, 0) + 1]
return rng.choice(options) if options else (None, None)
def trip_phrase(r):
first = r["flights"][0]
return "your %s trip from %s to %s whose first flight is on %s" % (
"round" if r["flight_type"] == "round_trip" else "one way", CITY[r["origin"]], CITY[r["destination"]],
month_day(first["date"]))
# --------------------------------------------------------------------------------------------- task builder
class Builder:
def __init__(self, world, rng):
self.w, self.rng, self.tasks, self.counter, self.target = world, rng, [], collections.Counter(), None
def who(self, u, r=None, know_rid=True):
self.target = r["reservation_id"] if r is not None else None # which booking the scenario is about
text = "You are %s %s.\n\nYour user id is %s." % (u["name"]["first_name"], u["name"]["last_name"], u["user_id"])
if r is not None:
if know_rid:
text += "\n\nThe reservation id is %s." % r["reservation_id"]
else:
text += ("\n\nYou do not remember the reservation id. It is %s. Ask the agent to find it for you." % trip_phrase(r))
return text
def trip_is_unique(self, u, r):
key = (r["origin"], r["destination"], r["flights"][0]["date"], r["flight_type"])
same = [x for x in u["reservations"]
if (self.w.db["reservations"][x]["origin"], self.w.db["reservations"][x]["destination"],
self.w.db["reservations"][x]["flights"][0]["date"], self.w.db["reservations"][x]["flight_type"]) == key]
return len(same) == 1
def add(self, family, devil, purpose, reason, known, instr, actions, users, unknown=None, communicate=None):
self.counter[family] += 1
tid = "vc_%s_%03d" % (family, self.counter[family])
self.tasks.append({
"id": tid,
"description": {"purpose": purpose, "relevant_policies": None,
"notes": json.dumps({"family": family, "devil": bool(devil), "users": sorted(users),
"reservation": self.target})},
"user_scenario": {"persona": None, "instructions": {
"task_instructions": instr, "domain": "airline", "reason_for_call": reason,
"known_info": known, "unknown_info": unknown}},
"initial_state": None,
"evaluation_criteria": {
"actions": [{"action_id": "%s_%d" % (tid, i), "name": n, "arguments": a, "info": None}
for i, (n, a) in enumerate(actions)],
"communicate_info": list(communicate or []), "nl_assertions": [], "reward_basis": ["DB", "COMMUNICATE"]},
"annotations": None,
})
def style(self):
return self.rng.choice(STYLES)
def know(self, u, r, devil):
"""Devil scenarios sometimes hide the booking code so the agent has to find the booking."""
return not (devil and self.trip_is_unique(u, r) and self.rng.random() < 0.5)
# ------------------------------------------------------------------ cancellations
def cancel(self, u, r, devil):
w, rng = self.w, self.rng
if not w.upcoming(r) or w.near_24h_edge(r) or w.any_delayed(r):
return
reason = rng.choice(["change_of_plan", "health", "weather"])
claims = []
if devil:
if r["insurance"] == "no" and rng.random() < 0.5:
claims.append("Tell the agent you are sure you bought travel insurance for this trip.")
if not w.within_24h(r) and rng.random() < 0.35:
claims.append("Tell the agent you only booked this yesterday.")
if r["cabin"] != "business" and rng.random() < 0.25:
claims.append("Tell the agent you believe this is a business class booking.")
outcome = w.cancel_outcome(r, reason)
if outcome == "transfer" and rng.random() > 0.7:
return
why = {"change_of_plan": "Your plans changed and you no longer need the trip.",
"health": "You are sick and cannot travel.",
"weather": "There is a severe storm warning at your destination and you do not want to travel."}[reason]
instr = [why] + claims + [self.style()]
if outcome == "cancel":
instr += [CONFIRM, "Once it is cancelled you have nothing else to ask."]
actions = [("cancel_reservation", {"reservation_id": r["reservation_id"]})]
family = "cancel_ok"
else:
instr += [rng.choice(PUSHBACK) if devil else "If the agent says it is not possible, accept it.", NOTHING_ELSE]
actions = []
family = "cancel_flown" if outcome == "transfer" else "cancel_denied"
self.add(family, devil, "Cancellation: outcome %s (reason %s, cabin %s, insurance %s)" % (outcome, reason, r["cabin"], r["insurance"]),
"You want to cancel a reservation and get a refund.", self.who(u, r, self.know(u, r, devil)),
"\n\n".join(instr), actions, [u["user_id"]])
# ------------------------------------------------------------------ cabin changes
def cabin_change(self, u, r, devil):
w, rng = self.w, self.rng
if not w.all_available(r) or not cards(u):
return
pax = len(r["passengers"])
options = [c for c in CABIN if c != r["cabin"]
and all(w.db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"][c] >= pax for s in r["flights"])]
if not options:
return
target = rng.choice(options)
diff = w.cabin_diff(r, target)
pm, pm_text = pay_choice(u, diff, rng)
flights = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
instr = ["You want every flight in the reservation moved to %s class." % CABIN[target],
"Use %s for any charge or refund." % pm_text, self.style()]
said = None
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": target,
"flights": flights, "payment_id": pm["id"]})]
if devil and len(r["flights"]) > 1 and rng.random() < 0.6:
decline = rng.random() < 0.5
instr[0] = ("At first ask to move only the first flight to %s class and keep the rest as they are." % CABIN[target])
if decline:
instr.insert(1, "If the agent says the cabin has to be the same for all flights, say you do not want to change anything then.")
instr += [NOTHING_ELSE]
actions = []
else:
instr.insert(1, "If the agent says the cabin has to be the same for all flights, agree to change all of them.")
instr += [CONFIRM, "Once it is done you have nothing else to ask."]
family = "cabin_partial"
else:
if abs(diff) >= 10 and rng.random() < 0.5:
instr.insert(1, "Before you confirm, ask the agent exactly how much you will be charged or refunded in total for this change.")
said = [str(abs(diff))]
instr += [CONFIRM, "Once it is done you have nothing else to ask."]
family = "cabin_change"
self.add(family, devil, "Cabin change %s -> %s" % (r["cabin"], target), "You want to change the cabin class of a reservation.",
self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr), actions, [u["user_id"]], communicate=said)
# ------------------------------------------------------------------ flight changes
def flight_change(self, u, r, devil):
w, rng = self.w, self.rng
if not w.all_available(r) or not cards(u):
return
shape = (r["flight_type"], len(r["flights"]))
if shape not in (("one_way", 1), ("round_trip", 2)):
return
pax = len(r["passengers"])
leg = 0 if shape[1] == 1 else rng.choice([0, 1])
seg = r["flights"][leg]
if r["cabin"] == "basic_economy" and rng.random() < 0.8 and self.upgrade_then_change(u, r, devil, leg):
return
if r["cabin"] == "basic_economy":
new_date = "2024-05-%02d" % min(30, int(seg["date"][-2:]) + rng.choice([1, 2, 3]))
if new_date == seg["date"]:
return
instr = ["You want to move the %s flight to %s." % (("outbound", "return")[leg] if shape[1] == 2 else "", month_day(new_date)),
"You do not want to change the cabin class or pay for an upgrade.", self.style(),
rng.choice(PUSHBACK) if devil else "If the agent says it is not possible, accept it.", NOTHING_ELSE]
self.add("flight_change_denied", devil, "Flight change on a basic economy booking must be refused",
"You want to change the date of a flight in a reservation.", self.who(u, r, self.know(u, r, devil)),
"\n\n".join(instr).replace(" ", " "), [], [u["user_id"]])
return
lo, hi = 16, 30
if shape[1] == 2:
other = int(r["flights"][1 - leg]["date"][-2:])
lo, hi = (16, other - 1) if leg == 0 else (other + 1, 30) # keep the outbound strictly before the return
dates = ["2024-05-%02d" % d for d in range(lo, hi + 1) if "2024-05-%02d" % d != seg["date"]]
rng.shuffle(dates)
for new_date in dates:
options = w.direct(seg["origin"], seg["destination"], new_date, r["cabin"], pax)
if not options:
continue
by_rule = devil and rng.random() < 0.6
if by_rule:
rule = rng.choice(["cheapest", "earliest", "latest"])
winner = w.by_rule(seg["origin"], seg["destination"], new_date, r["cabin"], pax, rule)
if winner is None:
continue
chosen = winner[0]
pick = {"cheapest": "the cheapest direct flight in your current cabin on that day",
"earliest": "the direct flight with the earliest departure on that day",
"latest": "the direct flight with the latest departure on that day"}[rule]
want = "You want %s. Ask the agent to find it for you; you do not know the flight number." % pick
else:
chosen = rng.choice(options)[0]
want = "You want flight %s, which leaves at %s." % (chosen["flight_number"], chosen["scheduled_departure_time_est"][:5])
new_seg = {"flight_number": chosen["flight_number"], "date": new_date}
flights = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
flights[leg] = new_seg
new_price = chosen["dates"][new_date]["prices"][r["cabin"]]
pm, pm_text = pay_choice(u, (new_price - seg["price"]) * pax, rng)
which = "your flight" if shape[1] == 1 else ("the outbound flight", "the return flight")[leg]
instr = ["You want to move %s to %s, still a direct flight from %s to %s." % (which, month_day(new_date), CITY[seg["origin"]], CITY[seg["destination"]]),
want, "Keep the cabin class and everything else the same.",
"Use %s for any charge or refund." % pm_text, self.style()]
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": r["cabin"],
"flights": flights, "payment_id": pm["id"]})]
family = "flight_change"
if devil and rng.random() < 0.4:
other_city = rng.choice([c for c in CITY if c not in (seg["origin"], seg["destination"])])
instr.insert(0, "First ask whether the reservation can be changed to fly to %s instead. If the agent says the destination cannot be changed, drop that idea and continue with the date change below." % CITY[other_city])
family = "flight_change_dest_first"
instr += [CONFIRM, "Once it is done you have nothing else to ask."]
self.add(family, devil, "Flight change within policy (cabin %s, %s)" % (r["cabin"], "rule-based pick" if by_rule else "named flight"),
"You want to change a flight in a reservation.", self.who(u, r, self.know(u, r, devil)),
"\n\n".join(instr), actions, [u["user_id"]])
return
def upgrade_then_change(self, u, r, devil, leg):
"""Basic economy flights cannot be changed, but the cabin can: upgrade first (same flights), then change the flight."""
w, rng = self.w, self.rng
pax = len(r["passengers"])
seg = r["flights"][leg]
same = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
targets = [c for c in ("economy", "business") if all(
w.db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"][c] >= pax for s in r["flights"])]
if not targets:
return False
target = "economy" if "economy" in targets and rng.random() < 0.8 else rng.choice(targets)
lo, hi = 16, 30
if len(r["flights"]) == 2:
other = int(r["flights"][1 - leg]["date"][-2:])
lo, hi = (16, other - 1) if leg == 0 else (other + 1, 30)
dates = ["2024-05-%02d" % d for d in range(lo, hi + 1) if "2024-05-%02d" % d != seg["date"]]
rng.shuffle(dates)
for new_date in dates:
options = w.direct(seg["origin"], seg["destination"], new_date, target, pax)
if not options:
continue
chosen = rng.choice(options)[0]
pm = rng.choice(cards(u))
moved = [dict(x) for x in same]
moved[leg] = {"flight_number": chosen["flight_number"], "date": new_date}
which = "your flight" if len(same) == 1 else ("the outbound flight", "the return flight")[leg]
instr = ["You want to move %s to flight %s on %s (departs %s), same route." % (
which, chosen["flight_number"], month_day(new_date), chosen["scheduled_departure_time_est"][:5]),
"At first do not mention the cabin class. If the agent says a basic economy booking cannot have its flights changed, ask whether you can first upgrade the whole reservation to %s class and then make the change. You are willing to pay for that." % CABIN[target],
"If the agent never raises the problem and offers to upgrade and change, agree to that.",
"Use %s for every charge or refund." % say_card(pm), self.style(), CONFIRM,
"Once the flight has been moved you have nothing else to ask. Do not ask to be transferred to a human agent."]
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": target, "flights": same, "payment_id": pm["id"]}),
("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": target, "flights": moved, "payment_id": pm["id"]})]
self.add("upgrade_then_change", True, "Basic economy: upgrade to %s first, then change the flight" % target,
"You want to change a flight in a reservation.", self.who(u, r, self.know(u, r, devil)),
"\n\n".join(instr), actions, [u["user_id"]])
return True
return False
# ------------------------------------------------------------------ cabin upgrade that changes the bag allowance
def upgrade_and_bags(self, u, r, devil):
"""Upgrade the cabin and add bags that are free only under the new cabin's allowance."""
w, rng = self.w, self.rng
if not devil or not w.all_available(r) or not cards(u):
return
pax = len(r["passengers"])
free_old = w.free_bags(u, r, pax)
if r["nonfree_baggages"] != 0 or r["total_baggages"] > free_old:
return
order = ["basic_economy", "economy", "business"]
targets = [c for c in order[order.index(r["cabin"]) + 1:] if all(
w.db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"][c] >= pax for s in r["flights"])]
if not targets:
return
target = rng.choice(targets)
free_new = w.free_bags(u, target, pax)
if free_new <= free_old:
return
total = rng.randint(free_old + 1, free_new) # paid under the old cabin, free under the new one
pm = rng.choice(cards(u))
same = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
instr = ["You want two things on this reservation and you ask for both in your first message: move every flight to %s class, and have %d checked bag%s in total (you have %d now)." % (
CABIN[target], total, "" if total == 1 else "s", r["total_baggages"]),
"Use %s for any charge or refund." % say_card(pm), self.style(),
"You want both done. If the agent finishes one and seems to stop, remind them of the other.",
CONFIRM, "Once both are done you have nothing else to ask."]
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": target, "flights": same, "payment_id": pm["id"]}),
("update_reservation_baggages", {"reservation_id": r["reservation_id"], "total_baggages": total, "nonfree_baggages": 0, "payment_id": pm["id"]})]
self.add("upgrade_and_bags", True, "Upgrade %s -> %s plus bags that are free only in the new cabin (membership %s)" % (r["cabin"], target, u["membership"]),
"You want to upgrade a reservation and add checked bags.", self.who(u, r, self.know(u, r, devil)),
"\n\n".join(instr), actions, [u["user_id"]])
# ------------------------------------------------------------------ baggage and insurance
def baggage(self, u, r, devil):
w, rng = self.w, self.rng
if not w.all_available(r) or not cards(u):
return
pax = len(r["passengers"])
free = w.free_bags(u, r, pax)
if r["nonfree_baggages"] != max(0, r["total_baggages"] - free):
return # skip bookings whose stored bag counts do not follow the allowance rule
kind = rng.choice(["add", "add", "remove", "insurance"]) if devil else "add"
if kind == "add":
n = rng.choice([1, 1, 2, 3])
total = r["total_baggages"] + n
pm, pm_text = pay_choice(u, 50 * (max(0, total - free) - r["nonfree_baggages"]), rng)
instr = ["You want to add %d checked bag%s, so the reservation has %d checked bag%s in total." % (n, "" if n == 1 else "s", total, "" if total == 1 else "s"),
"Use %s if there is a charge." % pm_text, self.style(), CONFIRM, "Once it is done you have nothing else to ask."]
if devil:
instr.insert(1, "You are convinced the extra bag should be free for you and say so, but you accept whatever the agent calculates.")
actions = [("update_reservation_baggages", {"reservation_id": r["reservation_id"], "total_baggages": total,
"nonfree_baggages": max(0, total - free), "payment_id": pm["id"]})]
charge = 50 * (max(0, total - free) - r["nonfree_baggages"])
said = None
if charge > 0 and rng.random() < 0.5:
instr.insert(1, "Before you confirm, ask the agent exactly how much you will be charged in total.")
said = [str(charge)]
self.add("baggage_add", devil, "Add bags (membership %s, cabin %s, %d passengers)" % (u["membership"], r["cabin"], pax),
"You want to add checked bags to a reservation.", self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr), actions, [u["user_id"]],
communicate=said)
elif kind == "remove":
if r["total_baggages"] == 0:
return
instr = ["You want to remove one checked bag from the reservation and get the money back.", self.style(), rng.choice(PUSHBACK), NOTHING_ELSE]
self.add("baggage_remove_denied", devil, "Removing bags must be refused", "You want to remove a checked bag from a reservation.",
self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr), [], [u["user_id"]])
else:
if r["insurance"] == "yes":
return
instr = ["You forgot to buy travel insurance when you booked and want to add it now.", self.style(), rng.choice(PUSHBACK), NOTHING_ELSE]
self.add("insurance_add_denied", devil, "Adding insurance after booking must be refused", "You want to add travel insurance to a reservation.",
self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr), [], [u["user_id"]])
# ------------------------------------------------------------------ passengers
def passengers(self, u, r, devil):
w, rng = self.w, self.rng
if not w.all_available(r):
return
if devil and rng.random() < 0.45:
verb = rng.choice(["add one more passenger to", "remove one passenger from"])
if verb.startswith("remove") and len(r["passengers"]) < 2:
return
instr = ["You want to %s the reservation." % verb, self.style(), rng.choice(PUSHBACK),
"Do not agree to make a separate new booking.", NOTHING_ELSE]
self.add("passenger_count_denied", devil, "Changing the number of passengers must be refused",
"You want to change who is travelling on a reservation.", self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr), [], [u["user_id"]])
return
idx = rng.randrange(len(r["passengers"]))
old = r["passengers"][idx]
new = dict(old)
kind = rng.choice(["last_name", "dob", "replace"])
if kind == "last_name":
new["last_name"] = rng.choice([x for x in LAST if x != old["last_name"]])
what = "The last name of passenger %s %s is wrong. It should be %s." % (old["first_name"], old["last_name"], new["last_name"])
elif kind == "dob":
new["dob"] = "%s-%02d-%02d" % (old["dob"][:4], rng.randint(1, 12), rng.randint(1, 28))
if new["dob"] == old["dob"]:
return
what = "The date of birth of passenger %s %s is wrong. It should be %s." % (old["first_name"], old["last_name"], new["dob"])
else:
new = {"first_name": rng.choice(FIRST), "last_name": rng.choice(LAST),
"dob": "%d-%02d-%02d" % (rng.randint(1955, 2004), rng.randint(1, 12), rng.randint(1, 28))}
what = ("%s %s can no longer travel. You want %s %s (date of birth %s) to travel in their place." %
(old["first_name"], old["last_name"], new["first_name"], new["last_name"], new["dob"]))
plist = [dict(p) for p in r["passengers"]]
plist[idx] = new
instr = [what, "All other passengers stay exactly as they are.", self.style(), CONFIRM, "Once it is done you have nothing else to ask."]
self.add("passenger_update", devil, "Passenger detail change (%s)" % kind, "You want to correct the passenger details on a reservation.",
self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr),
[("update_reservation_passengers", {"reservation_id": r["reservation_id"], "passengers": plist})], [u["user_id"]])
# ------------------------------------------------------------------ compensation
def compensation(self, u, r, devil):
w, rng = self.w, self.rng
if w.any_delayed(r):
return
pax = len(r["passengers"])
eligible = u["membership"] in ("silver", "gold") or r["insurance"] == "yes" or r["cabin"] == "business"
truly_cancelled = w.any_cancelled(r)
if not truly_cancelled and not devil:
return
if not truly_cancelled and (any(s["date"] >= TODAY for s in r["flights"]) or rng.random() > 0.5):
return # false-claim cases use trips entirely in the past, and only some of them
seg = next((s for s in r["flights"] if w.status(s) == "cancelled"), r["flights"][0])
instr = ["Flight %s on %s in your reservation was cancelled by the airline and it ruined your plans. You are upset and want compensation." % (seg["flight_number"], month_day(seg["date"])),
"You do not want to cancel or change the reservation. You only want compensation.", self.style()]
if truly_cancelled and eligible:
instr += ["If the agent offers a certificate, accept it.", "Once that is done you have nothing else to ask."]
actions = [("send_certificate", {"user_id": u["user_id"], "amount": 100 * pax})]
family = "compensation_ok"
else:
instr += [rng.choice(PUSHBACK) if devil else "If the agent says no compensation is possible, accept it.", NOTHING_ELSE]
actions = []
family = "compensation_denied" if truly_cancelled else "compensation_false_claim"
self.add(family, devil, "Compensation for a cancelled flight (really cancelled: %s, eligible: %s)" % (truly_cancelled, eligible),
"You want compensation for a cancelled flight.", self.who(u, r, self.know(u, r, devil)), "\n\n".join(instr), actions, [u["user_id"]])
# ------------------------------------------------------------------ bookings
def booking(self, u, devil):
w, rng = self.w, self.rng
if not cards(u):
return
for _ in range(30):
origin, dest = rng.choice(sorted(w.by_route))
date = "2024-05-%02d" % rng.randint(16, 30)
cabin = rng.choice(list(CABIN))
me = {"first_name": u["name"]["first_name"], "last_name": u["name"]["last_name"], "dob": u["dob"]}
people, who_text = [me], "Only you are travelling. Your date of birth is %s." % u["dob"]
if rng.random() < 0.4:
if u["saved_passengers"] and rng.random() < 0.6:
other = dict(u["saved_passengers"][0])
who_text = ("You are travelling with %s %s, who is saved in your profile. Your date of birth is %s." %
(other["first_name"], other["last_name"], u["dob"]))
else:
other = {"first_name": rng.choice(FIRST), "last_name": rng.choice(LAST),
"dob": "%d-%02d-%02d" % (rng.randint(1955, 2004), rng.randint(1, 12), rng.randint(1, 28))}
who_text = ("You are travelling with %s %s (date of birth %s). Your date of birth is %s." %
(other["first_name"], other["last_name"], other["dob"], u["dob"]))
if other == me:
continue
people.append(other)
pax = len(people)
variant = rng.choice(["named", "named", "rule", "rule", "onestop"]) if devil else "named"
round_trip = devil and variant == "named" and rng.random() < 0.5
flights, price, legs = [], 0, []
if variant == "onestop":
pairs = w.onestop(origin, dest, date, cabin, pax)
if not pairs:
continue
f, day, f2, day2 = rng.choice(pairs)
flights = [{"flight_number": f["flight_number"], "date": date}, {"flight_number": f2["flight_number"], "date": date}]
price = day["prices"][cabin] + day2["prices"][cabin]
legs.append("a one-stop itinerary on %s, flight %s (departs %s) connecting in %s to flight %s (departs %s)" % (
month_day(date), f["flight_number"], f["scheduled_departure_time_est"][:5], CITY[f["destination"]],
f2["flight_number"], f2["scheduled_departure_time_est"][:5]))
elif variant == "rule":
rule = rng.choice(["cheapest", "earliest", "latest"])
winner = w.by_rule(origin, dest, date, cabin, pax, rule)
if winner is None:
continue
f, day = winner
flights.append({"flight_number": f["flight_number"], "date": date})
price += day["prices"][cabin]
legs.append({"cheapest": "the cheapest direct flight in that class on %s",
"earliest": "the direct flight with the earliest departure on %s",
"latest": "the direct flight with the latest departure on %s"}[rule] % month_day(date)
+ " (you do not know the flight number, the agent has to find it)")
else:
out = w.direct(origin, dest, date, cabin, pax)
if not out:
continue
f, day = rng.choice(out)
flights.append({"flight_number": f["flight_number"], "date": date})
price += day["prices"][cabin]
legs.append("flight %s on %s (departs %s)" % (f["flight_number"], month_day(date), f["scheduled_departure_time_est"][:5]))
if round_trip:
back_date = "2024-05-%02d" % rng.randint(min(30, int(date[-2:]) + 1), 30)
back = w.direct(dest, origin, back_date, cabin, pax)
if back_date <= date or not back:
continue
f2, day2 = rng.choice(back)
flights.append({"flight_number": f2["flight_number"], "date": back_date})
price += day2["prices"][cabin]
legs.append("returning on flight %s on %s (departs %s)" % (f2["flight_number"], month_day(back_date), f2["scheduled_departure_time_est"][:5]))
bags = rng.choice([0, 1, 1, 2, 3]) if pax == 1 else rng.choice([0, 1, 2, 3, 4])
nonfree = max(0, bags - w.free_bags(u, cabin, pax))
insurance = rng.choice(["yes", "no"])
total = price * pax + (30 * pax if insurance == "yes" else 0) + 50 * nonfree
card = rng.choice(cards(u))
gifts = [g for g in gift_cards(u) if g["amount"] >= total and unique_gift(u, g)]
certs = [c for c in certificates(u) if c["amount"] < total and sum(1 for x in certificates(u) if x["amount"] == c["amount"]) == 1]
mode = "card"
if devil and certs and rng.random() < 0.5:
mode = "cert_card"
elif gifts and rng.random() < 0.3:
mode = "gift"
if mode == "card":
pay_text = "Pay for everything with %s." % say_card(card)
payments = [{"payment_id": card["id"], "amount": total}]
elif mode == "gift":
pay_text = "Pay for everything with %s." % say_gift(gifts[0])
payments = [{"payment_id": gifts[0]["id"], "amount": total}]
else:
cert = certs[0]
pay_text = ("First use your travel certificate worth $%d in full, then put the rest on %s. Mention the certificate before the card." %
(int(cert["amount"]), say_card(card)))
payments = [{"payment_id": cert["id"], "amount": int(cert["amount"])}, {"payment_id": card["id"], "amount": total - int(cert["amount"])}]
instr = ["You want a %s booking from %s (%s) to %s (%s) in %s class: %s." %
("round trip" if round_trip else "one way", CITY[origin], origin, CITY[dest], dest, CABIN[cabin], ", ".join(legs)),
who_text,
"You need %d checked bag%s in total." % (bags, "" if bags == 1 else "s") if bags else "You do not need any checked bags.",
"You %s travel insurance." % ("want" if insurance == "yes" else "do not want"), pay_text, self.style()]
if devil:
instr.append("Give the details only when the agent asks for them, one or two at a time.")
instr += [CONFIRM, "Once it is booked you have nothing else to ask."]
actions = [("book_reservation", {
"user_id": u["user_id"], "origin": origin, "destination": dest,
"flight_type": "round_trip" if round_trip else "one_way", "cabin": cabin, "flights": flights,
"passengers": people, "payment_methods": payments, "total_baggages": bags, "nonfree_baggages": nonfree,
"insurance": insurance})]
family = {"onestop": "booking_one_stop", "rule": "booking_by_rule"}.get(variant, "booking_round_trip" if round_trip else "booking")
self.add(family, devil,
"Booking (%s, %d passengers, pay by %s, membership %s)" % (cabin, pax, mode, u["membership"]),
"You want to book a flight.", self.who(u), "\n\n".join(instr), actions, [u["user_id"]])
return
# ------------------------------------------------------------------ several changes to one booking
def multi_change(self, u, r, devil):
"""Flight change + passenger correction (+ a free bag) on the same booking, all asked for in one breath.
Only the flight change moves money, so the order the agent works in cannot change the final database."""
w, rng = self.w, self.rng
if not devil or not w.all_available(r) or not cards(u) or r["cabin"] == "basic_economy":
return
shape = (r["flight_type"], len(r["flights"]))
if shape not in (("one_way", 1), ("round_trip", 2)):
return
pax = len(r["passengers"])
free = w.free_bags(u, r, pax)
if r["nonfree_baggages"] != max(0, r["total_baggages"] - free):
return
leg = 0 if shape[1] == 1 else rng.choice([0, 1])
seg = r["flights"][leg]
lo, hi = 16, 30
if shape[1] == 2:
other = int(r["flights"][1 - leg]["date"][-2:])
lo, hi = (16, other - 1) if leg == 0 else (other + 1, 30)
dates = ["2024-05-%02d" % d for d in range(lo, hi + 1) if "2024-05-%02d" % d != seg["date"]]
rng.shuffle(dates)
for new_date in dates:
options = w.direct(seg["origin"], seg["destination"], new_date, r["cabin"], pax)
if not options:
continue
chosen = rng.choice(options)[0]
flights = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
flights[leg] = {"flight_number": chosen["flight_number"], "date": new_date}
pm = rng.choice(cards(u))
idx = rng.randrange(pax)
old = r["passengers"][idx]
new = dict(old)
if rng.random() < 0.5:
new["last_name"] = rng.choice([x for x in LAST if x != old["last_name"]])
fix = "the last name of passenger %s %s should be %s" % (old["first_name"], old["last_name"], new["last_name"])
else:
new["dob"] = "%s-%02d-%02d" % (old["dob"][:4], rng.randint(1, 12), rng.randint(1, 28))
if new["dob"] == old["dob"]:
return
fix = "the date of birth of passenger %s %s should be %s" % (old["first_name"], old["last_name"], new["dob"])
plist = [dict(p) for p in r["passengers"]]
plist[idx] = new
which = "your flight" if shape[1] == 1 else ("the outbound flight", "the return flight")[leg]
wants = ["move %s to flight %s on %s (departs %s), same route and cabin" % (
which, chosen["flight_number"], month_day(new_date), chosen["scheduled_departure_time_est"][:5]),
"correct a passenger detail: %s; the other passengers stay as they are" % fix]
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": r["cabin"],
"flights": flights, "payment_id": pm["id"]}),
("update_reservation_passengers", {"reservation_id": r["reservation_id"], "passengers": plist})]
room = free - r["total_baggages"]
if room >= 1:
n = rng.randint(1, min(2, room))
total = r["total_baggages"] + n
wants.append("add %d checked bag%s so the reservation has %d in total" % (n, "" if n == 1 else "s", total))
actions.append(("update_reservation_baggages", {"reservation_id": r["reservation_id"], "total_baggages": total,
"nonfree_baggages": 0, "payment_id": pm["id"]}))
instr = ["You have %d changes for the same reservation and you list all of them in your first message:" % len(wants)
+ "".join("\n%d. %s" % (i + 1, x) for i, x in enumerate(wants)),
"Use %s for any charge or refund." % say_card(pm), self.style(),
"You want all of them done. If the agent finishes one and seems to stop, remind them of the others.",
CONFIRM, "Once all of them are done you have nothing else to ask."]
self.add("multi_change", True, "%d changes to one booking in one request (cabin %s)" % (len(wants), r["cabin"]),
"You want to make several changes to a reservation.", self.who(u, r, self.know(u, r, devil)),
"\n\n".join(instr), actions, [u["user_id"]])
return
# ------------------------------------------------------------------ one rule across all of a customer's bookings
def sweep_pool(self, u):
"""Upcoming, untouched bookings of a customer; None when any booking is neither clearly upcoming nor clearly past."""
res = [self.w.db["reservations"][x] for x in u["reservations"]]
if any(not self.w.clean_future(r) and not self.w.clearly_past(r) for r in res):
return None
return [r for r in res if self.w.clean_future(r)]
def sweep_cancel(self, u):
w, rng = self.w, self.rng
pool = self.sweep_pool(u)
if not pool or not 2 <= len(pool) <= 5 or any(w.near_24h_edge(r) for r in pool):
return
reason = rng.choice(["change_of_plan", "health", "weather"])
go = [r for r in pool if w.cancel_outcome(r, reason) == "cancel"]
if not go and rng.random() < 0.5:
return # keep some sweeps where nothing qualifies and every booking must be refused
why = {"change_of_plan": "Your plans changed and you no longer need any of these trips.",
"health": "You are sick and cannot travel on any of these trips.",
"weather": "Severe storms are forecast and you do not want to travel on any of these trips."}[reason]
instr = ["You want to cancel every one of your upcoming trips, meaning every reservation whose flights are all still in the future. Trips that already happened are not part of this.",
why + " The same reason applies to all of them.",
"You do not remember the reservation ids. Ask the agent to look them up in your profile.",
"If the agent says some of them cannot be cancelled, " + (
"argue once that it makes no sense to cancel some and not others, then accept it" if len(go) < len(pool) and rng.random() < 0.5
else "accept that") + " and have the ones that can be cancelled cancelled.",
self.style(), CONFIRM, "Once that is done you have nothing else to ask. Do not ask to be transferred to a human agent."]
self.add("sweep_cancel", True, "Cancel all upcoming trips: %d of %d qualify (reason %s)" % (len(go), len(pool), reason),
"You want to cancel all of your upcoming trips.", self.who(u), "\n\n".join(instr),
[("cancel_reservation", {"reservation_id": r["reservation_id"]}) for r in go], [u["user_id"]])
def sweep_cabin(self, u):
w, rng = self.w, self.rng
pool = self.sweep_pool(u)
if not pool or len(pool) < 2 or not cards(u):
return
source = rng.choice(sorted({r["cabin"] for r in pool}))
group = [r for r in pool if r["cabin"] == source]
if not 1 <= len(group) <= 4 or len(group) == len(pool) and len(group) < 2:
return
targets = [c for c in CABIN if c != source and all(
w.db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"][c] >= len(r["passengers"])
for r in group for s in r["flights"])]
if not targets:
return
target = rng.choice(targets)
pm = rng.choice(cards(u))
diffs = [w.cabin_diff(r, target) for r in group]
firsts = [r["payment_history"][0]["payment_id"] if len(r["payment_history"]) == 1 else None for r in group]
original = (all(f in u["payment_methods"] and (u["payment_methods"][f]["source"] == "credit_card" or
(u["payment_methods"][f]["source"] == "gift_card" and d <= 0))
for f, d in zip(firsts, diffs)) and len(set(firsts)) > 1 and rng.random() < 0.7)
pay = firsts if original else [pm["id"]] * len(group)
instr = ["You want every upcoming reservation of yours that is currently in %s class changed to %s class, keeping the same flights. Reservations in any other class, and trips that already happened, stay untouched." % (CABIN[source], CABIN[target]),
"You do not remember the reservation ids. Ask the agent to look them up in your profile.",
("For each reservation, any charge or refund must go to the payment method that was originally used to pay for that reservation."
if original else "Use %s for every charge or refund." % say_card(pm)), self.style(), CONFIRM,
"Once that is done you have nothing else to ask. Do not ask to be transferred to a human agent."]
said = None
if len(group) > 1 and abs(sum(diffs)) >= 10 and (all(d > 0 for d in diffs) or all(d < 0 for d in diffs)) and rng.random() < 0.6:
instr.insert(3, "After the last change is done, ask the agent for the overall total you were %s across all of these changes, as one number." % ("charged" if diffs[0] > 0 else "refunded"))
said = [str(abs(sum(diffs)))]
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": target,
"flights": [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]],
"payment_id": pid}) for r, pid in zip(group, pay)]
self.add("sweep_cabin", True, "Move all upcoming %s bookings to %s: %d of %d upcoming bookings" % (source, target, len(group), len(pool)),
"You want to change the cabin class on several reservations.", self.who(u), "\n\n".join(instr), actions, [u["user_id"]],
communicate=said)
def combine(builder, a, b, rng):
"""Two requests in one call: the second is raised only after the first is settled."""
ia, ib = a["user_scenario"]["instructions"], b["user_scenario"]["instructions"]
builder.counter["two_requests"] += 1
tid = "vc_two_requests_%03d" % builder.counter["two_requests"]
known_b = ib["known_info"].split("\n\n", 2)[2] if ib["known_info"].count("\n\n") >= 2 else ""
task = copy.deepcopy(a)
task["id"] = tid
meta_a, meta_b = json.loads(a["description"]["notes"]), json.loads(b["description"]["notes"])
task["description"] = {"purpose": "Two requests in one call: [%s] then [%s]" % (a["description"]["purpose"], b["description"]["purpose"]),
"relevant_policies": None,
"notes": json.dumps({"family": "two_requests", "devil": True, "users": meta_a["users"],
"reservation": None, "parts": [meta_a["family"], meta_b["family"]],
"part_reservations": [meta_a["reservation"], meta_b["reservation"]]})}
ins = task["user_scenario"]["instructions"]
ins["reason_for_call"] = "You have two separate requests. " + ia["reason_for_call"] + " Later in the call: " + ib["reason_for_call"]
ins["known_info"] = ia["known_info"] + ("\n\nFor your second request: " + known_b if known_b else "")
strip = lambda t: t.replace(NOTHING_ELSE, "").replace("Once it is done you have nothing else to ask.", "") \
.replace("Once it is cancelled you have nothing else to ask.", "").replace("Once that is done you have nothing else to ask.", "") \
.replace("Once it is booked you have nothing else to ask.", "").strip()
second = strip(ib["task_instructions"])
for style in STYLES: # one personality per caller: keep the first request's
second = second.replace(style + "\n\n", "").replace("\n\n" + style, "")
ins["task_instructions"] = ("FIRST REQUEST\n\n" + strip(ia["task_instructions"]) +
"\n\nSECOND REQUEST (raise it only after the first one has been completed or refused)\n\n" +
second +
"\n\nDo not ask to be transferred to a human agent. After both requests are settled, end the conversation.")
acts = [dict(x) for x in a["evaluation_criteria"]["actions"]] + [dict(x) for x in b["evaluation_criteria"]["actions"]]
for i, x in enumerate(acts):
x["action_id"] = "%s_%d" % (tid, i)
task["evaluation_criteria"]["actions"] = acts
return task
def build(db, benchmark_tasks, seed=7):
skinned, umap = reskin(db, seed)
blob = json.dumps(benchmark_tasks)
banned = {umap[u] for u in db["users"] if u in blob} # customers that appear in the benchmark's own tasks
banned |= {umap[r["user_id"]] for rid, r in db["reservations"].items() if '"%s"' % rid in blob or " %s" % rid in blob}
world, rng = World(skinned), random.Random(seed + 1)
users = [u for u in sorted(skinned["users"]) if u not in banned]
rng.shuffle(users)
devil_users = set(users[: len(users) // 5]) # held-out customers: only ever used for the devil set
weights = {"flight_change": 4.0, "multi_change": 8.0, "upgrade_and_bags": 1.2, "cancel": 2.0, "cabin_change": 1.5, "baggage": 1.5, "passengers": 1.5, "compensation": 1.5}
out = {}
for split, pool, devil_rate in (("train", [u for u in users if u not in devil_users], 0.45), ("devil", sorted(devil_users), 1.0)):
b = Builder(world, random.Random(seed + (2 if split == "train" else 3)))
for uid in pool:
u = skinned["users"][uid]
res = [skinned["reservations"][r] for r in u["reservations"]]
b.rng.shuffle(res)
for r in res[:4]:
# weighted order of scenario families; the first one this booking qualifies for is used
order = sorted(weights, key=lambda f: -weights[f] * b.rng.random())
for fam in order:
before = len(b.tasks)
getattr(b, fam)(u, r, b.rng.random() < devil_rate)
if len(b.tasks) > before:
break
if b.rng.random() < 0.3:
b.booking(u, b.rng.random() < devil_rate)
if b.rng.random() < (0.9 if split == "devil" else 0.6):
b.sweep_cancel(u)
if b.rng.random() < (0.9 if split == "devil" else 0.6):
b.sweep_cabin(u)
singles = [t for t in b.tasks if not json.loads(t["description"]["notes"])["family"].startswith(("sweep", "multi", "upgrade"))]
extras = [t for t in b.tasks if t not in singles]
by_user = collections.defaultdict(list)
for t in singles:
by_user[json.loads(t["description"]["notes"])["users"][0]].append(t)
combos = []
for uid in sorted(by_user):
ts = by_user[uid]
if len(ts) >= 2 and b.rng.random() < (1.0 if split == "devil" else 0.2):
a, c = b.rng.sample(ts, 2)
fa, fc = json.loads(a["description"]["notes"])["family"], json.loads(c["description"]["notes"])["family"]
rid = lambda t: [x["arguments"].get("reservation_id") for x in t["evaluation_criteria"]["actions"]]
same_booking = a["user_scenario"]["instructions"]["known_info"] == c["user_scenario"]["instructions"]["known_info"]
if fa == "cancel_flown":
a, c, fa, fc = c, a, fc, fa # a transfer ends the call, so it can only come second
if fa.startswith("booking"):
a, c, fa, fc = c, a, fc, fa # a new booking is always the second request
if (same_booking or fa == "cancel_flown" or fa.startswith("booking") or set(rid(a)) & set(rid(c))):
continue # keep the two requests independent of each other
combos.append(combine(b, a, c, b.rng))
out[split] = singles + extras + combos
tasks = out["train"] + out["devil"]
for t in out["devil"]:
t["id"] = t["id"].replace("vc_", "vcd_", 1)
for i, a in enumerate(t["evaluation_criteria"]["actions"]):
a["action_id"] = "%s_%d" % (t["id"], i)
# the devil set is a fixed-size hard cut of the held-out customers, shaped like the public benchmark but meaner:
# 50 scenarios where nothing may change, 34 with one change (trick and search scenarios first), 36 with two or more.
# "holdout" is everything from those customers.
pick = random.Random(seed + 4)
plain = {"cancel_ok", "passenger_update", "compensation_ok", "baggage_add", "cabin_change", "booking", "flight_change"}
buckets = {0: [], 1: [], 2: []}
for t in out["devil"]:
buckets[min(2, len(t["evaluation_criteria"]["actions"]))].append(t)
devil_ids = set()
for n, size in ((0, 50), (1, 34), (2, 36)):
pool = buckets[n][:]
pick.shuffle(pool)
seen, spread = collections.Counter(), []
for t in pool: # hard scenarios first, spread evenly over their families
fam = json.loads(t["description"]["notes"])["family"]
easy = fam in plain and not t["evaluation_criteria"]["communicate_info"]
seen[fam] += 1
spread.append((easy, seen[fam], t))
pool = [t for _, _, t in sorted(spread, key=lambda x: (x[0], x[1]))]
devil_ids |= {t["id"] for t in pool[:size]}
devil_ids = [t["id"] for t in out["devil"] if t["id"] in devil_ids]
splits = {"base": [t["id"] for t in tasks], "train": [t["id"] for t in out["train"]],
"holdout": [t["id"] for t in out["devil"]], "devil": devil_ids}
return skinned, tasks, splits, banned
def content_hash(*objs):
return hashlib.sha256(json.dumps(objs, sort_keys=True).encode()).hexdigest()[:16]
if __name__ == "__main__":
db_path, tasks_path, out_dir = sys.argv[1:4]
seed = int(sys.argv[4]) if len(sys.argv) > 4 else 7
db, bench = json.load(open(db_path)), json.load(open(tasks_path))
skinned, tasks, splits, banned = build(db, bench, seed)
os.makedirs(out_dir, exist_ok=True)
for name, obj in (("db.json", skinned), ("tasks.json", tasks), ("split_tasks.json", splits)):
json.dump(obj, open(os.path.join(out_dir, name), "w"))
fam = collections.Counter(json.loads(t["description"]["notes"])["family"] for t in tasks)
print("tasks: %d (train %d, held-out customers %d, of which devil set %d) | benchmark customers excluded: %d" % (
len(tasks), len(splits["train"]), len(splits["holdout"]), len(splits["devil"]), len(banned)))
print("families:", dict(sorted(fam.items())))
print("no-write share: %.0f%%" % (100.0 * sum(not t["evaluation_criteria"]["actions"] for t in tasks) / len(tasks)))
for name in ("train", "holdout", "devil"):
want = set(splits[name])
n = collections.Counter(min(len(t["evaluation_criteria"]["actions"]), 4) for t in tasks if t["id"] in want)
tot = float(sum(n.values()))
print("%s: %d scenarios | no change %.0f%% | one change %.0f%% | two or more %.0f%%" % (
name, tot, 100 * n[0] / tot, 100 * n[1] / tot, 100 * (tot - n[0] - n[1]) / tot))
print("CONTENT HASH:", content_hash(skinned, tasks, splits))