File size: 8,661 Bytes
c4a370a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08741fd
 
c4a370a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08741fd
 
 
 
 
 
 
 
 
c4a370a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""Build a native-format tool-calling dataset for openbmb/MiniCPM5-1B.

Source: Team-ACE/ToolACE (Apache-2.0), raw Pythonic calls like [fn(a=1, b="x")].

Output rows:
  {"tools": [...], "messages": [{"role": "user", "content": ...},
                                {"role": "assistant", "content": "", "tool_calls": [...]}]}
or, for abstention examples, an assistant message with plain content and no tool_calls.
"""
import ast
import json
import random
import re
import sys
from pathlib import Path

from transformers import AutoTokenizer

RAW = Path(sys.argv[1] if len(sys.argv) > 1 else "raw/data.json")
OUT = Path(sys.argv[2] if len(sys.argv) > 2 else "data_native")
SEED = 42
N_TRAIN, N_VAL, N_TEST, N_TEST_NEG = 6500, 400, 400, 100
# Abstention ("no tool needed") examples mixed into train/val so the model learns when NOT to call.
N_TRAIN_NEG, N_VAL_NEG = 1100, 120
TOOLS_MARKER = "Here is a list of functions in JSON format that you can invoke:"
MODEL_ID = "openbmb/MiniCPM5-1B"


def parse_tools(system: str):
    idx = system.find(TOOLS_MARKER)
    if idx == -1:
        return None
    start = system.find("[", idx)
    if start == -1:
        return None
    try:
        tools, _ = json.JSONDecoder().raw_decode(system[start:])
    except json.JSONDecodeError:
        return None
    if not isinstance(tools, list) or not tools:
        return None
    clean = []
    for t in tools:
        if not isinstance(t, dict) or not t.get("name"):
            continue
        params = t.get("parameters") or {}
        if not isinstance(params, dict) or params.get("type") not in ("dict", "object"):
            params = {"type": "object", "properties": {}}
        clean.append(
            {
                "name": t["name"],
                "description": t.get("description", ""),
                "parameters": params,
            }
        )
    return clean or None


def _split_top_level(body: str):
    """Split 'a=1, b=[2,3], c="x,y"' on depth-0 commas, respecting quotes."""
    parts, buf, depth, quote, esc = [], [], 0, None, False
    for ch in body:
        if quote:
            buf.append(ch)
            if esc:
                esc = False
            elif ch == "\\":
                esc = True
            elif ch == quote:
                quote = None
            continue
        if ch in "\"'":
            quote = ch
            buf.append(ch)
        elif ch in "([{":
            depth += 1
            buf.append(ch)
        elif ch in ")]}":
            depth -= 1
            buf.append(ch)
        elif ch == "," and depth == 0:
            parts.append("".join(buf))
            buf = []
        else:
            buf.append(ch)
    if buf:
        parts.append("".join(buf))
    return [p.strip() for p in parts if p.strip()]


def parse_calls(value: str):
    """Parse '[fn(a=1, b="x"), Other Name(c=2)]' -> [{'name', 'arguments'}, ...].

    ToolACE uses Pythonic calls whose names may contain spaces, so the name is
    split off textually and only the argument list goes through ast.
    """
    value = value.strip()
    if not (value.startswith("[") and value.endswith("]")):
        return None
    inner = value[1:-1].strip()
    if not inner:
        return None

    segments, buf, depth, quote, esc = [], [], 0, None, False
    for ch in inner:
        if quote:
            buf.append(ch)
            if esc:
                esc = False
            elif ch == "\\":
                esc = True
            elif ch == quote:
                quote = None
            continue
        if ch in "\"'":
            quote = ch
            buf.append(ch)
        elif ch in "([{":
            depth += 1
            buf.append(ch)
        elif ch in ")]}":
            depth -= 1
            buf.append(ch)
        elif ch == "," and depth == 0:
            segments.append("".join(buf))
            buf = []
        else:
            buf.append(ch)
    if buf:
        segments.append("".join(buf))

    calls = []
    for seg in segments:
        seg = seg.strip()
        if not seg.endswith(")") or "(" not in seg:
            return None
        name, _, raw_args = seg.partition("(")
        name = name.strip()
        raw_args = raw_args[:-1].strip()
        if not name:
            return None
        args = {}
        if raw_args:
            try:
                node = ast.parse(f"_f({raw_args})", mode="eval").body
                assert isinstance(node, ast.Call)
                for kw in node.keywords:
                    if kw.arg is None:
                        return None
                    args[kw.arg] = ast.literal_eval(kw.value)
                if node.args:
                    positional = [ast.literal_eval(a) for a in node.args]
                    if not all(isinstance(p, dict) for p in positional):
                        return None
                    for p in positional:
                        args.update(p)
            except (ValueError, TypeError, SyntaxError, AssertionError):
                return None
        calls.append({"name": name, "arguments": args})
    return calls or None


def main():
    data = json.loads(RAW.read_text(encoding="utf-8"))
    calls, negatives, seen = [], [], set()

    for row in data:
        tools = parse_tools(row.get("system", ""))
        if not tools:
            continue
        names = {t["name"] for t in tools}
        conv = row.get("conversations") or []
        if len(conv) < 2 or conv[0].get("from") != "user":
            continue
        user = conv[0].get("value", "").strip()
        assistant = conv[1]
        if not user or assistant.get("from") != "assistant":
            continue
        key = user[:200]
        if key in seen:
            continue

        if "<functioncall>" in assistant["value"]:
            continue

        parsed = parse_calls(assistant["value"])
        if parsed:
            if any(c["name"] not in names for c in parsed):
                continue
            seen.add(key)
            calls.append(
                {
                    "tools": tools,
                    "messages": [
                        {"role": "user", "content": user},
                        {"role": "assistant", "content": "", "tool_calls": parsed},
                    ],
                }
            )
        elif len(conv) == 2 and assistant["value"].strip():
            seen.add(key)
            negatives.append(
                {
                    "tools": tools,
                    "messages": [
                        {"role": "user", "content": user},
                        {"role": "assistant", "content": assistant["value"].strip()},
                    ],
                }
            )

    print(f"parsed calls: {len(calls)}  negatives: {len(negatives)}", flush=True)

    tok = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
    lengths = []
    keep = []
    for ex in calls:
        text = tok.apply_chat_template(ex["messages"], tools=ex["tools"], tokenize=False)
        n = len(tok(text, add_special_tokens=False)["input_ids"])
        lengths.append(n)
        if n <= 1400:
            keep.append(ex)

    lengths.sort()
    print(
        "token lengths: p50={} p90={} p99={} max={} kept={}".format(
            lengths[len(lengths) // 2],
            lengths[int(len(lengths) * 0.9)],
            lengths[int(len(lengths) * 0.99)],
            lengths[-1],
            len(keep),
        ),
        flush=True,
    )

    rng = random.Random(SEED)
    rng.shuffle(keep)
    rng.shuffle(negatives)
    need = N_TRAIN + N_VAL + N_TEST
    if len(keep) < need:
        raise SystemExit(f"not enough examples: {len(keep)} < {need}")
    if len(negatives) < N_TRAIN_NEG + N_VAL_NEG + N_TEST_NEG:
        raise SystemExit("not enough abstention examples")

    train = keep[:N_TRAIN] + negatives[:N_TRAIN_NEG]
    val = keep[N_TRAIN : N_TRAIN + N_VAL] + negatives[N_TRAIN_NEG : N_TRAIN_NEG + N_VAL_NEG]
    off = N_TRAIN_NEG + N_VAL_NEG
    test = keep[N_TRAIN + N_VAL : need] + negatives[off : off + N_TEST_NEG]
    for rows in (train, val, test):
        rng.shuffle(rows)

    OUT.mkdir(parents=True, exist_ok=True)
    for name, rows in (("train", train), ("val", val), ("test", test)):
        with (OUT / f"{name}.jsonl").open("w", encoding="utf-8") as f:
            for r in rows:
                f.write(json.dumps(r, ensure_ascii=False) + "\n")
        print(f"{name}: {len(rows)} -> {OUT / (name + '.jsonl')}", flush=True)

    sample = val[0]
    print("\n=== rendered sample ===")
    print(tok.apply_chat_template(sample["messages"], tools=sample["tools"], tokenize=False))
    print("=== end ===")


if __name__ == "__main__":
    main()