tkhersoft's picture
temp build/analysis scripts (54 py files) backup before prune
94da461 verified
Raw
History Blame Contribute Delete
8.01 kB
"""LLM authoring pass for the full unbundle rollout.
For every candidate (metadata.anchor_depth>=2 AND a non-empty tail), ask the
model to rewrite the single bundled query into natural multi-turn dialogue:
- q1: motivates ONLY turn 1 (auth + lookups + the divergence action F).
- turns[]: one entry per tail call, each a natural user follow-up + a short
assistant confirmation (bridge). One action per turn (matches real tau2's
~92% one-call turns).
CRITICAL invariants enforced by validation (retry on failure, skip if hopeless):
- len(turns) == len(tail_calls)
- no em dashes
- no NEW identifiers: every #W.../gift_card_.../long-digit token in the
generated text must already appear in the original query or a call's args
- tail-only ids must NOT leak into q1 (keeps turn 1 narrowed)
Caches to out/authored.json ({eid: {q1, turns:[{user,bridge}], skipped?}}).
Re-runs only fill missing/failed eids (idempotent).
Run: python -u temp/story_remediation/unbundle/author_splits.py
"""
from __future__ import annotations
import json, re, sys, threading
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))
import logging
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 # noqa: E402
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
AUTHORED = HERE / "out" / "authored.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 natural, "
"multi-turn dialogue instead of a single giant request.\n\n"
"You are given the customer's original bundled message and the ordered list of "
"backend actions the agent took (tool name + arguments). The FIRST GROUP of "
"actions (authentication + lookups + the primary action) all happen in turn 1. "
"Each remaining TAIL action becomes its own separate later turn.\n\n"
"Return a JSON object exactly like:\n"
'{ "q1": "<turn-1 customer message>", "turns": [ {"user":"<message>","bridge":"<agent one-line confirmation>"}, ... ] }\n\n'
"Rules:\n"
"1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n"
"2. Provide exactly one entry in \"turns\" per tail action, in the same order. Each "
"\"user\" message must naturally trigger exactly that one action; \"bridge\" is the "
"agent's short confirming reply that precedes it.\n"
"3. The customer is ALREADY authenticated after turn 1. Later turns must NOT ask to "
"re-verify identity or re-share name / ZIP / email / phone.\n"
"4. Copy every identifier verbatim from the provided arguments: order ids (#W...), "
"item / product numbers, gift card ids, dollar amounts, and any exact quoted message "
"or review text. NEVER invent, drop, or alter an id.\n"
"5. Natural, human, concise. Vary the phrasing of follow-ups (for example 'Thanks, "
"one more thing', 'Got it, could you also', 'Perfect. Now'). Contractions are good.\n"
"6. 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"]
def fmt(c):
return {"tool": c["name"], "arguments": c.get("arguments", {})}
turn1 = [fmt(c) for c in calls[:K]]
tail = [fmt(c) for c in calls[K:]]
return json.dumps({
"original_customer_message": row["query"],
"turn1_actions": turn1,
"tail_actions_each_its_own_turn": tail,
}, 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"); turns = out.get("turns")
if not isinstance(q1, str) or not q1.strip():
return "empty q1"
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] + [str(t.get("user", "")) + " " + str(t.get("bridge", "")) for t in turns]
for t in texts:
if "\u2014" in t or "\u2013" in t or " - " in t:
return "dash present"
# allowed identifier universe = original query + all call args
allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls])
gen = toks(*texts)
new = gen - allowed
if new:
return f"new ids {sorted(new)[:4]}"
# tail-only ids must not leak into q1
prefix_ids = toks(row["query"]) & toks(*[c.get("arguments", {}) for c in calls[:K]])
tail_ids = toks(*[c.get("arguments", {}) for c in tail]) - toks(*[c.get("arguments", {}) for c in calls[:K]])
leak = toks(q1) & tail_ids
if leak:
return f"tail id leaked into q1 {sorted(leak)}"
for t in turns:
if not isinstance(t, dict) or not str(t.get("user", "")).strip():
return "empty tail user"
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 attempt in range(3):
try:
out = judge.judge({"system": SYS, "user": user})
except Exception as e: # noqa
last = f"api:{e}"; continue
err = validate(r, K, out)
if err is None:
rec = {"q1": out["q1"].strip(),
"turns": [{"user": t["user"].strip(),
"bridge": str(t.get("bridge", "")).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 not authored.get(e, {}).get("_err") and "q1" in authored.get(e, {}))
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()