Datasets:
File size: 22,068 Bytes
bd43184 | 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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | #!/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())
|