tkhersoft's picture
temp build/analysis scripts (54 py files) backup before prune
94da461 verified
Raw
History Blame Contribute Delete
5.29 kB
"""Join every C3 result row to its confuser story and the EXACT text C3 judged.
For each caught row we emit: item_id, tool, real_id, confidence, the judge's
reasoning, the query, a compact history view, the rendered C3 conversation, and
tell tags (keyword-derived from the reasoning). Also emits an uncaught set so we
can study what already fools C3.
Run from repo root: python -u temp/story_remediation/build_join.py
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
from datasetreview import judge_prompts as J # noqa: E402
OUT = Path(__file__).resolve().parent / "out"
C3 = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
TRAJ = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
def _rows(p: Path):
return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()]
TELLS = {
"bundled_checklist": ("bundl", "packs", "checklist", "enumerat", "multiple distinct",
"multi-task", "one turn", "one message", "exercise many",
"exercise multiple", "one-to-one", "stack", "all at once",
"everything at once", "comprehensive", "front-load"),
"no_verification": ("verificat", "authenticat", "identity", "without verif",
"skips ident", "glossed", "no auth"),
"over_precise_ids": ("precise", "exact order", "exact item", "id-laden", "unprompted",
"conveniently", "verbatim", "recite", "specific order number"),
"agent_burst_no_confirm": ("fires", "burst", "no confirmation", "no intermediate",
"without confirm", "batch of tool", "silently", "no clarif",
"many tool call", "rapid sequence"),
"terse_closer": ("taken care of", "all set", "that's handled", "done.", "what else",
"formulaic", "terse"),
"duplicate_request": ("redundant", "restate", "re-asks", "re-state", "twice",
"double-statement", "identical repeated", "repeats the"),
"invented_capability": ("unusual", "atypical", "don't typically", "invent",
"doesn't typically", "not typically", "uncommon", "rarely"),
"sequential_orders": ("sequential", "conveniently formatted", "clean order number"),
"scripted_flavor": ("scripted", "staged", "stagey", "stilted", "canned", "test prompt",
"task prompt", "flavor text", "persona"),
}
def tag(reason: str) -> list[str]:
r = reason.lower()
return [k for k, ws in TELLS.items() if any(w in r for w in ws)]
def hist_view(story: dict):
out = []
for m in story.get("history") or []:
if m.get("role") == "tool":
continue
out.append({"role": m.get("role"),
"content": (m.get("content") or "").strip(),
"n_tool_calls": len(m.get("tool_calls") or [])})
return out
def main() -> int:
c3 = _rows(C3)
traj = {t["example_id"]: t for t in _rows(TRAJ)}
caught, fooled = [], []
missing = 0
for r in c3:
iid = r["item_id"]
story = traj.get(iid)
if story is None:
missing += 1
continue
parts = iid.split("-")
tool = parts[1] if len(parts) >= 3 else "?"
rec = {
"item_id": iid,
"tool": tool,
"real_id": r.get("real_id"),
"caught": bool(r.get("caught")),
"confidence": (r.get("result") or {}).get("confidence"),
"reasoning": (r.get("result") or {}).get("reasoning") or "",
"tells": tag((r.get("result") or {}).get("reasoning") or ""),
"n_calls": len(story.get("calls") or []),
"n_hist_turns": len(hist_view(story)),
"query": (story.get("query") or story.get("retrieval_text") or "").strip(),
"history": hist_view(story),
"c3_view": J.render_trajectory(story, blind_tools=True,
include_metadata=False, conversation_only=True),
}
(caught if rec["caught"] else fooled).append(rec)
(OUT / "caught_rows.jsonl").write_text(
"\n".join(json.dumps(r, ensure_ascii=False) for r in caught) + "\n", encoding="utf-8")
(OUT / "fooled_rows.jsonl").write_text(
"\n".join(json.dumps(r, ensure_ascii=False) for r in fooled) + "\n", encoding="utf-8")
from collections import Counter
tally = Counter(t for r in caught for t in r["tells"])
notag = sum(1 for r in caught if not r["tells"])
print(f"caught={len(caught)} fooled={len(fooled)} missing_story={missing}")
print(f"caught rows with NO tell tag: {notag}")
print("tell frequency among caught:")
for k, v in tally.most_common():
print(f" {v:4d} {k}")
# history presence
openers = sum(1 for r in caught if r["n_hist_turns"] == 0)
print(f"caught openers (no history): {openers} | caught with history: {len(caught)-openers}")
return 0
if __name__ == "__main__":
raise SystemExit(main())