File size: 4,454 Bytes
78f3315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Integrity checks for data/test.jsonl. Exits non-zero on any failure.

    python scripts/validate.py [--data data/test.jsonl]

Checks: required fields, unique ids, valid context, every gold call passes the
training schema, gold matches itself, gold_tools consistent with calls, every
tool name exists in the catalog, held-out labels consistent, no-call items have
no calls, and a distribution report.
"""

import argparse
import json
import sys
from collections import Counter
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from phonebench.run import load_jsonl  # noqa: E402
from phonebench.scoring import Scorer  # noqa: E402

REQUIRED = {"id", "language", "category", "subtype", "tool_split", "gold_tools", "context", "request", "calls"}
CATEGORIES = {"single", "multi", "reasoning", "lookalike", "no_tool", "clarify", "partial"}
NO_CALL = {"no_tool", "clarify"}
LANGS = {"en", "pt", "es", "de"}


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default=str(ROOT / "data" / "test.jsonl"))
    ap.add_argument("--tools", default=str(ROOT / "tools.json"))
    ap.add_argument("--scoring", default=str(ROOT / "scoring.json"))
    args = ap.parse_args(argv)

    items = load_jsonl(args.data)
    tools = json.loads(Path(args.tools).read_text(encoding="utf-8"))
    catalog = {t["function"]["name"] for t in tools}
    scorer = Scorer.from_files(args.tools, args.scoring)
    errors = []

    def fail(item, msg):
        errors.append(f"{item.get('id', '?')}: {msg}")

    ids = Counter(i.get("id") for i in items)
    for dup in (k for k, v in ids.items() if v > 1):
        errors.append(f"duplicate id {dup}")

    for item in items:
        missing = REQUIRED - item.keys()
        if missing:
            fail(item, f"missing fields {sorted(missing)}")
            continue
        if item["language"] not in LANGS:
            fail(item, f"unknown language {item['language']}")
        if item["category"] not in CATEGORIES:
            fail(item, f"unknown category {item['category']}")
        if (item["subtype"] is not None) != (item["category"] == "reasoning"):
            fail(item, "subtype must be set only for reasoning items")

        ctx = item["context"]
        try:
            datetime.fromisoformat(ctx["datetime"])
            ZoneInfo(ctx["timezone"])
        except (KeyError, ValueError) as e:
            fail(item, f"bad context: {e}")

        if not item["request"].strip():
            fail(item, "empty request")

        try:
            gold = json.loads(item["calls"])
        except json.JSONDecodeError as e:
            fail(item, f"calls is not JSON: {e}")
            continue

        for call in gold:
            if call.get("name") not in catalog:
                fail(item, f"tool {call.get('name')} not in catalog")
            for err in scorer.validate_call(call):
                fail(item, f"schema: {err}")

        if not scorer.calls_match(gold, gold):
            fail(item, "gold does not match itself")

        names = sorted({c["name"] for c in gold})
        if item["gold_tools"] != names:
            fail(item, "gold_tools does not match the tool names in calls")

        if item["category"] in NO_CALL and gold:
            fail(item, "no-call item has tool calls")
        if item["category"] not in NO_CALL and not gold:
            fail(item, "tool item has no calls")

    if len({i["request"] for i in items}) != len(items):
        errors.append("duplicate request texts")

    covered = {c["name"] for i in items for c in json.loads(i["calls"])}
    uncovered = sorted(catalog - covered)
    if uncovered:
        errors.append(f"catalog tools never used in gold: {uncovered}")

    print(f"items: {len(items)}")
    print("category:", dict(Counter(i["category"] for i in items)))
    print("language:", dict(Counter(i["language"] for i in items)))
    print("tool_split:", dict(Counter(i["tool_split"] for i in items)))
    print(f"catalog coverage: {len(covered & catalog)} / {len(catalog)}")
    print(f"gold calls per item: {dict(Counter(len(json.loads(i['calls'])) for i in items))}")

    if errors:
        print(f"\n{len(errors)} problem(s):")
        for e in errors[:50]:
            print("  -", e)
        return 1
    print("\nOK: all checks passed")
    return 0


if __name__ == "__main__":
    sys.exit(main())