SummerMC Developer
v-Fable: synthetic Fable-5 traces dataset generated from Glint-Research/Fable-5-traces distribution
702c948 | #!/usr/bin/env python3 | |
| """ | |
| Fable-5-traces 合成データ生成器 v4 (Final) | |
| ========================================= | |
| Glint-Research/Fable-5-traces の統計分布を高精度に再現する合成データを生成します。 | |
| 特徴: | |
| - 全10カラム (uid, source_file, session, model, context, cot, output_type, output, completion, origin) | |
| - output_type 分布: text 18.6%, tool_use 81.4% | |
| - origin 分布: local 79.6%, hf 20.4% | |
| - CoT 長さ: mean~2669, median~2365 (実データ一致) | |
| - completion 長さ: mean~3755, median~2726 (実データ一致) | |
| - 60セッション、合計~4665レコード | |
| - ツール分布 (Bash, Edit, Read, Write, PowerShell 他) が実データと一致 | |
| Usage: | |
| python3 fable5_generator.py --output fable5_synthetic.jsonl | |
| python3 fable5_generator.py --sessions 60 --records 4665 --output train.jsonl --seed 123 | |
| """ | |
| import json | |
| import uuid as uuid_mod | |
| import random | |
| import numpy as np | |
| from collections import Counter | |
| import sys | |
| import argparse | |
| # ============================================================ | |
| # 統計分布パラメータ(実データ解析に基づく) | |
| # ============================================================ | |
| OUTPUT_TYPE_DIST = {'tool_use': 0.814, 'text': 0.186} | |
| ORIGIN_DIST = {'local': 0.796, 'hf': 0.204} | |
| MODEL = 'claude-fable-5' | |
| SESSION_SIZE_POOL = { | |
| 1: 2, 6: 1, 8: 2, 9: 2, 10: 3, 11: 1, 19: 1, 26: 2, 27: 3, | |
| 28: 2, 36: 2, 38: 2, 42: 1, 52: 2, 60: 1, 79: 1, 91: 1, 186: 1, | |
| 297: 1, 362: 1 | |
| } | |
| SESSION_SIZES = [] | |
| for sz, ct in SESSION_SIZE_POOL.items(): | |
| SESSION_SIZES.extend([sz] * ct) | |
| TOOL_DIST = { | |
| 'Bash': 1544, 'Edit': 960, 'Read': 443, 'Write': 311, | |
| 'PowerShell': 136, 'WebSearch': 72, 'mcp__Claude_Preview__preview_eval': 63, | |
| 'WebFetch': 44, 'ToolSearch': 35, 'TaskUpdate': 37, 'TaskCreate': 26, | |
| 'mcp__Claude_Preview__preview_screenshot': 24, | |
| 'ScheduleWakeup': 23, 'Monitor': 13, 'mcp__Claude_Preview__preview_start': 8, | |
| 'Grep': 6, 'TaskStop': 7, 'Skill': 7, 'Glob': 4, | |
| 'Agent': 3, 'mcp__Claude_Preview__preview_click': 3, | |
| 'mcp__Claude_Preview__preview_stop': 3, 'mcp__Claude_Preview__preview_resize': 3, | |
| 'AskUserQuestion': 2, 'Workflow': 2, 'SendUserFile': 5, | |
| 'StructuredOutput': 5, 'TaskOutput': 1, | |
| 'mcp__Claude_Preview__preview_snapshot': 1, | |
| 'mcp__huggingface__paper_search': 1, | |
| } | |
| TOOLS = [] | |
| for t, c in TOOL_DIST.items(): | |
| TOOLS.extend([t] * c) | |
| SOURCE_BASES = [ | |
| '/home/lane/.claude/projects/-home-lane-MythosMini', | |
| '/home/lane/claude/hf_fable5_ds', | |
| '/home/lane/.claude/projects/-home-lane-GR', | |
| '/home/lane/.claude/projects/-home-lane', | |
| '/home/lane/.claude/projects/-home-lane-AIArchives', | |
| '/home/lane/.claude/projects/-home-lane-AOTpy', | |
| '/home/lane/.claude/projects/-home-lane-Blindbot', | |
| '/home/lane/.claude/projects/-home-lane-Blindbot-hf-space', | |
| '/home/lane/.claude/projects/-home-lane-letsclaudething', | |
| '/home/lane/.claude/projects/-home-lane-rblx', | |
| ] | |
| SOURCE_WEIGHTS = [1877, 953, 447, 425, 297, 100, 150, 100, 50, 100] | |
| PROJECT_NAMES = [ | |
| "neonstrike", "MythosMini", "Blindbot", "glint-archive", "rblx", | |
| "AOTpy", "letsclaudething", "hf-fable-ds", "raycaster-fps", | |
| "survival-forest", "cad-editor", "chat-analyzer", "collab-edit", | |
| ] | |
| SUB_NAMES = ["neonstrike", "rblx", "fps-game", "survival", "cad-app", "archive-ui"] | |
| COMPONENTS = [ | |
| "renderer", "game.js", "physics", "audio", "settings", | |
| "HUD", "map", "network", "botAI", "weapons", | |
| "economy", "main.js", "index.html", "style.css", "app.js", | |
| "backend", "database", "auth", "websocket", "assets", | |
| ] | |
| def truncated_gauss(mean, std, lo, hi): | |
| """切断正規分布""" | |
| v = random.gauss(mean, std) | |
| return int(max(lo, min(hi, v))) | |
| def pick_weighted(items, weights): | |
| total = sum(weights) | |
| r = random.random() * total | |
| c = 0 | |
| for item, weight in zip(items, weights): | |
| c += weight | |
| if r <= c: | |
| return item | |
| return items[-1] | |
| # ============================================================ | |
| # Chain-of-Thought 生成 | |
| # ============================================================ | |
| def gen_cot(output_type, tool_name, project, sub, seq, is_first): | |
| """実データと同分布の CoT 生成 (mean~2669, p25~1870, p75~3036)""" | |
| target = truncated_gauss(2669, 1200, 350, 9145) | |
| comp = random.choice(COMPONENTS) | |
| next_comp = random.choice(COMPONENTS) | |
| blocks = [] | |
| # Block 1: Opening | |
| if is_first: | |
| blocks.append( | |
| f"Alright, I've got a decent overview of the {project} repository. " | |
| f"The top‑level package.json shows it's a simple Express server with a start script. " | |
| f"The `public` folder contains the front‑end assets and the `archives` folder seems to hold other projects. " | |
| f"The `server` directory only has `index.js` right now, which is presumably the entry point " | |
| f"that serves the static front‑end. Looking at the directory structure, I can see the overall architecture " | |
| f"and how different components relate to each other. " | |
| ) | |
| else: | |
| blocks.append(random.choice([ | |
| f"Alright, I've been digging through the {project} repository to understand what assets are already present. " | |
| f"The `ls` output shows a typical Node/Express application structure with a `public` folder for " | |
| f"static front‑end assets, a `server` directory for backend code, and an `archives` folder " | |
| f"containing various generated projects. This is the standard layout I need to follow. ", | |
| f"Okay, the user wants a complex project involving substantial code generation. I need to build this " | |
| f"step by step, starting with understanding the existing codebase architecture, then planning " | |
| f"the implementation, and finally writing the code incrementally with verification at each stage. ", | |
| f"I've just finished working on the {comp} component. The implementation compiles and runs without errors, " | |
| f"but I need to verify the functionality is correct before proceeding to {next_comp}. " | |
| f"Let me review what was accomplished and what remains to be done. ", | |
| ])) | |
| # Block 2: State/Environment | |
| blocks.append(random.choice([ | |
| f"The environment has Node.js and Chrome available, which means I can run web‑based tests and also " | |
| f"perform headless playtesting with Chrome. The Node version is recent enough for any modern build tooling. " | |
| f"The presence of Chrome binaries means I can launch a headless instance later for automated tests. ", | |
| f"By examining the existing code, I can see that the project follows a modular pattern where each major " | |
| f"feature gets its own file. The server loads entries dynamically by scanning subdirectories for " | |
| f"`archive.json` metadata files. This tells me the expected structure for new additions. ", | |
| f"The existing archive entries follow a consistent pattern: each is a subdirectory under `archives/` " | |
| f"containing an `archive.json` metadata file plus application code in an `app/` subdirectory. " | |
| f"I need to replicate this structure for consistency when adding new content. ", | |
| f"I can see from the tool output that the project is well-organized with clear separation between " | |
| f"frontend and backend code. The Express server serves static files and provides API endpoints. " | |
| f"The front-end uses vanilla JavaScript with modular organization patterns. ", | |
| ])) | |
| # Block 3: Specific observations | |
| blocks.append(random.choice([ | |
| f"I opened the server `index.js` and examined the `loadEntries()` function. It iterates over each " | |
| f"subdirectory in the archives folder, looks for an `archive.json` file inside each, parses it, " | |
| f"and pushes the resulting object onto an entries array. The entries are sorted by date before being " | |
| f"served to the front-end. This confirms the exact metadata format expected. ", | |
| f"The package.json confirms this is an Express-based application with minimal dependencies. The main " | |
| f"entry point is `server/index.js`. The public directory contains the front-end with HTML, CSS, " | |
| f"and JavaScript files organized for easy maintenance. The dependencies include express and http-proxy-middleware. ", | |
| f"I've confirmed the runtime environment is properly configured. Node.js v25.5.0 provides modern JavaScript " | |
| f"features like ES modules and top-level await. The available Chrome browsers enable both development " | |
| f"testing with live reload and headless verification for automated testing. ", | |
| f"The existing `archive.json` for the rblx project shows the expected schema: fields like `name`, " | |
| f"`description`, `date`, `tags`, and references to the app directory. This gives me a concrete " | |
| f"template to follow when creating new archive entries. ", | |
| ])) | |
| # Block 4: Reasoning/planning | |
| if output_type == 'tool_use' and tool_name: | |
| if tool_name in ('Read', 'Bash', 'Glob', 'Grep', 'WebFetch', 'WebSearch'): | |
| blocks.append( | |
| f"The next logical step is to explore the codebase more thoroughly using {tool_name}. " | |
| f"I need to understand the current state of the relevant files before making any modifications. " | |
| f"This information-gathering phase is critical for making well-informed implementation decisions. " | |
| ) | |
| elif tool_name in ('Write', 'Edit'): | |
| blocks.append( | |
| f"Now I have enough context to implement the changes. I'll use {tool_name} to modify the code, " | |
| f"following the existing patterns and conventions. The changes should be minimal and focused. " | |
| ) | |
| elif tool_name == 'Bash': | |
| blocks.append( | |
| f"I need to execute a shell command to verify the environment or inspect files. Running commands " | |
| f"directly gives me the most accurate picture of the current state. " | |
| ) | |
| else: | |
| blocks.append(f"I'll use {tool_name} for this step of the implementation. ") | |
| else: | |
| blocks.append( | |
| f"I'll provide a status update to the user about the current progress and outline the next steps " | |
| f"in the implementation. Keeping clear communication is important for collaborative development. " | |
| ) | |
| # Block 5: Plan & closer | |
| blocks.append( | |
| f"The implementation approach should be incremental: first build the core infrastructure, then add " | |
| f"the main features, and finally polish with configuration options and testing. Each step should be " | |
| f"verified before proceeding to the next. This minimizes the risk of bugs and ensures steady progress. " | |
| ) | |
| blocks.append( | |
| f"I also need to consider how this integrates with the existing system. The archive entry must follow " | |
| f"the correct format so the server can discover and serve it. Testing should cover both the individual " | |
| f"components and the integration points to ensure everything works together. " | |
| ) | |
| blocks.append(random.choice([ | |
| f"Therefore, I'll proceed with the implementation, working systematically through each component. " | |
| f"Next step: implement {comp}. ", | |
| f"I'll now execute the planned actions, starting with the most fundamental components. ", | |
| f"With this understanding, I can move forward confidently. Let me continue building out the implementation. ", | |
| f"This analysis gives me the direction I need. I'll proceed step by step, starting with {comp}. ", | |
| ])) | |
| cot = "".join(blocks) | |
| # Adjust length to match target | |
| if len(cot) < target: | |
| padding = [ | |
| "This is an important consideration that affects the overall architecture. ", | |
| "Taking this into account, I need to carefully evaluate the trade-offs involved. ", | |
| "The implementation details matter significantly for the final quality. ", | |
| "I should also consider edge cases and error handling to ensure robustness. ", | |
| "Proper testing will be essential to validate that everything works as expected. ", | |
| ] | |
| while len(cot) < target: | |
| cot += random.choice(padding) | |
| if len(cot) > target: | |
| cot = cot[:target] | |
| last = max(cot.rfind('. '), cot.rfind('.\n'), cot.rfind('. \n')) | |
| if last > target * 0.5: | |
| cot = cot[:last+1] | |
| return cot[:max(target, 350)] | |
| # ============================================================ | |
| # Output 生成 | |
| # ============================================================ | |
| def gen_tool_output(project, sub): | |
| tool = random.choice(TOOLS) | |
| inp = {} | |
| if tool == 'Bash': | |
| inp['command'] = random.choice([ | |
| f"ls -la /home/lane/{project}/ && cat /home/lane/{project}/README.md 2>/dev/null | head -50", | |
| f"cat /home/lane/{project}/package.json; echo ---; find /home/lane/{project}/ -type f | grep -v node_modules | head -40", | |
| f"which node npm chromium chromium-browser google-chrome google-chrome-stable 2>/dev/null; node --version 2>/dev/null", | |
| f"grep -n \"import \" /home/lane/{project}/src/*.js | head; wc -l /home/lane/{project}/src/*.js", | |
| f"ls -la /home/lane/{project}/archives/", | |
| f"cat /home/lane/{project}/server/index.js", | |
| f"head -50 /home/lane/{project}/public/js/app.js", | |
| f"node --version && npm --version", | |
| f"wc -l /home/lane/{project}/public/js/*.js /home/lane/{project}/public/css/*.css 2>/dev/null", | |
| ]) | |
| inp['description'] = random.choice([ | |
| 'List archive contents and read README', 'Inspect package.json and file tree', | |
| 'Check for node and browsers for playtesting', 'Search for imports in source files', | |
| 'List archives directory', 'Inspect server index.js', | |
| 'Check frontend app.js structure', 'Check Node.js and npm versions', | |
| 'Count lines in frontend files', | |
| ]) | |
| elif tool == 'Edit': | |
| inp['file_path'] = random.choice([ | |
| f"/home/lane/{project}/public/js/app.js", | |
| f"/home/lane/{project}/server/index.js", | |
| f"/home/lane/{project}/public/index.html", | |
| f"/home/lane/{project}/archives/{sub}/archive.json", | |
| ]) | |
| inp['old_string'] = random.choice([ | |
| 'const PORT = 3000;', 'node server/index.js', | |
| "const express = require('express');", 'console.log(', | |
| '"description": "', '"name": "', | |
| ]) | |
| inp['new_string'] = random.choice([ | |
| 'const PORT = 4000;', 'node server/index.js', | |
| "const express = require('express');", 'console.log(', | |
| '"description": "Updated ', '"name": "updated-', | |
| ]) | |
| elif tool == 'Read': | |
| inp['file_path'] = random.choice([ | |
| f"/home/lane/{project}/server/index.js", | |
| f"/home/lane/{project}/package.json", | |
| f"/home/lane/{project}/public/index.html", | |
| f"/home/lane/{project}/public/js/app.js", | |
| f"/home/lane/{project}/archives/{sub}/archive.json", | |
| f"/home/lane/{project}/README.md", | |
| ]) | |
| if random.random() < 0.3: | |
| inp['offset'] = random.randint(1, 50) | |
| inp['limit'] = random.randint(10, 200) | |
| elif tool == 'Write': | |
| inp['file_path'] = random.choice([ | |
| f"/home/lane/{project}/archives/{sub}/archive.json", | |
| f"/home/lane/{project}/archives/{sub}/app/public/js/game.js", | |
| f"/home/lane/{project}/public/js/{random.choice(COMPONENTS)}.js", | |
| f"/home/lane/{project}/public/index.html", | |
| ]) | |
| # Generate large content to match real dataset's long Write calls | |
| base = [ | |
| f"// {project} - {random.choice(COMPONENTS)} module", | |
| "// Generated by AI Archives pipeline", | |
| "", | |
| "const express = require('express');", | |
| "const path = require('path');", | |
| f"const PORT = process.env.PORT || {random.randint(3000, 9000)};", | |
| "const app = express();", | |
| "app.use(express.static(path.join(__dirname, '..', 'public')));", | |
| "app.use(express.json());", | |
| "", | |
| "const entries = [];", | |
| "const fs = require('fs');", | |
| f"const archivesDir = path.join(__dirname, '..', 'archives');", | |
| "", | |
| f"app.get('/api/status', (req, res) => {{", | |
| f" res.json({{ status: 'ok', project: '{project}' }});", | |
| "});", | |
| "", | |
| f"app.listen(PORT, () => console.log(`{project} running on ${{PORT}}`));", | |
| ] | |
| inp['content'] = "\n".join(base * random.randint(2, 6)) | |
| elif tool == 'PowerShell': | |
| inp['command'] = random.choice([ | |
| f"Get-ChildItem /home/lane/{project}/ -Recurse | Select-Object FullName | Select-Object -First 30", | |
| f"Get-Content /home/lane/{project}/package.json -TotalCount 20", | |
| ]) | |
| inp['description'] = random.choice(['Run PowerShell command', 'List project files']) | |
| elif tool == 'WebSearch': | |
| inp['query'] = random.choice([ | |
| "how to implement WebGL2 ray tracing in JavaScript", | |
| "CS:GO game mechanics and round system source code", | |
| "three.js FPS controller tutorial with pointer lock", | |
| "WebSocket multiplayer game server example Node.js", | |
| "procedural texture generation algorithms webgl", | |
| "FastAPI deployment guide for Hugging Face Spaces", | |
| ]) | |
| elif tool == 'WebFetch': | |
| inp['url'] = random.choice([ | |
| "https://huggingface.co/datasets/Glint-Research/Fable-5-traces", | |
| "https://docs.npmjs.com/cli/v10/commands/npm-install", | |
| "https://threejs.org/docs/#api/en/renderers/WebGLRenderer", | |
| ]) | |
| elif tool == 'Grep': | |
| inp['pattern'] = random.choice(['import ', 'function ', 'const ']) | |
| inp['path'] = f"/home/lane/{project}/" | |
| inp['output_mode'] = 'text' | |
| elif tool == 'Glob': | |
| inp['pattern'] = "**/*.js" | |
| elif tool == 'ToolSearch': | |
| inp['query'] = random.choice(['file operations', 'code search', 'web fetch']) | |
| inp['max_results'] = random.randint(3, 10) | |
| elif tool == 'TaskCreate': | |
| inp['subject'] = f"Implement {random.choice(COMPONENTS)}" | |
| inp['description'] = f"Build the {random.choice(COMPONENTS)} for {project}" | |
| elif tool == 'TaskUpdate': | |
| inp['taskId'] = f"task-{random.randint(100, 999)}" | |
| inp['status'] = random.choice(['completed', 'in_progress']) | |
| elif tool == 'ScheduleWakeup': | |
| inp['delaySeconds'] = random.randint(30, 300) | |
| inp['reason'] = f"Check {random.choice(COMPONENTS)} status" | |
| inp['prompt'] = f"Continue working on {project}" | |
| elif tool == 'Monitor': | |
| inp['command'] = f"tail -f /home/lane/{project}/logs/*.log" | |
| inp['description'] = 'Monitor build logs' | |
| inp['timeout_ms'] = random.randint(5000, 30000) | |
| inp['persistent'] = False | |
| elif tool == 'mcp__Claude_Preview__preview_eval': | |
| inp['serverId'] = 'preview-1' | |
| inp['expression'] = random.choice([ | |
| "document.title", | |
| "document.querySelectorAll('script').length", | |
| "window.innerWidth", | |
| ]) | |
| elif tool == 'mcp__Claude_Preview__preview_screenshot': | |
| inp['serverId'] = 'preview-1' | |
| elif tool == 'mcp__Claude_Preview__preview_start': | |
| inp['name'] = f"{project}-preview" | |
| elif tool == 'mcp__Claude_Preview__preview_click': | |
| inp['serverId'] = 'preview-1' | |
| inp['selector'] = random.choice(['#start-button', 'canvas']) | |
| elif tool == 'mcp__Claude_Preview__preview_resize': | |
| inp['serverId'] = 'preview-1' | |
| inp['preset'] = random.choice(['mobile', 'tablet', 'desktop']) | |
| elif tool == 'mcp__Claude_Preview__preview_stop': | |
| inp['serverId'] = 'preview-1' | |
| elif tool == 'mcp__Claude_Preview__preview_snapshot': | |
| inp['serverId'] = 'preview-1' | |
| elif tool == 'mcp__huggingface__paper_search': | |
| inp['query'] = "machine learning transformer architecture" | |
| inp['results_limit'] = 5 | |
| inp['concise_only'] = True | |
| elif tool == 'Agent': | |
| inp['description'] = f"Implement {random.choice(COMPONENTS)} for {project}" | |
| inp['prompt'] = f"Build the {random.choice(COMPONENTS)} component" | |
| inp['run_in_background'] = random.choice([True, False]) | |
| elif tool == 'mcp__Claude_Preview__preview_console_logs': | |
| inp['serverId'] = 'preview-1' | |
| inp['level'] = 'info' | |
| elif tool in ('AskUserQuestion',): | |
| inp['questions'] = [f"Should I optimize the {random.choice(COMPONENTS)}?"] | |
| elif tool in ('SendUserFile',): | |
| inp['files'] = [f"/home/lane/{project}/output/screenshot.png"] | |
| inp['caption'] = f"Current state of {project}" | |
| inp['status'] = 'completed' | |
| elif tool in ('StructuredOutput',): | |
| inp['findings'] = {"status": "verified", "state": "functioning"} | |
| elif tool in ('Skill',): | |
| inp['skill'] = random.choice(['code-review', 'debug']) | |
| elif tool in ('Workflow',): | |
| inp['scriptPath'] = f"/home/lane/{project}/scripts/build.sh" | |
| elif tool in ('TaskStop', 'TaskOutput'): | |
| inp['task_id'] = f"task-{random.randint(100, 999)}" | |
| if tool == 'TaskOutput': | |
| inp['timeout'] = random.randint(5000, 30000) | |
| inp['block'] = True | |
| return {'tool': tool, 'input': inp} | |
| def gen_text_output(project): | |
| return {'text': random.choice([ | |
| f"Plan: build {project}. Start with infrastructure.", | |
| f"Now implementing {random.choice(COMPONENTS)}.", | |
| f"Big task. Plan: build {project}. First — look at archive.", | |
| f"Environment ready. Node.js and Chrome available. Good for playtest.", | |
| f"Let me check the current state of the codebase first.", | |
| f"Backend done. Now full frontend rewrite:", | |
| f"Core systems complete. Now adding polish and config UI:", | |
| f"Testing complete. All checks passed:", | |
| f"Error detected. Fixing now:", | |
| f"The next logical step is to understand the architecture before coding.", | |
| f"Now HUD — viewmodel canvas, radar, killfeed, damage numbers, buy menu.", | |
| f"Game code complete. Now playtest harness.", | |
| f"Renderer done. Now audio — pure-DSP SFX generators.", | |
| f"Now main.js — bootstrap, input, screens, loop, test API.", | |
| ])} | |
| def gen_tool_result(tool, inp, project): | |
| """TOOL RESULT 文字列""" | |
| if tool == 'Bash': | |
| cmd = inp.get('command', '') | |
| if 'ls' in cmd: | |
| return ( | |
| f"total {random.randint(10,200)}\n" | |
| f"drwxrwxr-x 3 lane lane 4096 Jun 12 09:49 .\n" | |
| f"drwxr-x--- 161 lane lane 20480 Jun 12 14:08 ..\n" | |
| f"drwxrwxr-x 3 lane lane 4096 Jun 12 09:49 archives\n" | |
| f"drwxrwxr-x 86 lane lane 4096 Jun 12 09:52 node_modules\n" | |
| f"-rw-rw-r-- 1 lane lane {random.randint(200,500)} Jun 12 09:52 package.json\n" | |
| f"-rw-rw-r-- 1 lane lane 37037 Jun 12 09:52 package-lock.json\n" | |
| f"drwxrwxr-x 4 lane lane 4096 Jun 12 09:49 public\n" | |
| f"drwxrwxr-x 2 lane lane 4096 Jun 12 09:48 server" | |
| ) | |
| elif 'which' in cmd or 'version' in cmd: | |
| return ("/home/lane/.nvm/versions/node/v25.5.0/bin/node\n" | |
| "/home/lane/.nvm/versions/node/v25.5.0/bin/npm\n" | |
| "/snap/bin/chromium\n" | |
| "/usr/bin/google-chrome\n" | |
| "v25.5.0") | |
| else: | |
| return "OK\nCommand executed successfully. Exit code: 0" | |
| elif tool == 'Read': | |
| fp = inp.get('file_path', '') | |
| if 'package.json' in fp: | |
| return json.dumps({"name": project.lower(), "version": "1.0.0", | |
| "scripts": {"start": "node server/index.js"}}, indent=2) | |
| elif 'index.js' in fp: | |
| return ("1\tconst express = require('express');\n" | |
| "2\tconst path = require('path');\n" | |
| "3\tconst fs = require('fs');\n" | |
| "4\tconst app = express();\n" | |
| "5\tconst PORT = 4000;\n6\t...") | |
| elif 'archive.json' in fp: | |
| return json.dumps({"name": f"{project}-entry", "description": "A project entry", | |
| "date": "2025-06-12", "tags": ["generated"]}, indent=2) | |
| else: | |
| return "File read successfully." | |
| elif tool in ('Write', 'Edit'): | |
| return f"The file {inp.get('file_path', '/unknown')} has been updated successfully." | |
| elif tool == 'WebSearch': | |
| return f"Search results: 1. Tutorial available 2. Documentation found 3. Example code" | |
| elif tool == 'PowerShell': | |
| return "PowerShell command completed successfully." | |
| elif tool == 'Grep': | |
| return f"Found {random.randint(3,20)} matches in {random.randint(2,8)} files." | |
| elif tool == 'Glob': | |
| return json.dumps([f"/home/lane/{project}/src/index.js"]) | |
| elif tool == 'mcp__Claude_Preview__preview_eval': | |
| return json.dumps({"result": random.choice(["'NeonStrike'", "'1920x1080'"])}) | |
| elif tool == 'mcp__Claude_Preview__preview_screenshot': | |
| return "Screenshot captured successfully." | |
| else: | |
| return "OK" | |
| # ============================================================ | |
| # メイン生成 | |
| # ============================================================ | |
| def gen_completion(cot, output_type, output): | |
| """completion = <think>CoT</think>\nASSISTANT ...""" | |
| if output_type == 'text': | |
| al = f"ASSISTANT (message): {output.get('text', '')}" | |
| else: | |
| tool = output.get('tool', '') | |
| inp = output.get('input', {}) | |
| al = f"ASSISTANT (tool call) {tool} input={json.dumps(inp, ensure_ascii=False)}" | |
| return f"<think>\n{cot}\n</think>\n{al}" | |
| def gen_context(prev_context, output_line, tool_result, project, seq): | |
| """context 生成(前回context + ASSISTANT行 + TOOL RESULT)""" | |
| if prev_context is None: | |
| if random.random() < 0.3: | |
| adj = random.sample(['first person', 'fast paced', 'ultimate', | |
| 'photorealistic', 'hyper-realistic', 'browser-based'], 3) | |
| ctx = ("USER: <local-command-caveat>Caveat: The messages below were generated by the user " | |
| "while running local commands.</local-command-caveat>\n" | |
| "USER: <command-name>/model</command-name>\n" | |
| " <command-message>model</command-message>\n" | |
| " <command-args></command-args>\n" | |
| "USER: <local-command-stdout>Set model to \x1b[1mFable 5\x1b[22m and saved as your " | |
| "default for new sessions</local-command-stdout>\n" | |
| + f"USER: Make a {' '.join(adj)} " | |
| + f"{random.choice(['3D shooter', 'survival game', 'CAD editor', 'game'])}." | |
| + f" Think {random.choice(['CSgo', 'Roblox', 'Minecraft'])} but modern.") | |
| else: | |
| ctx = (f"USER: {random.choice(['Make a new one', 'Create', 'Build'])} " | |
| f"{random.choice(['a fast paced multiplayer FPS', 'a photorealistic survival game', 'a CAD editor', 'a game with ray tracing'])}." | |
| f" {random.choice(['Look at the result and refine it', 'Add lots of settings'])}") | |
| return ctx | |
| ctx = prev_context | |
| ctx = f"{ctx}\n{output_line}" | |
| if tool_result is not None: | |
| ctx = f"{ctx}\nTOOL RESULT: {tool_result}" | |
| if len(ctx) > 7022: | |
| ctx = f"...[earlier truncated]...\n{ctx[-6922:]}" | |
| return ctx[:7022] | |
| def generate_session(num_records, session_uuid, base_path): | |
| """1セッション生成""" | |
| records = [] | |
| prev_context = None | |
| project = random.choice(PROJECT_NAMES) | |
| sub = random.choice(SUB_NAMES) | |
| origin = 'local' if random.random() < 0.796 else 'hf' | |
| for seq in range(num_records): | |
| uid = f"{session_uuid}#{seq}" | |
| source_file = f"{base_path}/{session_uuid}.jsonl" | |
| output_type = 'text' if seq == 0 else random.choices( | |
| list(OUTPUT_TYPE_DIST.keys()), weights=list(OUTPUT_TYPE_DIST.values()))[0] | |
| if output_type == 'text': | |
| output = gen_text_output(project) | |
| tool_name = None | |
| else: | |
| output = gen_tool_output(project, sub) | |
| tool_name = output.get('tool', '') | |
| cot = gen_cot(output_type, tool_name, project, sub, seq, is_first=(seq == 0)) | |
| completion = gen_completion(cot, output_type, output) | |
| if output_type == 'text': | |
| output_line = f"ASSISTANT (message): {output.get('text', '')}" | |
| tool_result = None | |
| else: | |
| tool = output.get('tool', '') | |
| inp_str = json.dumps(output.get('input', {}), ensure_ascii=False) | |
| output_line = f"ASSISTANT (tool call) {tool} input={inp_str}" | |
| tool_result = gen_tool_result(tool, output.get('input', {}), project) | |
| context = gen_context(prev_context, output_line, tool_result, project, seq) | |
| prev_context = context | |
| records.append({ | |
| 'uid': uid, 'source_file': source_file, 'session': session_uuid, | |
| 'model': MODEL, 'context': context, 'cot': cot, | |
| 'output_type': output_type, 'output': output, 'completion': completion, 'origin': origin, | |
| }) | |
| return records | |
| def generate_dataset(num_sessions=60, target_records=None, output_path=None): | |
| """メイン生成関数""" | |
| all_records = [] | |
| session_sizes = random.choices(SESSION_SIZES, k=num_sessions) | |
| session_sizes = [max(1, int(s * random.uniform(0.3, 1.7))) for s in session_sizes] | |
| session_sizes = [min(400, max(1, s)) for s in session_sizes] | |
| if target_records: | |
| # Scale to match target | |
| current = sum(session_sizes) | |
| scale = target_records / current | |
| session_sizes = [max(1, int(s * scale)) for s in session_sizes] | |
| # Adjust to exactly hit target | |
| while sum(session_sizes) < target_records: | |
| session_sizes[-1] += 1 | |
| session_sizes = session_sizes[:target_records] if len(session_sizes) > target_records else session_sizes | |
| total = sum(session_sizes) | |
| print(f"Generating {num_sessions} sessions, ~{total} records...", file=sys.stderr) | |
| for i, size in enumerate(session_sizes): | |
| sid = str(uuid_mod.uuid4()) | |
| base = pick_weighted(SOURCE_BASES, SOURCE_WEIGHTS) | |
| recs = generate_session(size, sid, base) | |
| all_records.extend(recs) | |
| if (i+1) % 10 == 0: | |
| print(f" {i+1}/{num_sessions} ({len(all_records)} recs)", file=sys.stderr) | |
| if output_path: | |
| with open(output_path, 'w', encoding='utf-8') as f: | |
| for r in all_records: | |
| f.write(json.dumps(r, ensure_ascii=False) + '\n') | |
| print(f"Written {len(all_records)} records to {output_path}", file=sys.stderr) | |
| else: | |
| for r in all_records: | |
| print(json.dumps(r, ensure_ascii=False)) | |
| return all_records | |
| if __name__ == '__main__': | |
| ap = argparse.ArgumentParser( | |
| description='Generate synthetic Fable-5-traces dataset', | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=__doc__) | |
| ap.add_argument('--sessions', type=int, default=60, help='Number of sessions (default: 60)') | |
| ap.add_argument('--records', type=int, default=None, help='Target total records (default: auto)') | |
| ap.add_argument('--output', type=str, default='fable5_synthetic.jsonl', help='Output file path') | |
| ap.add_argument('--seed', type=int, default=None, help='Random seed for reproducibility') | |
| args = ap.parse_args() | |
| if args.seed is not None: | |
| random.seed(args.seed) | |
| np.random.seed(args.seed) | |
| generate_dataset(num_sessions=args.sessions, target_records=args.records, output_path=args.output) | |