okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f5aa356f1
main
1"""serve/test_reasoning_tools.py - #804 (strict form of PR #787): a tool call the model writes inside its reasoning. 2 3A call inside the reasoning counts only when tools are declared and the name is one of them; anything else stays 4reasoning text. Without tools the parser is byte-identical to before. 5 6python -m unittest serve.test_reasoning_tools -v 7""" 8from __future__import annotations 9 10import json 11import sys 12import unittest 13import unittest .mock 14import urllib .request 15from pathlib import Path 16 17sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 18from serve .frontend import ChatTemplate ,OutputParser # noqa: E402 19from serve .server import ByteTokenizer ,MockEngine ,Service ,serve # noqa: E402 20from serve .test_server import CTX ,UnfinishedToolCall # noqa: E402 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23CALL = "<tool_call>\n<function=read_file>\n<parameter=limit>\n120\n</parameter>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>" 24OTHER = CALL .replace ("read_file" ,"not_declared" ) 25TOOLS = [{"name" :"read_file" ,"parameters" : {"properties" : {"limit" : {"type" :"integer" },"path" : {"type" :"string" }}}}] 26 27 28def run (text ,width ,tools = TOOLS ,thinking = True ,stream_tools = True ): 29p = OutputParser (thinking = thinking ,tools = tools ,stream_tools = stream_tools ) 30evs = [] 31for i in range (0 ,len (text ),width ): 32evs += p .feed (text [i :i + width ]) 33return evs + p .finish () 34 35 36def joined (evs ,kind ): 37return "" .join (e .text for e in evs if e .kind == kind ) 38 39 40class Parser (unittest .TestCase ): 41def test_a_declared_call_in_the_reasoning_is_a_call (self ): 42text = "before\n" + CALL + "\n</think>\n\nanswer" # at a line start, nothing but whitespace after it (#1058) 43for width in (1 ,2 ,7 ,100_000 ): 44with self .subTest (width = width ): 45evs = run (text ,width ) 46calls = [e .call for e in evs if e .kind == "tool_call" ] 47self .assertEqual ([(c .name ,c .arguments )for c in calls ], 48 [("read_file" , {"limit" :120 ,"path" :"file.txt" })]) 49self .assertEqual (joined (evs ,"reasoning" ),"before\n" ) 50self .assertEqual (joined (evs ,"content" ),"answer" ) 51self .assertFalse ([e for e in evs if e .kind in ("tool_start" ,"tool_args" )])# never streamed 52 53def test_an_undeclared_name_stays_reasoning (self ): 54text = "see " + OTHER + " done</think>\n\nanswer" 55for width in (1 ,5 ,100_000 ): 56with self .subTest (width = width ): 57evs = run (text ,width ) 58self .assertFalse ([e for e in evs if e .kind == "tool_call" ]) 59self .assertEqual (joined (evs ,"reasoning" ),"see " + OTHER + " done" ) 60self .assertEqual (joined (evs ,"content" ),"answer" ) 61 62def test_no_tools_declared_is_unchanged (self ): 63text = "before\n" + CALL + "\n</think>\n\nanswer" 64for tools in (None , []): 65for width in (1 ,7 ,100_000 ): 66with self .subTest (tools = tools ,width = width ): 67evs = run (text ,width ,tools = tools ) 68self .assertFalse ([e for e in evs if e .kind == "tool_call" ]) 69self .assertEqual (joined (evs ,"reasoning" ),"before\n" + CALL + "\n" ) 70self .assertEqual (joined (evs ,"content" ),"answer" ) 71 72def test_an_unfinished_call_is_never_a_call (self ): 73for text in ("before<tool_call>\n<function=read_file>\n" , 74"before<tool_call>\n<function=read_file>\n<parameter=path>\nfile.txt\n</parameter>\n" ): 75for width in (1 ,100_000 ): 76with self .subTest (text = text [- 20 :],width = width ): 77evs = run (text ,width ) 78self .assertFalse ([e for e in evs if e .kind == "tool_call" ]) 79self .assertEqual (joined (evs ,"reasoning" ),text ) 80 81def test_the_thinking_ending_inside_a_call_makes_it_text (self ): 82text = "a<tool_call>\n<function=read_file>\nhmm</think>\n\nthe answer" 83for width in (1 ,100_000 ): 84with self .subTest (width = width ): 85evs = run (text ,width ) 86self .assertFalse ([e for e in evs if e .kind == "tool_call" ]) 87self .assertEqual (joined (evs ,"reasoning" ),"a<tool_call>\n<function=read_file>\nhmm" ) 88self .assertEqual (joined (evs ,"content" ),"the answer" ) 89 90def test_a_call_in_the_answer_is_unchanged (self ): 91text = "think</think>\n\nok " + CALL 92for width in (1 ,100_000 ): 93evs = run (text ,width ) 94self .assertEqual (len ([e for e in evs if e .kind == "tool_call" ]),1 ) 95self .assertEqual (joined (evs ,"reasoning" ),"think" ) 96 97def test_a_tag_that_never_closes_does_not_hold_the_thinking_back (self ): 98from serve import frontend 99text = "a\n<tool_call> " + "thinking on and on " * 3000 + "</think>\n\nanswer" 100with unittest .mock .patch .object (frontend ,"RCALL_MAX" ,1000 ): 101evs = run (text ,50 ) 102first_reasoning_at = next (i for i ,e in enumerate (evs )if e .kind == "reasoning" and len (e .text )> 100 ) 103self .assertLess (first_reasoning_at ,100 )# streamed, not kept until </think> 104self .assertEqual (joined (evs ,"reasoning" ),text .split ("</think>" )[0 ]) 105self .assertEqual (joined (evs ,"content" ),"answer" ) 106 107def test_a_partial_tag_is_held (self ): 108p = OutputParser (thinking = True ,tools = TOOLS ) 109evs = p .feed ("hello <tool_c" ) 110self .assertEqual (joined (evs ,"reasoning" ),"hello " ) 111self .assertEqual (joined (p .feed ("ats are nice</think>" ),"reasoning" ),"<tool_cats are nice" ) 112 113 114class QuotedThinkEnd (unittest .TestCase ): 115"""#537: a `</think>` the model quotes while it thinks - right after a quote or backtick, with no line break after 116it - is reasoning text; the end of the thinking is still a `</think>` with a line break after it.""" 117 118def test_a_quoted_tag_stays_reasoning (self ): 119for quote in ("in rcall, `</think>` could arrive inside the held body" , 120'the mock engine returns "</think>\\n\\n2", no tool call' , 121'```python\ntext = ("</think>\\n\\nI will use the tag now.")\n```' , 122"split it on '</think>' first" ): 123text = "plan\n" + quote + "\ndone\n</think>\n\nanswer" 124for width in (1 ,7 ,100_000 ): 125with self .subTest (quote = quote [:24 ],width = width ): 126evs = run (text ,width ) 127self .assertEqual (joined (evs ,"reasoning" ),"plan\n" + quote + "\ndone\n" ) 128self .assertEqual (joined (evs ,"content" ),"answer" ) 129 130def test_a_call_quoted_after_it_is_not_run (self ): 131text = ('it returns "</think>\\n\\n2" here.\nThe call looks like this:\n' + CALL + " in the answer.\n" 132"</think>\n\n" + CALL ) 133for width in (1 ,7 ,100_000 ): 134with self .subTest (width = width ): 135evs = run (text ,width ) 136self .assertEqual (len ([e for e in evs if e .kind == "tool_call" ]),1 )# the answer's own call 137self .assertIn (CALL + " in the answer." ,joined (evs ,"reasoning" )) 138self .assertEqual (joined (evs ,"content" ),"" ) 139 140def test_the_end_after_a_quote_still_ends_the_thinking (self ): 141for thought in ('she said "yes"' ,"it is `x`" ,"it is 'x'" ): 142for width in (1 ,100_000 ): 143with self .subTest (thought = thought ,width = width ): 144evs = run (thought + "</think>\n\nanswer" ,width ) 145self .assertEqual (joined (evs ,"reasoning" ),thought ) 146self .assertEqual (joined (evs ,"content" ),"answer" ) 147 148def test_an_output_that_ends_on_the_tag (self ): 149for width in (1 ,100_000 ): 150evs = run ('say "</think>' ,width ) 151self .assertEqual (joined (evs ,"reasoning" ),'say "' ) 152self .assertEqual (joined (evs ,"content" ),"" ) 153 154 155class OverHttp (unittest .TestCase ): 156def test_finish_reasons_and_block_order (self ): 157helper = UnfinishedToolCall ("test_parser" ) 158helper .PROPS = {"path" : {"type" :"string" }} 159script = "Let me look.\n<tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n" \ 160"</tool_call>\n</think>\n\ndone" 161a = helper .answers (script ) 162self .assertEqual ((a ["openai" ,False ][0 ], [json .loads (x )for x in a ["openai" ,False ][1 ]]), 163 ("tool_calls" , [{"path" :"file.txt" }])) 164self .assertEqual (a ["anthropic" ,False ], ("tool_use" , [{"path" :"file.txt" }])) 165# the order of the Anthropic stream's blocks: thinking, the call, the answer 166tok = ByteTokenizer () 167svc = Service (MockEngine (tok ,script ,max_context = CTX ),tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 168httpd = serve (svc ,port = 0 ) 169try : 170body = {"model" :"x" ,"max_tokens" :500 ,"stream" :True ,"messages" : [{"role" :"user" ,"content" :"hi" }], 171"tools" : [{"name" :"write" ,"input_schema" : {"type" :"object" ,"properties" :helper .PROPS }}]} 172req = urllib .request .Request (f"http://127.0.0.1: { httpd . server_address [ 1 ] } /v1/messages" , 173data = json .dumps (body ).encode (),headers = {"Content-Type" :"application/json" , 174"anthropic-version" :"2023-06-01" }) 175with urllib .request .urlopen (req ,timeout = 30 )as r : 176raw = r .read ().decode () 177evs = [json .loads (line [6 :])for line in raw .splitlines ()if line .startswith ("data: {" )] 178order = [e ["content_block" ]["type" ]for e in evs if e ["type" ]== "content_block_start" ] 179self .assertEqual (order , ["thinking" ,"tool_use" ,"text" ]) 180tool = [e ["delta" ]["partial_json" ]for e in evs if e ["type" ]== "content_block_delta" 181and e ["delta" ]["type" ]== "input_json_delta" ] 182self .assertEqual (json .loads ("" .join (tool )), {"path" :"file.txt" }) 183finally : 184httpd .shutdown () 185httpd .server_close () 186 187 188if __name__ == "__main__" : 189unittest .main ()