File size: 16,597 Bytes
89951aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lossless positional CLI codec for xLAM's direct parameter mapping.

Run: python xlam_cli.py SOURCE.json --output-dir OUTPUT
This module parses text only; it never invokes a shell or executes a tool.
"""
from __future__ import annotations

import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path

SOURCE = "Salesforce/xlam-function-calling-60k"
FORMAT_VERSION = "xlam-positional-json-values-v3"
MISSING = "__MISSING__"
RULES = (
    "Use the CLI commands below. Arguments are positional in the documented order. "
    "Encode every present value as JSON: quote strings; use numeric, boolean, null, "
    "array and object literals without schema coercion. Use __MISSING__ for an omitted "
    "argument before a later present argument; omit trailing absent arguments. "
    "Emit only calls, one per line, in their intended order. "
    "There are no shell operators or shell expansion."
)


def J(value):
    return json.loads(value) if isinstance(value, str) else value


def compact(value):
    return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)


def deep_equal(a, b):
    """Compare values AND types; Python's True == 1 and 1 == 1.0 are insufficient."""
    if type(a) is not type(b):
        return False
    if isinstance(a, dict):
        return a.keys() == b.keys() and all(deep_equal(a[k], b[k]) for k in a)
    if isinstance(a, list):
        return len(a) == len(b) and all(deep_equal(x, y) for x, y in zip(a, b))
    return a == b


def params(tool):
    """xLAM parameters are a DIRECT mapping, including any 'properties' argument.

    Do not infer JSON Schema from key names or remove metadata-like names.
    Supporting JSON Schema for another source requires an explicit source adapter.
    """
    raw = tool.get("parameters")
    p = {} if raw is None else J(raw)
    if not isinstance(p, dict):
        raise TypeError(f"{tool.get('name')!r}: parameters must be a direct mapping")
    result = []
    for name, value in p.items():
        if not isinstance(name, str):
            raise TypeError("Argument names must be strings")
        if isinstance(value, dict):
            spec = dict(value)
        elif isinstance(value, str):
            spec = {"type": value}
        elif value is None:
            spec = {}
        else:
            spec = {"raw_schema": value}
        result.append((name, spec))
    return result


def tool_map(tools):
    result = {}
    for tool in tools:
        name = tool["name"]
        if not isinstance(name, str) or not name or any(c.isspace() for c in name):
            raise ValueError(f"Unsupported tool name: {name!r}")
        if name not in result:
            result[name] = {"name": name, "parameters": {}, "_variants": []}
        # A source name can identify several different APIs. The answer does not
        # identify which one. Preserve this ambiguity; never select an API using
        # the answer. The positional order is the union of schema keys, in first
        # appearance order, derived from the tool definitions alone.
        merged = result[name]
        merged["_variants"].append(tool)
        for key, spec in params(tool):
            merged["parameters"].setdefault(key, spec)
    return result


def enc_value(value):
    return compact(value)


def enc_call(answer, tmap):
    if set(answer) != {"name", "arguments"}:
        raise ValueError(f"Unsupported call fields: {list(answer)}")
    name = answer["name"]
    args = J(answer["arguments"])
    if not isinstance(args, dict):
        raise TypeError(f"{name}: arguments must be a mapping")
    order = [k for k, _ in params(tmap[name])]
    unknown = set(args) - set(order)
    if unknown:
        raise ValueError(f"{name}: undeclared arguments {sorted(unknown)!r}")
    last = max((i for i, key in enumerate(order) if key in args), default=-1)
    return " ".join([name] + [enc_value(args[k]) if k in args else MISSING
                              for k in order[:last + 1]])


def dec_call(line, tmap):
    if not isinstance(line, str) or "\n" in line or "\r" in line:
        raise ValueError("A CLI call must be a single physical line")
    name, separator, rest = line.partition(" ")
    if name not in tmap:
        raise ValueError(f"Unknown command {name!r}")
    order = [k for k, _ in params(tmap[name])]
    decoder = json.JSONDecoder()
    pos = 0
    values = []
    while pos < len(rest):
        while pos < len(rest) and rest[pos].isspace():
            pos += 1
        if pos == len(rest):
            break
        if rest.startswith(MISSING, pos):
            end = pos + len(MISSING)
            if end < len(rest) and not rest[end].isspace():
                raise ValueError("Invalid missing-argument marker")
            values.append((False, None))
        else:
            value, end = decoder.raw_decode(rest, pos)
            # Reject non-finite values accepted by Python's permissive JSON decoder.
            compact(value)
            values.append((True, value))
            if end < len(rest) and not rest[end].isspace():
                raise ValueError("CLI values must be separated by whitespace")
        pos = end
    if len(values) > len(order):
        raise ValueError(f"Too many positional arguments for {name}")
    args = {key: value for key, (present, value) in zip(order, values) if present}
    return {"name": name, "arguments": args}


