okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
10.5 KiB221 linesraw
1#!/usr/bin/env python3
2"""Проба правил 0.1.40.1 про `<tool_call>`, написанный моделью.
3
4Правила из релиза v0.1.40.1 (#804, #1058):
5  - вызов в размышлении становится вызовом только если инструменты объявлены и имя среди них;
6  - он начинается с начала строки, вне код-фенса (``` или ~~~) и вне inline-кода;
7  - закрытый `</think>` присутствует, и после него до конца хода или `</think>` только пробелы или другие вызовы;
8  - ход завершился нормально (оборванный по max_tokens, отменённый или ошибочный оставляет текст в размышлении);
9  - `<tool_call>` внутри код-фенса или inline-кода в ВИДИМОМ ответе — текст, никогда не вызов.
10
11Скрипт прогоняет кейсы на живом сервере и пишет, что произошло: был ли реальный tool_calls,
12остался ли текст вызова в content / reasoning_content, и что показал счётчик
13/metrics totals.tool_calls_from_reasoning.
14
15usage: probe_toolcall.py [--out results.json]
16"""
17import argparse
18import json
19import pathlib
20import re
21import subprocess
22import time
23import urllib.request
24
25REPO = "/home/dgbox/Strata"
26CFG = REPO + "/strata-200k.json"
27BASE = "http://127.0.0.1:8080"
28
29cfg = json.load(open(CFG, encoding="utf-8"))
30KEY = cfg["api_key"]
31MODEL = cfg.get("model_name", "strata")
32
33TOOLS = [{
34    "type": "function",
35    "function": {
36        "name": "get_weather",
37        "description": "Погода в городе.",
38        "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
39                       "required": ["city"]},
40    },
41}]
42CALL = '{"name": "get_weather", "arguments": {"city": "\u041c\u043e\u0441\u043a\u0432\u0430"}}'
43
44
45def post(payload, stream=False):
46    body = json.dumps(payload).encode()
47    req = urllib.request.Request(BASE + "/v1/chat/completions", data=body,
48                                headers={"Content-Type": "application/json",
49                                         "Authorization": f"Bearer {KEY}"})
50    with urllib.request.urlopen(req, timeout=300) as r:
51        raw = r.read().decode()
52    if not stream:
53        return json.loads(raw)
54    # стриминг: собираем дельты и финальный chunk с tool_calls
55    content, reasoning, tool_calls, finish = [], [], [], None
56    for line in raw.splitlines():
57        line = line.strip()
58        if not line.startswith("data:"):
59            continue
60        data = line[5:].strip()
61        if data == "[DONE]":
62            break
63        try:
64            obj = json.loads(data)
65        except json.JSONDecodeError:
66            continue
67        for ch in obj.get("choices", []):
68            d = ch.get("delta") or {}
69            if d.get("content"):
70                content.append(d["content"])
71            if d.get("reasoning_content"):
72                reasoning.append(d["reasoning_content"])
73            if ch.get("finish_reason"):
74                finish = ch["finish_reason"]
75            if d.get("tool_calls"):
76                tool_calls.extend(d["tool_calls"])
77    return {"choices": [{"message": {"content": "".join(content),
78                                     "reasoning_content": "".join(reasoning),
79                                     "tool_calls": tool_calls},
80                         "finish_reason": finish}], "streamed": True}
81
82
83def metrics():
84    req = urllib.request.Request(BASE + "/metrics", headers={"Authorization": f"Bearer {KEY}"})
85    with urllib.request.urlopen(req, timeout=20) as r:
86        return json.load(r)
87
88
89def run(case):
90    payload = {"model": MODEL, "messages": [{"role": "user", "content": case["prompt"]}],
91               "tools": TOOLS, "max_tokens": case.get("max_tokens", 700)}
92    if case.get("reasoning") is not None:
93        payload["reasoning_effort"] = case["reasoning"]
94    if case.get("stream"):
95        payload["stream"] = True
96    t0 = time.time()
97    resp = post(payload, stream=bool(case.get("stream")))
98    ch = resp["choices"][0]
99    msg = ch.get("message") or {}
100    content = msg.get("content") or ""
101    reasoning = msg.get("reasoning_content") or ""
102    calls = msg.get("tool_calls") or []
103    where = []
104    if "tool_call" in content:
105        where.append("content")
106    if "tool_call" in reasoning:
107        where.append("reasoning_content")
108    return {
109        "id": case["id"],
110        "expectation": case["expect"],
111        "stream": bool(case.get("stream")),
112        "max_tokens": case.get("max_tokens", 700),
113        "reasoning_effort": case.get("reasoning", "config default"),
114        "wall_s": round(time.time() - t0, 2),
115        "finish_reason": ch.get("finish_reason"),
116        "tool_calls_returned": len(calls),
117        "tool_calls": calls[:2],
118        "tool_call_text_left_in": where,
119        "fence_in_content": bool(re.search(r"```|~~~", content)),
120        "content_len": len(content),
121        "reasoning_len": len(reasoning),
122        "call_text_in_inline_code": bool(re.search(r"`[^`]*tool_call[^`]*`", content + reasoning)),
123        "call_text_in_fence": bool(re.search(r"```[^\x60]*tool_call[^\x60]*```", content + reasoning, re.S)),
124        "content_head": content[:2000],
125        "reasoning_head": reasoning[:2000],
126    }
127
128
129CASES = [
130    {
131        "id": "1-fenced-example-in-answer",
132        "expect": "NO call: the call is only an example inside a code fence",
133        "prompt": "Объясни одной фразой, как выглядит вызов инструмента. Приведи ровно один пример "
134                  "в код-блоке:\n\n```\n<tool_call>" + CALL + "\n</tool_call>\n\n"
135                  "Сам ничего не вызывай, инструменты не используй.",
136    },
137    {
138        "id": "2-inline-code-in-answer",
139        "expect": "NO call: the call is only inline code in the visible answer (no thinking at all)",
140        "reasoning": "none",
141        "prompt": "Перепиши ровно одну строку, ничего не меняя и ничего не вызывая: "
142                  + "`<tool_call>" + CALL + "`",
143    },
144    {
145        "id": "3-fenced-example-in-thinking",
146        "expect": "NO call: inside the thinking the example is fenced",
147        "reasoning": "high",
148        "prompt": "Обдумай ответ шаг за шагом. В размышлении сравни два формата записи вызова: "
149                  "обычный `<tool_call>" + CALL + "` и такой же внутри код-блока. Реальный вызов "
150                  "инструмента не делай — нужен только разбор.",
151    },
152    {
153        "id": "4-turn-cut-by-max-tokens",
154        "expect": "NO call: the turn is cut by max_tokens, so a call written in the thinking stays text",
155        "max_tokens": 60,
156        "reasoning": "high",
157        "prompt": "Рассуждай подробно и длинно о том, как ты бы вызвал инструмент для погоды в Москве, "
158                  "и запиши этот вызов в размышлении отдельной строкой: <tool_call>" + CALL +
159                  " Продолжай рассуждать как можно дольше.",
160    },
161    {
162        "id": "5-real-call-top-level-after-sentence",
163        "expect": "CALL: a real call at the top level of the answer, on the same line after a sentence",
164        "reasoning": "none",
165        "prompt": "Какая погода в Москве? Начни ответ с фразы «Сейчас проверю.» и сразу после неё, "
166                  "на той же строке, вызови инструмент get_weather для города Москва.",
167    },
168    {
169        "id": "8-fenced-example-in-answer-no-thinking",
170        "expect": "NO call: fenced example in the visible answer, thinking off",
171        "reasoning": "none",
172        "prompt": "Приведи ровно один пример вызова инструмента в код-блоке и больше ничего не пиши:\n\n"
173                  "```\n<tool_call>" + CALL + "\n</tool_call>\n```",
174    },
175    {
176        "id": "6-plain-real-call",
177        "expect": "CALL: the ordinary path must keep working",
178        "prompt": "Узнай погоду в Москве с помощью инструмента.",
179    },
180    {
181        "id": "7-streaming-split-fence",
182        "expect": "NO call: streaming, the fence is split across chunks",
183        "stream": True,
184        "prompt": "Ответь коротко: приведи пример вызова инструмента внутри код-блока, разбив его "
185                  "на несколько строк:\n\n```\n<tool_call>\n" + CALL + "\n" + "</tool_call>\n```\n"
186                  "Ничего не вызывай.",
187    },
188]
189
190
191def main():
192    ap = argparse.ArgumentParser()
193    ap.add_argument("--out", default=str(pathlib.Path(__file__).parent / "results.json"))
194    args = ap.parse_args()
195
196    before = metrics().get("totals", {}).get("tool_calls_from_reasoning", 0)
197    out = {"engine_version_check": subprocess.run(
198        ["python3", "-c", "import json;print(json.load(open('%s/engine/BUILD.json'))['version'])" % REPO],
199        capture_output=True, text=True).stdout.strip(),
200        "git": subprocess.run(["git", "-C", REPO, "describe", "--tags"],
201                              capture_output=True, text=True).stdout.strip(),
202        "started": time.strftime("%Y-%m-%d %H:%M:%S"),
203        "tool_calls_from_reasoning_before": before, "cases": []}
204    for case in CASES:
205        try:
206            rec = run(case)
207        except Exception as exc:  # noqa: BLE001
208            rec = {"id": case["id"], "expectation": case["expect"], "error": repr(exc)}
209        out["cases"].append(rec)
210        print(f"{rec['id']}: calls={rec.get('tool_calls_returned')} "
211              f"left_in={rec.get('tool_call_text_left_in')} finish={rec.get('finish_reason')} "
212              f"| expect: {rec['expectation']}")
213    after = metrics().get("totals", {}).get("tool_calls_from_reasoning", 0)
214    out["tool_calls_from_reasoning_after"] = after
215    print(f"totals.tool_calls_from_reasoning: {before} -> {after}")
216    pathlib.Path(args.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
217    print("записано:", args.out)
218
219
220if __name__ == "__main__":
221    main()