File size: 20,512 Bytes
f210f00 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | #!/usr/bin/env python3
"""Viperclaw bench, round 3: families aimed at what the round-2 model still got wrong on held-out tasks.
Same re-skinned database as rounds 1 and 2. New customers where possible, new routes, prices and wording; no
benchmark task is copied.
be_net basic economy + a flight change + a spending limit judged on the NET cost: the upgrade is charged first
and the flight change then charges or refunds the difference, and the user's limit applies to what they
end up paying overall. Mostly cases where the upgrade alone is over the limit but the net is under it
(go ahead, two separate calls), plus net-under and net-over cases. Replaces round 2's be_budget, whose
"upgrade alone must fit" rule was wrong.
rank_pick a new booking chosen by price rank in one cabin (second cheapest, cheapest, cheapest nonstop), where the
agent has to rank the options itself and name the single match with its total; payment only when asked;
insurance asked neutrally and declined
rebook_pay a destination change done as cancel + rebook (refundable cancellations only), where the user only says
"the same payment method as the original booking" when asked, and asks whether their insurance carries
over (it does not; they decline new insurance)
refuse_then_book, two_denied round-2 families again on new customers (no transfer, refusal held)
usage: vc_bench_r3.py <round-1 bench dir> <original airline db.json> <original airline tasks.json> <round-2 tasks.json> <out tasks.json>
"""
import collections
import json
import math
import random
import sys
import vc_bench as vb
import vc_bench_r2 as v2
from vc_bench import CITY, CONFIRM, FREE_BAGS, World, cards, month_day, say_card
from vc_bench_r2 import NO_HUMAN, REASONS, directions, ranked_pick, round_between
LIMIT_WORDS = [
"You are willing to pay up to ${L} for the change.",
"Your budget for this change is ${L}.",
"You can spend at most ${L} on this change.",
"You do not want this change to cost you more than ${L}.",
]
NET_RULE = ("What counts against that limit is what you end up paying overall once everything is done. If the agent explains "
"that the cabin upgrade is charged first and the flight change then refunds or charges a difference, judge the "
"net amount (upgrade charge minus any refund, plus any extra charge) against your limit. If the agent only gives "
"you the upgrade price, ask what the flight change itself would then cost or refund and what the net total is.")
class Builder3(v2.Builder2):
# ------------------------------------------------------------------ basic economy + change, limit on the net cost
def be_net(self, u, r):
w, rng = self.w, self.rng
if r["cabin"] != "basic_economy" or not w.clean_future(r) or not cards(u):
return False
pax = len(r["passengers"])
db = w.db
if any(db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"]["economy"] < pax for s in r["flights"]):
return False
dirs = directions(r)
k = rng.randrange(len(dirs))
segs = dirs[k]
if len(segs) > 2:
return False
origin, dest, date0 = segs[0]["origin"], segs[-1]["destination"], segs[0]["date"]
if len(segs) == 2 and rng.random() < 0.7:
date, kind = date0, "nonstop"
else:
lo, hi = 16, 30
if len(dirs) == 2:
other = dirs[1 - k][0]["date"]
lo, hi = (16, int(other[-2:]) - 1) if k == 0 else (int(dirs[0][-1]["date"][-2:]) + 1, 30)
days = [d for d in range(lo, hi + 1) if d != int(date0[-2:])]
if not days:
return False
date, kind = "2024-05-%02d" % rng.choice(days), "date"
options = [f for f in self.L.direct(origin, dest, date)
if f["dates"][date]["available_seats"]["economy"] >= pax
and not (len(segs) == 1 and f["flight_number"] == segs[0]["flight_number"] and date == date0)]
if not options:
return False
old_econ0 = sum(db["flights"][s["flight_number"]]["dates"][s["date"]]["prices"]["economy"] for s in segs)
cheaper = [f for f in options if f["dates"][date]["prices"]["economy"] < old_econ0 - 15]
new = rng.choice(cheaper) if cheaper and rng.random() < 0.8 else rng.choice(options)
upgrade = w.cabin_diff(r, "economy")
if upgrade <= 0:
return False
old_econ = sum(db["flights"][s["flight_number"]]["dates"][s["date"]]["prices"]["economy"] for s in segs)
change = (new["dates"][date]["prices"]["economy"] - old_econ) * pax
net = upgrade + change
cases = []
if change < -30 and upgrade - max(net, 0) > 30:
cases += ["net_ok_upgrade_over"] * 10
cases += ["both_under"] * 3
if net > 40:
cases += ["net_over"] * 2
case = rng.choice(cases)
if case == "net_ok_upgrade_over":
limit = round_between(max(net, 0), upgrade, rng)
elif case == "both_under":
limit = int(math.ceil((max(upgrade, net) + 15) / 50.0)) * 50
else:
limit = round_between(10, net, rng)
if not limit:
return False
pm = self.pick_card(u)
same = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
moved = []
for i, d in enumerate(dirs):
if i == k:
moved.append({"flight_number": new["flight_number"], "date": date})
else:
moved += [{"flight_number": s["flight_number"], "date": s["date"]} for s in d]
which = "your flight" if len(dirs) == 1 else ("your outbound trip", "your return trip")[k]
if kind == "nonstop":
want = ("You want %s from %s on %s, which currently has a connection, changed to a nonstop flight on the same day." %
(which, CITY[origin], month_day(date0)))
if len(options) > 1:
want += " You want flight %s (departs %s)." % (new["flight_number"], new["scheduled_departure_time_est"][:5])
else:
want = ("You want %s from %s to %s moved from %s to %s, on flight %s (departs %s)." %
(which, CITY[origin], CITY[dest], month_day(date0), month_day(date), new["flight_number"],
new["scheduled_departure_time_est"][:5]))
step = rng.random() < 0.5
tell_card = rng.random() < 0.55
instr = [want,
"You do not want to buy a new reservation or cancel anything.",
"At first, do not mention the cabin class. If the agent says basic economy flights cannot be changed, you are willing to upgrade the whole reservation to economy so that the change becomes possible.",
rng.choice(LIMIT_WORDS).replace("{L}", str(limit)) + " " + NET_RULE,
"If the net amount would be more than $%d, you do not want any change at all; say so and end the conversation." % limit,
("You want the upgrade done and confirmed first, and then the flight change done separately, so you can check each step."
if step else "Once the agent has explained the costs, you are happy for it to do the upgrade and then the flight change."),
("Use %s for any charge or refund." % say_card(pm)) if tell_card else
("Only when the agent asks how you want to pay, say %s." % say_card(pm)),
self.style(), CONFIRM, NO_HUMAN, "Once it is done or you have decided against it, end the conversation."]
actions = []
if case != "net_over":
actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": "economy", "flights": same, "payment_id": pm["id"]}),
("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": "economy", "flights": moved, "payment_id": pm["id"]})]
self.add("be_net", True, "Basic economy change, $%d limit on the net: upgrade %+d then change %+d = net %+d (%s)" % (limit, upgrade, change, net, case),
"You need to change a flight in one of your reservations because of %s." % rng.choice(REASONS),
self.who(u, r, self.know(u, r, True)), "\n\n".join(instr), actions, [u["user_id"]])
return True
# ------------------------------------------------------------------ a new booking picked by price rank in one cabin
def rank_pick(self, u):
w, rng = self.w, self.rng
if not cards(u):
return False
companions = u.get("saved_passengers") or []
pax = 2 if companions and rng.random() < 0.35 else 1
cabin = "economy" if rng.random() < 0.8 else "business"
for _ in range(40):
origin, dest = rng.choice(sorted(w.by_route))
date = "2024-05-%02d" % rng.randint(16, 29)
rule = rng.choice(["second", "second", "second", "cheapest_any", "cheapest_nonstop", "second_nonstop"])
its = self.L.itineraries(origin, dest, date, cabin)
if rule in ("cheapest_nonstop", "second_nonstop"):
its = [o for o in its if len(o[2]) == 1]
if len(its) < (2 if rule == "cheapest_nonstop" else 3):
continue
elif not any(len(o[2]) == 2 for o in its) or not any(len(o[2]) == 1 for o in its) or len(its) < 3:
continue
pick = ranked_pick(its, 1 if rule.startswith("second") else 0, pax)
if pick is None:
continue
price, _, legs = pick
break
else:
return False
me = {"first_name": u["name"]["first_name"], "last_name": u["name"]["last_name"], "dob": u["dob"]}
people = [me] + ([dict(rng.choice(companions))] if pax == 2 else [])
pm = self.pick_card(u)
bags = rng.choice([0, 0, 1, 2]) * pax
nonfree = max(0, bags - FREE_BAGS[u["membership"]][cabin] * pax)
total = price * pax + 50 * nonfree
cab = {"economy": "economy", "business": "business class"}[cabin]
what = {"second": "the second cheapest %s option, counting both nonstop and one-stop options (the cheapest one is usually not great)" % cab,
"cheapest_any": "the cheapest %s option, whether nonstop or with one stop" % cab,
"cheapest_nonstop": "the cheapest nonstop flight in %s" % cab,
"second_nonstop": "the second cheapest nonstop flight in %s" % cab}[rule]
who = ("only for yourself" if pax == 1 else "for yourself and %s %s (who is saved on your profile)" % (people[1]["first_name"], people[1]["last_name"]))
instr = ["You want to book a one-way trip from %s to %s on %s, %s." % (CITY[origin], CITY[dest], month_day(date), who),
"You want %s. You want the agent to work out which option that is and tell you its price; do not work it out yourself." % what,
"If the agent shows you a list of options without saying which one matches what you asked for, ask it which one that is. Do not pick from a list yourself.",
"If the agent asks for passenger details, say they are on your profile; do not give a date of birth yourself.",
("You want %d checked bag%s in total." % (bags, "" if bags == 1 else "s")) if bags else "You do not need any checked bags.",
"If the agent asks whether you want travel insurance, say no.",
"Only when the agent asks how you want to pay, say %s." % say_card(pm),
self.style(), CONFIRM, NO_HUMAN, "Once the trip is booked, end the conversation."]
actions = [("book_reservation", {
"user_id": u["user_id"], "origin": origin, "destination": dest, "flight_type": "one_way", "cabin": cabin,
"flights": [{"flight_number": f["flight_number"], "date": d} for f, d in legs], "passengers": people,
"payment_methods": [{"payment_id": pm["id"], "amount": total}], "total_baggages": bags, "nonfree_baggages": nonfree,
"insurance": "no"})]
self.target = None
known = "You are %s %s.\n\nYour user id is %s." % (u["name"]["first_name"], u["name"]["last_name"], u["user_id"])
self.add("rank_pick", True, "Book by rank %s in %s for %d ($%d)" % (rule, cabin, pax, total),
"You want to book a new flight from %s to %s on %s." % (CITY[origin], CITY[dest], month_day(date)),
known, "\n\n".join(instr), actions, [u["user_id"]])
return True
# ------------------------------------------------------------------ destination change, rebook paid like the original
def rebook_pay(self, u, r):
w, rng = self.w, self.rng
if not w.clean_future(r) or w.near_24h_edge(r) or not r["payment_history"]:
return False
orig_pm = u["payment_methods"].get(r["payment_history"][0]["payment_id"])
if not orig_pm or orig_pm["source"] != "credit_card":
return False
dirs = directions(r)
if any(len(d) > 2 for d in dirs):
return False
pax = len(r["passengers"])
if r["insurance"] == "yes" and rng.random() < 0.8:
reason = "health"
else:
reason = "change_of_plan"
if w.cancel_outcome(r, reason) != "cancel":
return False
origin, old_dest = r["origin"], r["destination"]
out_date = dirs[0][0]["date"]
back_date = dirs[1][0]["date"] if len(dirs) == 2 else None
dests = sorted({f["destination"] for f in self.L.direct(origin, None, out_date)} - {old_dest, origin})
rng.shuffle(dests)
for new_dest in dests:
a = self.pick_by_time(origin, new_dest, out_date, pax)
if a is None:
continue
b = None
if back_date:
b = self.pick_by_time(new_dest, origin, back_date, pax)
if b is None:
continue
break
else:
return False
legs = [(a[0], out_date)] + ([(b[0], back_date)] if b else [])
price = sum(f["dates"][d]["prices"]["economy"] for f, d in legs)
bags = rng.choice([0, 1, 1, 2]) * (1 if pax == 1 else rng.choice([1, 2]))
nonfree = max(0, bags - FREE_BAGS[u["membership"]]["economy"] * pax)
total = price * pax + 50 * nonfree
trip = "round trip" if b else "one-way trip"
why = {"health": "You have a health problem and you bought travel insurance for this trip, so you expect a full refund. Mention the health problem at the start of the conversation.",
"change_of_plan": "Your plans changed."}[reason]
pay_line = rng.choice([
"When the agent asks how you want to pay for the new booking, say you want to use the same payment method you used for the original reservation. Do not name a card.",
"Only when the agent asks how to pay, say: the card you paid the original booking with. Do not name the card.",
])
instr = ["You want to change your upcoming %s from %s to %s so that it goes to %s instead, on the same date%s, with nonstop flights." % (
trip, CITY[origin], CITY[old_dest], CITY[new_dest], "s" if b else ""),
why,
"If the agent says the destination cannot be changed, ask to cancel the current reservation and book a new one instead, as long as the cancellation gives you a full refund.",
"For the new booking you want, going out on %s: %s." % (month_day(out_date), a[1]) +
(" Coming back on %s: %s." % (month_day(back_date), b[1]) if b else ""),
"You want the agent to figure out which flights fit and tell you the prices. The passengers are the same as on your current reservation.",
("You want %d checked bag%s in total." % (bags, "" if bags == 1 else "s")) if bags else "You do not need any checked bags.",
("Ask the agent whether the travel insurance on your current reservation carries over to the new one. If the agent says it does not, you do not want to buy new insurance."
if r["insurance"] == "yes" else "If the agent asks whether you want travel insurance, say no."),
pay_line, self.style(), CONFIRM, NO_HUMAN, "Once that is all done, end the conversation."]
actions = [("cancel_reservation", {"reservation_id": r["reservation_id"]}),
("book_reservation", {
"user_id": u["user_id"], "origin": origin, "destination": new_dest,
"flight_type": "round_trip" if b else "one_way", "cabin": "economy",
"flights": [{"flight_number": f["flight_number"], "date": d} for f, d in legs],
"passengers": [dict(p) for p in r["passengers"]],
"payment_methods": [{"payment_id": orig_pm["id"], "amount": total}],
"total_baggages": bags, "nonfree_baggages": nonfree, "insurance": "no"})]
self.add("rebook_pay", True, "Destination change -> cancel (%s) and rebook %s on the original card ($%d)" % (reason, trip, total),
"You want to change the destination of an upcoming reservation.", self.who(u, r, self.know(u, r, True)),
"\n\n".join(instr), actions, [u["user_id"]])
return True
def build_r3(bench_dir, orig_db, orig_tasks, r2_tasks, counts, seed=33):
db = json.load(open(bench_dir + "/db.json"))
r1_tasks = json.load(open(bench_dir + "/tasks.json"))
splits = json.load(open(bench_dir + "/split_tasks.json"))
_, umap = vb.reskin(orig_db, 7)
blob = json.dumps(orig_tasks)
banned = {umap[u] for u in orig_db["users"] if u in blob}
banned |= {umap[r["user_id"]] for rid, r in orig_db["reservations"].items() if '"%s"' % rid in blob or " %s" % rid in blob}
holdout = set(splits["holdout"])
devil_users = {u for t in r1_tasks if t["id"] in holdout for u in json.loads(t["description"]["notes"])["users"]}
used_r2 = {u for t in r2_tasks for u in json.loads(t["description"]["notes"])["users"]}
allowed = [u for u in sorted(db["users"]) if u not in banned and u not in devil_users]
fresh = [u for u in allowed if u not in used_r2]
world = World(db)
b = Builder3(world, random.Random(seed))
b.rng.shuffle(fresh)
rest = [u for u in allowed if u in used_r2]
b.rng.shuffle(rest)
users = fresh + rest # new customers first
count = collections.Counter()
for fam in ("be_net", "rebook_pay", "refuse_then_book"):
for uid in users:
if count[fam] >= counts[fam]:
break
u = db["users"][uid]
res = [db["reservations"][x] for x in u["reservations"]]
b.rng.shuffle(res)
for r in (res + res if fam == "be_net" else res):
if count[fam] < counts[fam] and getattr(b, fam)(u, r):
count[fam] += 1
if fam != "be_net":
break
for fam in ("rank_pick", "two_denied"):
for uid in users:
if count[fam] >= counts[fam]:
break
if getattr(b, fam)(db["users"][uid]):
count[fam] += 1
tasks = b.tasks
for t in tasks:
t["id"] = t["id"].replace("vc_", "vc3_", 1)
for i, a in enumerate(t["evaluation_criteria"]["actions"]):
a["action_id"] = "%s_%d" % (t["id"], i)
return tasks, count
if __name__ == "__main__":
bench_dir, db_path, tasks_path, r2_path, out = sys.argv[1:6]
counts = {"be_net": 70, "rank_pick": 45, "rebook_pay": 45, "refuse_then_book": 18, "two_denied": 15}
tasks, count = build_r3(bench_dir, json.load(open(db_path)), json.load(open(tasks_path)), json.load(open(r2_path)), counts)
json.dump(tasks, open(out, "w"), indent=1)
print("round-3 scenarios:", len(tasks), dict(count))
cases = collections.Counter(t["description"]["purpose"].rsplit("(", 1)[-1].rstrip(")") for t in tasks if "be_net" in t["id"])
print("be_net cases:", dict(cases))
print("no-change share: %.0f%%" % (100.0 * sum(not t["evaluation_criteria"]["actions"] for t in tasks) / len(tasks)))
|