def cli_help(tools):
    blocks = []
    for tool in tool_map(tools).values():
        ps = params(tool)
        usage = " ".join([tool["name"]] + [f"<{k}>" for k, _ in ps])
        lines = [usage]
        variants = tool["_variants"]
        if len(variants) > 1:
            lines.append("  Source repeats this name. All definitions share the positional order above;")
            lines.append("  original answers do not specify a definition ID.")
        for variant_index, variant in enumerate(variants):
            if len(variants) > 1:
                lines.append(f"  Source definition {variant_index + 1}:")
            if variant.get("description"):
                lines.append("  " + str(variant["description"]).replace("\n", "\n  "))
            for key, spec in params(variant):
                details = []
                if "type" in spec:
                    details.append("declared type=" + str(spec["type"]))
                if "required" in spec:
                    details.append("required=" + compact(spec["required"]))
                if "default" in spec:
                    details.append("default=" + compact(spec["default"]))
                text = f"  {key}"
                if details:
                    text += " (" + ", ".join(details) + ")"
                if spec.get("description"):
                    text += ": " + str(spec["description"]).replace("\n", "\n    ")
                lines.append(text)
        blocks.append("\n".join(lines))
    return "\n\n".join(blocks)


def convert(row, row_index=0):
    tools, answers = J(row["tools"]), J(row["answers"])
    tmap = tool_map(tools)
    calls = [enc_call(answer, tmap) for answer in answers]
    decoded = [dec_call(call, tmap) for call in calls]
    if not deep_equal(decoded, answers):
        raise AssertionError(f"Round-trip mismatch in source row {row_index}")
    context = cli_help(tools)
    assistant = "\n".join(calls)
    duplicates = [name for name, tool in tmap.items() if len(tool["_variants"]) > 1]
    ambiguous = [name for name in duplicates if any(
        not deep_equal(tmap[name]["_variants"][0], variant)
        for variant in tmap[name]["_variants"][1:])]
    return {
        "source_id": str(row["id"]),
        "source_row_index": row_index,
        "source_dataset": SOURCE,
        "format_version": FORMAT_VERSION,
        "query": row["query"],
        "tools_json": row["tools"] if isinstance(row["tools"], str) else compact(tools),
        "answers_json": row["answers"] if isinstance(row["answers"], str) else compact(answers),
        "cli_tool_context": context,
        "cli_answers": calls,
        "assistant_cli": assistant,
        "messages": [
            {"role": "system", "content": RULES + "\n\n" + context},
            {"role": "user", "content": row["query"]},
            {"role": "assistant", "content": assistant},
        ],
        "roundtrip_ok": True,
        "call_count": len(calls),
        "duplicate_tool_names": duplicates,
        "ambiguous_tool_names": ambiguous,
        "called_ambiguous_tool_names": [name for name in ambiguous
                                        if any(a["name"] == name for a in answers)],
        "has_ambiguous_tool_names": bool(ambiguous),
    }


def validate_row(row):
    tools, answers = J(row["tools_json"]), J(row["answers_json"])
    tmap = tool_map(tools)
    decoded = [dec_call(call, tmap) for call in row["cli_answers"]]
    if not deep_equal(decoded, answers):
        raise AssertionError(f"Round-trip failure in {row['source_id']}")
    expected = convert({"id": row["source_id"], "query": row["query"],
                        "tools": row["tools_json"], "answers": row["answers_json"]},
                       row["source_row_index"])
    if not deep_equal(expected, row):
        raise AssertionError(f"Derived field mismatch in {row['source_id']}")
    return len(decoded)


def file_sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1024 * 1024), b""):
            h.update(block)
    return h.hexdigest()


