Datasets:
Download scripts/normalize_openai_wire_format.py from reflectio/swe-smith-frozen-trajectories-openai: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/reflectio/swe-smith-frozen-trajectories-openai/resolve/main/scripts/normalize_openai_wire_format.py
- Command line
-
hf download hf://datasets/reflectio/swe-smith-frozen-trajectories-openai/scripts/normalize_openai_wire_format.py
-
curl -L -o normalize_openai_wire_format.py https://huggingface.co/datasets/reflectio/swe-smith-frozen-trajectories-openai/resolve/main/scripts/normalize_openai_wire_format.py
11.6 kB
| #!/usr/bin/env python3 | |
| """Normalize frozen SWE-Smith requests to OpenAI chat wire format. | |
| The source workload stores some structured message fields in a tokenizer-friendly | |
| representation. OpenAI-compatible HTTP endpoints require function arguments and | |
| object-valued message content to be JSON strings, and tool result messages must | |
| carry the ID of the tool call they answer. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| from collections import Counter | |
| from itertools import zip_longest | |
| from pathlib import Path | |
| from typing import Any | |
| FORMAT_VERSION = "openai-chat-completions-wire-v1" | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--requests", required=True) | |
| parser.add_argument("--metadata", required=True) | |
| parser.add_argument("--output", required=True) | |
| parser.add_argument("--metadata-output", required=True) | |
| parser.add_argument("--stats-output", required=True) | |
| parser.add_argument( | |
| "--source-dataset", | |
| default="reflectio/swe-smith-frozen-trajectories", | |
| ) | |
| return parser.parse_args() | |
| def compact_json(value: Any) -> str: | |
| return json.dumps(value, ensure_ascii=False, separators=(",", ":")) | |
| def normalize_messages( | |
| messages: list[dict[str, Any]], counters: Counter[str] | |
| ) -> list[dict[str, Any]]: | |
| normalized_messages: list[dict[str, Any]] = [] | |
| pending_tool_call_ids: list[str] = [] | |
| for message_index, message in enumerate(messages): | |
| if not isinstance(message, dict): | |
| raise ValueError(f"messages[{message_index}] is not an object") | |
| normalized = dict(message) | |
| role = normalized.get("role") | |
| if not isinstance(role, str) or not role: | |
| raise ValueError(f"messages[{message_index}] has an invalid role") | |
| if pending_tool_call_ids and role != "tool": | |
| raise ValueError( | |
| f"messages[{message_index}] starts role={role!r} before tool calls " | |
| f"{pending_tool_call_ids!r} receive results" | |
| ) | |
| content = normalized.get("content") | |
| if isinstance(content, dict): | |
| normalized["content"] = compact_json(content) | |
| counters["object_contents_serialized"] += 1 | |
| elif content is not None and not isinstance(content, (str, list)): | |
| normalized["content"] = compact_json(content) | |
| counters["other_contents_serialized"] += 1 | |
| tool_calls = normalized.get("tool_calls") | |
| if tool_calls is not None: | |
| if not isinstance(tool_calls, list): | |
| raise ValueError(f"messages[{message_index}].tool_calls is not a list") | |
| normalized_calls: list[dict[str, Any]] = [] | |
| call_ids: list[str] = [] | |
| for call_index, tool_call in enumerate(tool_calls): | |
| if not isinstance(tool_call, dict): | |
| raise ValueError( | |
| f"messages[{message_index}].tool_calls[{call_index}] " | |
| "is not an object" | |
| ) | |
| call = dict(tool_call) | |
| call_id = call.get("id") | |
| if not isinstance(call_id, str) or not call_id: | |
| raise ValueError( | |
| f"messages[{message_index}].tool_calls[{call_index}] " | |
| "has no string id" | |
| ) | |
| if call_id in call_ids: | |
| raise ValueError( | |
| f"messages[{message_index}] repeats tool call id {call_id!r}" | |
| ) | |
| call_ids.append(call_id) | |
| function = call.get("function") | |
| if not isinstance(function, dict): | |
| raise ValueError( | |
| f"messages[{message_index}].tool_calls[{call_index}].function " | |
| "is not an object" | |
| ) | |
| normalized_function = dict(function) | |
| if not isinstance(normalized_function.get("name"), str): | |
| raise ValueError( | |
| f"messages[{message_index}].tool_calls[{call_index}].function " | |
| "has no string name" | |
| ) | |
| if "arguments" not in normalized_function: | |
| raise ValueError( | |
| f"messages[{message_index}].tool_calls[{call_index}].function " | |
| "has no arguments" | |
| ) | |
| arguments = normalized_function["arguments"] | |
| if not isinstance(arguments, str): | |
| normalized_function["arguments"] = compact_json(arguments) | |
| counters["tool_arguments_serialized"] += 1 | |
| call["function"] = normalized_function | |
| call.setdefault("type", "function") | |
| normalized_calls.append(call) | |
| counters["tool_calls"] += 1 | |
| normalized["tool_calls"] = normalized_calls | |
| pending_tool_call_ids = call_ids | |
| if role == "tool": | |
| tool_call_id = normalized.get("tool_call_id") | |
| if tool_call_id is None: | |
| if not pending_tool_call_ids: | |
| raise ValueError( | |
| f"messages[{message_index}] is missing tool_call_id and " | |
| "has no pending tool call" | |
| ) | |
| normalized["tool_call_id"] = pending_tool_call_ids[0] | |
| tool_call_id = pending_tool_call_ids[0] | |
| counters["tool_call_ids_inferred"] += 1 | |
| if not isinstance(tool_call_id, str) or not tool_call_id: | |
| raise ValueError( | |
| f"messages[{message_index}].tool_call_id is not a string" | |
| ) | |
| if tool_call_id not in pending_tool_call_ids: | |
| raise ValueError( | |
| f"messages[{message_index}].tool_call_id={tool_call_id!r} " | |
| f"does not match pending calls {pending_tool_call_ids!r}" | |
| ) | |
| pending_tool_call_ids.remove(tool_call_id) | |
| counters["tool_results"] += 1 | |
| normalized_messages.append(normalized) | |
| counters["messages"] += 1 | |
| if pending_tool_call_ids: | |
| raise ValueError(f"unanswered tool calls at end of prompt: {pending_tool_call_ids}") | |
| return normalized_messages | |
| def validate_wire_messages(messages: list[dict[str, Any]]) -> None: | |
| pending: set[str] = set() | |
| for message_index, message in enumerate(messages): | |
| role = message.get("role") | |
| content = message.get("content") | |
| if isinstance(content, dict): | |
| raise ValueError(f"messages[{message_index}].content remains an object") | |
| if pending and role != "tool": | |
| raise ValueError(f"messages[{message_index}] leaves tool calls unanswered") | |
| calls = message.get("tool_calls") | |
| if calls is not None: | |
| for call in calls: | |
| call_id = call["id"] | |
| arguments = call["function"]["arguments"] | |
| if not isinstance(arguments, str): | |
| raise ValueError( | |
| f"messages[{message_index}] has non-string tool arguments" | |
| ) | |
| json.loads(arguments) | |
| pending.add(call_id) | |
| if role == "tool": | |
| call_id = message.get("tool_call_id") | |
| if call_id not in pending: | |
| raise ValueError( | |
| f"messages[{message_index}] has unmatched tool_call_id={call_id!r}" | |
| ) | |
| pending.remove(call_id) | |
| if pending: | |
| raise ValueError(f"unanswered tool calls: {sorted(pending)}") | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as file: | |
| for chunk in iter(lambda: file.read(8 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def main() -> None: | |
| args = parse_args() | |
| request_path = Path(args.requests) | |
| metadata_path = Path(args.metadata) | |
| output_path = Path(args.output) | |
| metadata_output_path = Path(args.metadata_output) | |
| stats_output_path = Path(args.stats_output) | |
| for path in (output_path, metadata_output_path, stats_output_path): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| counters: Counter[str] = Counter() | |
| trajectory_ids: set[str] = set() | |
| max_messages = 0 | |
| with request_path.open(encoding="utf-8") as requests, metadata_path.open( | |
| encoding="utf-8" | |
| ) as metadata, output_path.open("w", encoding="utf-8") as output, ( | |
| metadata_output_path.open("w", encoding="utf-8") | |
| ) as metadata_output: | |
| for line_index, pair in enumerate(zip_longest(requests, metadata)): | |
| request_line, metadata_line = pair | |
| if request_line is None or metadata_line is None: | |
| raise ValueError("request and metadata files have different line counts") | |
| request = json.loads(request_line) | |
| meta = json.loads(metadata_line) | |
| if meta.get("request_index") != line_index: | |
| raise ValueError(f"metadata request_index mismatch at line {line_index}") | |
| messages = request.get("messages") | |
| if not isinstance(messages, list) or not messages: | |
| raise ValueError(f"request {line_index} has no message list") | |
| request["messages"] = normalize_messages(messages, counters) | |
| validate_wire_messages(request["messages"]) | |
| max_messages = max(max_messages, len(request["messages"])) | |
| trajectory_ids.add(str(meta["trajectory_id"])) | |
| meta["wire_format_version"] = FORMAT_VERSION | |
| meta["prompt_tokens_basis"] = "qwen-oriented-source-conversion" | |
| output.write(compact_json(request) + "\n") | |
| metadata_output.write(compact_json(meta) + "\n") | |
| counters["requests"] += 1 | |
| stats = { | |
| "format_version": FORMAT_VERSION, | |
| "source_dataset": args.source_dataset, | |
| "source_requests_file": request_path.name, | |
| "source_metadata_file": metadata_path.name, | |
| "requests": counters["requests"], | |
| "trajectories": len(trajectory_ids), | |
| "messages": counters["messages"], | |
| "max_messages_per_request": max_messages, | |
| "normalization": { | |
| "object_contents_serialized": counters["object_contents_serialized"], | |
| "other_contents_serialized": counters["other_contents_serialized"], | |
| "tool_arguments_serialized": counters["tool_arguments_serialized"], | |
| "tool_call_ids_inferred": counters["tool_call_ids_inferred"], | |
| "tool_calls": counters["tool_calls"], | |
| "tool_results": counters["tool_results"], | |
| }, | |
| "validation": { | |
| "request_metadata_alignment": "passed", | |
| "openai_wire_types": "passed", | |
| "tool_call_id_associations": "passed", | |
| "function_arguments_parse_as_json": "passed", | |
| }, | |
| "sha256": { | |
| output_path.name: sha256(output_path), | |
| metadata_output_path.name: sha256(metadata_output_path), | |
| }, | |
| "token_metadata": { | |
| "status": "carried_from_source_qwen_oriented_conversion", | |
| "usage": "reference_and_client_fallback_only", | |
| "recommendation": "use_server_usage_for_model_specific_token_counts", | |
| }, | |
| } | |
| stats_output_path.write_text( | |
| json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" | |
| ) | |
| print(json.dumps(stats, indent=2, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |