Download make_hard_set.py from DevGwardo/minicpm5-toolcall-code: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/datasets/DevGwardo/minicpm5-toolcall-code/resolve/main/make_hard_set.py
- Command line
-
hf download hf://datasets/DevGwardo/minicpm5-toolcall-code/make_hard_set.py
-
curl -L -o make_hard_set.py https://huggingface.co/datasets/DevGwardo/minicpm5-toolcall-code/resolve/main/make_hard_set.py
14.4 kB
| """Build a 50-example adversarial hard set from data_native/test.jsonl. | |
| Categories (10 each): nested_args, enum_args, multi_call, long_tools, abstention. | |
| Deterministic (seed 13). Output: data_native/hard_test.jsonl | |
| Schema per row: {"tools":[...], "messages":[...], "_category":..., "_source_i":...} | |
| """ | |
| import copy | |
| import json | |
| import random | |
| from pathlib import Path | |
| SEED = 13 | |
| N_PER_CAT = 10 | |
| SRC = Path(__file__).resolve().parent.parent / "data_native" / "test.jsonl" | |
| DST = Path(__file__).resolve().parent.parent / "data_native" / "hard_test.jsonl" | |
| TYPE_ALIASES = { | |
| "dict": "dict", "object": "dict", | |
| "array": "array", "list": "array", | |
| "string": "string", "str": "string", | |
| "int": "int", "integer": "int", | |
| "float": "float", "number": "float", | |
| "boolean": "boolean", "bool": "boolean", | |
| } | |
| def norm_type(t): | |
| if isinstance(t, list): | |
| return [TYPE_ALIASES.get(str(x).lower(), str(x).lower()) for x in t] | |
| return TYPE_ALIASES.get(str(t).lower(), str(t).lower()) | |
| def type_ok(value, declared): | |
| allowed = norm_type(declared) if isinstance(declared, list) else [norm_type(declared)] | |
| for a in allowed: | |
| if a == "string" and isinstance(value, str): | |
| return True | |
| if a == "int" and isinstance(value, int) and not isinstance(value, bool): | |
| return True | |
| if a == "float" and isinstance(value, (int, float)) and not isinstance(value, bool): | |
| return True | |
| if a == "boolean" and isinstance(value, bool): | |
| return True | |
| if a == "dict" and isinstance(value, dict): | |
| return True | |
| if a == "array" and isinstance(value, list): | |
| return True | |
| if a == "null" and value is None: | |
| return True | |
| return False | |
| def synth_values_for_type(declared, current, rng): | |
| """Two synthetic values of the same JSON kind as current (deterministic).""" | |
| if isinstance(current, bool): | |
| return [not current] | |
| if isinstance(current, int) and not isinstance(current, bool): | |
| return [current + 1, current + 2] | |
| if isinstance(current, float): | |
| return [round(float(current) + 0.5, 3), round(float(current) + 1.5, 3)] | |
| if isinstance(current, str): | |
| cands = [current + "_alt", current + "_v2", "auto", "manual", "standard"] | |
| out = [] | |
| for c in cands: | |
| if c != current and c not in out: | |
| out.append(c) | |
| if len(out) == 2: | |
| break | |
| return out | |
| if isinstance(current, list): | |
| return [[], current + current[:1]] | |
| if isinstance(current, dict): | |
| return [{}, current] | |
| return ["alt1", "alt2"] | |
| def find_tool(tools, name): | |
| for t in tools: | |
| if t.get("name") == name: | |
| return t | |
| return None | |
| def assistant_msg(row): | |
| for m in row["messages"]: | |
| if m.get("role") == "assistant": | |
| return m | |
| return None | |
| def user_msg(row): | |
| for m in row["messages"]: | |
| if m.get("role") == "user": | |
| return m | |
| return None | |
| # ---------------- transforms ---------------- | |
| def make_nested(row, rng): | |
| r = copy.deepcopy(row) | |
| am = assistant_msg(r) | |
| tc = am["tool_calls"][0] | |
| tool = find_tool(r["tools"], tc["name"]) | |
| params = tool.setdefault("parameters", {}) | |
| props = params.get("properties", {}) | |
| req = list(params.get("required", [])) | |
| orig_args = dict(tc.get("arguments", {}) or {}) | |
| # wrap all original props under a nested object "request" | |
| nested_props = copy.deepcopy(props) | |
| tool["parameters"] = { | |
| "type": "dict", | |
| "properties": { | |
| "request": { | |
| "description": "Nested object grouping all request arguments.", | |
| "type": "dict", | |
| "properties": nested_props, | |
| **({"required": req} if req else {}), | |
| } | |
| }, | |
| "required": ["request"], | |
| } | |
| tc["arguments"] = {"request": orig_args} | |
| # rewrite every call of this tool in the turn the same way | |
| for other in am["tool_calls"][1:]: | |
| if other["name"] == tc["name"]: | |
| other["arguments"] = {"request": dict(other.get("arguments", {}) or {})} | |
| um = user_msg(r) | |
| um["content"] = um["content"].rstrip() + ( | |
| " Provide all details inside the single 'request' object parameter " | |
| "of the '%s' tool." % tc["name"] | |
| ) | |
| return r | |
| def make_enum(row, rng): | |
| r = copy.deepcopy(row) | |
| am = assistant_msg(r) | |
| tc = am["tool_calls"][0] | |
| tool = find_tool(r["tools"], tc["name"]) | |
| props = tool.get("parameters", {}).get("properties", {}) | |
| args = tc.get("arguments", {}) or {} | |
| # prefer a string-valued arg present in schema, else any arg key in schema | |
| prop_key = None | |
| for k, v in args.items(): | |
| if k in props and isinstance(v, str): | |
| prop_key = k | |
| break | |
| if prop_key is None: | |
| for k in args: | |
| if k in props: | |
| prop_key = k | |
| break | |
| if prop_key is None: | |
| # fallback: first schema property (add arg for it if missing? keep valid: use existing) | |
| prop_key = next(iter(props.keys())) | |
| cur = args.get(prop_key) | |
| if cur is None: | |
| # arg missing for that prop; pick first existing arg instead | |
| prop_key = next(iter(args.keys())) | |
| cur = args[prop_key] | |
| prop = props[prop_key] | |
| extra = synth_values_for_type(prop.get("type", "string"), cur, rng) | |
| enum_vals = [cur] + [e for e in extra if e != cur] | |
| # ensure uniqueness preserving order, take 3 | |
| seen, enum_vals2 = set(), [] | |
| for e in enum_vals: | |
| key = json.dumps(e, sort_keys=True, default=str) | |
| if key not in seen: | |
| seen.add(key) | |
| enum_vals2.append(e) | |
| prop["enum"] = enum_vals2[:3] | |
| if len(prop["enum"]) < 2: | |
| prop["enum"] = prop["enum"] + ["fallback_option"] | |
| um = user_msg(r) | |
| um["content"] = um["content"].rstrip() + ( | |
| " The '%s' parameter must be exactly one of: %s." | |
| % (prop_key, ", ".join(json.dumps(e, ensure_ascii=False) for e in prop["enum"])) | |
| ) | |
| return r | |
| def make_multi(row, rng): | |
| r = copy.deepcopy(row) | |
| um = user_msg(r) | |
| if not um["content"].rstrip().endswith("Please make all requested calls in one turn."): | |
| um["content"] = um["content"].rstrip() + " Please make all requested calls in one turn." | |
| return r | |
| def make_long_tools(row, rng): | |
| r = copy.deepcopy(row) | |
| existing = {t.get("name") for t in r["tools"]} | |
| calls = {c["name"] for c in (assistant_msg(r).get("tool_calls") or [])} | |
| base_pool = [t for t in r["tools"]] | |
| # build distractors from clones with similar names | |
| i = 0 | |
| suffixes = ["Plus", "Pro", "v2", "Extended", "Helper", "Util", "V2", "Advanced", "Lite", "X"] | |
| while len(r["tools"]) < 20: | |
| src = base_pool[i % len(base_pool)] | |
| sfx = suffixes[(i // max(len(base_pool), 1)) % len(suffixes)] | |
| cand = "%s %s %d" % (src.get("name"), sfx, i) | |
| i += 1 | |
| if cand in existing: | |
| continue | |
| d = copy.deepcopy(src) | |
| d["name"] = cand | |
| r["tools"].append(d) | |
| existing.add(cand) | |
| if i > 500: | |
| break | |
| # shuffle distractors but keep target call valid (order irrelevant); deterministic | |
| targets = calls | |
| fixed = [t for t in r["tools"] if t.get("name") in targets] | |
| rest = [t for t in r["tools"] if t.get("name") not in targets] | |
| rng.shuffle(rest) | |
| # interleave: keep at least one target not at position 0 to force retrieval | |
| r["tools"] = rest[:10] + fixed + rest[10:] | |
| assert len(r["tools"]) == 20 | |
| return r | |
| # ---------------- validation ---------------- | |
| def validate_row(row): | |
| errs = [] | |
| tools = row.get("tools", []) | |
| names = {t.get("name") for t in tools} | |
| seen_prompts = None # checked globally | |
| for m in row.get("messages", []): | |
| if m.get("role") == "assistant" and m.get("tool_calls"): | |
| for tc in m["tool_calls"]: | |
| if tc.get("name") not in names: | |
| errs.append("call name %r not in tools" % tc.get("name")) | |
| continue | |
| tool = find_tool(tools, tc["name"]) | |
| params = tool.get("parameters", {}) if isinstance(tool, dict) else {} | |
| # nested_args rows: required lives on outer + inner; check outer only here, | |
| # deep check below handles nested required | |
| req = params.get("required", []) or [] | |
| args = tc.get("arguments", {}) or {} | |
| for rk in req: | |
| if rk not in args: | |
| errs.append("missing required arg %r for %s" % (rk, tc["name"])) | |
| props = params.get("properties", {}) or {} | |
| for k, v in args.items(): | |
| if k in props and isinstance(props[k], dict) and "type" in props[k]: | |
| ptype = props[k]["type"] | |
| if ptype in ("dict", "object") and isinstance(v, dict) and "properties" in props[k]: | |
| # deep-check nested object | |
| sub_props = props[k].get("properties", {}) or {} | |
| sub_req = props[k].get("required", []) or [] | |
| for rk in sub_req: | |
| if rk not in v: | |
| errs.append("missing nested required %r for %s" % (rk, tc["name"])) | |
| for sk, sv in v.items(): | |
| if sk in sub_props and isinstance(sub_props[sk], dict) and "type" in sub_props[sk]: | |
| if not type_ok(sv, sub_props[sk]["type"]): | |
| errs.append("type mismatch nested %r" % sk) | |
| if "enum" in sub_props[sk] and sv not in sub_props[sk]["enum"]: | |
| errs.append("enum violation nested %r" % sk) | |
| else: | |
| if not type_ok(v, ptype): | |
| errs.append("type mismatch %r: %r vs %s" % (k, v, ptype)) | |
| if "enum" in props[k] and v not in props[k]["enum"]: | |
| errs.append("enum violation %r" % k) | |
| return errs | |
| def main(): | |
| rng = random.Random(SEED) | |
| rows = [json.loads(l) for l in SRC.open(encoding="utf-8")] | |
| pos_idx = [i for i, r in enumerate(rows) if assistant_msg(r).get("tool_calls")] | |
| abst_idx = [i for i, r in enumerate(rows) if not assistant_msg(r).get("tool_calls")] | |
| def target_tool_of(i): | |
| r = rows[i] | |
| am = assistant_msg(r) | |
| tcs = am.get("tool_calls") or [] | |
| if not tcs: | |
| return None, None | |
| t = find_tool(r["tools"], tcs[0]["name"]) | |
| return t, tcs[0] | |
| nested_pool = [i for i in pos_idx if (lambda x: x[0] is not None and (x[1].get("arguments")) and x[0].get("parameters", {}).get("properties"))(target_tool_of(i))] | |
| enum_pool = [i for i in pos_idx if (lambda x: x[0] is not None and (x[1].get("arguments")) and any(k in x[0].get("parameters", {}).get("properties", {}) for k in (x[1].get("arguments") or {})))(target_tool_of(i))] | |
| multi_pool = [i for i in pos_idx if 2 <= len(assistant_msg(rows[i]).get("tool_calls") or []) <= 3] | |
| long_pool = [i for i in pos_idx if len(rows[i]["tools"]) < 20] | |
| for name, pool in [("nested", nested_pool), ("enum", enum_pool), ("multi", multi_pool), ("long", long_pool)]: | |
| print("%s candidates: %d" % (name, len(pool))) | |
| print("abstention candidates: %d" % len(abst_idx)) | |
| assert len(nested_pool) >= 10 and len(enum_pool) >= 10 and len(multi_pool) >= 10 and len(abst_idx) >= 10 | |
| rng.shuffle(nested_pool) | |
| rng.shuffle(enum_pool) | |
| rng.shuffle(multi_pool) | |
| rng.shuffle(long_pool) | |
| rng.shuffle(abst_idx) | |
| used = set() | |
| out = [] | |
| def take(pool, n): | |
| sel = [] | |
| for i in pool: | |
| if i not in used: | |
| sel.append(i) | |
| if len(sel) == n: | |
| break | |
| assert len(sel) == n, "pool exhausted" | |
| used.update(sel) | |
| return sel | |
| for i in take(nested_pool, N_PER_CAT): | |
| r = make_nested(rows[i], rng) | |
| r["_category"] = "nested_args" | |
| r["_source_i"] = i | |
| out.append(r) | |
| for i in take(enum_pool, N_PER_CAT): | |
| r = make_enum(rows[i], rng) | |
| r["_category"] = "enum_args" | |
| r["_source_i"] = i | |
| out.append(r) | |
| for i in take(multi_pool, N_PER_CAT): | |
| r = make_multi(rows[i], rng) | |
| r["_category"] = "multi_call" | |
| r["_source_i"] = i | |
| out.append(r) | |
| for i in take(long_pool, N_PER_CAT): | |
| r = make_long_tools(rows[i], rng) | |
| r["_category"] = "long_tools" | |
| r["_source_i"] = i | |
| out.append(r) | |
| for i in take(abst_idx, N_PER_CAT): | |
| r = copy.deepcopy(rows[i]) | |
| r["_category"] = "abstention" | |
| r["_source_i"] = i | |
| out.append(r) | |
| assert len(out) == 50 | |
| # dedupe prompts | |
| seen = set() | |
| for r in out: | |
| p = user_msg(r)["content"] | |
| if p in seen: | |
| k = 1 | |
| while ("%s [variant %d]" % (p, k)) in seen: | |
| k += 1 | |
| p = "%s [variant %d]" % (p, k) | |
| user_msg(r)["content"] = p | |
| seen.add(p) | |
| assert len(seen) == 50, "duplicate prompts remain" | |
| # validate | |
| from collections import Counter | |
| cat_counts = Counter(r["_category"] for r in out) | |
| n_pass, failures = 0, [] | |
| for r in out: | |
| errs = validate_row(r) | |
| if errs: | |
| failures.append((r["_category"], r["_source_i"], errs)) | |
| else: | |
| n_pass += 1 | |
| # global dup check | |
| assert len({user_msg(r)["content"] for r in out}) == 50 | |
| DST.parent.mkdir(parents=True, exist_ok=True) | |
| with DST.open("w", encoding="utf-8") as f: | |
| for r in out: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| print("wrote %s (%d rows)" % (DST, len(out))) | |
| print("category counts:", dict(cat_counts)) | |
| print("schema-validation pass: %d/%d" % (n_pass, len(out))) | |
| if failures: | |
| print("FAILURES:") | |
| for c, i, e in failures[:10]: | |
| print(" ", c, i, e) | |
| else: | |
| print("all rows valid; no duplicate prompts") | |
| # 2 example prompts | |
| for r in out[:2]: | |
| print("--- [%s src=%s] %s" % (r["_category"], r["_source_i"], user_msg(r)["content"][:220])) | |
| if __name__ == "__main__": | |
| main() | |