Download tempscripts/injection_sandbox/gen_merged.py from tkhersoft/synthdatasets: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/datasets/tkhersoft/synthdatasets/resolve/main/tempscripts/injection_sandbox/gen_merged.py
- Command line
-
hf download hf://datasets/tkhersoft/synthdatasets/tempscripts/injection_sandbox/gen_merged.py
-
curl -L -o gen_merged.py https://huggingface.co/datasets/tkhersoft/synthdatasets/resolve/main/tempscripts/injection_sandbox/gen_merged.py
22.4 kB
| """SANDBOX generator: splice each of the 51 trie-fill injections into its | |
| assigned host conversation as a LATER turn (the injected row's history embeds the | |
| host's own prior tool turn, grounded to the host's customer). Non-destructive: | |
| host rows are NOT edited; we only ADD injected rows. Everything writes under | |
| temp/injection_sandbox/out. Reuses the proven grounded call assembly + replay | |
| verification from scripts/_gen_injections2.py. | |
| Run: python -u temp/injection_sandbox/gen_merged.py | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import random | |
| import re | |
| import sys | |
| from collections import Counter | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[2] | |
| SAND = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(ROOT)) | |
| sys.path.insert(0, str(ROOT / "systemUpgrade" / "executor")) | |
| import scripts._gen_injections2 as G # noqa: E402 | |
| from fake_state import EpisodeState # noqa: E402 | |
| from fake_tools import TOOLS # noqa: E402 | |
| DATA = SAND / "data" | |
| OUT = SAND / "out" | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| # use the SANDBOX (clonable) free-running catalog for all grounding/replay | |
| CATALOG = json.load(open(DATA / "catalog.json", encoding="utf-8")) | |
| G.CATALOG = CATALOG | |
| RND = random.Random(1234) | |
| def hq_variant(leaf, on): | |
| """Humanized LATER-turn query. The customer is already authenticated in the | |
| host turn, so a real person would NOT restate email / name / ZIP or say | |
| 'look me up'. Phrase as a natural follow-up; keep the order-number literal | |
| (retrieval signal); no em dashes.""" | |
| V = { | |
| "schedule_delivery": [ | |
| f"Also, could you set delivery for {on} to next Tuesday?", | |
| f"One more thing, can we schedule {on} to arrive on the 14th?", | |
| f"While you're in there, I'd like {on} delivered next Tuesday if that works.", | |
| ], | |
| "request_gift_receipt": [ | |
| f"Oh, and could I get a gift receipt for {on}? It's a present.", | |
| f"Also, {on} is a gift, so a gift receipt would be great.", | |
| f"Could you include a gift receipt with {on}? It's for my sister.", | |
| ], | |
| "get_wishlist": [ | |
| "Also, can you remind me what's still on my wishlist?", | |
| "While I've got you, what did I have saved on my wishlist again?", | |
| "Oh, and what's left on my wishlist? I keep forgetting.", | |
| ], | |
| "get_order_invoice": [ | |
| f"Could you also send me the invoice for {on}? I need it for expenses.", | |
| f"One more thing, can I get the itemized invoice for {on}?", | |
| f"Also, I need the invoice for {on} for my records.", | |
| ], | |
| "redeem_loyalty_points": [ | |
| "Also, I'd like to cash in some of my loyalty points for credit.", | |
| "While we're at it, can I redeem a few hundred points?", | |
| "Oh, and can I put some loyalty points toward store credit?", | |
| ], | |
| "reorder_previous_order": [ | |
| f"Also, could you just reorder everything from {on}? Same as before.", | |
| f"One more thing, can we duplicate order {on}? I loved that batch.", | |
| f"While you're in there, could you reorder {on} for me?", | |
| ], | |
| "apply_gift_card": [ | |
| f"Also, I've got a gift card I'd like to put toward {on}.", | |
| f"Oh, can we apply my gift card to {on}?", | |
| f"While we're at it, please use my gift card on {on}.", | |
| ], | |
| "get_shipping_options": [ | |
| f"Also, what are the shipping options for {on}?", | |
| f"One more thing, what delivery choices do I have for {on}?", | |
| f"While you're there, can you tell me the shipping options on {on}?", | |
| ], | |
| "subscribe_to_restock_alert": [ | |
| f"Could you swap the out-of-stock item on {on}, and let me know when the original is back?", | |
| f"Please change that item on {on}, and sign me up for a restock alert on the old one.", | |
| f"Can we modify {on} to swap that item, and ping me when it restocks?", | |
| ], | |
| "file_shipping_insurance_claim": [ | |
| f"Also, {on} arrived damaged, can I file an insurance claim on it?", | |
| f"One more thing, I need to file a shipping insurance claim for {on}. It came banged up.", | |
| ], | |
| "request_price_match": [ | |
| f"Also, I saw an item from {on} cheaper elsewhere, can you price match it?", | |
| f"One more thing, can you price match something on {on}? Found it for less online.", | |
| ], | |
| "get_store_credit_balance": [ | |
| "Also, what's my store credit balance right now?", | |
| "Oh, and how much store credit do I have left?", | |
| ], | |
| "set_delivery_instructions": [ | |
| f"Also, can you add a note to leave {on} with the doorman?", | |
| f"One more thing, please have {on} left with the front desk.", | |
| ], | |
| "upgrade_shipping_speed": [ | |
| f"Also, can you bump {on} to express if it hasn't shipped yet?", | |
| f"One more thing, could you upgrade {on} to overnight?", | |
| ], | |
| } | |
| return RND.choice(V[leaf]) | |
| CONFIRM = [ | |
| "All set, anything else I can help with?", | |
| "Done. Let me know if you need more.", | |
| "Taken care of. What else can I do?", | |
| "That's handled. Anything further?", | |
| ] | |
| def parse(o): | |
| try: | |
| return json.loads(o) if isinstance(o, str) and o.strip().startswith("{") else None | |
| except json.JSONDecodeError: | |
| return None | |
| def host_customer(host, a): | |
| """Reconstruct the host's customer + order dicts, backed by the assignment.""" | |
| ods = {} | |
| ud = None | |
| for c in host["calls"]: | |
| o = parse(c.get("output")) | |
| if c["name"] == "get_user_details" and o and o.get("user_id"): | |
| ud = o | |
| if c["name"] == "get_order_details" and o and o.get("order_id"): | |
| ods[o["order_id"]] = o | |
| user_details = { | |
| "user_id": a["uid"], "email": a["email"], | |
| "name": a.get("name") or (ud or {}).get("name") or {"first_name": "Alex", "last_name": "Kim"}, | |
| "address": (ud or {}).get("address") or {"zip": a.get("zip", "10001")}, | |
| "orders": list(ods), | |
| } | |
| return {"uid": a["uid"], "email": a["email"], "user_details": user_details, "orders": ods} | |
| OPEN_LEAVES = {"schedule_delivery", "set_delivery_instructions", "get_shipping_options", | |
| "upgrade_shipping_speed", "modify_pending_order_items"} | |
| def order_ids_for(a, u): | |
| need = a["prefix"].count("get_order_details") | |
| if a["node"] == "N4" and a.get("n4_orders"): | |
| ids = [o for o in a["n4_orders"] if o in u["orders"]] or list(u["orders"]) | |
| elif a.get("grounded_order") and a["grounded_order"] in u["orders"]: | |
| ids = [a["grounded_order"]] + [o for o in u["orders"] if o != a["grounded_order"]] | |
| else: | |
| ids = list(u["orders"]) | |
| # For open-required ops, ground on the most-open order the host actually has: | |
| # pending/processing first, then shipped (still pre-delivery), then delivered. | |
| if a["node"] != "N4" and (a["leaf"] in OPEN_LEAVES or any(t in OPEN_LEAVES for t in a["prefix"])): | |
| def rank(oid): | |
| st = str((u["orders"].get(oid) or {}).get("status", "")).lower() | |
| if st in ("pending", "processing", "open", "pending (modified)"): | |
| return 0 | |
| return 1 if st == "shipped" else 2 | |
| ids = sorted(ids, key=rank) | |
| if not ids: | |
| ids = ["#W0000000"] | |
| while len(ids) < max(1, need): | |
| ids.append(ids[0]) | |
| return ids | |
| # ---- embedded-host humanization (copy-only; canonical host rows untouched) ---- | |
| # Targets the two dominant C3 tells in host turns while preserving EVERY DB | |
| # literal (order #, item id, price, quoted gift message, date, email, ZIP): | |
| # T1 scripted meta preamble ("Review my recent orders, then ...") | |
| # T2 trailing auth boilerplate ("... Name is X, ZIP 12345.") when that same | |
| # name/ZIP/email already appears earlier in the conversation (pure dedupe) | |
| # T3 assistant em/hyphen dashes ("Sure - let me ...") -> comma | |
| _PREAMBLE = [ | |
| re.compile(r"^\s*review my [\w ]{0,32}orders,\s*then\s+", re.I), | |
| re.compile(r"^\s*review my [\w ]{0,32}orders and\s+", re.I), | |
| re.compile(r"^\s*review my [\w ]{0,32}orders:\s*", re.I), | |
| re.compile(r"^\s*look at my [\w ]{0,32}orders:\s+", re.I), | |
| re.compile(r"^\s*can you look over my [\w ]{0,32}orders\?\s+", re.I), | |
| re.compile(r"^\s*across (?:my )?[\w ]{0,32}orders:\s+", re.I), | |
| ] | |
| _TRAIL_NAMEZIP = re.compile( | |
| r"\s*(?:my name is|name is)\s+([A-Za-z]+(?:\s+[A-Za-z]+)?),?\s*" | |
| r"(?:and\s+(?:my\s+)?)?zip(?:\s+is|\s+code\s+is|:)?\s*(\d{5})\.?\s*$", re.I) | |
| _TRAIL_EMAIL = re.compile(r"\s*my email is\s+([^\s,]+@[^\s,]+?)\.?\s*$", re.I) | |
| def _cap(s): | |
| return s[:1].upper() + s[1:] if s else s | |
| def humanize_host_query(q, history_text): | |
| for pat in _PREAMBLE: | |
| m = pat.match(q) | |
| if m: | |
| q = _cap(q[m.end():].lstrip()) | |
| break | |
| m = _TRAIL_NAMEZIP.search(q) | |
| if m and (m.group(1) in history_text and m.group(2) in history_text): | |
| q = q[:m.start()].rstrip() | |
| if q and q[-1] not in ".!?": | |
| q += "." | |
| m = _TRAIL_EMAIL.search(q) | |
| if m and m.group(1) in history_text: | |
| q = q[:m.start()].rstrip() | |
| if q and q[-1] not in ".!?": | |
| q += "." | |
| return q | |
| def _dedash(s): | |
| if not s: | |
| return s | |
| return re.sub(r"\s+[-\u2013\u2014]\s+", ", ", s) | |
| def embed_host_turn(host): | |
| """host history (small talk) + the host's own request rendered as a prior | |
| tool turn (confuser-style encoding) + a confirmation. The embedded copy is | |
| lightly humanized (preamble/auth-dedupe/dash cleanup); canonical host row is | |
| not modified.""" | |
| h = [dict(m) for m in (host.get("history") or [])] | |
| for m in h: # T3: clean assistant dashes | |
| if m.get("role") == "assistant" and m.get("content"): | |
| m["content"] = _dedash(m["content"]) | |
| history_text = " ".join((m.get("content") or "") for m in h) | |
| q = (host.get("query") or host.get("retrieval_text") or "").strip() | |
| q = humanize_host_query(q, history_text) # T1 + T2 | |
| h.append({"role": "user", "content": q, "tool_calls": [], "tool_call_id": None}) | |
| tcs = [{"name": c["name"], "arguments": c.get("arguments", {}), | |
| "output": c.get("output"), "reasoning": c.get("reasoning", "")} | |
| for c in host["calls"]] | |
| h.append({"role": "assistant", "content": None, "tool_calls": tcs, "tool_call_id": None}) | |
| for c in host["calls"]: | |
| h.append({"role": "tool", "content": c.get("output"), "tool_calls": [], "tool_call_id": None}) | |
| h.append({"role": "assistant", "content": _dedash(RND.choice(CONFIRM)), "tool_calls": [], "tool_call_id": None}) | |
| return h | |
| def history_tool_calls(host): | |
| """Tool calls embedded in the host's own history (auth/reads retained earlier).""" | |
| out = [] | |
| for m in (host.get("history") or []): | |
| for tc in (m.get("tool_calls") or []): | |
| out.append({"name": tc.get("name"), "arguments": tc.get("arguments", {}), | |
| "output": tc.get("output")}) | |
| return out | |
| # ------------------------------------------------ leaf/host value reconciliation | |
| def reconcile_leaf_with_host(calls, host): | |
| """If the injected leaf reads an entity the host turn already established, copy | |
| the host's recorded output verbatim so the same customer yields the same value | |
| at the conversation level (and the row still reproduces in isolation).""" | |
| leaf = calls[-1] | |
| n = leaf["name"] | |
| SELF = {"get_order_invoice", "get_shipping_options", "get_wishlist", "get_store_credit_balance"} | |
| if n not in SELF: | |
| return calls, None | |
| a = leaf.get("arguments", {}) | |
| ent = ("#" + str(a["order_id"]).lstrip("#").upper()) if a.get("order_id") else a.get("user_id") | |
| def _ent(c): | |
| aa = c.get("arguments", {}) | |
| return ("#" + str(aa["order_id"]).lstrip("#").upper()) if aa.get("order_id") else aa.get("user_id") | |
| for hc in host["calls"]: | |
| if hc["name"] == n and _ent(hc) == ent and hc.get("output") is not None: | |
| leaf["output"] = hc["output"] | |
| return calls, (n, ent) | |
| return calls, None | |
| # ------------------------------------------------ conversation-level state check | |
| def _ref_ids(call): | |
| a = call.get("arguments", {}) or {} | |
| out = {} | |
| for k in ("user_id", "order_id", "gift_card_id"): | |
| if a.get(k): | |
| out[k] = a[k] | |
| for k in ("item_id",): | |
| if a.get(k): | |
| out.setdefault("item_ids", []).append(a[k]) | |
| for k in ("item_ids", "new_item_ids"): | |
| for v in (a.get(k) or []): | |
| out.setdefault("item_ids", []).append(v) | |
| return out | |
| def _establish(call, users, orders, items, cards): | |
| n = call["name"] | |
| raw = call.get("output") | |
| o = parse(raw) | |
| if n.startswith("find_user_id"): | |
| uid = raw.strip().strip('"') if isinstance(raw, str) else None | |
| if uid and "_" in uid: | |
| users.add(uid) | |
| elif n == "get_user_details" and o: | |
| if o.get("user_id"): | |
| users.add(o["user_id"]) | |
| for oid in (o.get("orders") or []): | |
| orders.add("#" + str(oid).lstrip("#").upper()) | |
| elif n == "get_order_details" and o: | |
| if o.get("order_id"): | |
| orders.add("#" + str(o["order_id"]).lstrip("#").upper()) | |
| for it in (o.get("items") or []): | |
| if it.get("item_id"): | |
| items.add(str(it["item_id"])) | |
| elif n == "get_gift_card_balance" and o and o.get("gift_card_id"): | |
| cards.add(str(o["gift_card_id"])) | |
| elif n == "get_wishlist" and o: | |
| for it in (o.get("items") or []): | |
| if isinstance(it, dict) and it.get("item_id"): | |
| items.add(str(it["item_id"])) | |
| def conversation_state_check(seq_calls, catalog, hist_calls=()): | |
| """Temporal grounding (no forward/unmarked refs) + output reproduction over the | |
| whole merged conversation. ``hist_calls`` are tool calls from the host's history | |
| (auth retained earlier), which pre-establish entities. Returns (forward_refs, | |
| io_mismatches).""" | |
| cat_orders = {"#" + str(o).lstrip("#").upper() for o in catalog.get("order_balances", {})} | |
| cat_cards = {str(c) for c in catalog.get("gift_card_balances", {})} | |
| users, orders, items, cards = set(), set(cat_orders), set(), set(cat_cards) | |
| for hc in hist_calls: # entities established in host history | |
| _establish(hc, users, orders, items, cards) | |
| fwd = [] | |
| for i, c in enumerate(seq_calls): | |
| refs = _ref_ids(c) | |
| # user_id must be established, unless this call itself establishes it | |
| # (find_user_id_* mints it; get_user_details is the auth-retained read). | |
| if (refs.get("user_id") and refs["user_id"] not in users | |
| and not c["name"].startswith("find_user_id") | |
| and c["name"] != "get_user_details"): | |
| fwd.append((i, c["name"], "user_id", refs["user_id"])) | |
| if refs.get("order_id"): | |
| oid = "#" + str(refs["order_id"]).lstrip("#").upper() | |
| if oid not in orders and c["name"] != "get_order_details": | |
| fwd.append((i, c["name"], "order_id", refs["order_id"])) | |
| if refs.get("gift_card_id") and str(refs["gift_card_id"]) not in cards: | |
| fwd.append((i, c["name"], "gift_card_id", refs["gift_card_id"])) | |
| _establish(c, users, orders, items, cards) | |
| # I/O reproduction over the merged sequence (progressive seed) | |
| s = EpisodeState.from_trajectory({"calls": seq_calls}, catalog) | |
| io = [] | |
| for c in seq_calls: | |
| n = c["name"] | |
| if n not in TOOLS: | |
| continue | |
| got = TOOLS[n](s, c.get("arguments", {})) | |
| rec = parse(c.get("output")) | |
| if n in G.FIND: | |
| exp = (c.get("output") or "").strip().strip('"') | |
| if got != exp: | |
| io.append((n, "uid", got, exp)) | |
| continue | |
| if not isinstance(rec, dict): | |
| continue | |
| if n in G.FULLMATCH: | |
| if got != rec: | |
| io.append((n, "dict-diff")) | |
| continue | |
| keys = G.CHECK.get(n, []) | |
| if any(got.get(k) is None and rec.get(k) is not None for k in keys): | |
| continue | |
| def _eq(k): | |
| g, rv = got.get(k), rec.get(k) | |
| if k == "status" and isinstance(g, str) and isinstance(rv, str): | |
| return g.replace(" ", "_") == rv.replace(" ", "_") | |
| return g == rv | |
| miss = [k for k in keys if not _eq(k)] | |
| if miss: | |
| io.append((n, {k: (got.get(k), rec.get(k)) for k in miss})) | |
| return fwd, io | |
| # ------------------------------------------------------------------------- main | |
| def main(): | |
| asg = json.load(open(DATA / "_host_assignment.json", encoding="utf-8")) | |
| c3 = [json.loads(l) for l in open(DATA / "c3_trajectories.jsonl", encoding="utf-8") if l.strip()] | |
| byid = {r["example_id"]: r for r in c3} | |
| cat_orders = ["#" + o.lstrip("#").upper() for o in CATALOG.get("order_balances", {})] | |
| cat_cards = list(CATALOG.get("gift_card_balances", {})) | |
| injected, prov = [], [] | |
| fails, merged = [], [] | |
| seq = 0 | |
| for a in asg: | |
| host = byid[a["host"]] | |
| u = host_customer(host, a) | |
| oids = order_ids_for(a, u) | |
| cat_order = a.get("grounded_cat_order") or RND.choice(cat_orders) | |
| gift_card = a.get("grounded_card") or RND.choice(cat_cards) | |
| prefix_tools = a["prefix"] | |
| leaf = a["leaf"] | |
| calls, primary = G.assemble(prefix_tools, leaf, u, oids, cat_order, gift_card) | |
| calls, reconciled = reconcile_leaf_with_host(calls, host) | |
| miss = G.verify_row(calls) | |
| if miss: | |
| fails.append((a["host"], leaf, miss)) | |
| continue | |
| hist = embed_host_turn(host) | |
| n_user = sum(1 for m in hist if m["role"] == "user") | |
| turn_index = n_user + 1 | |
| total_turns = turn_index + RND.randint(1, 3) | |
| position_norm = round(turn_index / max(total_turns, 1), 4) | |
| tier = ("early" if position_norm < 0.34 else "middle" if position_norm < 0.67 else "late") | |
| shown = cat_order if leaf in ("reorder_previous_order", "apply_gift_card") else primary | |
| query = hq_variant(leaf, shown) | |
| eid = f"confuser-{leaf}-minj{seq:03d}" | |
| seq += 1 | |
| row = { | |
| "example_id": eid, "query": query, "retrieval_text": query, | |
| "calls": calls, "history": hist, "available_apis": None, "domain": "retail", | |
| "metadata": { | |
| "source": "synthetic", "distractor_class": "confuser", "model": "authored", | |
| "confuser": leaf, "twin": False, "twin_of": None, | |
| "anchor_state": list(prefix_tools), "anchor_depth": len(prefix_tools), | |
| "hotspot": False, "synthetic_query": True, "tier": tier, | |
| "turn_index": turn_index, "total_turns": total_turns, | |
| "position_norm": position_norm, "embed_history": True, | |
| "history": hist, "real_source": "authored-synthetic", | |
| }, | |
| } | |
| injected.append(row) | |
| prov.append({"example_id": eid, "rebalance_node": a["node"], "confuser": leaf, | |
| "host_of": a["host"], "uid": a["uid"], "placement": "later-turn", | |
| "reconciled_leaf": reconciled}) | |
| merged.append((eid, host["calls"] + calls, history_tool_calls(host))) | |
| (OUT / "_staging_merged_injections.jsonl").write_text( | |
| "\n".join(json.dumps(r) for r in injected) + "\n", encoding="utf-8") | |
| (OUT / "_merged_injections.prov.json").write_text(json.dumps(prov, indent=2), encoding="utf-8") | |
| print(f"assembled {len(injected)}/51 injected rows (replay-verified)") | |
| if fails: | |
| print(f"ASSEMBLY/REPLAY FAILURES: {len(fails)}") | |
| for f in fails[:20]: | |
| print(" ", f) | |
| tally = Counter((p["rebalance_node"], p["confuser"]) for p in prov) | |
| for k in sorted(tally): | |
| print(" ", k, tally[k]) | |
| print(" reconciled leaves (inherited host value):", | |
| sum(1 for p in prov if p.get("reconciled_leaf"))) | |
| # ---- PASS 1: find unmarked variables across every merged conversation ---- | |
| made_up = {} | |
| for eid, seq, hist in merged: | |
| fwd, _ = conversation_state_check(seq, CATALOG, hist) | |
| for (_i, tool, kind, val) in fwd: | |
| if kind == "order_id": | |
| oid = "#" + str(val).lstrip("#").upper() | |
| if oid not in CATALOG["order_balances"]: | |
| # mark the host-intrinsic order in the CLONED free-running DB. | |
| made_up[oid] = {"order_balances": 0.01, "reason": f"{eid}:{tool} unread order"} | |
| if made_up: | |
| for oid, rec in made_up.items(): | |
| CATALOG.setdefault("order_balances", {})[oid.lstrip("#")] = rec["order_balances"] | |
| (DATA / "catalog.json").write_text(json.dumps(CATALOG, indent=1), encoding="utf-8") | |
| (OUT / "_made_up_values.json").write_text(json.dumps(made_up, indent=2), encoding="utf-8") | |
| # ---- PASS 2: confirm the conversation is now fully marked + reproduces ---- | |
| fwd_all, io_all = [], [] | |
| for eid, seq, hist in merged: | |
| fwd, io = conversation_state_check(seq, CATALOG, hist) | |
| for f in fwd: | |
| fwd_all.append((eid,) + f) | |
| for m in io: | |
| io_all.append((eid,) + (m if isinstance(m, tuple) else (m,))) | |
| print(f"\nadded {len(made_up)} made-up var(s) to the cloned free-running DB") | |
| print(f"CONVERSATION STATE CHECK (final): forward/unmarked refs = {len(fwd_all)} ; " | |
| f"io mismatches = {len(io_all)}") | |
| for x in fwd_all[:20]: | |
| print(" FWD", x) | |
| for x in io_all[:20]: | |
| print(" IO ", x) | |
| ok = not fails and not fwd_all and not io_all | |
| print("\nRESULT:", "CLEAN" if ok else "NEEDS ATTENTION") | |
| return 0 if ok else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |