File size: 14,447 Bytes
17b0632 | 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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | """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()
|