okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cded60248
main
1"""Anthropic tool_result blocks must follow tool_use_id before the template drops it.""" 2import copy 3import http .client 4import json 5from pathlib import Path 6import unittest 7 8from serve .frontend import ChatTemplate ,anthropic_to_messages 9from serve .server import ByteTokenizer ,MockEngine ,Service ,serve 10 11 12TEMPLATE = ChatTemplate (Path (__file__ ).with_name ("chat_template.jinja" )) 13DEEPSEEK = ChatTemplate (Path (__file__ ).with_name ("fixtures" )/ "deepseek41" / "chat_template.jinja" ) 14 15 16def history (): 17"""Two calls of one tool, answered in the order they finished: what Claude Code 2.1.316 sends for parallel Greps.""" 18return [ 19 {"role" :"user" ,"content" :"Search for both." }, 20 {"role" :"assistant" ,"content" : [ 21 {"type" :"tool_use" ,"id" :"toolu_slow" ,"name" :"Grep" ,"input" : {"pattern" :"slow" }}, 22 {"type" :"tool_use" ,"id" :"toolu_fast" ,"name" :"Grep" ,"input" : {"pattern" :"fast" }}]}, 23 {"role" :"user" ,"content" : [ 24 {"type" :"tool_result" ,"tool_use_id" :"toolu_fast" ,"content" :"RESULT_FROM_FAST" }, 25 {"type" :"tool_result" ,"tool_use_id" :"toolu_slow" ,"content" :"RESULT_FROM_SLOW" }]}, 26 ] 27 28 29def in_call_order (): 30raw = history () 31raw [2 ]["content" ].reverse () 32return raw 33 34 35def normalized (messages ): 36return anthropic_to_messages ({"messages" :messages })[0 ] 37 38 39def results (messages ): 40return [m ["content" ]for m in normalized (messages )if m ["role" ]== "tool" ] 41 42 43class AnthropicToolResults (unittest .TestCase ): 44def test_reversed_results_of_the_same_tool_follow_tool_use_id (self ): 45raw = history () 46before = copy .deepcopy (raw ) 47self .assertEqual (results (raw ), ["RESULT_FROM_SLOW" ,"RESULT_FROM_FAST" ]) 48self .assertEqual (raw ,before ) 49for template in (TEMPLATE ,DEEPSEEK ): 50with self .subTest (template = str (template )): 51prompt = template .render (normalized (raw ),enable_thinking = False ) 52self .assertEqual (prompt ,template .render (normalized (in_call_order ()),enable_thinking = False )) 53self .assertLess (prompt .index ("RESULT_FROM_SLOW" ),prompt .index ("RESULT_FROM_FAST" )) 54 55def test_already_ordered_and_legacy_prompts_are_identical (self ): 56ordered = in_call_order () 57legacy = copy .deepcopy (ordered ) 58for block in legacy [1 ]["content" ]: 59block .pop ("id" ) 60for block in legacy [2 ]["content" ]: 61block .pop ("tool_use_id" ) 62self .assertEqual (normalized (ordered ),normalized (legacy )) 63self .assertEqual ([m ["content" ]for m in normalized (ordered )[2 :]], ["RESULT_FROM_SLOW" ,"RESULT_FROM_FAST" ]) 64 65def test_ids_never_reach_the_template (self ): 66for raw in (history (),in_call_order ()): 67messages = normalized (raw ) 68self .assertTrue (all (set (m )== {"role" ,"content" }for m in messages [2 :])) 69self .assertTrue (all (set (c )== {"function" }for c in messages [1 ]["tool_calls" ])) 70 71def test_ambiguous_or_incomplete_ids_preserve_received_order (self ): 72for case in ("missing_call" ,"missing_result" ,"duplicate_call" ,"duplicate_result" ,"unknown" , 73"list_call" ,"list_result" ,"empty_call" ,"empty_result" ,"partial" ): 74raw = history () 75calls ,blocks = raw [1 ]["content" ],raw [2 ]["content" ] 76if case == "missing_call" : 77calls [0 ].pop ("id" ) 78elif case == "missing_result" : 79blocks [0 ].pop ("tool_use_id" ) 80elif case == "duplicate_call" : 81calls [1 ]["id" ]= "toolu_slow" 82elif case == "duplicate_result" : 83blocks [1 ]["tool_use_id" ]= "toolu_fast" 84elif case == "unknown" : 85blocks [0 ]["tool_use_id" ]= "unknown" 86elif case == "list_call" : 87calls [0 ]["id" ]= [] 88elif case == "list_result" : 89blocks [0 ]["tool_use_id" ]= [] 90elif case == "empty_call" : 91calls [0 ]["id" ]= "" 92elif case == "empty_result" : 93blocks [0 ]["tool_use_id" ]= "" 94else : 95blocks .pop () 96with self .subTest (case = case ): 97self .assertEqual (results (raw ), [b ["content" ]for b in blocks ]) 98 99def test_each_tool_run_is_scoped_to_its_assistant_turn (self ): 100self .assertEqual (results (history ()+ history ()), ["RESULT_FROM_SLOW" ,"RESULT_FROM_FAST" ]* 2 ) 101 102def test_results_split_across_user_messages_are_one_run (self ): 103raw = history () 104first ,second = raw [2 ]["content" ] 105raw [2 :]= [{"role" :"user" ,"content" : [first ]}, {"role" :"user" ,"content" : [second ]}] 106self .assertEqual (results (raw ), ["RESULT_FROM_SLOW" ,"RESULT_FROM_FAST" ]) 107 108def test_system_message_between_calls_and_results_keeps_received_order (self ): 109raw = history () 110raw .insert (2 , {"role" :"system" ,"content" :"late note" }) 111self .assertEqual (results (raw ), ["RESULT_FROM_FAST" ,"RESULT_FROM_SLOW" ]) 112 113def test_text_beside_the_results_stays_after_them (self ): 114raw = history () 115raw [2 ]["content" ].append ({"type" :"text" ,"text" :"and then?" }) 116self .assertEqual ([(m ["role" ],m ["content" ])for m in normalized (raw )[2 :]], 117 [("tool" ,"RESULT_FROM_SLOW" ), ("tool" ,"RESULT_FROM_FAST" ), ("user" ,"and then?" )]) 118 119def test_multimodal_result_moves_with_its_call (self ): 120raw = history () 121image = {"type" :"image" ,"source" : {"type" :"base64" ,"media_type" :"image/png" ,"data" :"AA==" }} 122raw [2 ]["content" ][0 ]["content" ]= [{"type" :"text" ,"text" :"RESULT_FROM_FAST" },image ] 123got = results (raw ) 124self .assertEqual (got [0 ],"RESULT_FROM_SLOW" ) 125self .assertEqual ([p .get ("type" )for p in got [1 ]], ["text" ,"image" ]) 126 127def test_http_engine_receives_the_ordered_prompt (self ): 128tok = ByteTokenizer () 129engine = MockEngine (tok ,"ok" ,max_context = 4096 ) 130service = Service (engine ,tok ,TEMPLATE ) 131httpd = serve (service ,port = 0 ) 132try : 133for stream in (False ,True ): 134with self .subTest (stream = stream ): 135engine .last_prompt = None 136connection = http .client .HTTPConnection ("127.0.0.1" ,httpd .server_address [1 ],timeout = 10 ) 137try : 138connection .request ("POST" ,"/v1/messages" ,json .dumps ({ 139"model" :"x" ,"messages" :history (),"max_tokens" :16 ,"stream" :stream , 140"thinking" : {"type" :"disabled" }}), {"Content-Type" :"application/json" }) 141response = connection .getresponse () 142body = response .read () 143finally : 144connection .close () 145self .assertEqual (response .status ,200 ,body ) 146prompt = tok .decode (engine .last_prompt ) 147self .assertLess (prompt .index ("RESULT_FROM_SLOW" ),prompt .index ("RESULT_FROM_FAST" )) 148finally : 149httpd .shutdown () 150httpd .server_close () 151 152 153 154if __name__ == "__main__" : 155unittest .main ()