File size: 3,174 Bytes
17e10c6 | 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 | """Extract multi-turn tool loops from ToolACE: user -> call -> tool -> follow-up.
Each output row is exactly one round trip, which is what makes staged evaluation
possible: stage 1 predicts the call, stage 2 sees the ground-truth tool result and
must decide whether to answer or call again.
"""
import json
import random
import sys
from pathlib import Path
from transformers import AutoTokenizer
sys.path.insert(0, str(Path(__file__).parent))
from prepare_data import parse_calls, parse_tools
RAW = Path("raw/data.json")
OUT = Path("data_native")
MODEL_ID = "openbmb/MiniCPM5-1B"
N_TEST, N_VAL = 100, 15
MAX_LEN = 1800
def main():
data = json.loads(RAW.read_text(encoding="utf-8"))
rows, seen = [], set()
for d in data:
conv = d.get("conversations") or []
if len(conv) < 4:
continue
if [m.get("from") for m in conv[:4]] != ["user", "assistant", "tool", "assistant"]:
continue
tools = parse_tools(d.get("system", ""))
if not tools:
continue
names = {t["name"] for t in tools}
user = conv[0]["value"].strip()
call = parse_calls(conv[1]["value"])
if not user or not call or any(c["name"] not in names for c in call):
continue
key = user[:150]
if key in seen:
continue
seen.add(key)
follow = conv[3]["value"].strip()
follow_calls = parse_calls(follow)
if follow_calls and any(c["name"] not in names for c in follow_calls):
continue
assistant2 = {"role": "assistant", "content": "" if follow_calls else follow}
if follow_calls:
assistant2["tool_calls"] = follow_calls
rows.append(
{
"tools": tools,
"messages": [
{"role": "user", "content": user},
{"role": "assistant", "content": "", "tool_calls": call},
{"role": "tool", "content": conv[2]["value"]},
assistant2,
],
}
)
tok = AutoTokenizer.from_pretrained(MODEL_ID)
kept = []
for r in rows:
text = tok.apply_chat_template(r["messages"], tools=r["tools"], tokenize=False)
if len(tok(text, add_special_tokens=False)["input_ids"]) <= MAX_LEN:
kept.append(r)
print(f"multi-turn rows: {len(rows)} kept={len(kept)}", flush=True)
if len(kept) < N_TEST + N_VAL + 100:
raise SystemExit("not enough multi-turn rows")
rng = random.Random(7)
rng.shuffle(kept)
test, val, train = kept[:N_TEST], kept[N_TEST : N_TEST + N_VAL], kept[N_TEST + N_VAL :]
for name, rs in (("mt_train", train), ("mt_val", val), ("mt_test", test)):
p = OUT / f"{name}.jsonl"
with p.open("w", encoding="utf-8") as f:
for r in rs:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"{name}: {len(rs)} -> {p}", flush=True)
first = train[0]
print("\n=== rendered (truncated) ===")
print(tok.apply_chat_template(first["messages"], tools=first["tools"], tokenize=False)[:1200])
if __name__ == "__main__":
main()
|