| """V2 authoring: fix the bridge-ordering logic bug.
|
|
|
| The v1 'bridge' confirmed the action the customer was ABOUT to request, which
|
| produced a time-travel contradiction (agent: "I've filed the claim" -> user:
|
| "please file the claim" -> agent files it). C3 caught ~94% of tail turns on that.
|
|
|
| V2 schema makes every acknowledgement PAST-TENSE and about its OWN turn's action
|
| only. An ack is only ever shown once its turn is completed, so no confirmation
|
| can precede its request:
|
|
|
| {
|
| "q1": "<turn-1 user message: auth + lookups + the first action>",
|
| "ack1": "<agent confirms ONLY what turn 1 did, past tense>",
|
| "turns":[ {"user":"<request for tail call k>", "ack":"<agent confirms THAT
|
| call, past tense>"}, ... ] # one per tail call, in order
|
| }
|
|
|
| Cache -> out/authored_v2.json (idempotent; re-fills only missing/failed).
|
| Run: python -u temp/story_remediation/unbundle/author_splits_v2.py
|
| """
|
| from __future__ import annotations
|
| import json, re, sys, threading, logging
|
| from concurrent.futures import ThreadPoolExecutor
|
| from pathlib import Path
|
| import yaml
|
|
|
| HERE = Path(__file__).resolve().parent
|
| ROOT = HERE.parents[2]
|
| sys.path.insert(0, str(ROOT))
|
| for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| logging.getLogger(_n).setLevel(logging.WARNING)
|
| from datasetreview.llm_client import make_judge
|
|
|
| N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| AUTHORED = HERE / "out" / "authored_v2.json"
|
| cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| WORKERS = 8
|
|
|
| SYS = (
|
| "You rewrite ONE retail customer-support conversation so it reads as a natural, "
|
| "coherent multi-turn dialogue instead of a single giant request. The conversation "
|
| "must make perfect sense read start to finish.\n\n"
|
| "You are given the customer's original bundled message and the ordered backend "
|
| "actions the agent took (tool name + arguments). The FIRST GROUP of actions "
|
| "(authentication + lookups + the first real action) all happen in TURN 1. Each "
|
| "remaining TAIL action becomes its own separate later turn, in order.\n\n"
|
| "Return a JSON object EXACTLY like:\n"
|
| '{ "q1": "<turn-1 customer message>", "ack1": "<agent reply AFTER turn 1>",\n'
|
| ' "turns": [ {"user":"<customer message>","ack":"<agent reply AFTER doing it>"}, ... ] }\n\n'
|
| "THE #1 RULE (this is what you are fixing): An agent reply may ONLY confirm actions "
|
| "that have ALREADY been performed. It must be PAST TENSE and describe ONLY its own "
|
| "turn's action. NEVER let an agent say it did something the customer has not yet "
|
| "asked for. Do not preview or promise the next step.\n"
|
| " - ack1 confirms ONLY the turn-1 actions. It must NOT mention any tail action.\n"
|
| " - Each turns[k].ack confirms ONLY that same turn's single action.\n\n"
|
| "Other rules:\n"
|
| "1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n"
|
| "2. Exactly one entry in \"turns\" per tail action, same order. Each \"user\" message "
|
| "naturally triggers exactly that one action and nothing else.\n"
|
| "3. The customer is ALREADY authenticated after turn 1. Later turns must NOT re-verify "
|
| "identity or re-share name / ZIP / email / phone (unless an action's arguments are "
|
| "about a DIFFERENT person, e.g. looking up a relative, which is fine).\n"
|
| "4. Do NOT re-request anything already done in an earlier turn.\n"
|
| "5. Copy every identifier verbatim from the arguments: order ids (#W...), item / "
|
| "product numbers, gift card ids, dollar amounts, exact quoted message or review text. "
|
| "NEVER invent, drop, or alter an id.\n"
|
| "6. Natural, human, concise. Vary follow-up phrasing ('Thanks, one more thing', 'Got "
|
| "it, could you also', 'Perfect, now'). Contractions are good.\n"
|
| "7. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n"
|
| "Return ONLY the JSON object."
|
| )
|
|
|
| _TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b")
|
|
|
|
|
| def toks(*strings):
|
| s = set()
|
| for x in strings:
|
| if x:
|
| s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x)))
|
| return s
|
|
|
|
|
| def build_user(row, K):
|
| calls = row["calls"]
|
| fmt = lambda c: {"tool": c["name"], "arguments": c.get("arguments", {})}
|
| return json.dumps({
|
| "original_customer_message": row["query"],
|
| "turn1_actions": [fmt(c) for c in calls[:K]],
|
| "tail_actions_each_its_own_turn": [fmt(c) for c in calls[K:]],
|
| }, ensure_ascii=False, indent=2)
|
|
|
|
|
| def validate(row, K, out):
|
| calls = row["calls"]; tail = calls[K:]
|
| if not isinstance(out, dict):
|
| return "not a dict"
|
| q1 = out.get("q1"); ack1 = out.get("ack1"); turns = out.get("turns")
|
| if not isinstance(q1, str) or not q1.strip():
|
| return "empty q1"
|
| if not isinstance(ack1, str) or not ack1.strip():
|
| return "empty ack1"
|
| if not isinstance(turns, list) or len(turns) != len(tail):
|
| return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}"
|
| texts = [q1, ack1]
|
| for t in turns:
|
| if not isinstance(t, dict) or not str(t.get("user", "")).strip() or not str(t.get("ack", "")).strip():
|
| return "empty turn user/ack"
|
| texts += [t["user"], t["ack"]]
|
| for t in texts:
|
| if "\u2014" in t or "\u2013" in t or " - " in t:
|
| return "dash present"
|
| allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls])
|
| new = toks(*texts) - allowed
|
| if new:
|
| return f"new ids {sorted(new)[:4]}"
|
| tail_ids = (toks(*[c.get("arguments", {}) for c in tail])
|
| - toks(*[c.get("arguments", {}) for c in calls[:K]]))
|
| leak = toks(q1, ack1) & tail_ids
|
| if leak:
|
| return f"tail id leaked into q1/ack1 {sorted(leak)}"
|
| return None
|
|
|
|
|
| def main():
|
| rows = {json.loads(l)["example_id"]: json.loads(l)
|
| for l in open(N100, encoding="utf-8") if l.strip()}
|
| cand = []
|
| for eid, r in rows.items():
|
| md = r.get("metadata") or {}; ad = md.get("anchor_depth")
|
| calls = r.get("calls") or []
|
| if ad is None or ad < 2 or len(calls) <= ad + 1:
|
| continue
|
| cand.append(eid)
|
| cand.sort()
|
| print(f"candidates: {len(cand)}")
|
|
|
| authored = {}
|
| if AUTHORED.exists():
|
| authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| todo = [e for e in cand if e not in authored or authored[e].get("_err")]
|
| print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}")
|
|
|
| judge = make_judge(cfg["model"])
|
| lock = threading.Lock(); done = [0]
|
|
|
| def work(eid):
|
| r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1
|
| user = build_user(r, K); last = None
|
| for _ in range(3):
|
| try:
|
| out = judge.judge({"system": SYS, "user": user})
|
| except Exception as e:
|
| last = f"api:{e}"; continue
|
| err = validate(r, K, out)
|
| if err is None:
|
| rec = {"q1": out["q1"].strip(), "ack1": out["ack1"].strip(),
|
| "turns": [{"user": t["user"].strip(), "ack": t["ack"].strip()}
|
| for t in out["turns"]]}
|
| with lock:
|
| authored[eid] = rec; done[0] += 1
|
| if done[0] % 20 == 0:
|
| AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| print(f" ...{done[0]}/{len(todo)}")
|
| return
|
| last = err
|
| with lock:
|
| authored[eid] = {"_err": last or "unknown"}
|
| print(f" SKIP {eid}: {last}")
|
|
|
| AUTHORED.parent.mkdir(parents=True, exist_ok=True)
|
| with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| list(ex.map(work, todo))
|
| AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
|
| ok = sum(1 for e in cand if "q1" in authored.get(e, {}) and not authored.get(e, {}).get("_err"))
|
| err = [e for e in cand if authored.get(e, {}).get("_err")]
|
| print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}")
|
| for e in err[:15]:
|
| print(" ", e, authored[e]["_err"])
|
| print(f"wrote {AUTHORED.relative_to(ROOT)}")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|