File size: 5,236 Bytes
5755408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""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  # noqa: E402

from common import Ctx, dumps, iso, person, sample_now  # noqa: E402
from domains import DOMAINS, DOMAIN_BY_KEY  # noqa: E402
from templates import PLAN  # noqa: E402

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()