okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b82d1d456
main
1"""#4427, #4077, #4078 through the HTTP routes: what a client gets for the damaged calls and the stray closing think tag. 2 3The model's text is replayed by the mock engine; the reply is read from Chat Completions, the Anthropic Messages API and 4the Responses API, each whole and streamed. Every route must hand over the same calls with the same arguments. 5 6python -m unittest serve.test_tool_routes -v 7""" 8from __future__import annotations 9 10import contextlib 11import http .client 12import io 13import json 14import sys 15import unittest 16from pathlib import Path 17 18sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 19from serve .frontend import ChatTemplate # noqa: E402 20from serve .server import ByteTokenizer ,MockEngine ,Service ,serve # noqa: E402 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23TEMPLATE = ChatTemplate (ROOT / "serve/chat_template.jinja" ) 24PROPS = {"todos" : {"type" :"array" },"path" : {"type" :"string" },"content" : {"type" :"string" }} 25NAMES = ("todo_write" ,"write_file" ) 26 27 28def call (name ,** params ): 29body = "" .join (f"<parameter= { k } >\n { v } \n</parameter>\n" for k ,v in params .items ()) 30return f"<tool_call>\n<function= { name } >\n { body } </function>\n</tool_call>" 31 32 33class Routes (unittest .TestCase ): 34def read (self ,script ,** service ): 35"""{route: (finish, [(name, arguments)], answer text)} for the model's `script`, on every route.""" 36tok = ByteTokenizer () 37svc = Service (MockEngine (tok ,script ,max_context = 16384 ),tok ,TEMPLATE ) 38for k ,v in service .items (): 39setattr (svc ,k ,v ) 40httpd = serve (svc ,port = 0 ) 41port = httpd .server_address [1 ] 42out = {} 43 44def post (path ,body ): 45c = http .client .HTTPConnection ("127.0.0.1" ,port ,timeout = 60 ) 46try : 47with contextlib .redirect_stdout (io .StringIO ()): 48c .request ("POST" ,path ,body = json .dumps (body ).encode (), 49headers = {"Content-Type" :"application/json" ,"anthropic-version" :"2023-06-01" }) 50return c .getresponse ().read ().decode () 51finally : 52c .close () 53 54def sse (raw ): 55return [json .loads (line [6 :])for line in raw .splitlines ()if line .startswith ("data: {" )] 56 57chat_tools = [{"type" :"function" ,"function" : {"name" :n ,"parameters" : {"type" :"object" ,"properties" :PROPS }}} 58for n in NAMES ] 59try : 60for stream in (False ,True ): 61raw = post ("/v1/chat/completions" , {"model" :"x" ,"max_tokens" :900 ,"stream" :stream ,"tools" :chat_tools , 62"messages" : [{"role" :"user" ,"content" :"go" }]}) 63if stream : 64evs ,calls ,text ,finish = sse (raw ), {},"" ,None 65for e in evs : 66ch = e ["choices" ][0 ] 67text += ch ["delta" ].get ("content" )or "" 68finish = ch .get ("finish_reason" )or finish 69for tc in ch ["delta" ].get ("tool_calls" )or []: 70slot = calls .setdefault (tc ["index" ], {"name" :None ,"args" :"" }) 71slot ["name" ]= (tc .get ("function" )or {}).get ("name" )or slot ["name" ] 72slot ["args" ]+= (tc .get ("function" )or {}).get ("arguments" )or "" 73got = [(c ["name" ],json .loads (c ["args" ]))for _ ,c in sorted (calls .items ())] 74else : 75d = json .loads (raw )["choices" ][0 ] 76text ,finish = d ["message" ].get ("content" )or "" ,d ["finish_reason" ] 77got = [(t ["function" ]["name" ],json .loads (t ["function" ]["arguments" ]))for t in d ["message" ].get ("tool_calls" )or []] 78out ["chat" ,stream ]= (finish ,got ,text .strip ()) 79 80raw = post ("/v1/messages" , {"model" :"x" ,"max_tokens" :900 ,"stream" :stream , 81"tools" : [{"name" :n ,"input_schema" : {"type" :"object" ,"properties" :PROPS }}for n in NAMES ], 82"messages" : [{"role" :"user" ,"content" :"go" }]}) 83if stream : 84evs ,blocks ,text ,finish = sse (raw ), {},"" ,None 85for e in evs : 86if e ["type" ]== "content_block_start" and e ["content_block" ]["type" ]== "tool_use" : 87blocks [e ["index" ]]= {"name" :e ["content_block" ]["name" ],"json" :"" } 88elif e ["type" ]== "content_block_delta" : 89if e ["delta" ]["type" ]== "input_json_delta" : 90blocks [e ["index" ]]["json" ]+= e ["delta" ]["partial_json" ] 91elif e ["delta" ]["type" ]== "text_delta" : 92text += e ["delta" ]["text" ] 93elif e ["type" ]== "message_delta" : 94finish = e ["delta" ]["stop_reason" ] 95got = [(b ["name" ],json .loads (b ["json" ]or "{}" ))for _ ,b in sorted (blocks .items ())] 96else : 97d = json .loads (raw ) 98finish = d ["stop_reason" ] 99text = "" .join (b .get ("text" ,"" )for b in d ["content" ]if b ["type" ]== "text" ) 100got = [(b ["name" ],b ["input" ])for b in d ["content" ]if b ["type" ]== "tool_use" ] 101out ["anthropic" ,stream ]= (finish ,got ,text .strip ()) 102 103raw = post ("/v1/responses" , {"model" :"x" ,"input" :"go" ,"stream" :stream ,"store" :False , 104"tools" : [{"type" :"function" ,"name" :n ,"parameters" : {"type" :"object" ,"properties" :PROPS }} 105for n in NAMES ]}) 106if stream : 107items = [e ["item" ]for e in sse (raw )if e ["type" ]== "response.output_item.done" ] 108else : 109items = json .loads (raw )["output" ] 110got = [(i ["name" ],json .loads (i ["arguments" ]))for i in items if i ["type" ]== "function_call" ] 111text = "" .join (c ["text" ]for i in items if i ["type" ]== "message" for c in i ["content" ]if c ["type" ]== "output_text" ) 112out ["responses" ,stream ]= ("-" ,got ,text .strip ()) 113finally : 114httpd .shutdown () 115httpd .server_close () 116return out 117 118def every_route (self ,script ,calls ,text = "" ,finish = ("tool_calls" ,"tool_use" ),** service ): 119got = self .read (script ,** service ) 120for (route ,stream ), (fin ,got_calls ,got_text )in got .items (): 121with self .subTest (route = route ,stream = stream ): 122self .assertEqual (got_calls ,calls ) 123self .assertEqual (got_text ,text ) 124if route == "chat" : 125self .assertEqual (fin ,finish [0 ]) 126elif route == "anthropic" : 127self .assertEqual (fin ,finish [1 ]) 128 129def test_a_damaged_array_argument_arrives_as_the_array (self ): 130stray = ('[{"content": "Init", "status": "in_progress", "pending": false}, ' 131'{"content": "Write", "status": "pending", "in_progress", "pending": false}]' ) 132want = [{"content" :"Init" ,"status" :"in_progress" ,"pending" :False }, 133 {"content" :"Write" ,"status" :"pending" ,"pending" :False }] 134self .every_route ("Plan.\n</think>\n\n" + call ("todo_write" ,todos = stray ), [("todo_write" , {"todos" :want })]) 135 136def test_a_call_without_its_function_closer (self ): 137text = ("Plan.\n</think>\n\n<tool_call>\n<function=write_file>\n<parameter=path>\nout.txt\n</parameter>\n" 138"<parameter=content>\nhello\n</parameter>\n</tool_call>" ) 139self .every_route (text , [("write_file" , {"path" :"out.txt" ,"content" :"hello" })]) 140 141def test_a_call_without_its_wrapper_closer_at_the_end (self ): 142text = "Plan.\n</think>\n\n" + call ("write_file" ,path = "out.txt" ,content = "hello" ).removesuffix ("\n</tool_call>" ) 143self .every_route (text , [("write_file" , {"path" :"out.txt" ,"content" :"hello" })]) 144 145def test_a_value_that_quotes_a_whole_call (self ): 146value = "first line\n" + call ("write_file" ,path = "nested.txt" )+ "\nlast line" 147self .every_route ("Plan.\n</think>\n\n" + call ("write_file" ,path = "fixture.txt" ,content = value ), 148 [("write_file" , {"path" :"fixture.txt" ,"content" :value })]) 149 150def test_a_stray_closing_think_tag_keeps_the_call (self ): 151value = "reasoning sample:\n</think>\nanswer sample" 152script = ("The content is\n```\n" + value + "\n```\nCall it.\n</think>\n\n" + call ("write_file" ,path = "out.txt" ,content = value )) 153got = self .read (script ) 154for (route ,stream ), (fin ,calls ,text )in got .items (): 155with self .subTest (route = route ,stream = stream ): 156self .assertEqual (calls , [("write_file" , {"path" :"out.txt" ,"content" :value })]) 157self .assertNotIn ("</think>" ,text ) 158 159 160if __name__ == "__main__" : 161unittest .main ()