def regression_tests():
    tool = {"name": "demo", "parameters": {
        "type": {"type": "integer"}, "description": "string", "title": None,
        "properties": {"type": "object", "description": "An actual argument"},
        "optional": {"type": "string"}, "last": {"type": "string"}}}
    tmap = tool_map([tool])
    cases = [
        {"type": 0.3163, "description": "hello world", "title": None,
         "properties": {"nested": [1, "a b", False]}, "last": "__MISSING__"},
        {"last": 'quotes " and \\ and\nnewlines; $(literal)'},
        {"type": "0.3163", "description": True, "title": 1.0},
        {},
    ]
    for args in cases:
        answer = {"name": "demo", "arguments": args}
        assert deep_equal(dec_call(enc_call(answer, tmap), tmap), answer)
    assert not deep_equal(True, 1) and not deep_equal(1, 1.0)
    for line in ['demo 1true', 'demo "unterminated', 'demo [1,2',
                 'demo __MISSING__bad', 'demo NaN', 'unknown 1',
                 'demo 1 2 3 4 5 6 7']:
        try:
            dec_call(line, tmap)
        except (ValueError, KeyError):
            pass
        else:
            raise AssertionError(f"Malformed CLI accepted: {line!r}")
    try:
        enc_call({"name": "demo", "arguments": {"undeclared": 1}}, tmap)
    except ValueError:
        pass
    else:
        raise AssertionError("Unknown argument was silently discarded")
    other = {"name": "demo", "parameters": {"new": "string", "last": "integer"}}
    merged = tool_map([tool, other])
    assert [k for k, _ in params(merged["demo"])] == list(tool["parameters"]) + ["new"]
    answer = {"name": "demo", "arguments": {"new": "from second definition", "type": 0.3163}}
    assert deep_equal(dec_call(enc_call(answer, merged), merged), answer)
    return True


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--provenance", type=Path)
    ns = parser.parse_args()
    regression_tests()
    rows = json.loads(ns.source.read_text(encoding="utf-8"))
    if not isinstance(rows, list):
        raise TypeError("Source must be a JSON array")
    ns.output_dir.mkdir(parents=True, exist_ok=True)
    import pyarrow as pa
    import pyarrow.parquet as pq
    dataset_path = ns.output_dir / "xlam_cli_train.parquet"
    writer = None
    accepted = 0
    calls = 0
    omitted = 0
    duplicate_rows = ambiguous_rows = called_ambiguous_rows = 0
    schema_names = Counter()
    errors = []
    batch = []
    try:
        for i, row in enumerate(rows):
            try:
                output = convert(row, i)
                calls += output["call_count"]
                tmap = tool_map(J(row["tools"]))
                for answer in J(row["answers"]):
                    order = [k for k, _ in params(tmap[answer["name"]])]
                    args = J(answer["arguments"])
                    last = max((j for j, key in enumerate(order) if key in args), default=-1)
                    omitted += sum(key not in args for key in order[:last + 1])
                duplicate_rows += bool(output["duplicate_tool_names"])
                ambiguous_rows += output["has_ambiguous_tool_names"]
                called_ambiguous_rows += bool(output["called_ambiguous_tool_names"])
                for tool in J(row["tools"]):
                    schema_names.update(k for k, _ in params(tool))
                batch.append(output)
                accepted += 1
            except Exception as exc:
                errors.append({"index": i, "source_id": str(row.get("id")),
                               "error": type(exc).__name__, "message": str(exc)})
            if len(batch) >= 1000 or (i == len(rows) - 1 and batch):
                schema = writer.schema if writer else pa.schema([
                    ("source_id", pa.string()), ("source_row_index", pa.int64()),
                    ("source_dataset", pa.string()), ("format_version", pa.string()),
                    ("query", pa.string()), ("tools_json", pa.string()),
                    ("answers_json", pa.string()), ("cli_tool_context", pa.string()),
                    ("cli_answers", pa.list_(pa.string())), ("assistant_cli", pa.string()),
                    ("messages", pa.list_(pa.struct([("role", pa.string()), ("content", pa.string())]))),
                    ("roundtrip_ok", pa.bool_()), ("call_count", pa.int64()),
                    ("duplicate_tool_names", pa.list_(pa.string())),
                    ("ambiguous_tool_names", pa.list_(pa.string())),
                    ("called_ambiguous_tool_names", pa.list_(pa.string())),
                    ("has_ambiguous_tool_names", pa.bool_()),
                ])
                table = pa.Table.from_pylist(batch, schema=schema)
                if writer is None:
                    writer = pq.ParquetWriter(dataset_path, table.schema, compression="zstd")
                writer.write_table(table)
                batch.clear()
            if (i + 1) % 10000 == 0:
                print(f"Converted {i + 1:,}/{len(rows):,} rows", flush=True)
    finally:
        if writer:
            writer.close()
    report = {"format_version": FORMAT_VERSION, "source_rows": len(rows),
              "accepted_rows": accepted, "failed_rows": len(errors),
              "validated_calls": calls, "missing_argument_markers": omitted,
              "rows_with_duplicate_tool_names": duplicate_rows,
              "rows_with_ambiguous_tool_names": ambiguous_rows,
              "rows_calling_ambiguous_tool_names": called_ambiguous_rows,
              "duplicate_name_policy": "union of parameters in first-appearance order; preserve all definitions and flag ambiguity",
              "source_sha256": file_sha256(ns.source),
              "dataset_sha256": file_sha256(dataset_path) if dataset_path.exists() else None,
              "source_provenance": json.loads(ns.provenance.read_text()) if ns.provenance else {},
              "schema_argument_name_counts": dict(schema_names.most_common()),
              "errors": errors}
    (ns.output_dir / "validation_report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    if errors:
        raise RuntimeError(f"{len(errors)} rows failed; see validation_report.json. Do not publish.")
    # Read back the exported file, independently validating every serialized row.
    read_rows = read_calls = 0
    for record_batch in pq.ParquetFile(dataset_path).iter_batches(batch_size=1000):
        for row in record_batch.to_pylist():
            read_calls += validate_row(row)
            read_rows += 1
    assert read_rows == accepted and read_calls == calls
    report["parquet_readback_rows"] = read_rows
    report["parquet_readback_calls"] = read_calls
    report["all_checks_passed"] = True
    (ns.output_dir / "validation_report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(f"Validated {accepted:,} rows and {calls:,} calls; exported {dataset_path}", flush=True)


if __name__ == "__main__":
    main()