Datasets:
Download scripts/generate_swival_dataset.py from jedisct1/tool-calling: direct link, hf CLI and curl.
- Browser
- Download file 31.7 kB
-
https://huggingface.co/datasets/jedisct1/tool-calling/resolve/main/scripts/generate_swival_dataset.py
- Command line
-
hf download hf://datasets/jedisct1/tool-calling/scripts/generate_swival_dataset.py
-
curl -L -o generate_swival_dataset.py https://huggingface.co/datasets/jedisct1/tool-calling/resolve/main/scripts/generate_swival_dataset.py
31.7 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import ast | |
| import json | |
| import random | |
| import shutil | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA_DIR = ROOT / "data" | |
| TMP_DIR = ROOT / "tmp" | |
| SWIVAL_ROOT = Path("/Users/j/src/swival") | |
| SWIVAL_TOOLS = SWIVAL_ROOT / "swival" / "tools.py" | |
| PYTEST_SHIM = """import importlib.util | |
| import pathlib | |
| import sys | |
| failed = 0 | |
| for raw in sys.argv[1:]: | |
| path = pathlib.Path(raw) | |
| spec = importlib.util.spec_from_file_location(path.stem, path) | |
| mod = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(mod) | |
| for name in dir(mod): | |
| if name.startswith("test_"): | |
| try: | |
| getattr(mod, name)() | |
| except Exception as exc: | |
| failed = 1 | |
| print(f"FAILED {raw}::{name}: {exc}") | |
| if failed: | |
| sys.exit(1) | |
| print("passed") | |
| """ | |
| TOOL_EXEMPLARS: dict[str, list[dict[str, Any]]] = { | |
| "read_file": [ | |
| {"file_path": "src/app.py"}, | |
| {"file_path": "logs/server.log", "tail_lines": 80}, | |
| {"file_path": "src/app.py", "offset": 201, "limit": 80}, | |
| {"file_path": "."}, | |
| ], | |
| "read_multiple_files": [ | |
| {"files": [{"file_path": "pyproject.toml"}, {"file_path": "src/app.py", "offset": 40, "limit": 80}]}, | |
| {"files": [{"file_path": "README.md"}, {"file_path": "tests/test_app.py", "tail_lines": 120}]}, | |
| ], | |
| "write_file": [ | |
| {"file_path": "notes/summary.md", "content": "# Summary\n\nDone.\n"}, | |
| {"file_path": "src/config.py", "move_from": "tmp/generated_config.py"}, | |
| ], | |
| "edit_file": [ | |
| {"file_path": "src/app.py", "old_string": "return False\n", "new_string": "return True\n", "line_number": 42}, | |
| {"file_path": "README.md", "old_string": "teh", "new_string": "the", "replace_all": True}, | |
| {"file_path": "src/app.py", "old_string": "timeout = 5\n", "new_string": "timeout = 10\n", "checksum": "1a2b3c4d"}, | |
| ], | |
| "list_files": [ | |
| {"pattern": "**/*.py"}, | |
| {"pattern": "*.md", "path": "docs"}, | |
| ], | |
| "grep": [ | |
| {"pattern": "TODO|FIXME", "path": ".", "include": "**/*.py"}, | |
| {"pattern": "authorization", "path": "src", "include": "**/*.py", "case_insensitive": True, "context_lines": 2}, | |
| ], | |
| "think": [ | |
| {"thought": "The failure is probably in the parsing layer, so inspect callers before editing.", "thought_number": 1, "total_thoughts": 3}, | |
| {"thought": "The first plan missed the generated file path; revise the target to src/generated.py.", "mode": "revision", "revises_thought": 1}, | |
| {"thought": "Try a narrower edit that keeps the public API unchanged.", "mode": "branch", "branch_from_thought": 2, "branch_id": "minimal-fix"}, | |
| ], | |
| "todo": [ | |
| {"action": "add", "tasks": ["inspect parser", "patch failing case", "run focused tests"]}, | |
| {"action": "done", "tasks": "inspect parser"}, | |
| {"action": "list"}, | |
| {"action": "clear"}, | |
| ], | |
| "view_image": [ | |
| {"image_path": "screenshots/failure.png", "question": "Which UI element overlaps the submit button?"}, | |
| {"image_path": "assets/logo.webp"}, | |
| ], | |
| "delete_file": [ | |
| {"file_path": "src/old_module.py"}, | |
| ], | |
| "fetch_url": [ | |
| {"url": "https://example.com/api-reference", "format": "markdown", "timeout": 20}, | |
| {"url": "https://example.com/status.txt", "format": "text"}, | |
| ], | |
| "snapshot": [ | |
| {"action": "save", "label": "parser investigation"}, | |
| {"action": "status"}, | |
| {"action": "restore", "summary": "Parser bug is in src/parser.py:88. The tokenizer accepts empty identifiers; fix by rejecting zero-length names and run tests/test_parser.py.", "force": True}, | |
| {"action": "cancel"}, | |
| ], | |
| "outline": [ | |
| {"file_path": "src/app.py", "depth": 2}, | |
| {"file_path": "src", "depth": 1}, | |
| {"files": [{"file_path": "src/app.py", "depth": 2}, {"file_path": "src/parser.py", "depth": 3}]}, | |
| ], | |
| "use_skill": [ | |
| {"name": "frontend-design"}, | |
| {"name": "github:gh-fix-ci"}, | |
| ], | |
| "run_metaskill": [ | |
| {"name": "repo_survey", "input": {"task": "find the CLI entrypoint"}, "max_ask_calls": 3}, | |
| {"name": "focused_review", "input": {"path": "src/auth.py", "question": "look for token validation bugs"}, "max_command_calls": 0}, | |
| ], | |
| "run_command": [ | |
| {"command": ["uv", "run", "pytest", "tests/test_parser.py"], "timeout": 120}, | |
| {"command": ["rg", "-n", "SessionUsage", "swival"], "timeout": 30}, | |
| {"command": ["npm", "run", "dev"], "background": True, "timeout": 5}, | |
| ], | |
| "run_shell_command": [ | |
| {"command": "rg -n 'TODO|FIXME' src | head -20", "timeout": 30}, | |
| {"command": "python3 -m http.server 8000 > server.log 2>&1", "background": True, "timeout": 5}, | |
| ], | |
| "complete_goal": [ | |
| {}, | |
| ], | |
| "spawn_subagent": [ | |
| {"task": "Inspect src/parser.py and tests/test_parser.py. Report the smallest change that would fix empty identifiers. Do not edit files."}, | |
| {"task": "Patch the README examples only. Do not touch source files.", "max_turns": 6}, | |
| {"task": "Review docs/usage.md for stale commands.", "system_hint": "Return file paths and suggested replacements only."}, | |
| ], | |
| "check_subagents": [ | |
| {"action": "poll"}, | |
| {"action": "collect", "subagent_id": "subagent-1", "timeout": 300}, | |
| {"action": "cancel", "subagent_id": "subagent-2"}, | |
| ], | |
| "mcp__docs__search": [ | |
| {"query": "parser API reject empty identifiers", "limit": 3}, | |
| {"query": "command provider argv tool calling"}, | |
| ], | |
| "a2a__reviewer": [ | |
| {"message": "Review the proposed auth change in src/auth.py: reject blank bearer tokens before lookup."}, | |
| {"message": "Continue reviewing the same task and focus on missing tests.", "context_id": "ctx-123", "task_id": "task-456"}, | |
| ], | |
| } | |
| class Example: | |
| id: str | |
| split: str | |
| tags: list[str] | |
| messages: list[dict[str, Any]] | |
| def _literal(node: ast.AST) -> Any: | |
| try: | |
| return ast.literal_eval(node) | |
| except Exception: | |
| return None | |
| def extract_tool_inventory(path: Path = SWIVAL_TOOLS) -> list[dict[str, Any]]: | |
| source = path.read_text() | |
| tree = ast.parse(source, filename=str(path)) | |
| values: dict[str, Any] = {} | |
| tools: list[dict[str, Any]] = [] | |
| for node in tree.body: | |
| if isinstance(node, ast.Assign): | |
| val = _literal(node.value) | |
| for target in node.targets: | |
| if isinstance(target, ast.Name) and val is not None: | |
| values[target.id] = val | |
| if target.id == "TOOLS": | |
| tools = list(val) | |
| elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call): | |
| call = node.value | |
| if isinstance(call.func, ast.Attribute) and call.func.attr == "append": | |
| if isinstance(call.func.value, ast.Name) and call.func.value.id == "TOOLS": | |
| arg = call.args[0] if call.args else None | |
| if isinstance(arg, ast.Name) and arg.id in values: | |
| tools.append(values[arg.id]) | |
| for name in [ | |
| "USE_SKILL_TOOL", | |
| "RUN_METASKILL_TOOL", | |
| "RUN_COMMAND_TOOL", | |
| "RUN_SHELL_COMMAND_TOOL", | |
| "COMPLETE_GOAL_TOOL", | |
| ]: | |
| if name in values: | |
| tools.append(values[name]) | |
| seen: set[str] = set() | |
| out: list[dict[str, Any]] = [] | |
| for tool in tools: | |
| fn = tool.get("function", {}) | |
| name = fn.get("name") | |
| if not name or name in seen: | |
| continue | |
| seen.add(name) | |
| params = fn.get("parameters", {}) | |
| out.append( | |
| { | |
| "name": name, | |
| "description": fn.get("description", ""), | |
| "required": params.get("required", []), | |
| "properties": sorted((params.get("properties") or {}).keys()), | |
| } | |
| ) | |
| for dynamic in ["spawn_subagent", "check_subagents"]: | |
| if dynamic not in seen: | |
| out.append( | |
| { | |
| "name": dynamic, | |
| "description": "Runtime conditional Swival subagent tool.", | |
| "required": ["task"] if dynamic == "spawn_subagent" else ["action"], | |
| "properties": ["task", "max_turns", "system_hint"] if dynamic == "spawn_subagent" else ["action", "subagent_id", "timeout"], | |
| } | |
| ) | |
| for dynamic in ["mcp__docs__search", "a2a__reviewer"]: | |
| if dynamic not in seen: | |
| out.append( | |
| { | |
| "name": dynamic, | |
| "description": "Representative dynamic Swival integration tool.", | |
| "required": ["query"] if dynamic.startswith("mcp__") else ["message"], | |
| "properties": ["query", "limit"] if dynamic.startswith("mcp__") else ["message", "context_id", "task_id"], | |
| } | |
| ) | |
| return sorted(out, key=lambda item: item["name"]) | |
| def tool_call(name: str, args: dict[str, Any], call_id: str = "call_1") -> dict[str, Any]: | |
| return { | |
| "id": call_id, | |
| "type": "function", | |
| "function": {"name": name, "arguments": json.dumps(args, separators=(",", ":"))}, | |
| } | |
| def user(text: str) -> dict[str, Any]: | |
| return {"role": "user", "content": text} | |
| def assistant_tool(name: str, args: dict[str, Any], call_id: str = "call_1") -> dict[str, Any]: | |
| return {"role": "assistant", "content": "", "tool_calls": [tool_call(name, args, call_id)]} | |
| def tool(name: str, content: str, call_id: str = "call_1") -> dict[str, Any]: | |
| return {"role": "tool", "tool_call_id": call_id, "name": name, "content": content} | |
| def assistant(text: str) -> dict[str, Any]: | |
| return {"role": "assistant", "content": text} | |
| def one_shot_examples(inventory: list[dict[str, Any]], per_tool: int) -> list[Example]: | |
| examples: list[Example] = [] | |
| for item in inventory: | |
| name = item["name"] | |
| variants = TOOL_EXEMPLARS.get(name, [{}]) | |
| for idx in range(per_tool): | |
| args = variants[idx % len(variants)] | |
| task = prompt_for_tool(name, args, idx) | |
| result = result_for_tool(name, args) | |
| examples.append( | |
| Example( | |
| id=f"single-{name}-{idx:03d}", | |
| split="train", | |
| tags=["single_tool", name], | |
| messages=[user(task), assistant_tool(name, args), tool(name, result), assistant(final_for_tool(name))], | |
| ) | |
| ) | |
| return examples | |
| def prompt_for_tool(name: str, args: dict[str, Any], idx: int) -> str: | |
| prompts = { | |
| "read_file": f"Open {args.get('file_path', 'the file')} and show the relevant part before making changes.", | |
| "read_multiple_files": "Read the project config and the implementation together so you can compare them.", | |
| "write_file": f"Create or move the requested file at {args.get('file_path', 'the destination')}.", | |
| "edit_file": f"Apply the smallest edit to {args.get('file_path', 'the file')} using the text I already identified.", | |
| "list_files": f"Find files matching {args.get('pattern', '**/*')} for the next pass.", | |
| "grep": f"Search the workspace for {args.get('pattern', 'the pattern')}.", | |
| "think": "Think through the next move before touching files.", | |
| "todo": "Track this work with a checklist.", | |
| "view_image": f"Inspect {args.get('image_path', 'the image')} before deciding what changed.", | |
| "delete_file": f"Remove {args.get('file_path', 'the obsolete file')} safely.", | |
| "fetch_url": f"Look up the external reference at {args.get('url', 'the URL')}.", | |
| "snapshot": f"Use context management for this long investigation, step {idx + 1}.", | |
| "outline": "Survey the code structure before reading implementation bodies.", | |
| "use_skill": f"Load the {args.get('name', 'relevant')} skill before proceeding.", | |
| "run_metaskill": f"Run the {args.get('name', 'metaskill')} workflow for this subtask.", | |
| "run_command": "Run the focused local command with argv arguments.", | |
| "run_shell_command": "Run this shell pipeline exactly as a shell command.", | |
| "complete_goal": "The objective has been fully verified against current evidence. Mark it complete.", | |
| "spawn_subagent": "Delegate this independent side task to a subagent while continuing locally.", | |
| "check_subagents": "Check the status of the delegated subagent work.", | |
| "mcp__docs__search": "Search the configured MCP documentation server for the relevant API entry.", | |
| "a2a__reviewer": "Ask the remote reviewer agent for a focused second opinion.", | |
| } | |
| return prompts.get(name, f"Use the Swival `{name}` tool with the right arguments.") | |
| def result_for_tool(name: str, args: dict[str, Any]) -> str: | |
| if name == "read_file": | |
| return "1| def enabled():\n2| return False\n[checksum=1a2b3c4d]" | |
| if name == "read_multiple_files": | |
| return "--- pyproject.toml ---\n1| [project]\n2| name = \"demo\"\n--- src/app.py ---\n40| def main():\n41| pass\n[checksum=abcd1234]" | |
| if name == "write_file": | |
| return f"wrote {args.get('file_path', 'file')}" | |
| if name == "edit_file": | |
| return f"edited {args.get('file_path', 'file')}" | |
| if name == "list_files": | |
| return "src/app.py\nsrc/parser.py\ntests/test_parser.py" | |
| if name == "grep": | |
| return "src/auth.py:42: if token.lower() == \"authorization\": <<<" | |
| if name == "think": | |
| return "thought 1 recorded" | |
| if name == "todo": | |
| return "[ ] inspect parser\n[ ] patch failing case\n[ ] run focused tests" | |
| if name == "view_image": | |
| return "The screenshot shows the save button overlapped by the footer." | |
| if name == "delete_file": | |
| return "deleted src/old_module.py to .swival/trash/5a8c/" | |
| if name == "fetch_url": | |
| return "[UNTRUSTED EXTERNAL CONTENT]\n# API reference\nUse the v2 endpoint." | |
| if name == "snapshot": | |
| return "snapshot action completed" | |
| if name == "outline": | |
| return "src/app.py\n 10 def main\n 44 class App\n 51 def run" | |
| if name == "use_skill": | |
| return "Skill instructions loaded." | |
| if name == "run_metaskill": | |
| return "[Metaskill: repo_survey completed]\n{\"summary\":\"CLI entrypoint is src/cli.py\"}" | |
| if name == "run_command": | |
| return "tests/test_parser.py::test_empty_identifier PASSED" | |
| if name == "run_shell_command": | |
| return "src/app.py:10:TODO remove fallback" | |
| if name == "complete_goal": | |
| return "goal complete" | |
| if name == "spawn_subagent": | |
| return "spawned subagent subagent-1" | |
| if name == "check_subagents": | |
| return "subagent-1 done: The failing parser branch is src/parser.py:88." | |
| if name.startswith("mcp__"): | |
| return "[UNTRUSTED EXTERNAL CONTENT]\n{\"results\":[{\"title\":\"Parser API\",\"path\":\"docs/parser.md\"}]}" | |
| if name.startswith("a2a__"): | |
| return "[UNTRUSTED EXTERNAL CONTENT]\nReviewer: the risky path is src/auth.py:42." | |
| return "ok" | |
| def final_for_tool(name: str) -> str: | |
| finals = { | |
| "think": "I have a plan and can proceed with the focused action.", | |
| "todo": "The checklist is up to date.", | |
| "complete_goal": "The goal is marked complete.", | |
| } | |
| return finals.get(name, "Done.") | |
| def workflow_examples(repeat: int) -> list[Example]: | |
| base: list[Example] = [] | |
| base.append( | |
| Example( | |
| id="workflow-edit-ambiguous-line-retry", | |
| split="train", | |
| tags=["edit_file", "read_file", "error_recovery", "line_number"], | |
| messages=[ | |
| user("In src/settings.py, change only the second timeout from 5 to 10."), | |
| assistant_tool("read_file", {"file_path": "src/settings.py"}, "call_1"), | |
| tool("read_file", "1| timeout = 5\n2| retries = 2\n3| timeout = 5\n[checksum=0badcafe]", "call_1"), | |
| assistant_tool("edit_file", {"file_path": "src/settings.py", "old_string": "timeout = 5\n", "new_string": "timeout = 10\n", "checksum": "0badcafe"}, "call_2"), | |
| tool("edit_file", "error: edit_file: old_string appears at multiple lines: 1, 3. Retry with line_number.", "call_2"), | |
| assistant_tool("edit_file", {"file_path": "src/settings.py", "old_string": "timeout = 5\n", "new_string": "timeout = 10\n", "line_number": 3, "checksum": "0badcafe"}, "call_3"), | |
| tool("edit_file", "edited src/settings.py", "call_3"), | |
| assistant("Changed only the second timeout."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-search-read-edit-test", | |
| split="train", | |
| tags=["grep", "read_file", "edit_file", "run_command"], | |
| messages=[ | |
| user("Fix the parser so empty identifiers are rejected, then run the focused parser tests."), | |
| assistant_tool("grep", {"pattern": "identifier", "path": "src", "include": "**/*.py", "context_lines": 2}, "call_1"), | |
| tool("grep", "src/parser.py:86: def parse_identifier(tok): <<<\nsrc/parser.py:88: return tok.value", "call_1"), | |
| assistant_tool("read_file", {"file_path": "src/parser.py", "offset": 80, "limit": 30}, "call_2"), | |
| tool("read_file", "80| class Parser:\n86| def parse_identifier(tok):\n87| if tok.value is None:\n88| return tok.value\n[checksum=feedbeef]", "call_2"), | |
| assistant_tool("edit_file", {"file_path": "src/parser.py", "old_string": " if tok.value is None:\n return tok.value\n", "new_string": " if not tok.value:\n raise ParseError(\"empty identifier\")\n return tok.value\n", "line_number": 87, "checksum": "feedbeef"}, "call_3"), | |
| tool("edit_file", "edited src/parser.py", "call_3"), | |
| assistant_tool("run_command", {"command": ["uv", "run", "pytest", "tests/test_parser.py"], "timeout": 120}, "call_4"), | |
| tool("run_command", "5 passed", "call_4"), | |
| assistant("The parser now rejects empty identifiers and the focused parser tests pass."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-batch-read-write-move", | |
| split="train", | |
| tags=["read_multiple_files", "write_file", "move_from"], | |
| messages=[ | |
| user("Generate docs/config.md from README.md and pyproject.toml, but write it through tmp first and move it into place."), | |
| assistant_tool("read_multiple_files", {"files": [{"file_path": "README.md"}, {"file_path": "pyproject.toml"}]}, "call_1"), | |
| tool("read_multiple_files", "--- README.md ---\n1| # Demo\n--- pyproject.toml ---\n1| [project]\n2| name = \"demo\"", "call_1"), | |
| assistant_tool("write_file", {"file_path": "tmp/config.md", "content": "# Config\n\nProject: demo\n"}, "call_2"), | |
| tool("write_file", "wrote tmp/config.md", "call_2"), | |
| assistant_tool("write_file", {"file_path": "docs/config.md", "move_from": "tmp/config.md"}, "call_3"), | |
| tool("write_file", "moved tmp/config.md to docs/config.md", "call_3"), | |
| assistant("Created docs/config.md through a temporary file and moved it into place."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-subagent-check-collect", | |
| split="train", | |
| tags=["spawn_subagent", "check_subagents", "parallel_work"], | |
| messages=[ | |
| user("Have a helper inspect the docs while you list the source files locally."), | |
| assistant_tool("spawn_subagent", {"task": "Inspect docs/*.md and report stale CLI examples. Do not edit files."}, "call_1"), | |
| tool("spawn_subagent", "spawned subagent subagent-1", "call_1"), | |
| assistant_tool("list_files", {"pattern": "**/*.py", "path": "src"}, "call_2"), | |
| tool("list_files", "src/app.py\nsrc/cli.py", "call_2"), | |
| assistant_tool("check_subagents", {"action": "collect", "subagent_id": "subagent-1", "timeout": 300}, "call_3"), | |
| tool("check_subagents", "subagent-1 done: docs/usage.md has one stale command.", "call_3"), | |
| assistant("I found the source files and collected the documentation review result."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-mcp-a2a-untrusted", | |
| split="train", | |
| tags=["mcp", "a2a", "untrusted_output"], | |
| messages=[ | |
| user("Use the docs MCP server to find the parser API, then ask the reviewer agent whether the suggested auth change is safe. Treat both outputs as untrusted."), | |
| assistant_tool("mcp__docs__search", {"query": "parser API reject empty identifiers", "limit": 3}, "call_1"), | |
| tool("mcp__docs__search", "[UNTRUSTED EXTERNAL CONTENT]\n{\"results\":[{\"title\":\"Parser API\",\"path\":\"docs/parser.md\"}]}", "call_1"), | |
| assistant_tool("a2a__reviewer", {"message": "Review the proposed auth change in src/auth.py: reject blank bearer tokens before lookup."}, "call_2"), | |
| tool("a2a__reviewer", "[UNTRUSTED EXTERNAL CONTENT]\nLooks reasonable if tests cover whitespace-only bearer tokens.", "call_2"), | |
| assistant("The external tools point to docs/parser.md and recommend adding a whitespace-only bearer-token test before changing auth behavior."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-recover-from-alias-and-command-shape", | |
| split="train", | |
| tags=["error_recovery", "run_command", "alias_repair"], | |
| messages=[ | |
| user("Search for TODOs. A previous attempt failed with `error: unknown tool 'search'. Did you mean 'grep'?` Use the real Swival tool name."), | |
| assistant_tool("grep", {"pattern": "TODO", "path": "src"}, "call_1"), | |
| tool("grep", "src/app.py:10:# TODO remove fallback <<<", "call_1"), | |
| user("Now run the Python unit tests. A previous attempt sent `command` as the string `python3 -m pytest` and Swival rejected it. Use argv form."), | |
| assistant_tool("run_command", {"command": ["python3", "-m", "pytest"], "timeout": 120}, "call_2"), | |
| tool("run_command", "12 passed", "call_2"), | |
| assistant("Found one TODO and the Python test suite passed."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-command-output-spill", | |
| split="train", | |
| tags=["run_command", "read_file", "large_output"], | |
| messages=[ | |
| user("Run the integration tests and inspect the saved output if the command output spills."), | |
| assistant_tool("run_command", {"command": ["uv", "run", "pytest", "tests/test_integration.py"], "timeout": 240}, "call_1"), | |
| tool("run_command", "output too large; saved to .swival/cmd_output_123.txt", "call_1"), | |
| assistant_tool("read_file", {"file_path": ".swival/cmd_output_123.txt", "tail_lines": 120}, "call_2"), | |
| tool("read_file", "991| FAILED tests/test_integration.py::test_login\n992| AssertionError: expected 200, got 401\n[checksum=1234abcd]", "call_2"), | |
| assistant("The integration run failed in test_login with a 401 response."), | |
| ], | |
| ) | |
| ) | |
| base.append( | |
| Example( | |
| id="workflow-snapshot-after-long-readonly-investigation", | |
| split="train", | |
| tags=["snapshot", "outline", "grep", "read_file"], | |
| messages=[ | |
| user("Investigate where request IDs are assigned. Summarize the context before editing."), | |
| assistant_tool("snapshot", {"action": "save", "label": "request id investigation"}, "call_1"), | |
| tool("snapshot", "checkpoint saved", "call_1"), | |
| assistant_tool("outline", {"file_path": "src", "depth": 1}, "call_2"), | |
| tool("outline", "src/server.py\n 10 def handle\nsrc/middleware.py\n 8 def attach_request_id", "call_2"), | |
| assistant_tool("grep", {"pattern": "request_id", "path": "src", "include": "**/*.py"}, "call_3"), | |
| tool("grep", "src/middleware.py:8:def attach_request_id(req): <<<", "call_3"), | |
| assistant_tool("read_file", {"file_path": "src/middleware.py", "offset": 1, "limit": 80}, "call_4"), | |
| tool("read_file", "8| def attach_request_id(req):\n9| req.id = uuid4().hex\n[checksum=5678abcd]", "call_4"), | |
| assistant_tool("snapshot", {"action": "restore", "summary": "Request IDs are assigned in src/middleware.py:8 by attach_request_id, which sets req.id to uuid4().hex. The server handler calls it before routing."}, "call_5"), | |
| tool("snapshot", "restored context from request id investigation", "call_5"), | |
| assistant("I summarized the read-only investigation and can now make a focused edit."), | |
| ], | |
| ) | |
| ) | |
| out: list[Example] = [] | |
| for i in range(repeat): | |
| for ex in base: | |
| out.append(Example(id=f"{ex.id}-{i:03d}", split=ex.split, tags=ex.tags, messages=ex.messages)) | |
| return out | |
| def synthesize_examples(inventory: list[dict[str, Any]], count: int, seed: int) -> list[Example]: | |
| rng = random.Random(seed) | |
| names = [item["name"] for item in inventory] | |
| examples: list[Example] = [] | |
| intents = [ | |
| "Inspect the relevant files before editing.", | |
| "Make the smallest safe change and verify it.", | |
| "Find where this behavior is implemented.", | |
| "Run the focused command and summarize the result.", | |
| "Recover from the tool error by sending a corrected call.", | |
| ] | |
| for i in range(count): | |
| name = rng.choice(names) | |
| exemplar = rng.choice(TOOL_EXEMPLARS.get(name, [{}])) | |
| args = json.loads(json.dumps(exemplar)) | |
| prompt = f"{rng.choice(intents)} Use the appropriate Swival tool for step {i + 1}." | |
| examples.append( | |
| Example( | |
| id=f"synthetic-{i:05d}-{name}", | |
| split="train", | |
| tags=["synthetic", name], | |
| messages=[user(prompt), assistant_tool(name, args), tool(name, result_for_tool(name, args)), assistant(final_for_tool(name))], | |
| ) | |
| ) | |
| return examples | |
| def eval_examples() -> list[dict[str, Any]]: | |
| return [ | |
| { | |
| "id": "eval-edit-line-number", | |
| "prompt": "In settings.py, change only the second timeout value from 5 to 10. Do not change the first timeout.", | |
| "files": {"settings.py": "timeout = 5\nretries = 2\ntimeout = 5\n"}, | |
| "verify": {"settings.py": "timeout = 5\nretries = 2\ntimeout = 10\n"}, | |
| "expected_tools": ["read_file", "edit_file"], | |
| }, | |
| { | |
| "id": "eval-grep-edit-test", | |
| "prompt": "Find the Python function that accepts empty names, make it reject empty strings, and run `python3 -m pytest tests/test_names.py`.", | |
| "files": { | |
| "src/names.py": "class NameError(Exception):\n pass\n\n\ndef normalize_name(name):\n if name is None:\n raise NameError('missing')\n return name.strip()\n", | |
| "tests/test_names.py": "from src.names import NameError, normalize_name\n\n\ndef test_empty_name_rejected():\n try:\n normalize_name(' ')\n except NameError:\n return\n raise AssertionError('empty name accepted')\n", | |
| "pytest.py": PYTEST_SHIM, | |
| "pyproject.toml": "[tool.pytest.ini_options]\npythonpath = ['.']\n", | |
| }, | |
| "verify": { | |
| "src/names.py": "class NameError(Exception):\n pass\n\n\ndef normalize_name(name):\n if name is None:\n raise NameError('missing')\n normalized = name.strip()\n if not normalized:\n raise NameError('missing')\n return normalized\n" | |
| }, | |
| "expected_tools": ["grep", "read_file", "edit_file", "run_command"], | |
| }, | |
| { | |
| "id": "eval-batch-read-write", | |
| "prompt": "Read README.md and pyproject.toml, then create docs/summary.md with the project name and one-sentence description.", | |
| "files": { | |
| "README.md": "# Widget\n\nA tiny request router.\n", | |
| "pyproject.toml": "[project]\nname = 'widget'\n", | |
| }, | |
| "verify_contains": {"docs/summary.md": ["widget", "tiny request router"]}, | |
| "expected_tools": ["read_multiple_files", "write_file"], | |
| }, | |
| { | |
| "id": "eval-delete-obsolete", | |
| "prompt": "Delete obsolete.py and leave keep.py alone.", | |
| "files": {"obsolete.py": "print('old')\n", "keep.py": "print('keep')\n"}, | |
| "verify_missing": ["obsolete.py"], | |
| "verify": {"keep.py": "print('keep')\n"}, | |
| "expected_tools": ["delete_file"], | |
| }, | |
| { | |
| "id": "eval-command-argv", | |
| "prompt": "Run the test command `python3 -m pytest tests/test_math.py` and report whether it passed. Use argv form, not a shell string.", | |
| "files": { | |
| "mathlib.py": "def add(a, b):\n return a + b\n", | |
| "tests/test_math.py": "from mathlib import add\n\n\ndef test_add():\n assert add(2, 3) == 5\n", | |
| "pytest.py": PYTEST_SHIM, | |
| }, | |
| "verify_command": ["python3", "-m", "pytest", "tests/test_math.py"], | |
| "expected_tools": ["run_command"], | |
| }, | |
| ] | |
| def write_jsonl(path: Path, examples: list[Example]) -> None: | |
| with path.open("w") as f: | |
| for ex in examples: | |
| f.write(json.dumps({"id": ex.id, "split": ex.split, "tags": ex.tags, "messages": ex.messages}, separators=(",", ":")) + "\n") | |
| def main() -> int: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--per-tool", type=int, default=12) | |
| parser.add_argument("--synthetic-count", type=int, default=5000) | |
| parser.add_argument("--workflow-repeat", type=int, default=100) | |
| parser.add_argument("--seed", type=int, default=20260607) | |
| parser.add_argument("--clean", action="store_true") | |
| args = parser.parse_args() | |
| DATA_DIR.mkdir(exist_ok=True) | |
| TMP_DIR.mkdir(exist_ok=True) | |
| if args.clean and DATA_DIR.exists(): | |
| shutil.rmtree(DATA_DIR) | |
| DATA_DIR.mkdir() | |
| inventory = extract_tool_inventory() | |
| examples = [] | |
| examples.extend(one_shot_examples(inventory, args.per_tool)) | |
| examples.extend(workflow_examples(args.workflow_repeat)) | |
| examples.extend(synthesize_examples(inventory, args.synthetic_count, args.seed)) | |
| write_jsonl(DATA_DIR / "swival_tool_calling_train.jsonl", examples) | |
| with (DATA_DIR / "swival_tool_inventory.json").open("w") as f: | |
| json.dump({"source": str(SWIVAL_TOOLS), "tools": inventory}, f, indent=2) | |
| f.write("\n") | |
| with (DATA_DIR / "swival_tool_calling_eval.jsonl").open("w") as f: | |
| for row in eval_examples(): | |
| f.write(json.dumps(row, separators=(",", ":")) + "\n") | |
| print(f"wrote {len(examples)} training examples") | |
| print(f"wrote {len(eval_examples())} eval tasks") | |
| print(f"covered {len(inventory)} tools") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |