rapidchat-data / code /vc_bench_r3b.py
badr7's picture
rapidchat-data
f210f00 verified
Raw History Blame Contribute Delete
12.3 kB
#!/usr/bin/env python3
"""Round 3b: two basic-economy budget families that replace round 3's be_net, matching how the two kinds of request differ.
be_willing the user says they are willing to upgrade the whole reservation so the flight can be changed, and gives a
budget for the flight change itself; the upgrade is a separate charge they accept. Go ahead (two calls)
when the change step is within the budget, even when the upgrade alone is far above it; no change when the
change step itself is over the budget.
be_nooffer the user wants a basic economy flight changed, never mentions the cabin, and will only do it if it costs
less than a limit; the upgrade (charged in full first) is at or above that limit. Right outcome: no change.
The agent should not offer an upgrade on its own; if it does, or the user asks whether there is any way,
the upgrade charge on its own decides, never netted against a later refund.
usage: vc_bench_r3b.py <round-1 bench dir> <original airline db.json> <original airline tasks.json> <round-2 tasks.json> <round-3 tasks.json> <out tasks.json>
"""
import collections
import json
import math
import random
import sys
import vc_bench as vb
import vc_bench_r3 as v3
from vc_bench import CITY, CONFIRM, World, cards, month_day, say_card
from vc_bench_r2 import NO_HUMAN, REASONS, directions, round_between
class Builder3b(v3.Builder3):
def be_setup(self, u, r):
"""A change on a basic economy booking: (segments info, new flight, upgrade, change, same, moved, text) or None."""
w, rng = self.w, self.rng
if r["cabin"] != "basic_economy" or not w.clean_future(r) or not cards(u):
return None
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 None
dirs = directions(r)
k = rng.randrange(len(dirs))
segs = dirs[k]
if len(segs) > 2:
return None
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 None
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 None
old_econ = 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_econ - 15]
new = rng.choice(cheaper) if cheaper and rng.random() < 0.7 else rng.choice(options)
upgrade = w.cabin_diff(r, "economy")
if upgrade <= 0:
return None
change = (new["dates"][date]["prices"]["economy"] - old_econ) * pax
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]))
return upgrade, change, same, moved, want
# ------------------------------------------------------------------ user agrees to upgrade; budget is for the change step
def be_willing(self, u, r):
rng = self.rng
got = self.be_setup(u, r)
if not got:
return False
upgrade, change, same, moved, want = got
cases = []
if change < -20:
cases += ["go_upgrade_over"] * 8
if change <= 60:
cases += ["go"] * 3
if change > 40:
cases += ["change_over"] * 3
if not cases:
return False
case = rng.choice(cases)
if case == "go_upgrade_over":
limit = round_between(max(change, 0) + 5, upgrade, rng) if upgrade > max(change, 0) + 30 else None
elif case == "go":
limit = int(math.ceil((max(change, 0) + 20) / 50.0)) * 50
else:
limit = round_between(5, change, rng)
if not limit:
return False
pm = self.pick_card(u)
step = rng.random() < 0.5
tell_card = rng.random() < 0.55
budget = rng.choice([
"You are willing to pay up to ${L} for the change.",
"Apart from the upgrade, you will pay at most ${L} for the flight change itself.",
"Your budget for the flight change is ${L}.",
]).replace("{L}", str(limit))
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, say you are willing to upgrade the whole reservation to economy so that the change can be made. You accept paying the upgrade charge, whatever it is.",
budget + " That limit is about the flight change step itself: if, once the reservation is in economy, moving to the new flight costs $%d or less, or gives you money back, you go ahead with both steps. If the flight change itself would cost more than $%d, you do not want anything done, not even the upgrade; say so and end the conversation." % (limit, 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 != "change_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_willing", True, "Basic economy change, upgrade agreed, $%d limit on the change step: upgrade %+d then change %+d (%s)" % (limit, upgrade, change, 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
# ------------------------------------------------------------------ user never offers to upgrade; upgrade alone is over the limit
def be_nooffer(self, u, r):
rng = self.rng
got = self.be_setup(u, r)
if not got:
return False
upgrade, change, same, moved, want = got
if upgrade < 60:
return False
limit = round_between(max(10, upgrade + change + 5) if upgrade + change > 0 and rng.random() < 0.6 else 20, upgrade, rng)
if not limit:
return False
pm = self.pick_card(u)
ask_way = rng.random() < 0.5
instr = [want,
"You are willing to do the change only if it costs you less than $%d." % limit,
"You do not want to buy a new reservation or cancel anything.",
"Never bring up the cabin class or upgrading yourself.",
("If the agent says the flight cannot be changed, ask once whether there is any other way to make the change. " if ask_way else
"If the agent says the flight cannot be changed, accept it. ") +
"If the agent offers a cabin upgrade, ask exactly how much you would be charged for the upgrade itself. You are charged for the upgrade before anything else, so if that charge on its own is $%d or more, it is too much and you decline, whatever happens afterwards." % limit,
"If you are asked how you would pay, say %s." % say_card(pm),
self.style(), CONFIRM, NO_HUMAN, "Once the agent has told you what is possible and you have decided, end the conversation."]
self.add("be_nooffer", True, "Basic economy change, no upgrade offered by the user, limit $%d: upgrade %+d then change %+d (no change)" % (limit, upgrade, change),
"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), [], [u["user_id"]])
return True
def build(bench_dir, orig_db, orig_tasks, prior, counts, seed=44):
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"])
banned |= {u for t in r1_tasks if t["id"] in holdout for u in json.loads(t["description"]["notes"])["users"]}
users = [u for u in sorted(db["users"]) if u not in banned]
b = Builder3b(World(db), random.Random(seed))
b.rng.shuffle(users)
count = collections.Counter()
for fam in ("be_nooffer", "be_willing"):
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 count[fam] < counts[fam] and getattr(b, fam)(u, r):
count[fam] += 1
for t in b.tasks:
t["id"] = t["id"].replace("vc_", "vc3b_", 1)
for i, a in enumerate(t["evaluation_criteria"]["actions"]):
a["action_id"] = "%s_%d" % (t["id"], i)
return b.tasks, count
if __name__ == "__main__":
bench_dir, db_path, tasks_path, r2_path, r3_path, out = sys.argv[1:7]
r3 = json.load(open(r3_path))
new, count = build(bench_dir, json.load(open(db_path)), json.load(open(tasks_path)), r3, {"be_willing": 55, "be_nooffer": 35})
keep = [t for t in r3 if json.loads(t["description"]["notes"])["family"] != "be_net"]
json.dump(keep + new, open(out, "w"), indent=1)
print("round-3b scenarios:", len(new), dict(count), "| kept from round 3:", len(keep), "| total", len(keep) + len(new))
print("be_willing cases:", dict(collections.Counter(t["description"]["purpose"].rsplit("(", 1)[-1].rstrip(")") for t in new if "be_willing" in t["id"])))