File size: 6,065 Bytes
7ff93da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""繁體中文推理鏈(think)生成:依工具、參數與干擾項組出 CoT。"""
import json

from param_zh import label

OPEN = [
    "好的,我來拆解這個需求。使用者想{intent},",
    "先看清楚使用者要什麼。這題是要{intent},",
    "使用者的問題是{intent}。",
    "讓我理一下。需求是{intent},",
    "這個請求的重點在於{intent},",
    "收到,使用者需要的是{intent}。",
]

PICK_ONE = [
    "目前只有一個可用函式 `{tool}`,功能描述正好對應這個需求,所以直接用它。",
    "工具清單裡只提供了 `{tool}`,其用途與此需求相符,選它沒有問題。",
    "可用函式只有 `{tool}` 一個,先確認它的描述確實涵蓋這個情境——是的,可以使用。",
]

PICK_MANY = [
    "工具清單裡有 {n} 個函式,其中 {others} 分別處理{other_domains},跟這題無關;只有 `{tool}` 的描述對應{purpose},所以選它。",
    "先排除不相干的選項:{others} 是{other_domains}用的,都不符合。剩下 `{tool}` 才是處理{purpose}的函式。",
    "共有 {n} 個候選函式。{others} 的功能與本題情境不符,正確的是 `{tool}`,因為它就是用來{purpose}的。",
    "掃過 {n} 個工具後,{others} 明顯屬於其他業務範疇;`{tool}` 才是負責{purpose}的那一個,就用它。",
]

PICK_SECOND = [
    "使用者在後半段還問了另一件事——{intent2},那要另外呼叫 `{tool2}`。",
    "另外,題目後半是{intent2},這部分得靠 `{tool2}` 處理,不能硬塞進前一個函式。",
    "問題其實包了兩個不同的需求;第二段要{intent2},對應的是 `{tool2}`。",
]

ARG_LEAD = [
    "接著逐一對應參數:",
    "然後把使用者給的條件填進參數:",
    "參數的部分這樣對:",
    "把題目資訊映射到函式參數:",
    "接下來確認每個參數要帶什麼:",
]

ARG_LEAD_N = [
    "`{tool}` 的參數這樣填:",
    "至於 `{tool}`,參數對應如下:",
    "再看 `{tool}` 這一組:",
]

ARG_LINE = [
    "`{k}` 就是{desc},這裡填 {v}。",
    "`{k}`({desc})帶 {v}。",
    "{desc}對應到 `{k}`,值是 {v}。",
    "`{k}` 設為 {v},也就是題目說的{desc}。",
]

TYPE_NOTE = [
    "注意 `{k}` 的型別是 {t},不要寫成字串。",
    "`{k}` 要用 {t} 型別傳入。",
    "型別上 `{k}` 是 {t},格式別弄錯。",
]

MULTI = [
    "使用者一次問了 {n} 個情境,所以要輸出 {n} 次呼叫,各自帶不同參數。",
    "這題有 {n} 組條件要比較,必須分成 {n} 個獨立的函式呼叫。",
    "因為要對照 {n} 種情況,我會產生 {n} 個 tool_call,而不是把值塞在同一次呼叫裡。",
]

CLOSE = [
    "最後只要輸出純 JSON 的函式呼叫,不加任何多餘說明或 Markdown。",
    "確認 JSON 格式正確、引號與逗號都沒漏,然後直接回傳呼叫內容。",
    "所有參數都有明確來源,沒有需要臆測的值,可以輸出了。",
    "格式上以 tool_call 包住 JSON 物件,不要額外加解釋文字。",
    "檢查一遍沒有遺漏必要參數,就照 schema 回傳。",
]

DOMAIN_ZH = {
    "securities": "台股交易", "tax": "稅務試算", "pension": "勞健保與退休金",
    "banking": "銀行存放款", "funds": "基金與 ETF", "fx": "外匯", "bond": "債券與利率",
    "compliance": "法令遵循", "credit": "信用與授信", "planning": "財務規劃",
    "knowledge": "金融知識查詢",
}


def _fmt_val(v):
    if isinstance(v, bool):
        return "true" if v else "false"
    if isinstance(v, str):
        return '"%s"' % v
    if isinstance(v, list):
        return json.dumps(v, ensure_ascii=False)
    return str(v)


def _arg_para(rng, tool, call, lead):
    out = [lead]
    params = tool["spec"]["parameters"]
    for k, v in call["arguments"].items():
        out.append(rng.choice(ARG_LINE).format(
            k=k, desc=label(tool["name"], k), v=_fmt_val(v)))
    tricky = [k for k in call["arguments"] if params[k]["type"] in ("bool", "float", "int", "list")]
    if tricky and rng.random() < 0.55:
        k = rng.choice(tricky)
        out.append(rng.choice(TYPE_NOTE).format(k=k, t=params[k]["type"]))
    return "".join(out)


def build_think(rng, groups, all_tools, intents):
    """groups: [(tool, [call, ...]), ...],第一組為主要工具。"""
    main, main_calls = groups[0]
    intent, purpose = intents[main["name"]]
    n_calls = sum(len(c) for _, c in groups)

    p1 = [rng.choice(OPEN).format(intent=intent)]
    others = [t for t in all_tools if t["name"] not in {g[0]["name"] for g in groups}]
    if others:
        od = sorted({DOMAIN_ZH.get(t["domain"], "其他") for t in others})
        p1.append(rng.choice(PICK_MANY).format(
            n=len(all_tools), tool=main["name"], purpose=purpose,
            others="、".join("`%s`" % t["name"] for t in others[:3]),
            other_domains="、".join(od[:3]),
        ))
    else:
        p1.append(rng.choice(PICK_ONE).format(tool=main["name"]))

    if len(groups) > 1:
        second = groups[1][0]
        p1.append(rng.choice(PICK_SECOND).format(
            intent2=intents[second["name"]][0], tool2=second["name"]))
    elif n_calls > 1:
        p1.append(rng.choice(MULTI).format(n=n_calls))
    para = ["".join(p1)]

    para.append(_arg_para(rng, main, main_calls[0], rng.choice(ARG_LEAD)))
    if len(main_calls) > 1:
        para.append(_arg_para(rng, main, main_calls[1],
                              "第二組條件則是:"))
    for tool, calls in groups[1:]:
        para.append(_arg_para(rng, tool, calls[0],
                              rng.choice(ARG_LEAD_N).format(tool=tool["name"])))

    facts = list(main["facts"])
    for tool, _ in groups[1:]:
        facts += tool["facts"]
    if facts and rng.random() < 0.85:
        para.append("另外要記住的規則:" + rng.choice(facts))

    para.append(rng.choice(CLOSE))
    return "\n\n".join(para)