minicpm5-toolcall-code / prepare_data.py
DevGwardo's picture
Abstention mix + decode fix + eval-only
08741fd verified
Raw History Blame Contribute Delete
8.66 kB
"""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()