Simon-Liu's picture
Add tw-finance-function-call-reasoning (research-only, CC BY-NC 4.0)
7ff93da verified
Raw History Blame Contribute Delete
8.28 kB
# -*- coding: utf-8 -*-
"""資料集品質驗證。
檢查項目:
1. 欄位與型別是否對齊 twinkle-ai/tw-function-call-reasoning-10k
2. answer 是否為合法 JSON,且呼叫的函式都在 tools 清單內
3. 參數名稱是否都存在於該函式的 schema
4. messages 三段是否與 query_zhtw / think / answer 完全一致(可還原)
5. 參數值是否「有據可循」——能在題目文字裡找到來源,而非模型臆測
6. train / test 是否有完全重複的樣本
"""
import json
import re
import sys
from collections import Counter
SCHEMA = ["id", "query", "tools", "query_zhtw", "think", "answer", "messages"]
TYPES = {"id": int, "query": str, "tools": str, "query_zhtw": str,
"think": str, "answer": str, "messages": list}
# enum 參數在題目中常以中文表達,驗證溯源時需一併認列
ENUM_ZH = {
"standard": "標準扣除額", "itemized": "列舉扣除額",
"single": "單身", "married_joint": "夫妻合併申報",
"fixed": "固定利率", "floating": "機動利率",
"simple": "單利存本取息", "monthly_compound": "整存整付按月複利",
"equal_total": "本息平均攤還", "equal_principal": "本金平均攤還",
"income_replacement": "所得替代法", "needs_based": "需求分析法",
"stable": "穩定", "moderate": "普通", "volatile": "不穩定",
"mortgage_application": "房貸申請", "credit_card_application": "信用卡申請",
"self_inquiry": "本人查詢", "personal_loan": "信用貸款",
"buy": "買進", "sell": "賣出",
"stock": "股票", "etf": "股票型ETF", "warrant": "權證", "corporate_bond_etf": "債券型ETF",
"dividend": "股利", "bonus": "年終獎金", "rent": "租金",
"professional_fee": "執行業務所得", "part_time_salary": "兼職薪資", "interest": "利息",
"cash_buy": "現金買入", "cash_sell": "現金賣出",
"spot_buy": "即期買入", "spot_sell": "即期賣出",
"rediscount": "重貼現率", "accommodations_with_collateral": "擔保放款融通利率",
"accommodations_without_collateral": "短期融通利率",
"monthly": "月配", "quarterly": "季配", "semiannual": "半年配",
"cash_deposit": "現金存入", "cash_withdrawal": "現金提領",
"wire_transfer": "電匯", "fx_exchange": "結匯",
"individual": "自然人", "corporate": "法人", "trust": "信託",
"beginner": "完全新手", "intermediate": "有基礎", "professional": "從業人員",
"TAIEX": "台股加權指數", "TPEx": "櫃買指數", "TWSE50": "台灣50指數",
"TAIEX_TR": "發行量加權股價報酬指數", "FITX": "台指期近月",
"USD": "美元", "JPY": "日圓", "EUR": "歐元", "CNY": "人民幣",
"AUD": "澳幣", "HKD": "港幣", "GBP": "英鎊", "KRW": "韓元",
"zh-TW": "繁體中文", "close": "收盤", "change_pct": "漲跌",
"open": "開", "high": "高", "low": "低", "volume": "量",
}
def load(p):
with open(p, encoding="utf-8") as f:
return [json.loads(l) for l in f if l.strip()]
def grounded(val, text):
"""參數值是否能在題目文字中找到來源(容許萬元、百分比等常見換算)。"""
if isinstance(val, bool):
return True # 布林多由中文語意表達(如「當沖」「自住」),另由模板保證
if isinstance(val, (int, float)) and not isinstance(val, bool):
s = ("%g" % val)
cands = {s, str(val), "%g" % abs(val)}
if isinstance(val, int):
if val % 10000 == 0:
cands.add(str(val // 10000))
cands.add("{:,}".format(val))
else:
cands.add("%g" % (val * 100))
return any(c in text for c in cands)
if isinstance(val, str):
return val in text or ENUM_ZH.get(val, "\x00") in text
if isinstance(val, list):
return all(grounded(v, text) for v in val)
return True
def check(rows, name, errors, stats):
for r in rows:
rid = r.get("id", "?")
if list(r.keys()) != SCHEMA:
errors.append("%s#%s 欄位不符:%s" % (name, rid, list(r.keys())))
continue
for k, t in TYPES.items():
if not isinstance(r[k], t):
errors.append("%s#%s 欄位 %s 型別應為 %s" % (name, rid, k, t.__name__))
try:
tools = json.loads(r["tools"])
calls = json.loads(r["answer"])
except Exception as e:
errors.append("%s#%s JSON 解析失敗:%s" % (name, rid, e))
continue
tmap = {t["name"]: t for t in tools}
for c in calls:
if c["name"] not in tmap:
errors.append("%s#%s 呼叫了不在 tools 清單的函式 %s" % (name, rid, c["name"]))
continue
params = tmap[c["name"]]["parameters"]
for k, v in c["arguments"].items():
if k not in params:
errors.append("%s#%s 參數 %s 不在 %s 的 schema" % (name, rid, k, c["name"]))
stats["args_total"] += 1
if grounded(v, r["query_zhtw"] + " " + r["query"]):
stats["args_grounded"] += 1
else:
stats["ungrounded"].append((rid, c["name"], k, v))
m = r["messages"]
if len(m) != 3 or [x["role"] for x in m] != ["system", "user", "assistant"]:
errors.append("%s#%s messages 結構不是 system/user/assistant" % (name, rid))
continue
if m[1]["content"] != r["query_zhtw"]:
errors.append("%s#%s messages[1] 與 query_zhtw 不一致" % (name, rid))
if r["think"] not in m[2]["content"]:
errors.append("%s#%s think 未出現在 assistant 訊息" % (name, rid))
found = re.findall(r"<tool_call>\n(.*?)\n</tool_call>", m[2]["content"], re.S)
if len(found) != len(calls):
errors.append("%s#%s tool_call 數量(%d)與 answer(%d)不符"
% (name, rid, len(found), len(calls)))
else:
for got, want in zip(found, calls):
if json.loads(got) != want:
errors.append("%s#%s tool_call 內容與 answer 不一致" % (name, rid))
for t in tools:
if ('"%s"' % t["name"]) not in m[0]["content"]:
errors.append("%s#%s system 訊息缺少工具 %s" % (name, rid, t["name"]))
stats["calls"] += len(calls)
stats["tools_offered"] += len(tools)
def main():
tr = load(sys.argv[1] if len(sys.argv) > 1 else "data/train.jsonl")
te = load(sys.argv[2] if len(sys.argv) > 2 else "data/test.jsonl")
errors = []
stats = Counter()
stats["ungrounded"] = []
check(tr, "train", errors, stats)
check(te, "test", errors, stats)
ids = [r["id"] for r in tr + te]
if len(set(ids)) != len(ids):
errors.append("id 有重複")
tr_keys = {(r["query_zhtw"], r["answer"]) for r in tr}
dup = [r["id"] for r in te if (r["query_zhtw"], r["answer"]) in tr_keys]
if dup:
errors.append("test 有 %d 筆與 train 完全重複:%s" % (len(dup), dup[:10]))
n = len(tr) + len(te)
print("=" * 66)
print("資料集驗證報告")
print("=" * 66)
print("train / test : %d / %d (%.1f%% : %.1f%%)"
% (len(tr), len(te), 100 * len(tr) / n, 100 * len(te) / n))
print("函式呼叫總數 : %d(平均每題 %.2f 次)" % (stats["calls"], stats["calls"] / n))
print("平均提供工具數 : %.2f" % (stats["tools_offered"] / n))
print("參數溯源率 : %d/%d = %.2f%%"
% (stats["args_grounded"], stats["args_total"],
100 * stats["args_grounded"] / max(1, stats["args_total"])))
print("train/test 完全重複 : %d 筆" % len(dup))
print("-" * 66)
if stats["ungrounded"]:
print("題目中找不到來源的參數(前 10 筆):")
for u in stats["ungrounded"][:10]:
print(" #%s %s.%s = %r" % u)
print()
if errors:
print("發現 %d 項錯誤:" % len(errors))
for e in errors[:25]:
print(" x", e)
sys.exit(1)
print("結果:通過,無結構性錯誤。")
if __name__ == "__main__":
main()