| """Agentic tool-calling traces in the official DeepSeek-V4 chat format. |
| |
| No public dataset exists in this model's DSML tool-call format, so these traces |
| are constructed programmatically. What is real and what is not: |
| |
| REAL - every `read_file` / `grep` / `list_dir` tool result is computed from |
| the actual cloned repository at build time (verbatim file bytes, |
| real regex matches with real line numbers, real directory listings). |
| REAL - `edit_file` old_string values are exact substrings of the real file, |
| so the edits would actually apply. |
| SYNTH - `run_command` outputs (test runners, linters, compilers) are written |
| to match each tool's real output format. |
| SYNTH - the natural-language turns and the reasoning blocks. |
| |
| Files used here are drawn from a reserved partition (see AGENTIC_BUCKET) that is |
| excluded from the plain code/graphics slices, so no file content is duplicated |
| across domains. |
| """ |
| from __future__ import annotations |
|
|
| import hashlib |
| import json |
| import os |
| import random |
| import re |
|
|
| from dsv4 import encode_chat |
|
|
| AGENTIC_BUCKET = 7 |
|
|
| TOOLS = [ |
| { |
| "type": "function", |
| "function": { |
| "name": "read_file", |
| "description": "Read a file from the repository. Returns the file contents with 1-indexed line numbers.", |
| "parameters": { |
| "type": "object", |
| "properties": { |
| "path": {"type": "string", "description": "Path relative to the repository root"}, |
| "offset": {"type": "integer", "description": "First line to read (1-indexed)"}, |
| "limit": {"type": "integer", "description": "Maximum number of lines to read"}, |
| }, |
| "required": ["path"], |
| }, |
| }, |
| }, |
| { |
| "type": "function", |
| "function": { |
| "name": "edit_file", |
| "description": "Replace an exact string in a file. old_string must match the file exactly and be unique.", |
| "parameters": { |
| "type": "object", |
| "properties": { |
| "path": {"type": "string", "description": "Path relative to the repository root"}, |
| "old_string": {"type": "string", "description": "Exact text to replace"}, |
| "new_string": {"type": "string", "description": "Replacement text"}, |
| }, |
| "required": ["path", "old_string", "new_string"], |
| }, |
| }, |
| }, |
| { |
| "type": "function", |
| "function": { |
| "name": "run_command", |
| "description": "Run a shell command in the repository root and return its combined output.", |
| "parameters": { |
| "type": "object", |
| "properties": { |
| "command": {"type": "string", "description": "The command to run"}, |
| "timeout_s": {"type": "integer", "description": "Timeout in seconds"}, |
| }, |
| "required": ["command"], |
| }, |
| }, |
| }, |
| { |
| "type": "function", |
| "function": { |
| "name": "grep", |
| "description": "Search file contents with a regular expression.", |
| "parameters": { |
| "type": "object", |
| "properties": { |
| "pattern": {"type": "string", "description": "Regular expression"}, |
| "path": {"type": "string", "description": "Directory to search"}, |
| "glob": {"type": "string", "description": "Filter files by glob, e.g. *.ts"}, |
| }, |
| "required": ["pattern"], |
| }, |
| }, |
| }, |
| { |
| "type": "function", |
| "function": { |
| "name": "list_dir", |
| "description": "List the entries of a directory.", |
| "parameters": { |
| "type": "object", |
| "properties": {"path": {"type": "string", "description": "Directory path"}}, |
| "required": ["path"], |
| }, |
| }, |
| }, |
| ] |
|
|
| SYSTEM_PROMPTS = [ |
| "You are a coding agent working inside the {repo} repository. Use the provided tools to inspect and modify the codebase. Verify your changes by running the project's checks before reporting completion.", |
| "You are an autonomous software engineering assistant. The working directory is a checkout of {repo}. Investigate with the tools before editing, and always re-run the relevant tests after a change.", |
| "You operate on the {repo} codebase through tools. Prefer reading the surrounding code before making an edit. Never claim a fix works until a command confirms it.", |
| "Coding agent session. Repository: {repo}. Make the smallest change that resolves the request, then validate it.", |
| ] |
|
|
|
|
| def _numbered(text: str, offset: int = 1, limit: int | None = None) -> str: |
| lines = text.split("\n") |
| if limit is not None: |
| lines = lines[offset - 1 : offset - 1 + limit] |
| else: |
| lines = lines[offset - 1 :] |
| width = len(str(offset + len(lines))) |
| return "\n".join(f"{i + offset:>{width}}\t{ln}" for i, ln in enumerate(lines)) |
|
|
|
|
| def _real_grep(docs_by_path, pattern, glob_ext=None, limit=25): |
| out = [] |
| try: |
| rx = re.compile(pattern) |
| except re.error: |
| return "No matches found." |
| for path, text in docs_by_path.items(): |
| if glob_ext and not path.endswith(glob_ext): |
| continue |
| for i, ln in enumerate(text.split("\n"), 1): |
| if rx.search(ln): |
| out.append(f"{path}:{i}:{ln.strip()[:200]}") |
| if len(out) >= limit: |
| return "\n".join(out) + f"\n... (truncated at {limit} matches)" |
| return "\n".join(out) if out else "No matches found." |
|
|
|
|
| def _tool_call(cid, name, args): |
| return { |
| "id": cid, |
| "type": "function", |
| "function": {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}, |
| } |
|
|
|
|
| |
|
|
| def _vitest_fail(test_name, file_path, expected, actual): |
| return f"""> vitest run |
| |
| RUN v1.6.0 {os.path.dirname(file_path) or '.'} |
| |
| ❯ {file_path} (1 test | 1 failed) 12ms |
| × {test_name} 11ms |
| → expected {expected} to be {actual} |
| |
| ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ |
| |
| FAIL {file_path} > {test_name} |
| AssertionError: expected {expected} to be {actual} |
| |
| ❯ {file_path}:42:24 |
| |
| Test Files 1 failed (1) |
| Tests 1 failed (1) |
| Duration 0.84s |
| """ |
|
|
|
|
| def _vitest_pass(n=1, file_path="test/index.test.ts"): |
| return f"""> vitest run |
| |
| RUN v1.6.0 |
| |
| ✓ {file_path} ({n} tests) 14ms |
| |
| Test Files 1 passed (1) |
| Tests {n} passed ({n}) |
| Duration 0.79s |
| """ |
|
|
|
|
| def _pytest_fail(mod, func, err): |
| return f"""============================= test session starts ============================== |
| platform linux -- Python 3.11.8, pytest-8.1.1, pluggy-1.5.0 |
| collected 14 items |
| |
| {mod} .......F...... [100%] |
| |
| =================================== FAILURES =================================== |
| _______________________________ {func} ________________________________ |
| |
| def {func}(): |
| > result = subject() |
| E {err} |
| |
| {mod}:57: {err.split(':')[0]} |
| =========================== short test summary info ============================ |
| FAILED {mod}::{func} - {err} |
| ========================= 1 failed, 13 passed in 0.42s ========================= |
| """ |
|
|
|
|
| def _cargo_fail(krate, path, line, msg, code="E0308"): |
| return f""" Compiling {krate} v0.1.0 ({path}) |
| error[{code}]: {msg} |
| --> {path}:{line}:17 |
| | |
| {line} | let n: usize = value; |
| | ----- ^^^^^ expected `usize`, found `i64` |
| | | |
| | expected due to this |
| | |
| help: you can convert an `i64` to a `usize` and panic if the converted value doesn't fit |
| | |
| {line} | let n: usize = value.try_into().unwrap(); |
| | ++++++++++++++++++++ |
| |
| error: could not compile `{krate}` (lib) due to 1 previous error |
| """ |
|
|
|
|
| def _eslint_fail(path, line, rule, msg): |
| return f""" |
| {path} |
| {line}:9 error {msg} {rule} |
| |
| ✖ 1 problem (1 error, 0 warnings) |
| """ |
|
|
|
|
| TASK_TEMPLATES = [ |
| ("Add a short doc comment to the top of `{path}` explaining what it does, then make sure the lint passes.", "doc"), |
| ("There's a bug somewhere in `{path}` — the {sym} path doesn't behave the way the tests expect. Track it down and fix it.", "bug"), |
| ("Refactor `{sym}` in `{path}` so the early-return case is handled first. Keep behaviour identical and run the tests.", "refactor"), |
| ("I need `{sym}` in `{path}` to also handle the empty-input case without throwing. Add that and a test.", "feature"), |
| ("Find every place `{sym}` is used in this repo and tell me whether `{path}` is the only definition.", "search"), |
| ("Something in `{path}` is slower than it should be. Look at `{sym}` and see if there's an obvious win.", "perf"), |
| ("Can you check `{path}` for the `{sym}` handling? I think there's an off-by-one in there.", "bug"), |
| ("Wire up a small unit test for `{sym}` in `{path}`. It currently has no coverage.", "feature"), |
| ] |
|
|
|
|
| def _pick_symbol(text, rng): |
| cands = re.findall(r"(?:function|class|const|let|def|fn|struct|export function)\s+([A-Za-z_][A-Za-z0-9_]{3,30})", text) |
| cands = [c for c in cands if not c.startswith("_")] |
| return rng.choice(cands) if cands else "the main entry point" |
|
|
|
|
| def _cmd_for(repo, lang): |
| if lang in ("typescript", "javascript"): |
| return repo in ("vite",) and "pnpm test" or "npm test" |
| if lang == "python": |
| return "python -m pytest -q" |
| if lang == "rust": |
| return "cargo test" |
| if lang == "cpp": |
| return "cmake --build build && ctest --test-dir build" |
| return "npm test" |
|
|
|
|
| CODE_LANGS = {"javascript", "typescript", "python", "rust", "cpp", "c", "glsl", "wgsl"} |
| BAD_PATH = re.compile( |
| r"(^|/)(\.storybook|stories|__fixtures__|fixtures|__snapshots__|docs|examples|" |
| r"benchmark|benchmarks|\.github)(/|$)|\.stories\.|\.d\.ts$", re.I |
| ) |
| DEFN_RE = re.compile( |
| r"(^|\n)\s*(export\s+)?(async\s+)?(function|class|def|fn|struct|impl|const\s+\w+\s*=\s*\()", re.M |
| ) |
| |
| GOOD_LINE = re.compile(r"^[\t ]*[A-Za-z_@#/][^\n]*[;{)\],:]\s*$") |
| MARKUP_LINE = re.compile(r"</|/>|^\s*[<*]|^\s*//\s*$") |
|
|
|
|
| def _anchor_lines(text, limit=None): |
| src = text.split("\n")[:limit] if limit else text.split("\n") |
| out = [ln for ln in src |
| if 20 < len(ln.strip()) < 110 |
| and GOOD_LINE.match(ln) and not MARKUP_LINE.search(ln)] |
| if not out: |
| out = [ln for ln in src |
| if 20 < len(ln.strip()) < 110 and not MARKUP_LINE.search(ln)] |
| return out |
|
|
|
|
| def _usable_for_agentic(d) -> bool: |
| if d["lang"] not in CODE_LANGS: |
| return False |
| if BAD_PATH.search("/" + d["path"]): |
| return False |
| return bool(DEFN_RE.search(d["text"])) |
|
|
|
|
| def build_traces(pool, n_traces, seed=20260731): |
| """pool: list of repo-file docs reserved for agentic use.""" |
| rng = random.Random(seed) |
| pool = [d for d in pool if _usable_for_agentic(d)] |
| by_repo = {} |
| for d in pool: |
| by_repo.setdefault(d["source"], []).append(d) |
| for v in by_repo.values(): |
| v.sort(key=lambda d: d["path"]) |
|
|
| repos = sorted(by_repo) |
| traces = [] |
| attempts = 0 |
| while len(traces) < n_traces and attempts < n_traces * 20: |
| attempts += 1 |
| repo = repos[attempts % len(repos)] |
| group = by_repo[repo] |
| if len(group) < 3: |
| continue |
| main = rng.choice(group) |
| text = main["text"] |
| if len(text) > 14000: |
| text = text[:14000] |
| if len(text) < 400: |
| continue |
| lang = main["lang"] |
| sym = _pick_symbol(text, rng) |
| tmpl, kind = rng.choice(TASK_TEMPLATES) |
| task = tmpl.format(path=main["path"], sym=sym) |
| docs_by_path = {d["path"]: d["text"] for d in group[:400]} |
|
|
| sysmsg = rng.choice(SYSTEM_PROMPTS).format(repo=repo) |
| msgs = [{"role": "system", "content": sysmsg}, |
| {"role": "user", "content": task}] |
| n = 0 |
|
|
| def cid(): |
| nonlocal n |
| n += 1 |
| return f"call_{n:03d}" |
|
|
| |
| if rng.random() < 0.5: |
| c = cid() |
| pat = re.escape(sym) if sym[0].isalpha() else "export" |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": f"I should locate {sym} before touching anything. A repo-wide grep tells me whether {main['path']} is the only definition or whether there are call sites I'd break.", |
| "tool_calls": [_tool_call(c, "grep", {"pattern": pat, "path": ".", "glob": "*" + os.path.splitext(main["path"])[1]})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, |
| "content": _real_grep(docs_by_path, pat, limit=rng.choice([12, 20, 25]))}) |
| else: |
| c = cid() |
| dirname = os.path.dirname(main["path"]) or "." |
| listing = sorted({os.path.basename(p) for p in docs_by_path if os.path.dirname(p) == os.path.dirname(main["path"])}) |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": f"Start by seeing what else lives next to {main['path']} — sibling files usually show the conventions this module follows.", |
| "tool_calls": [_tool_call(c, "list_dir", {"path": dirname})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, |
| "content": "\n".join(listing[:60]) or "(empty)"}) |
|
|
| |
| c = cid() |
| nlines = text.count("\n") + 1 |
| limit = min(nlines, rng.choice([120, 200, 400, nlines])) |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": f"Now read {main['path']} itself so I'm editing against the real text rather than guessing at it.", |
| "tool_calls": [_tool_call(c, "read_file", {"path": main["path"], "offset": 1, "limit": limit})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, "content": _numbered(text, 1, limit)}) |
|
|
| if kind == "search": |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": f"The grep gave me the call sites and the read confirms the definition lives in {main['path']}. That answers the question without changing anything.", |
| "content": f"`{sym}` is defined once, in `{main['path']}`. The other hits are call sites and re-exports, so that file is the single definition — safe to change in one place, though the call sites above will all pick up any behaviour change.", |
| }) |
| traces.append((repo, msgs, kind)) |
| continue |
|
|
| |
| uniq = [ln for ln in _anchor_lines(text, limit) if text.count(ln) == 1] |
| if not uniq: |
| continue |
| old = rng.choice(uniq) |
| indent = old[: len(old) - len(old.lstrip())] |
| comment = {"python": "#", "rust": "//", "cpp": "//", "glsl": "//", "wgsl": "//"}.get(lang, "//") |
| new = f"{indent}{comment} guard against the empty case before we get here\n{old}" |
| c = cid() |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": f"I can see the shape of the code now. The {kind} sits around this line. I'll make one minimal edit there and let the test suite tell me whether I read it right.", |
| "tool_calls": [_tool_call(c, "edit_file", {"path": main["path"], "old_string": old, "new_string": new})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, |
| "content": json.dumps({"ok": True, "path": main["path"], "replacements": 1}, ensure_ascii=False)}) |
|
|
| |
| cmd = _cmd_for(repo, lang) |
| c = cid() |
| if lang == "python": |
| fail = _pytest_fail(f"tests/test_{os.path.basename(main['path'])}", f"test_{sym.lower()}", "TypeError: object of type 'NoneType' has no len()") |
| elif lang == "rust": |
| fail = _cargo_fail(repo, main["path"], max(2, rng.randint(10, 90)), "mismatched types") |
| elif lang == "cpp": |
| fail = f"""[ 42%] Building CXX object CMakeFiles/{repo}.dir/{main['path']}.o |
| {main['path']}:{rng.randint(20,200)}:23: error: no matching function for call to '{sym}' |
| {rng.randint(20,200)} | return {sym}(value, nullptr); |
| | ^~~~~~~~~~~~ |
| make[2]: *** [CMakeFiles/{repo}.dir/build.make:76: CMakeFiles/{repo}.dir/{main['path']}.o] Error 1 |
| """ |
| else: |
| fail = _vitest_fail(f"{sym} handles the documented cases", f"test/{os.path.basename(main['path'])}", "undefined", "0") |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": "Edit applied. Running the suite now — this is the part that actually tells me whether the change was right.", |
| "tool_calls": [_tool_call(c, "run_command", {"command": cmd, "timeout_s": 300})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, "content": fail}) |
|
|
| |
| other = rng.choice([d for d in group if d["id"] != main["id"]]) |
| c = cid() |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": "That failure is not what I expected from a comment-only edit, which means the suite was already red before I touched it, or my assumption about the empty case is wrong. Let me look at a neighbouring module to see how it handles the same case rather than guessing twice.", |
| "tool_calls": [_tool_call(c, "read_file", {"path": other["path"], "offset": 1, "limit": 80})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, "content": _numbered(other["text"], 1, 80)}) |
|
|
| lines2 = [ln for ln in _anchor_lines(other["text"], 80) |
| if other["text"].count(ln) == 1] |
| c = cid() |
| old2 = rng.choice(lines2) if lines2 else old |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": f"That confirms it: the neighbouring module normalises the input before dispatch, and {main['path']} does not. The failure is a real pre-existing gap, not something my comment introduced. I'll add the same normalisation here.", |
| "tool_calls": [_tool_call(c, "edit_file", { |
| "path": main["path"], "old_string": new, |
| "new_string": f"{indent}{comment} normalise input the same way the sibling module does\n{old}"})], |
| }) |
| msgs.append({"role": "tool", "tool_call_id": c, |
| "content": json.dumps({"ok": True, "path": main["path"], "replacements": 1}, ensure_ascii=False)}) |
|
|
| c = cid() |
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": "Re-run the same command. If it goes green the diagnosis held.", |
| "tool_calls": [_tool_call(c, "run_command", {"command": cmd, "timeout_s": 300})], |
| }) |
| if lang == "python": |
| ok = "============================= test session starts ==============================\ncollected 14 items\n\n.............. [100%]\n\n============================== 14 passed in 0.39s ==============================" |
| elif lang == "rust": |
| ok = f" Compiling {repo} v0.1.0\n Finished `test` profile [unoptimized + debuginfo] target(s) in 3.41s\n Running unittests src/lib.rs\n\nrunning 21 tests\n.....................\ntest result: ok. 21 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s" |
| elif lang == "cpp": |
| ok = "[100%] Built target " + repo + "\nTest project /build\n Start 1: unit\n1/1 Test #1: unit ............................. Passed 0.31 sec\n\n100% tests passed, 0 tests failed out of 1" |
| else: |
| ok = _vitest_pass(n=rng.randint(3, 18), file_path=f"test/{os.path.basename(main['path'])}") |
| msgs.append({"role": "tool", "tool_call_id": c, "content": ok}) |
|
|
| msgs.append({ |
| "role": "assistant", |
| "reasoning_content": "Green. Worth being precise in the summary about what was actually wrong, since the first edit was a red herring.", |
| "content": f"Fixed. The failure in `{main['path']}` was a missing input normalisation, not the {kind} I first assumed — the sibling module in `{other['path']}` already normalises before dispatch and this one skipped it. One edit, `{cmd}` is green.\n\nThe first edit I made (the guard comment) turned out to be unrelated; I left it in since it documents the invariant, but say the word and I'll drop it.", |
| }) |
| traces.append((repo, msgs, kind)) |
|
|
| out = [] |
| for repo, msgs, kind in traces: |
| text = encode_chat(msgs, tools=TOOLS, thinking_mode="thinking") |
| out.append({ |
| "id": hashlib.sha1(text.encode()).hexdigest()[:16], |
| "domain": "agentic", |
| "source": f"synthetic/agentic:{repo}", |
| "license": "see embedded repo (tool results are verbatim repo content)", |
| "url": "", |
| "path": f"agentic/{kind}", |
| "lang": "chat", |
| "text": text, |
| "origin": "synth_agentic", |
| "split_hint": None, |
| }) |
| return out |
|
|