okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
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 ): 46body = json .dumps (payload ).encode () 47req = urllib .request .Request (BASE + "/v1/chat/completions" ,data = body , 48headers = {"Content-Type" :"application/json" , 49"Authorization" :f"Bearer { KEY } " }) 50with urllib .request .urlopen (req ,timeout = 300 )as r : 51raw = r .read ().decode () 52if not stream : 53return json .loads (raw ) 54# стриминг: собираем дельты и финальный chunk с tool_calls 55content ,reasoning ,tool_calls ,finish = [], [], [],None 56for line in raw .splitlines (): 57line = line .strip () 58if not line .startswith ("data:" ): 59continue 60data = line [5 :].strip () 61if data == "[DONE]" : 62break 63try : 64obj = json .loads (data ) 65except json .JSONDecodeError : 66continue 67for ch in obj .get ("choices" , []): 68d = ch .get ("delta" )or {} 69if d .get ("content" ): 70content .append (d ["content" ]) 71if d .get ("reasoning_content" ): 72reasoning .append (d ["reasoning_content" ]) 73if ch .get ("finish_reason" ): 74finish = ch ["finish_reason" ] 75if d .get ("tool_calls" ): 76tool_calls .extend (d ["tool_calls" ]) 77return {"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 (): 84req = urllib .request .Request (BASE + "/metrics" ,headers = {"Authorization" :f"Bearer { KEY } " }) 85with urllib .request .urlopen (req ,timeout = 20 )as r : 86return json .load (r ) 87 88 89def run (case ): 90payload = {"model" :MODEL ,"messages" : [{"role" :"user" ,"content" :case ["prompt" ]}], 91"tools" :TOOLS ,"max_tokens" :case .get ("max_tokens" ,700 )} 92if case .get ("reasoning" )is not None : 93payload ["reasoning_effort" ]= case ["reasoning" ] 94if case .get ("stream" ): 95payload ["stream" ]= True 96t0 = time .time () 97resp = post (payload ,stream = bool (case .get ("stream" ))) 98ch = resp ["choices" ][0 ] 99msg = ch .get ("message" )or {} 100content = msg .get ("content" )or "" 101reasoning = msg .get ("reasoning_content" )or "" 102calls = msg .get ("tool_calls" )or [] 103where = [] 104if "tool_call" in content : 105where .append ("content" ) 106if "tool_call" in reasoning : 107where .append ("reasoning_content" ) 108return { 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 (): 192ap = argparse .ArgumentParser () 193ap .add_argument ("--out" ,default = str (pathlib .Path (__file__ ).parent / "results.json" )) 194args = ap .parse_args () 195 196before = metrics ().get ("totals" , {}).get ("tool_calls_from_reasoning" ,0 ) 197out = {"engine_version_check" :subprocess .run ( 198 ["python3" ,"-c" ,"import json;print(json.load(open('%s/engine/BUILD.json'))['version'])" % REPO ], 199capture_output = True ,text = True ).stdout .strip (), 200"git" :subprocess .run (["git" ,"-C" ,REPO ,"describe" ,"--tags" ], 201capture_output = True ,text = True ).stdout .strip (), 202"started" :time .strftime ("%Y-%m-%d %H:%M:%S" ), 203"tool_calls_from_reasoning_before" :before ,"cases" : []} 204for case in CASES : 205try : 206rec = run (case ) 207except Exception as exc :# noqa: BLE001 208rec = {"id" :case ["id" ],"expectation" :case ["expect" ],"error" :repr (exc )} 209out ["cases" ].append (rec ) 210f" { rec [ 'id' ] } : calls= { rec . get ( 'tool_calls_returned' ) } " 211f"left_in= { rec . get ( 'tool_call_text_left_in' ) } finish= { rec . get ( 'finish_reason' ) } " 212f"| expect: { rec [ 'expectation' ] } " ) 213after = metrics ().get ("totals" , {}).get ("tool_calls_from_reasoning" ,0 ) 214out ["tool_calls_from_reasoning_after" ]= after 215f"totals.tool_calls_from_reasoning: { before } -> { after } " ) 216pathlib .Path (args .out ).write_text (json .dumps (out ,ensure_ascii = False ,indent = 1 ),encoding = "utf-8" ) 217"записано:" ,args .out ) 218 219 220if __name__ == "__main__" : 221main ()