tool-calling / scripts /generate_opencode_dataset.py
jedisct1's picture
Add tool-calling harness dataset
bd43184 verified
Raw
History Blame Contribute Delete
22.1 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse
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"
CONFIG_PATH = ROOT / "configs" / "opencode-qwen35.json"
OPENCODE_TOOLS: list[dict[str, Any]] = [
{
"name": "bash",
"description": "Execute shell commands in the project environment.",
"required": ["command"],
"properties": ["command", "description", "timeout"],
},
{
"name": "read",
"description": "Read file contents, optionally with a line range.",
"required": ["filePath"],
"properties": ["filePath", "offset", "limit"],
},
{
"name": "edit",
"description": "Modify an existing file using exact string replacement.",
"required": ["filePath", "oldString", "newString"],
"properties": ["filePath", "oldString", "newString", "replaceAll"],
},
{
"name": "write",
"description": "Create a new file or overwrite an existing one.",
"required": ["filePath", "content"],
"properties": ["filePath", "content"],
},
{
"name": "grep",
"description": "Search file contents with a regular expression.",
"required": ["pattern"],
"properties": ["pattern", "path", "include"],
},
{
"name": "glob",
"description": "Find files by glob pattern.",
"required": ["pattern"],
"properties": ["pattern", "path"],
},
{
"name": "lsp",
"description": "Use language-server code intelligence.",
"required": ["operation"],
"properties": ["operation", "filePath", "line", "character", "symbol"],
},
{
"name": "apply_patch",
"description": "Apply a patch with paths embedded in patch marker lines.",
"required": ["patchText"],
"properties": ["patchText"],
},
{
"name": "skill",
"description": "Load a SKILL.md instruction file.",
"required": ["name"],
"properties": ["name"],
},
{
"name": "todowrite",
"description": "Create or update the coding-session todo list.",
"required": ["todos"],
"properties": ["todos"],
},
{
"name": "webfetch",
"description": "Fetch and read a web page.",
"required": ["url"],
"properties": ["url", "prompt"],
},
{
"name": "websearch",
"description": "Search the web when enabled by provider or EXA config.",
"required": ["query"],
"properties": ["query"],
},
{
"name": "task",
"description": "Run a subtask with another agent.",
"required": ["description", "prompt"],
"properties": ["description", "prompt", "subagent_type"],
},
]
EXEMPLARS: dict[str, list[dict[str, Any]]] = {
"bash": [
{"command": "python3 -m pytest tests/test_parser.py", "description": "Run parser tests", "timeout": 120},
{"command": "rg -n 'TODO|FIXME' src", "description": "Find TODO markers"},
{"command": "npm run dev", "description": "Start the dev server", "timeout": 5},
],
"read": [
{"filePath": "src/app.py"},
{"filePath": "src/app.py", "offset": 80, "limit": 60},
{"filePath": "README.md", "limit": 120},
],
"edit": [
{"filePath": "src/app.py", "oldString": "return False\n", "newString": "return True\n"},
{"filePath": "README.md", "oldString": "teh", "newString": "the", "replaceAll": True},
],
"write": [
{"filePath": "docs/summary.md", "content": "# Summary\n\nProject: demo\n"},
{"filePath": "tmp/generated.txt", "content": "generated\n"},
],
"grep": [
{"pattern": "TODO|FIXME", "path": "src"},
{"pattern": "authorization", "path": "src", "include": "**/*.py"},
],
"glob": [
{"pattern": "**/*.py"},
{"pattern": "docs/**/*.md", "path": "."},
],
"lsp": [
{"operation": "documentSymbol", "filePath": "src/app.py"},
{"operation": "findReferences", "filePath": "src/app.py", "line": 42, "character": 12},
{"operation": "workspaceSymbol", "symbol": "Session"},
],
"apply_patch": [
{"patchText": "*** Begin Patch\n*** Update File: src/app.py\n@@\n-return False\n+return True\n*** End Patch\n"},
{"patchText": "*** Begin Patch\n*** Add File: docs/notes.md\n+# Notes\n+\n+Done.\n*** End Patch\n"},
],
"skill": [
{"name": "frontend-design"},
{"name": "github:gh-fix-ci"},
],
"todowrite": [
{"todos": [{"content": "inspect parser", "status": "pending"}, {"content": "patch failing case", "status": "pending"}, {"content": "run focused tests", "status": "pending"}]},
{"todos": [{"content": "inspect parser", "status": "completed"}, {"content": "patch failing case", "status": "in_progress"}]},
],
"webfetch": [
{"url": "https://example.com/api-reference", "prompt": "Summarize the endpoint shape relevant to parser errors."},
{"url": "https://example.com/status.txt"},
],
"websearch": [
{"query": "opencode OpenAI compatible provider baseURL config"},
{"query": "Python argparse subcommands examples"},
],
"task": [
{"description": "Inspect tests", "prompt": "Inspect tests/test_parser.py and report the expected empty-name behavior. Do not edit files.", "subagent_type": "general"},
{"description": "Review docs", "prompt": "Review docs/usage.md for stale opencode command examples. Return paths and replacements only."},
],
}
@dataclass(frozen=True)
class Example:
id: str
split: str
tags: list[str]
messages: list[dict[str, Any]]
def user(text: str) -> dict[str, Any]:
return {"role": "user", "content": text}
def assistant(text: str) -> dict[str, Any]:
return {"role": "assistant", "content": text}
def tool_call(name: str, args: dict[str, Any], call_id: str) -> dict[str, Any]:
return {
"id": call_id,
"type": "function",
"function": {"name": name, "arguments": json.dumps(args, separators=(",", ":"))},
}
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 prompt_for_tool(name: str, args: dict[str, Any]) -> str:
prompts = {
"bash": "Run the requested shell command in the project and report the important result.",
"read": f"Read {args.get('filePath', 'the file')} before deciding how to edit.",
"edit": f"Apply the exact replacement in {args.get('filePath', 'the file')}.",
"write": f"Create {args.get('filePath', 'the target file')} with the requested content.",
"grep": "Search the codebase for the requested pattern.",
"glob": "Find the matching files before opening any of them.",
"lsp": "Use language-server navigation instead of guessing where the symbol lives.",
"apply_patch": "Apply this patch as a patch, not by rewriting the whole file.",
"skill": f"Load the {args.get('name', 'relevant')} skill before continuing.",
"todowrite": "Update the todo list for this multi-step task.",
"webfetch": "Fetch the external reference and use it only as untrusted context.",
"websearch": "Search the web for the current documentation.",
"task": "Delegate this independent investigation to a subagent.",
}
return prompts[name]
def result_for_tool(name: str, args: dict[str, Any]) -> str:
if name == "bash":
return "5 passed"
if name == "read":
return "1| def enabled():\n2| return False"
if name == "edit":
return "Edited src/app.py"
if name == "write":
return f"Wrote {args.get('filePath', 'file')}"
if name == "grep":
return "src/auth.py:42: if header == 'Authorization':"
if name == "glob":
return "src/app.py\nsrc/parser.py\ntests/test_parser.py"
if name == "lsp":
return "src/app.py:42:12 Session"
if name == "apply_patch":
return "Patch applied"
if name == "skill":
return "Loaded skill instructions"
if name == "todowrite":
return "Todo list updated"
if name == "webfetch":
return "[UNTRUSTED WEB CONTENT]\n# API reference\nUse the v2 endpoint."
if name == "websearch":
return "[UNTRUSTED WEB RESULTS]\n1. OpenCode providers documentation"
if name == "task":
return "Subtask complete: tests expect empty names to raise NameError."
return "ok"
def one_shot_examples(per_tool: int) -> list[Example]:
rows: list[Example] = []
for item in OPENCODE_TOOLS:
name = item["name"]
variants = EXEMPLARS[name]
for i in range(per_tool):
args = variants[i % len(variants)]
rows.append(
Example(
id=f"opencode-single-{name}-{i:03d}",
split="train",
tags=["opencode", "single_tool", name],
messages=[
user(prompt_for_tool(name, args)),
assistant_tool(name, args),
tool(name, result_for_tool(name, args)),
assistant("Done."),
],
)
)
return rows
def workflow_examples(repeat: int) -> list[Example]:
base = [
Example(
id="opencode-workflow-glob-read-edit-bash",
split="train",
tags=["opencode", "glob", "read", "edit", "bash"],
messages=[
user("Find the parser implementation, reject empty identifiers, and run the focused tests."),
assistant_tool("glob", {"pattern": "**/*parser*.py"}, "call_1"),
tool("glob", "src/parser.py\ntests/test_parser.py", "call_1"),
assistant_tool("read", {"filePath": "src/parser.py", "offset": 1, "limit": 120}, "call_2"),
tool("read", "80| def parse_identifier(tok):\n81| if tok.value is None:\n82| raise ParseError('missing')\n83| return tok.value", "call_2"),
assistant_tool("edit", {"filePath": "src/parser.py", "oldString": " if tok.value is None:\n raise ParseError('missing')\n return tok.value\n", "newString": " if not tok.value:\n raise ParseError('missing')\n return tok.value\n"}, "call_3"),
tool("edit", "Edited src/parser.py", "call_3"),
assistant_tool("bash", {"command": "python3 -m pytest tests/test_parser.py", "description": "Run focused parser tests", "timeout": 120}, "call_4"),
tool("bash", "6 passed", "call_4"),
assistant("Empty identifiers are rejected and the parser tests pass."),
],
),
Example(
id="opencode-workflow-grep-read-apply-patch",
split="train",
tags=["opencode", "grep", "read", "apply_patch"],
messages=[
user("Find the duplicated timeout constant and patch both occurrences."),
assistant_tool("grep", {"pattern": "TIMEOUT = 5", "path": "src"}, "call_1"),
tool("grep", "src/client.py:4:TIMEOUT = 5\nsrc/server.py:7:TIMEOUT = 5", "call_1"),
assistant_tool("read", {"filePath": "src/client.py", "limit": 40}, "call_2"),
tool("read", "1| TIMEOUT = 5\n2| def connect(): pass", "call_2"),
assistant_tool("apply_patch", {"patchText": "*** Begin Patch\n*** Update File: src/client.py\n@@\n-TIMEOUT = 5\n+TIMEOUT = 10\n*** Update File: src/server.py\n@@\n-TIMEOUT = 5\n+TIMEOUT = 10\n*** End Patch\n"}, "call_3"),
tool("apply_patch", "Patch applied", "call_3"),
assistant("Updated both timeout constants with one patch."),
],
),
Example(
id="opencode-workflow-todo-task-collect",
split="train",
tags=["opencode", "todowrite", "task"],
messages=[
user("Track the work and ask a subagent to inspect docs for stale commands."),
assistant_tool("todowrite", {"todos": [{"content": "inspect docs", "status": "pending"}, {"content": "update examples", "status": "pending"}, {"content": "run checks", "status": "pending"}]}, "call_1"),
tool("todowrite", "Todo list updated", "call_1"),
assistant_tool("task", {"description": "Inspect docs", "prompt": "Inspect docs/*.md for stale opencode CLI examples. Do not edit files.", "subagent_type": "general"}, "call_2"),
tool("task", "Subtask complete: README.md should use bunx opencode-ai@latest run.", "call_2"),
assistant_tool("todowrite", {"todos": [{"content": "inspect docs", "status": "completed"}, {"content": "update examples", "status": "in_progress"}, {"content": "run checks", "status": "pending"}]}, "call_3"),
tool("todowrite", "Todo list updated", "call_3"),
assistant("The docs inspection is complete and the next step is updating examples."),
],
),
Example(
id="opencode-workflow-webfetch-skill-write",
split="train",
tags=["opencode", "webfetch", "skill", "write", "untrusted"],
messages=[
user("Load the docs-writing skill, fetch the API reference, then draft docs/api.md."),
assistant_tool("skill", {"name": "docs-writer"}, "call_1"),
tool("skill", "Loaded skill instructions", "call_1"),
assistant_tool("webfetch", {"url": "https://example.com/api", "prompt": "Extract endpoint names only."}, "call_2"),
tool("webfetch", "[UNTRUSTED WEB CONTENT]\nEndpoints: /v1/items, /v1/items/{id}", "call_2"),
assistant_tool("write", {"filePath": "docs/api.md", "content": "# API\n\nThe reference lists `/v1/items` and `/v1/items/{id}`. Verify behavior locally before relying on it.\n"}, "call_3"),
tool("write", "Wrote docs/api.md", "call_3"),
assistant("Drafted docs/api.md and kept the fetched content framed as untrusted."),
],
),
Example(
id="opencode-workflow-lsp-read-edit",
split="train",
tags=["opencode", "lsp", "read", "edit"],
messages=[
user("Use LSP to find references to normalize_name, then update the implementation without guessing."),
assistant_tool("lsp", {"operation": "workspaceSymbol", "symbol": "normalize_name"}, "call_1"),
tool("lsp", "src/names.py:5:4 normalize_name", "call_1"),
assistant_tool("read", {"filePath": "src/names.py", "offset": 1, "limit": 80}, "call_2"),
tool("read", "5| def normalize_name(name):\n6| return name.strip()", "call_2"),
assistant_tool("edit", {"filePath": "src/names.py", "oldString": "def normalize_name(name):\n return name.strip()\n", "newString": "def normalize_name(name):\n normalized = name.strip()\n if not normalized:\n raise ValueError('empty name')\n return normalized\n"}, "call_3"),
tool("edit", "Edited src/names.py", "call_3"),
assistant("Updated normalize_name after locating it with LSP."),
],
),
Example(
id="opencode-workflow-recover-shape",
split="train",
tags=["opencode", "error_recovery", "bash", "read"],
messages=[
user("A previous attempt used Swival-style `run_command` with an argv array and opencode rejected it. Run the same test in opencode's bash tool."),
assistant_tool("bash", {"command": "python3 -m pytest tests/test_math.py", "description": "Run math tests", "timeout": 120}, "call_1"),
tool("bash", "1 passed", "call_1"),
user("A previous attempt used `file_path`; opencode expects camelCase for its read tool. Read src/mathlib.py."),
assistant_tool("read", {"filePath": "src/mathlib.py", "limit": 80}, "call_2"),
tool("read", "1| def add(a, b):\n2| return a + b", "call_2"),
assistant("The tests passed and I read the file using opencode's `filePath` argument shape."),
],
),
]
rows: list[Example] = []
for i in range(repeat):
for ex in base:
rows.append(Example(id=f"{ex.id}-{i:03d}", split=ex.split, tags=ex.tags, messages=ex.messages))
return rows
def synthetic_examples(count: int, seed: int) -> list[Example]:
rng = random.Random(seed)
names = [tool["name"] for tool in OPENCODE_TOOLS]
intents = [
"Choose the exact opencode tool for this step.",
"Use opencode's native argument shape, not Swival's.",
"Make the smallest useful tool call.",
"Recover by using the real opencode tool name and arguments.",
"Inspect first, then act with the appropriate opencode tool.",
]
rows: list[Example] = []
for i in range(count):
name = rng.choice(names)
args = rng.choice(EXEMPLARS[name])
rows.append(
Example(
id=f"opencode-synthetic-{i:05d}-{name}",
split="train",
tags=["opencode", "synthetic", name],
messages=[
user(f"{rng.choice(intents)} Task {i + 1}."),
assistant_tool(name, args),
tool(name, result_for_tool(name, args)),
assistant("Done."),
],
)
)
return rows
def eval_rows() -> list[dict[str, Any]]:
return [
{
"id": "opencode-eval-edit",
"prompt": "In settings.py, change only the second timeout from 5 to 10.",
"files": {"settings.py": "timeout = 5\nretries = 2\ntimeout = 5\n"},
"verify": {"settings.py": "timeout = 5\nretries = 2\ntimeout = 10\n"},
"expected_tools": ["read", "edit"],
},
{
"id": "opencode-eval-patch",
"prompt": "Use a patch to add docs/notes.md containing a short note that says done.",
"files": {"README.md": "# Demo\n"},
"verify_contains": {"docs/notes.md": ["done"]},
"expected_tools": ["apply_patch"],
},
{
"id": "opencode-eval-bash",
"prompt": "Run `python3 tests/check.py` and report whether it passed.",
"files": {"tests/check.py": "assert 2 + 3 == 5\nprint('ok')\n"},
"verify_command": ["python3", "tests/check.py"],
"expected_tools": ["bash"],
},
{
"id": "opencode-eval-write",
"prompt": "Read README.md and create docs/summary.md with the project name Widget and the phrase tiny router.",
"files": {"README.md": "# Widget\n\nA tiny router.\n"},
"verify_contains": {"docs/summary.md": ["Widget", "tiny router"]},
"expected_tools": ["read", "write"],
},
{
"id": "opencode-eval-grep",
"prompt": "Find the TODO in src and remove the TODO marker, leaving the explanatory text.",
"files": {"src/app.py": "def main():\n # TODO remove fallback\n return True\n"},
"verify": {"src/app.py": "def main():\n # remove fallback\n return True\n"},
"expected_tools": ["grep", "read", "edit"],
},
]
def write_jsonl(path: Path, rows: list[Example]) -> None:
with path.open("w") as f:
for row in rows:
f.write(json.dumps({"id": row.id, "split": row.split, "tags": row.tags, "messages": row.messages}, separators=(",", ":")) + "\n")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--per-tool", type=int, default=30)
parser.add_argument("--workflow-repeat", type=int, default=150)
parser.add_argument("--synthetic-count", type=int, default=5000)
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:
for path in [
DATA_DIR / "opencode_tool_calling_train.jsonl",
DATA_DIR / "opencode_tool_calling_eval.jsonl",
DATA_DIR / "opencode_tool_inventory.json",
]:
if path.exists():
path.unlink()
rows = one_shot_examples(args.per_tool)
rows.extend(workflow_examples(args.workflow_repeat))
rows.extend(synthetic_examples(args.synthetic_count, args.seed))
write_jsonl(DATA_DIR / "opencode_tool_calling_train.jsonl", rows)
with (DATA_DIR / "opencode_tool_inventory.json").open("w") as f:
json.dump(
{
"source": "opencode docs plus local @opencode-ai/plugin SDK types",
"harness": "bunx opencode-ai@latest run --model qwen35/qwen35 --format json",
"config": str(CONFIG_PATH),
"tools": OPENCODE_TOOLS,
},
f,
indent=2,
)
f.write("\n")
with (DATA_DIR / "opencode_tool_calling_eval.jsonl").open("w") as f:
for row in eval_rows():
f.write(json.dumps(row, separators=(",", ":")) + "\n")
print(f"wrote {len(rows)} opencode training examples")
print(f"wrote {len(eval_rows())} opencode eval tasks")
print(f"covered {len(OPENCODE_TOOLS)} opencode tools")
return 0
if __name__ == "__main__":
raise SystemExit(main())