#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 生成 MiniMind 格式的 Tool Call 合成训练数据(含短 thinking)。 用法: python make_toolcall_data.py python make_toolcall_data.py --out sft_toolcall_synthetic.jsonl --seed 42 """ import json import random import math import ast import operator import argparse from pathlib import Path # ============================================================ # 1. 工具定义(3 个,schema 极简) # ============================================================ TOOLS = [ { "name": "calculate_math", "description": "计算数学表达式,支持 + - * / ** sqrt sin cos tan log10 abs", "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "数学表达式,如 256*37 或 sqrt(144)" } }, "required": ["expression"] } }, { "name": "get_current_time", "description": "查询指定时区的当前时间", "parameters": { "type": "object", "properties": { "timezone": { "type": "string", "description": "IANA 时区名,如 Asia/Shanghai、America/New_York、UTC" } }, "required": ["timezone"] } }, { "name": "search_web", "description": "搜索实时信息,返回摘要", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "搜索关键词" } }, "required": ["query"] } } ] TOOLS_JSON = json.dumps(TOOLS, ensure_ascii=False) # ============================================================ # 2. 安全的数学表达式求值器 # ============================================================ _ALLOWED_BINOPS = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow, ast.Mod: operator.mod, ast.FloorDiv: operator.floordiv, } _ALLOWED_UNARY = { ast.UAdd: operator.pos, ast.USub: operator.neg, } _ALLOWED_FUNCS = { "sqrt": math.sqrt, "sin": math.sin, "cos": math.cos, "tan": math.tan, "log10": math.log10, "log": math.log, "exp": math.exp, "abs": abs, "floor": math.floor, "ceil": math.ceil, } def _safe_eval_node(node): if isinstance(node, ast.Expression): return _safe_eval_node(node.body) if isinstance(node, ast.Constant): if isinstance(node.value, (int, float)): return node.value raise ValueError(f"不支持的常量: {node.value!r}") if isinstance(node, ast.BinOp): op_type = type(node.op) if op_type not in _ALLOWED_BINOPS: raise ValueError(f"不支持的运算符: {op_type.__name__}") return _ALLOWED_BINOPS[op_type]( _safe_eval_node(node.left), _safe_eval_node(node.right) ) if isinstance(node, ast.UnaryOp): op_type = type(node.op) if op_type not in _ALLOWED_UNARY: raise ValueError(f"不支持的一元运算符: {op_type.__name__}") return _ALLOWED_UNARY[op_type](_safe_eval_node(node.operand)) if isinstance(node, ast.Call): if isinstance(node.func, ast.Name) and node.func.id in _ALLOWED_FUNCS: args = [_safe_eval_node(a) for a in node.args] return _ALLOWED_FUNCS[node.func.id](*args) raise ValueError(f"不支持的函数: {getattr(node.func, 'id', node.func)}") raise ValueError(f"不支持的语法节点: {type(node).__name__}") def safe_math_eval(expr: str) -> float: normalized = expr.replace("^", "**") tree = ast.parse(normalized, mode="eval") return _safe_eval_node(tree) def format_number(x) -> str: if isinstance(x, float): if math.isfinite(x) and x.is_integer(): return str(int(x)) return f"{x:.6g}" return str(x) # ============================================================ # 3. 伪工具执行器 # ============================================================ FAKE_NOW = "2026-09-04 16:27:31" FAKE_SEARCH_DB = { "今天北京天气": "北京今天晴,26℃,北风 3 级,空气质量良。", "英伟达最新财报": "英伟达最新季度营收同比增长约 94%,数据中心业务仍是主要增长来源。", "2026年世界杯赛程": "2026 世界杯由美加墨联合举办,小组赛将于 6 月开打。", "苹果发布会时间": "苹果通常在 9 月举行秋季新品发布会,具体日期以官方邀请函为准。", "比特币价格": "比特币价格实时波动,请以交易所行情为准。", "火星移民最新进展": "目前火星移民仍处于无人探测和载人计划论证阶段,尚无永久定居点。", "火星殖民计划 2026": "SpaceX 星舰计划在 2026 年继续推进轨道试飞,为后续载人任务积累数据。", "今天上海天气": "上海今天多云,24℃,东南风 2 级。", "特斯拉股价": "特斯拉股价实时波动,请以交易所行情为准。", "OpenAI 最新模型": "OpenAI 近期发布了新一代模型,具体能力以官方文档为准。", "华为新手机": "华为近期发布了新款手机,具体参数以官方信息为准。", "2026 年春节日期": "2026 年春节是 2 月 17 日。", "诺贝尔文学奖得主": "最近一届诺贝尔文学奖得主信息请以官方公布为准。", "巴黎奥运会金牌榜": "巴黎奥运会金牌榜以官方最终统计为准。", "日本地震最新消息": "日本地震最新消息请以气象厅和新闻机构发布为准。", "美联储利率决议": "美联储利率决议以官方声明为准。", "国产大飞机进展": "国产大飞机 C919 已进入商业运营阶段,后续进展以官方发布为准。", "比亚迪销量": "比亚迪月度销量以公司公告为准。", "新能源汽车补贴政策": "新能源汽车补贴政策以各地最新文件为准。", "今天广州天气": "广州今天雷阵雨,28℃,南风 2 级。", "世界杯预选赛比分": "世界杯预选赛比分以赛事官方结果为准。", } def fake_execute(tool_name: str, args: dict) -> str: try: if tool_name == "calculate_math": expr = args.get("expression", "") if not expr: return json.dumps({"error": "missing expression"}, ensure_ascii=False) try: value = safe_math_eval(expr) return json.dumps({"result": format_number(value)}, ensure_ascii=False) except Exception as e: return json.dumps({"error": f"invalid expression: {e}"}, ensure_ascii=False) if tool_name == "get_current_time": tz = args.get("timezone", "UTC") if not tz: return json.dumps({"error": "missing timezone"}, ensure_ascii=False) return json.dumps({"datetime": FAKE_NOW, "timezone": tz}, ensure_ascii=False) if tool_name == "search_web": query = args.get("query", "") if not query: return json.dumps({"error": "missing query"}, ensure_ascii=False) if query in FAKE_SEARCH_DB: return json.dumps({"result": FAKE_SEARCH_DB[query]}, ensure_ascii=False) for k, v in FAKE_SEARCH_DB.items(): if k in query or query in k: return json.dumps({"result": v}, ensure_ascii=False) return json.dumps({"result": ""}, ensure_ascii=False) return json.dumps({"error": f"unknown tool: {tool_name}"}, ensure_ascii=False) except Exception as e: return json.dumps({"error": str(e)}, ensure_ascii=False) # ============================================================ # 4. 消息构造器 # ============================================================ def system_msg(): return {"role": "system", "content": "", "tools": TOOLS_JSON} def user_msg(text): return {"role": "user", "content": text} def assistant_tool_call(tool_name, args, thought=None): content = thought if thought else "" return { "role": "assistant", "content": content, "tool_calls": json.dumps( [{"name": tool_name, "arguments": args}], ensure_ascii=False ) } def tool_msg(result_str): return {"role": "tool", "content": result_str} def assistant_answer(text): return {"role": "assistant", "content": text} def make_sample(conversations): return {"conversations": conversations} # ============================================================ # 5. 短 thinking 池(10~30 字,只用于调用前) # ============================================================ THINK_CALC = [ "这个需要精确计算。", "手算容易错,调计算工具。", "用计算工具算一下。", "数字较大,交给计算器。", "需要精确结果。", "这个算一下更稳妥。", ] THINK_TIME = [ "需要查实时时间。", "时间不能靠猜,查一下。", "调时间工具确认。", "需要当前时区时间。", "查一下具体时间。", ] THINK_SEARCH = [ "这是实时信息,需要搜索。", "我的知识可能过期,搜一下。", "需要最新信息。", "调搜索工具查证。", "搜一下更准确。", ] THINK_RECOVER = [ "没搜到,换个关键词试试。", "这个结果不行,换一种说法。", "刚才失败了,调整一下再试。", "没查到,缩小一下范围。", ] # ============================================================ # 6. 模板与参数池 # ============================================================ CALC_TEMPLATES = [ "帮我算一下 {expr} 等于多少", "计算 {expr}", "{expr} 是多少?", "请计算:{expr}", "算一下 {expr}", "{expr} 的结果是什么", ] CALC_EXPRS = [ "256 * 37", "125 + 379", "1024 / 8", "9999 * 8888", "123456 + 654321", "45 * 12 - 180", "789 - 456 + 123", "8642 / 14", "37 * 41 + 59 * 63", "1000000 - 987654", "2^10", "3^5", "sqrt(144)", "sqrt(2) * 100", "sqrt(1024)", "2^16", "5^3 + 4^2", "sqrt(81) + sqrt(49)", "sin(30) + cos(60)", "log10(1000)", "log10(100000)", "tan(45) * 100", "sin(90) * 50", "cos(0) + sin(90)", "3.14 * 5^2", "(12 + 8) * 7", "100 / (2 + 3)", "2 * (3 + 4)^2", "abs(-256) + 44", "floor(3.7) + ceil(2.1)", "12345 * 6789", "98765 / 5", "4321 + 8765 - 1234", "sqrt(2) + sqrt(3)", "2^8 - 2^4", "1000 / 8 + 125", "987654 * 321098", "2^20", "sin(45) + cos(45)", "123456 / 789", ] TIME_TEMPLATES = [ "现在{tz}时间是多少?", "查一下{tz}的当前时间", "{tz}现在几点了?", "告诉我{tz}的时间", "{tz}现在是什么时间", ] TIMEZONES = [ "Asia/Shanghai", "America/New_York", "Europe/London", "Asia/Tokyo", "UTC", "Europe/Paris", "Australia/Sydney", "America/Los_Angeles", "Asia/Singapore", "Asia/Seoul", "Europe/Berlin", "America/Chicago", "Asia/Dubai", "America/Sao_Paulo", "Pacific/Auckland", ] SEARCH_TEMPLATES = [ "帮我搜索一下 {query}", "查一下 {query} 的最新消息", "{query} 现在什么情况?", "搜搜看 {query}", "帮我查查 {query}", ] SEARCH_QUERIES = [ "今天北京天气", "英伟达最新财报", "2026年世界杯赛程", "苹果发布会时间", "比特币价格", "火星移民最新进展", "今天上海天气", "特斯拉股价", "OpenAI 最新模型", "华为新手机", "2026 年春节日期", "诺贝尔文学奖得主", "巴黎奥运会金牌榜", "日本地震最新消息", "美联储利率决议", "国产大飞机进展", "比亚迪销量", "新能源汽车补贴政策", "今天广州天气", "世界杯预选赛比分", ] # ============================================================ # 7. 直接回答池(不加 thinking,只学“不调工具”) # ============================================================ DIRECT_QA = [ ("你好", "你好!有什么可以帮你的?"), ("你叫什么名字", "我是一个 AI 助手。"), ("地球是圆的吗", "是的,地球是球形的。"), ("水的沸点是多少", "标准大气压下水的沸点是 100 摄氏度。"), ("1+1等于几?", "1+1 等于 2。"), ("2+3等于多少", "2+3 等于 5。"), ("今天心情不好", "听起来你有点难过,愿意说说发生了什么吗?"), ("讲个笑话", "为什么程序员总分不清万圣节和圣诞节?因为 Oct 31 等于 Dec 25。"), ("太阳从哪边升起", "太阳从东方升起。"), ("一年有多少天", "平年 365 天,闰年 366 天。"), ("中国首都是哪里", "中国首都是北京。"), ("推荐一本书", "可以试试《小王子》,短小但耐读。"), ("你是谁", "我是一个基于语言模型的 AI 助手。"), ("谢谢你", "不客气,随时可以找我。"), ("再见", "再见,祝你今天顺利。"), ("你吃饭了吗", "我不需要吃饭,不过谢谢关心。"), ("天空为什么是蓝的", "因为大气对短波长的蓝光散射更强。"), ("人为什么要睡觉", "睡眠有助于记忆巩固、免疫调节和身体恢复。"), ("猫和狗哪个更聪明", "两者智能类型不同,很难直接比较。"), ("什么是光合作用", "植物利用光能把二氧化碳和水合成有机物并释放氧气的过程。"), ("地球到月球多远", "平均约 38.4 万公里。"), ("世界上最长的河", "按长度通常认为是尼罗河,按流量是亚马逊河。"), ("1 米等于多少厘米", "1 米等于 100 厘米。"), ("水的化学式", "水的化学式是 H2O。"), ("光速是多少", "真空中光速约为每秒 30 万公里。"), ("人类有几个心脏", "正常人类只有一个心脏。"), ("一年有几个季节", "温带地区通常分为春夏秋冬四季。"), ("熊猫吃什么", "熊猫主要以竹子为食。"), ("怎么学英语", "坚持输入输出,多听多读多说多写,配合反馈。"), ("怎么减肥", "控制饮食热量、增加运动、保证睡眠,循序渐进。"), ("感冒了怎么办", "多休息多喝水,症状重或持续不缓解及时就医。"), ("怎么提高专注力", "减少干扰、拆分任务、番茄工作法、保证睡眠。"), ("为什么天空会下雨", "水汽凝结成云滴,增大后降落形成降雨。"), ("月亮为什么会变形", "因为月球绕地球公转,我们看到的受光面在变化。"), ("什么是人工智能", "让机器具备感知、学习、推理和决策能力的技术领域。"), ("什么是互联网", "全球互联的计算机网络系统。"), ("0 是偶数吗", "0 是偶数。"), ("负数有平方根吗", "在实数范围内没有,在复数范围内有。"), ("为什么会有四季", "因为地球自转轴倾斜,公转时各地获得的太阳辐射不同。"), ("海水为什么是咸的", "因为海水中溶解了大量盐类矿物质。"), ("彩虹是怎么形成的", "阳光经过水滴折射、反射和色散后形成。"), ("为什么打雷先看到闪电", "因为光速远快于声速。"), ("铁为什么会生锈", "铁与氧气和水发生氧化反应生成铁锈。"), ("什么是DNA", "DNA 是储存遗传信息的双螺旋分子。"), ("为什么叶子是绿的", "因为叶绿素主要反射绿光。"), ("人有多少根骨头", "成年人通常有 206 根骨头。"), ("为什么会有潮汐", "主要由月球和太阳的引力引起。"), ("什么是疫苗", "疫苗通过模拟病原体训练免疫系统产生保护力。"), ("为什么水会结冰", "温度降到冰点以下时水分子排列成晶体。"), ] # ============================================================ # 8. 澄清 / 无工具 / 过度拒绝 / 错误恢复 # ============================================================ CLARIFY_CASES = [ ("帮我算一下", "好的,请问要计算什么表达式?比如 256*37。"), ("计算一下这个", "可以,请把要计算的数学表达式发给我。"), ("现在几点了?", "请问您想查询哪个时区的时间?比如 Asia/Shanghai。"), ("帮我查一下时间", "没问题,请告诉我具体时区,比如 UTC 或 Asia/Tokyo。"), ("帮我搜一下", "好的,请问想搜索什么关键词?"), ("查一下新闻", "可以,请告诉我具体想查哪方面的新闻。"), ("算个数学题", "可以,请把题目或表达式发给我。"), ("我想知道现在的时间", "请问您想查询哪个城市或时区的时间?"), ("搜个东西", "好的,请告诉我要搜索的关键词。"), ("帮我算算", "没问题,请给出具体的计算式。"), ("查一下天气", "请问要查哪个城市的天气?"), ("现在那边几点", "请问“那边”指的是哪个时区或城市?"), ("帮我查个资料", "可以,请告诉我具体想查的主题或关键词。"), ("算一下这个数", "好的,请把具体的数字或表达式发给我。"), ] NO_TOOL_CASES = [ ("帮我订一张明天去上海的机票", "抱歉,我暂时没有订票工具,无法帮你直接下单。你可以通过航空公司官网或订票平台操作。"), ("帮我把这封邮件发给老板", "抱歉,我暂时没有发送邮件的工具。你可以复制内容到邮箱中发送。"), ("帮我打开空调", "抱歉,我暂时没有控制家电的工具,无法直接操作空调。"), ("帮我叫一辆出租车", "抱歉,我暂时没有叫车工具。你可以使用打车软件下单。"), ("帮我设置一个明天早上 7 点的闹钟", "抱歉,我暂时没有闹钟工具,无法直接设置。你可以在手机时钟里添加。"), ("帮我转账 500 块给张三", "抱歉,我暂时没有支付或转账工具,无法执行资金操作。"), ("帮我把这张图片修一下", "抱歉,我暂时没有图像编辑工具,无法直接修改图片。"), ("帮我播放一首歌", "抱歉,我暂时没有音乐播放工具,无法直接播放。"), ("帮我订一份外卖", "抱歉,我暂时没有外卖下单工具,你可以通过外卖平台操作。"), ("帮我关灯", "抱歉,我暂时没有智能家居控制工具,无法直接关灯。"), ("帮我查一下我的快递到哪了", "抱歉,我暂时没有快递查询工具,建议用快递 App 或官网查询。"), ("帮我把这段文字翻译成日语并朗读", "我可以翻译文字,但暂时没有语音朗读工具。"), ("帮我预约明天上午的牙医", "抱歉,我暂时没有预约工具,建议直接联系诊所。"), ("帮我把电脑关机", "抱歉,我暂时没有系统控制权限,无法直接关机。"), ] OVER_REFUSAL_CASES = [ ("帮我精确算一下 987654 * 321098", "calculate_math", {"expression": "987654 * 321098"}), ("sqrt(2) 大约是多少", "calculate_math", {"expression": "sqrt(2)"}), ("现在纽约时间是多少", "get_current_time", {"timezone": "America/New_York"}), ("帮我查查今天北京天气", "search_web", {"query": "今天北京天气"}), ("2 的 20 次方是多少", "calculate_math", {"expression": "2^20"}), ("sin(45) 加 cos(45) 等于多少", "calculate_math", {"expression": "sin(45) + cos(45)"}), ("东京现在几点", "get_current_time", {"timezone": "Asia/Tokyo"}), ("伦敦现在是什么时间", "get_current_time", {"timezone": "Europe/London"}), ("帮我搜一下特斯拉股价", "search_web", {"query": "特斯拉股价"}), ("查一下 OpenAI 最新模型", "search_web", {"query": "OpenAI 最新模型"}), ("123456 除以 789 等于多少", "calculate_math", {"expression": "123456 / 789"}), ("悉尼现在几点", "get_current_time", {"timezone": "Australia/Sydney"}), ] # ============================================================ # 9. 样本生成器 # ============================================================ def _final_for_calc(result): try: value = json.loads(result).get("result", "") return f"结果是 {value}。" except Exception: return "抱歉,这个表达式我没算出来。" def _final_for_time(result): try: d = json.loads(result) return f"当前时间是 {d['datetime']}({d['timezone']})。" except Exception: return "抱歉,时间查询失败了。" def _final_for_search(result): try: d = json.loads(result) if d.get("result"): return f"我查到:{d['result']}" return "抱歉,没有搜到相关信息。" except Exception: return "抱歉,搜索失败了。" def gen_calc_sample(rng, with_thought=False): tmpl = rng.choice(CALC_TEMPLATES) expr = rng.choice(CALC_EXPRS) user_text = tmpl.format(expr=expr) args = {"expression": expr} result = fake_execute("calculate_math", args) final = _final_for_calc(result) thought = rng.choice(THINK_CALC) if with_thought else None return make_sample([ system_msg(), user_msg(user_text), assistant_tool_call("calculate_math", args, thought), tool_msg(result), assistant_answer(final), ]) def gen_time_sample(rng, with_thought=False): tmpl = rng.choice(TIME_TEMPLATES) tz = rng.choice(TIMEZONES) user_text = tmpl.format(tz=tz) args = {"timezone": tz} result = fake_execute("get_current_time", args) final = _final_for_time(result) thought = rng.choice(THINK_TIME) if with_thought else None return make_sample([ system_msg(), user_msg(user_text), assistant_tool_call("get_current_time", args, thought), tool_msg(result), assistant_answer(final), ]) def gen_search_sample(rng, with_thought=False): tmpl = rng.choice(SEARCH_TEMPLATES) query = rng.choice(SEARCH_QUERIES) user_text = tmpl.format(query=query) args = {"query": query} result = fake_execute("search_web", args) final = _final_for_search(result) thought = rng.choice(THINK_SEARCH) if with_thought else None return make_sample([ system_msg(), user_msg(user_text), assistant_tool_call("search_web", args, thought), tool_msg(result), assistant_answer(final), ]) def gen_direct_sample(rng): q, a = rng.choice(DIRECT_QA) return make_sample([ system_msg(), user_msg(q), assistant_answer(a), ]) def gen_clarify_sample(rng): q, a = rng.choice(CLARIFY_CASES) return make_sample([ system_msg(), user_msg(q), assistant_answer(a), ]) def gen_no_tool_sample(rng): q, a = rng.choice(NO_TOOL_CASES) return make_sample([ system_msg(), user_msg(q), assistant_answer(a), ]) def gen_over_refusal_sample(rng, with_thought=False): user_text, tool_name, args = rng.choice(OVER_REFUSAL_CASES) result = fake_execute(tool_name, args) if tool_name == "calculate_math": final = _final_for_calc(result) elif tool_name == "get_current_time": final = _final_for_time(result) else: final = _final_for_search(result) if with_thought: pool = { "calculate_math": THINK_CALC, "get_current_time": THINK_TIME, "search_web": THINK_SEARCH, }[tool_name] thought = rng.choice(pool) else: thought = None return make_sample([ system_msg(), user_msg(user_text), assistant_tool_call(tool_name, args, thought), tool_msg(result), assistant_answer(final), ]) def gen_error_recovery_sample(rng, with_thought=False): q1 = "查一下火星移民最新进展" args1 = {"query": "火星移民最新进展"} r1 = json.dumps({"result": ""}, ensure_ascii=False) q2 = "火星殖民计划 2026" args2 = {"query": "火星殖民计划 2026"} r2 = fake_execute("search_web", args2) final = _final_for_search(r2) thought = rng.choice(THINK_RECOVER) if with_thought else None return make_sample([ system_msg(), user_msg(q1), assistant_tool_call("search_web", args1, thought), tool_msg(r1), assistant_tool_call("search_web", args2), tool_msg(r2), assistant_answer(final), ]) def gen_tool_error_recovery_sample(rng, with_thought=False): args1 = {"expression": "12 / 0"} r1 = json.dumps({"error": "invalid expression: division by zero"}, ensure_ascii=False) args2 = {"expression": "12 / 3"} r2 = fake_execute("calculate_math", args2) try: value = json.loads(r2).get("result", "") final = f"刚才那个表达式除数为 0,换成 12 / 3 后结果是 {value}。" except Exception: final = "抱歉,还是没算出来。" thought = "这个表达式有问题,换一个试试。" if with_thought else None return make_sample([ system_msg(), user_msg("帮我算一下 12 除以 0"), assistant_tool_call("calculate_math", args1, thought), tool_msg(r1), assistant_tool_call("calculate_math", args2), tool_msg(r2), assistant_answer(final), ]) # ============================================================ # 10. 主流程:约 1000 条,去重,短 thinking 约 20% # ============================================================ def _user_text(sample): for c in sample["conversations"]: if c["role"] == "user": return c["content"] return None def build_dataset(seed=42, out_path="sft_toolcall_synthetic.jsonl"): rng = random.Random(seed) samples = [] seen = set() # 只对 calc/time/search 的 user 文本去重 plan = [ # (name, count, with_thought) ("direct", 340, False), ("calc_plain", 120, False), ("calc_thought", 60, True), ("time_plain", 60, False), ("time_thought", 30, True), ("search_plain", 50, False), ("search_thought", 40, True), ("clarify", 80, False), ("no_tool", 70, False), ("over_plain", 40, False), ("over_thought", 30, True), ("error_recovery", 80, None), # 一半带 thinking ] def add(sample, key=None): if key is not None: if key in seen: return False seen.add(key) samples.append(sample) return True for name, count, with_thought in plan: added = 0 attempts = 0 max_attempts = count * 20 while added < count and attempts < max_attempts: attempts += 1 if name == "direct": s = gen_direct_sample(rng) add(s) # direct 不去重 elif name == "calc_plain": s = gen_calc_sample(rng, with_thought=False) if not add(s, _user_text(s)): continue elif name == "calc_thought": s = gen_calc_sample(rng, with_thought=True) if not add(s, _user_text(s)): continue elif name == "time_plain": s = gen_time_sample(rng, with_thought=False) if not add(s, _user_text(s)): continue elif name == "time_thought": s = gen_time_sample(rng, with_thought=True) if not add(s, _user_text(s)): continue elif name == "search_plain": s = gen_search_sample(rng, with_thought=False) if not add(s, _user_text(s)): continue elif name == "search_thought": s = gen_search_sample(rng, with_thought=True) if not add(s, _user_text(s)): continue elif name == "clarify": add(gen_clarify_sample(rng)) elif name == "no_tool": add(gen_no_tool_sample(rng)) elif name == "over_plain": add(gen_over_refusal_sample(rng, with_thought=False)) elif name == "over_thought": add(gen_over_refusal_sample(rng, with_thought=True)) elif name == "error_recovery": if rng.random() < 0.5: add(gen_error_recovery_sample(rng, with_thought=(rng.random() < 0.5))) else: add(gen_tool_error_recovery_sample(rng, with_thought=(rng.random() < 0.5))) added += 1 if added < count: print(f"[warn] {name}: 目标 {count},实际 {added},池子可能不够大") rng.shuffle(samples) out_path = Path(out_path) out_path.parent.mkdir(parents=True, exist_ok=True) with out_path.open("w", encoding="utf-8") as f: for s in samples: f.write(json.dumps(s, ensure_ascii=False) + "\n") # 统计 stats = {} thought_count = 0 for s in samples: roles = [c["role"] for c in s["conversations"]] key = " -> ".join(roles) stats[key] = stats.get(key, 0) + 1 for c in s["conversations"]: if c["role"] == "assistant" and c.get("content") and c.get("tool_calls"): thought_count += 1 break print(f"已生成 {len(samples)} 条 -> {out_path}") print(f"带短 thinking 的样本数:{thought_count}(约 {thought_count/len(samples)*100:.1f}%)") print("消息结构分布:") for k, v in sorted(stats.items(), key=lambda x: -x[1]): print(f" {v:4d} {k}") return samples if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--out", default="sft_toolcall_synthetic.jsonl") parser.add_argument("--seed", type=int, default=42) args = parser.parse_args() build_dataset(seed=args.seed, out_path=args.out)