| """Generate ToolFault-Bench. |
| |
| python scripts/generate.py --out data --seed 20260923 |
| |
| Writes data/test-00000-of-00001.parquet and data/validation-00000-of-00001.parquet. |
| Deterministic for a given seed. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import random |
| import sys |
|
|
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
|
|
| import pandas as pd |
|
|
| from common import Ctx, dumps, iso, person, sample_now |
| from domains import DOMAINS, DOMAIN_BY_KEY |
| from templates import PLAN |
|
|
| VAL_FRACTION = 0.15 |
|
|
|
|
| def assignments(subtype: str, n: int, rng: random.Random): |
| """Yield (domain, extra) pairs for each item of a subtype.""" |
| if subtype == "invalid_args": |
| for rep in range(n // (len(DOMAINS) * 3)): |
| for d in DOMAINS: |
| for k in range(3): |
| yield d, {"k": k} |
| return |
| if subtype == "none_old_timestamp_ok": |
| for _ in range(4): |
| yield DOMAIN_BY_KEY["brokerage"], {"weekend": True} |
| for i in range(n - 4): |
| yield DOMAINS[i % len(DOMAINS)], {} |
| return |
| off = rng.randrange(len(DOMAINS)) |
| for i in range(n): |
| yield DOMAINS[(i + off) % len(DOMAINS)], {} |
|
|
|
|
| def build_messages(d, c, it): |
| msgs = [{"role": "system", "content": d.system(c)}, {"role": "user", "content": it["request"]}] |
| k = 0 |
|
|
| def add(call, result, note=None): |
| nonlocal k |
| k += 1 |
| cid = f"call_{k}" |
| msgs.append({"role": "assistant", "content": note or "", |
| "tool_calls": [{"id": cid, "type": "function", |
| "function": {"name": call.tool, "arguments": json.dumps(call.args, ensure_ascii=False)}}]}) |
| msgs.append({"role": "tool", "tool_call_id": cid, "name": call.tool, "content": dumps(result)}) |
|
|
| for p in it["prefix"]: |
| add(p, p.response) |
| for call, err, note in it["history"]: |
| add(call, err, note) |
| add(it["call"], it["result"], it.get("prior_note")) |
| return msgs |
|
|
|
|
| def generate(seed: int): |
| rows = [] |
| for subtype, (builder, n) in PLAN.items(): |
| srng = random.Random(f"{seed}:{subtype}") |
| count = 0 |
| for i, (d, extra) in enumerate(assignments(subtype, n, srng)): |
| rng = random.Random(f"{seed}:{subtype}:{i}") |
| c = Ctx(rng=rng, now=sample_now(rng, weekend=extra.get("weekend", False)), org=rng.choice(d.orgs), |
| user=person(rng), extra=extra) |
| it = builder(d, c) |
| tools = d.tools(it["overrides"]) |
| msgs = build_messages(d, c, it) |
| rows.append({ |
| "domain": d.key, |
| "subtype": it["subtype"], |
| "fault_type": it["fault_type"], |
| "next_action": it["next_action"], |
| "acceptable_next_actions": list(it["acceptable"]), |
| "critical_next_actions": list(it["critical"]), |
| "difficulty": it["difficulty"], |
| "is_hard_negative": bool(it["is_hard_negative"]), |
| "current_time": iso(c.now), |
| "user_request": it["request"], |
| "tools": json.dumps(tools, ensure_ascii=False), |
| "messages": json.dumps(msgs, ensure_ascii=False), |
| "num_tool_calls": sum(1 for m in msgs if m["role"] == "tool"), |
| "last_tool_name": it["call"].tool, |
| "last_tool_result": msgs[-1]["content"], |
| "gold_recovery": it["gold_recovery"], |
| "rationale": it["rationale"], |
| "meta": json.dumps(it["meta"], ensure_ascii=False), |
| }) |
| count += 1 |
| assert count == n, (subtype, count, n) |
| return rows |
|
|
|
|
| def split_and_id(rows, seed: int): |
| rng = random.Random(f"{seed}:split") |
| by_sub = {} |
| for r in rows: |
| by_sub.setdefault(r["subtype"], []).append(r) |
| for rs in by_sub.values(): |
| rng.shuffle(rs) |
| k = max(1, round(len(rs) * VAL_FRACTION)) |
| for j, r in enumerate(rs): |
| r["split"] = "validation" if j < k else "test" |
| rows = [r for rs in by_sub.values() for r in rs] |
| rng.shuffle(rows) |
| for j, r in enumerate(rows): |
| r["id"] = f"tfb-{j + 1:04d}" |
| return rows |
|
|
|
|
| COLUMNS = ["id", "domain", "subtype", "fault_type", "next_action", "acceptable_next_actions", "critical_next_actions", |
| "difficulty", "is_hard_negative", "current_time", "user_request", "tools", "messages", "num_tool_calls", |
| "last_tool_name", "last_tool_result", "gold_recovery", "rationale", "meta"] |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--out", default="data") |
| ap.add_argument("--seed", type=int, default=20260923) |
| a = ap.parse_args() |
| rows = split_and_id(generate(a.seed), a.seed) |
| os.makedirs(a.out, exist_ok=True) |
| df = pd.DataFrame(rows) |
| for split in ("test", "validation"): |
| part = df[df.split == split][COLUMNS].sort_values("id").reset_index(drop=True) |
| path = os.path.join(a.out, f"{split}-00000-of-00001.parquet") |
| part.to_parquet(path, index=False) |
| print(f"{split}: {len(part)} rows -> {path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|