okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
82f46a8c8
main
1"""serve/test_reasoning_rescue.py - #804 / #1058: when a `<tool_call>` written inside the reasoning is a real call. 2 3A call inside the reasoning counts only when ALL hold: tools are declared and the name is one of them; the opener is 4at the start of a line; it is outside a Markdown code fence and outside inline code; the call closes with 5</tool_call> and nothing but whitespace (or more calls) follows it before the end of the turn or `</think>`; and the 6turn did not end by max tokens (or a cancel or an error). Anything else stays reasoning text. 7 8The corpus in serve/fixtures/rcall_specimens.json holds 25 entries from PR #525's corpus and the 12 live strandings 9recovered by 47Hunter47 (gist 4abcd3a8...): 16 act, 21 must not (the reporter's 20 negative controls 10plus the live one cut by max tokens). 11 12python -m unittest serve.test_reasoning_rescue -v 13""" 14from __future__import annotations 15 16import json 17import random 18import sys 19import unittest 20import urllib .request 21from pathlib import Path 22 23sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 24from serve .frontend import ChatTemplate ,OutputParser # noqa: E402 25from serve .server import ByteTokenizer ,MockEngine ,Service ,serve # noqa: E402 26from serve .test_server import CTX # noqa: E402 27 28ROOT = Path (__file__ ).resolve ().parents [1 ] 29SPECIMENS = json .loads ((ROOT / "serve/fixtures/rcall_specimens.json" ).read_text (encoding = "utf-8" ))["specimens" ] 30CALL = "<tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>" 31RM = CALL .replace ("file.txt" ,"rm -rf build" ) 32PROPS = {"path" : {"type" :"string" }} 33SCHEMA = [{"name" :"write" ,"parameters" : {"properties" :PROPS }}] 34 35 36def parse (text ,width ,tools = SCHEMA ,finish = None ,stream_tools = True ): 37"""Events for `text` fed `width` characters at a time (0 = random 1-9, seeded).""" 38p = OutputParser (thinking = True ,tools = tools ,stream_tools = stream_tools ) 39evs ,rnd ,i = [],random .Random (7 ),0 40while i < len (text ): 41k = width or rnd .randint (1 ,9 ) 42evs += p .feed (text [i :i + k ]) 43i += k 44return evs + p .finish (finish ) 45 46 47def calls (evs ): 48return [e .call .name for e in evs if e .kind == "tool_call" ] 49 50 51def reasoning (evs ): 52return "" .join (e .text for e in evs if e .kind == "reasoning" ) 53 54 55WIDTHS = (1 ,2 ,3 ,7 ,0 ,100_000 ) 56 57 58class Corpus (unittest .TestCase ): 59def test_every_specimen_whole_and_in_chunks (self ): 60for sp in SPECIMENS : 61tools = [{"name" :n ,"parameters" : {"properties" : {}}}for n in sp ["tools" ]] 62seen = set () 63for width in WIDTHS : 64for st in (True ,False ): 65with self .subTest (name = sp ["name" ],width = width ,stream_tools = st ): 66evs = parse (sp ["input" ],width ,tools ,sp ["finish" ],st ) 67self .assertEqual (calls (evs ),sp ["calls" ]) 68seen .add ((reasoning (evs ),tuple (e .call .name for e in evs if e .kind == "tool_call" ))) 69self .assertEqual (len (seen ),1 ,sp ["name" ])# streamed and whole agree 70 71def test_the_corpus_has_the_reported_split (self ): 72self .assertEqual ((len (SPECIMENS ),sum (bool (s ["calls" ])for s in SPECIMENS )), (37 ,16 )) 73 74 75class Gates (unittest .TestCase ): 76def check (self ,text ,expect ,finish = None ,tools = SCHEMA ): 77for width in WIDTHS : 78with self .subTest (text = text [:40 ],width = width ): 79evs = parse (text ,width ,tools ,finish ) 80self .assertEqual (len (calls (evs )),expect ) 81if not expect : 82self .assertEqual (reasoning (evs ),text )# nothing lost, nothing turned into content 83 84def test_a_stranded_call_is_recovered (self ): 85self .check ("I will write it now.\n\n" + CALL ,1 ) 86self .check (CALL ,1 ) 87self .check ("Hmm.\n " + CALL + "\n" ,1 )# indented opener and trailing blank lines 88self .check ("Two steps.\n" + CALL + "\n\n" + CALL ,2 ) 89self .check ("Two steps.\n" + CALL + "\n</think>\n\ndone" ,1 ) 90 91def test_recovered_call_keeps_the_text_before_it (self ): 92evs = parse ("Let me think.\n\n" + CALL ,3 ) 93self .assertEqual (reasoning (evs ),"Let me think.\n\n" ) 94 95def test_the_reporters_negative_controls (self ): 96self .check ("I could run\n" + RM + "\nbut first let me check what build holds..." ,0 ) 97self .check ("I could run\n" + RM ,0 ,finish = "length" )# cut by max tokens: the destructive one 98self .check ("Example:\n```xml\n" + RM + "\n```\nok" ,0 ) 99self .check ("Example:\n~~~\n" + RM + "\n~~~\nok" ,0 ) 100self .check ("The format is " + RM + " ok." ,0 ) 101self .check ("I must emit `<tool_call>` then more" ,0 ) 102self .check ("Use `\n" + RM ,0 )# inside inline code spanning a line 103self .check ("> " + RM ,0 ) 104self .check ("Plan: " + RM ,0 ) 105 106def test_a_length_cut_keeps_even_a_clean_stranded_call_as_text (self ): 107for finish in ("length" ,"cancel" ,"error" ,"disconnect" ): 108self .check ("Now.\n" + CALL ,0 ,finish = finish ) 109self .check ("Now.\n" + CALL ,1 ,finish = "stop" ) 110 111def test_after_a_closed_fence_a_call_counts_again (self ): 112self .check ("```\nx\n```\n" + CALL ,1 ) 113self .check ("~~~\nx\n~~~\n" + CALL ,1 ) 114self .check ("a `b` c\n" + CALL ,1 ) 115 116def test_a_fence_needs_the_same_marker_to_close (self ): 117self .check ("~~~\n```\n" + CALL ,0 ) 118 119def test_fence_split_across_chunks (self ): 120text = "Format:\n```xml\n" + CALL + "\n```\n" 121for cut in range (1 ,len (text )): 122with self .subTest (cut = cut ): 123p = OutputParser (thinking = True ,tools = SCHEMA ,stream_tools = True ) 124evs = p .feed (text [:cut ])+ p .feed (text [cut :])+ p .finish () 125self .assertEqual (calls (evs ), []) 126self .assertEqual (reasoning (evs ),text ) 127 128def test_opener_split_across_chunks (self ): 129text = "Go.\n" + CALL 130for cut in range (1 ,len (text )): 131with self .subTest (cut = cut ): 132p = OutputParser (thinking = True ,tools = SCHEMA ,stream_tools = True ) 133evs = p .feed (text [:cut ])+ p .feed (text [cut :])+ p .finish ("stop" ) 134self .assertEqual (calls (evs ), ["write" ]) 135quoted = "Go " + CALL 136for cut in range (1 ,len (quoted )): 137with self .subTest (cut = cut ,quoted = True ): 138p = OutputParser (thinking = True ,tools = SCHEMA ,stream_tools = True ) 139evs = p .feed (quoted [:cut ])+ p .feed (quoted [cut :])+ p .finish ("stop" ) 140self .assertEqual (calls (evs ), []) 141 142def test_the_end_of_the_turn_splits_a_held_tail (self ): 143p = OutputParser (thinking = True ,tools = SCHEMA ) 144evs = p .feed ("ok\n" + CALL + "\n<tool_c" )# a half opener after the call: it was prose 145evs += p .finish ("stop" ) 146self .assertEqual (calls (evs ), []) 147self .assertEqual (reasoning (evs ),"ok\n" + CALL + "\n<tool_c" ) 148 149def test_a_call_waits_and_is_not_streamed_early (self ): 150p = OutputParser (thinking = True ,tools = SCHEMA ) 151evs = p .feed ("go\n" + CALL + "\n" ) 152self .assertEqual (calls (evs ), [])# not yet: the turn could still say it was a quote 153self .assertEqual (calls (p .finish ("stop" )), ["write" ]) 154 155def test_no_tools_declared_is_unchanged (self ): 156text = "before\n" + CALL + "\n</think>\n\nanswer" 157for tools in (None , []): 158evs = parse (text ,5 ,tools ) 159self .assertEqual (calls (evs ), []) 160self .assertEqual (reasoning (evs ),"before\n" + CALL + "\n" ) 161 162def test_an_undeclared_name_stays_reasoning (self ): 163self .check ("go\n" + CALL .replace ("write" ,"other" ),0 ) 164 165def test_the_counters (self ): 166p = OutputParser (thinking = True ,tools = SCHEMA ) 167p .feed ("go\n" + CALL ) 168p .finish ("length" ) 169self .assertEqual ((p .rescued ,p .refused ), (0 ,1 )) 170p = OutputParser (thinking = True ,tools = SCHEMA ) 171p .feed ("go\n" + CALL ) 172p .finish ("stop" ) 173self .assertEqual ((p .rescued ,p .refused ), (1 ,0 )) 174 175 176class VisibleAnswer (unittest .TestCase ): 177"""#1058: the same fence / inline-code rule for a call in the visible answer (after </think>).""" 178HEAD = "ok</think>\n\n" 179 180def run_all (self ,text ,finish = None ): 181res = set () 182for width in WIDTHS : 183evs = parse (text ,width ,SCHEMA ,finish ) 184res .add ((tuple (calls (evs )),"" .join (e .text for e in evs if e .kind == "content" ))) 185self .assertEqual (len (res ),1 ,res )# every chunking agrees 186return res .pop () 187 188def test_quoted_calls_stay_text (self ): 189for body in ("Format:\n```xml\n" + RM + "\n```\nDone." ,"Format:\n~~~\n" + RM + "\n~~~\nDone." , 190"Use `" + RM + "` like this." ,"Use `x`, then `\n" + RM + "`" ,"```\n" + RM , 191"Text\n\n```python\nx = 1\n```\n```\n" + CALL ): 192with self .subTest (body = body [:30 ]): 193got ,text = self .run_all (self .HEAD + body ) 194self .assertEqual (got , ()) 195self .assertEqual (text ,body )# nothing lost 196 197def test_real_calls_still_fire (self ): 198for body in (CALL ,"Let me do it.\n\n" + CALL ,"Let me do it. " + CALL ,"```\ncode\n```\n" + CALL , 199"`a` and `b` " + CALL ,"~~~\nx\n~~~\n\n" + CALL ): 200with self .subTest (body = body [:30 ]): 201self .assertEqual (self .run_all (self .HEAD + body )[0 ], ("write" ,)) 202self .assertEqual (self .run_all (self .HEAD + CALL + "\n" + CALL )[0 ], ("write" ,"write" )) 203 204def test_a_closed_call_in_a_length_cut_answer_stays_a_call (self ): 205self .assertEqual (self .run_all (self .HEAD + "Now.\n" + CALL ,finish = "length" )[0 ], ("write" ,)) 206 207def test_without_thinking (self ): 208p = OutputParser (thinking = False ,tools = SCHEMA ) 209evs = p .feed ("```\n" + RM + "\n```" )+ p .finish () 210self .assertEqual (calls (evs ), []) 211 212 213class OverHttp (unittest .TestCase ): 214"""The same rules through the real server: OpenAI chat (whole and streamed), Anthropic and Responses.""" 215 216def ask (self ,script ,max_tokens = 800 ): 217tok = ByteTokenizer () 218svc = Service (MockEngine (tok ,script ,max_context = CTX ),tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 219httpd = serve (svc ,port = 0 ) 220base = f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 221msgs = [{"role" :"user" ,"content" :"save my notes" }] 222reqs = { 223"openai" : ("/v1/chat/completions" , {"tools" : [{"type" :"function" ,"function" : { 224"name" :"write" ,"parameters" : {"type" :"object" ,"properties" :PROPS }}}],"messages" :msgs , 225"max_tokens" :max_tokens }), 226"anthropic" : ("/v1/messages" , {"tools" : [{"name" :"write" ,"input_schema" : { 227"type" :"object" ,"properties" :PROPS }}],"messages" :msgs ,"max_tokens" :max_tokens }), 228"responses" : ("/v1/responses" , {"tools" : [{"type" :"function" ,"name" :"write" ,"parameters" : { 229"type" :"object" ,"properties" :PROPS }}],"input" :"save my notes" ,"max_output_tokens" :max_tokens }), 230 } 231out = {} 232try : 233for api , (path ,body )in reqs .items (): 234for stream in (False ,True ): 235req = urllib .request .Request (base + path ,data = json .dumps (dict (body ,model = "x" ,stream = stream )).encode (), 236headers = {"Content-Type" :"application/json" ,"anthropic-version" :"2023-06-01" }) 237with urllib .request .urlopen (req ,timeout = 30 )as r : 238raw = r .read ().decode () 239out [api ,stream ]= self .tool_uses (api ,stream ,raw ) 240finally : 241httpd .shutdown () 242httpd .server_close () 243return out 244 245@staticmethod 246def tool_uses (api ,stream ,raw ): 247"""How many tool calls the answer carries.""" 248if not stream : 249m = json .loads (raw ) 250if api == "openai" : 251return len (m ["choices" ][0 ]["message" ].get ("tool_calls" )or []) 252if api == "anthropic" : 253return sum (b ["type" ]== "tool_use" for b in m ["content" ]) 254return sum (o ["type" ]== "function_call" for o in m ["output" ]) 255evs = [json .loads (line [6 :])for line in raw .splitlines ()if line .startswith ("data: {" )] 256if api == "openai" : 257return len ({tc ["index" ]for e in evs for c in e ["choices" ]for tc in c ["delta" ].get ("tool_calls" )or []}) 258if api == "anthropic" : 259return sum (e ["type" ]== "content_block_start" and e ["content_block" ]["type" ]== "tool_use" for e in evs ) 260return sum (e ["type" ]== "response.output_item.added" and e ["item" ]["type" ]== "function_call" for e in evs ) 261 262def test_a_stranded_call_is_a_call_in_every_api (self ): 263a = self .ask ("Writing the file now.\n\n" + CALL ) 264self .assertEqual (set (a .values ()), {1 },a ) 265 266def test_quotes_and_cuts_are_not (self ): 267for name ,script ,tokens in ( 268 ("fence" ,"Format:\n```xml\n" + RM + "\n```\nand that is all." ,800 ), 269 ("midsentence" ,"I could run " + RM + " but no." ,800 ), 270 ("prose after" ,"I could run\n" + RM + "\nbut first let me check what build holds." ,800 ), 271 ("cut" ,"I could run\n" + RM + "\nthen more thinking " * 40 ,len ("I could run\n" + RM )), 272 ("cut exactly at the call" ,"Now.\n" + CALL + "\nmore thought " * 40 ,len ("Now.\n" + CALL ))): 273with self .subTest (name ): 274a = self .ask (script ,max_tokens = tokens ) 275self .assertEqual (set (a .values ()), {0 },a ) 276 277def test_visible_answer_fences_on_all_three_apis (self ): 278for name ,body ,want in (("fence" ,"Format:\n```xml\n" + RM + "\n```\nDone." ,0 ), 279 ("inline" ,"Use `" + RM + "` here." ,0 ), 280 ("real" ,"Doing it.\n\n" + CALL ,1 )): 281with self .subTest (name ): 282a = self .ask ("ok</think>\n\n" + body ) 283self .assertEqual (set (a .values ()), {want },a ) 284 285 286if __name__ == "__main__" : 287unittest .main ()