okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
311926416
main
1"""Chat history normalization before rendering the model's prompt.""" 2import copy 3from pathlib import Path 4import unittest 5 6from serve .frontend import ChatTemplate ,anthropic_to_messages ,openai_to_messages ,require_messages 7from serve .server import ByteTokenizer ,MockEngine ,Service 8 9 10class EmptyAssistantHistory (unittest .TestCase ): 11def setUp (self ): 12self .template = ChatTemplate (Path (__file__ ).with_name ("chat_template.jinja" )) 13tok = ByteTokenizer () 14self .service = Service (MockEngine (tok ,"ok" ),tok ,self .template ) 15 16def test_openai_empty_replies_are_not_rendered (self ): 17for content in (None ,"" ," \n\t" , [], [{"type" :"text" ,"text" :"" }]): 18for preserve in (True ,False ): 19with self .subTest (content = content ,preserve_thinking = preserve ): 20history = [] 21for _ in range (3 ): 22history .extend ([{"role" :"user" ,"content" :"haz un ls" }, 23 {"role" :"assistant" ,"content" :content , 24"reasoning_content" :"Let me run ls." }]) 25history .append ({"role" :"user" ,"content" :"haz un ls" }) 26messages ,tools ,kwargs = openai_to_messages ({"messages" :history }) 27kwargs ["preserve_thinking" ]= preserve 28clean = [m for m in messages if m ["role" ]== "user" ] 29self .assertEqual (self .service .encode_prompt (messages ,tools ,kwargs ), 30self .service .encode_prompt (clean ,tools ,kwargs )) 31 32def test_anthropic_thinking_only_replies_are_not_rendered (self ): 33messages ,tools ,kwargs = anthropic_to_messages ({"messages" : [ 34 {"role" :"user" ,"content" :"haz un ls" }, 35 {"role" :"assistant" ,"content" : [{"type" :"thinking" ,"thinking" :"Let me run ls." }]}, 36 {"role" :"user" ,"content" :"haz un ls" }, 37 ]}) 38self .assertEqual (self .service .encode_prompt (messages ,tools ,kwargs ), 39self .service .encode_prompt ([messages [0 ],messages [2 ]],tools ,kwargs )) 40 41def test_text_and_tool_calls_are_kept (self ): 42messages ,tools ,kwargs = openai_to_messages ({"messages" : [ 43 {"role" :"user" ,"content" :"haz un ls" }, 44 {"role" :"assistant" ,"content" : [{"type" :"text" ,"text" :"Running ls." }]}, 45 {"role" :"assistant" ,"content" :None ,"tool_calls" : [ 46 {"type" :"function" ,"function" : {"name" :"run" ,"arguments" :'{"command":"ls"}' }}, 47 ]}, 48 {"role" :"tool" ,"content" :"file.txt" }, 49 {"role" :"user" ,"content" :"thanks" }, 50 ]}) 51before = copy .deepcopy (messages ) 52prompt = self .template .render (messages ,tools = tools ,** kwargs ) 53self .assertIn ("Running ls." ,prompt ) 54self .assertIn ("<function=run>" ,prompt ) 55self .assertIn ("file.txt" ,prompt ) 56self .assertEqual (messages ,before ) 57 58def test_image_only_assistant_turn_is_kept (self ): 59messages ,tools ,kwargs = openai_to_messages ({"messages" : [ 60 {"role" :"user" ,"content" :"describe the image" }, 61 {"role" :"assistant" ,"content" : [{"type" :"image_url" ,"image_url" :"image.png" }]}, 62 {"role" :"user" ,"content" :"thanks" }, 63 ]}) 64self .assertIn ("<|vision_start|><|image_pad|><|vision_end|>" , 65self .template .render (messages ,tools = tools ,** kwargs )) 66 67def test_final_empty_assistant_turn_is_kept (self ): 68prompt = self .template .render ([{"role" :"user" ,"content" :"hi" }, 69 {"role" :"assistant" ,"content" :"" }],add_generation_prompt = False ) 70self .assertIn ("<|im_start|>assistant\n" ,prompt ) 71 72def test_empty_user_and_tool_turns_are_kept (self ): 73prompt = self .template .render ([{"role" :"user" ,"content" :"" }, 74 {"role" :"tool" ,"content" :"" }, 75 {"role" :"user" ,"content" :"hi" }]) 76self .assertEqual (prompt .count ("<|im_start|>user\n" ),3 ) 77self .assertIn ("<tool_response>\n\n</tool_response>" ,prompt ) 78 79 80class UnreadContentParts (unittest .TestCase ): 81"""A content part the server does not read is refused naming it and where it sits, as /v1/responses does; chat 82and messages used to drop it without a word, and the model answered about a file it had never seen.""" 83 84def setUp (self ): 85self .template = ChatTemplate (Path (__file__ ).with_name ("chat_template.jinja" )) 86tok = ByteTokenizer () 87self .service = Service (MockEngine (tok ,"ok" ),tok ,self .template ) 88 89def test_chat_file_and_audio_parts_are_left_out (self ): 90parts = ({"type" :"file" ,"file" : {"filename" :"a.pdf" ,"file_data" :"data:application/pdf;base64,AA" }}, 91 {"type" :"input_audio" ,"input_audio" : {"data" :"AA" ,"format" :"wav" }}) 92plain = [{"role" :"user" ,"content" :"summarize" }, {"role" :"user" ,"content" :"this one" }] 93for part in parts : 94with self .subTest (kind = part ["type" ]): 95got = openai_to_messages ({"messages" : [ 96 {"role" :"user" ,"content" :"summarize" }, 97 {"role" :"user" ,"content" : [{"type" :"text" ,"text" :"this one" },part ]}]}) 98want = openai_to_messages ({"messages" : [ 99 {"role" :"user" ,"content" :"summarize" }, 100 {"role" :"user" ,"content" : [{"type" :"text" ,"text" :"this one" }]}]}) 101self .assertEqual (got ,want ) 102 103def test_messages_blocks_real_clients_send_are_left_out (self ): 104# tool_reference (Claude Code's tool search), documents, search results, server tool blocks, signed thinking 105extra = [{"type" :"document" ,"source" : {"type" :"base64" ,"media_type" :"application/pdf" ,"data" :"AA" }}, 106 {"type" :"search_result" ,"source" :"s" ,"title" :"t" ,"content" : [{"type" :"text" ,"text" :"x" }]}, 107 {"type" :"server_tool_use" ,"id" :"s1" ,"name" :"web_search" ,"input" : {}}, 108 {"type" :"web_search_tool_result" ,"tool_use_id" :"s1" ,"content" : []}, 109 {"type" :"container_upload" ,"file_id" :"f" }] 110for block in extra : 111with self .subTest (kind = block ["type" ]): 112got = anthropic_to_messages ({"messages" : [ 113 {"role" :"user" ,"content" :"hi" }, 114 {"role" :"assistant" ,"content" : [{"type" :"text" ,"text" :"ok" },block ]}, 115 {"role" :"user" ,"content" : [{"type" :"text" ,"text" :"go" },block ]}]}) 116want = anthropic_to_messages ({"messages" : [ 117 {"role" :"user" ,"content" :"hi" }, 118 {"role" :"assistant" ,"content" : [{"type" :"text" ,"text" :"ok" }]}, 119 {"role" :"user" ,"content" : [{"type" :"text" ,"text" :"go" }]}]}) 120self .assertEqual (got ,want ) 121 122def test_messages_tool_reference_in_a_tool_result_is_left_out (self ): 123def run (extra ): 124return anthropic_to_messages ({"messages" : [ 125 {"role" :"user" ,"content" :"find a tool" }, 126 {"role" :"assistant" ,"content" : [{"type" :"tool_use" ,"id" :"t1" ,"name" :"ToolSearch" ,"input" : {}}]}, 127 {"role" :"user" ,"content" : [ 128 {"type" :"tool_result" ,"tool_use_id" :"t1" ,"content" : [{"type" :"text" ,"text" :"found" }]+ extra }]}]}) 129self .assertEqual (run ([{"type" :"tool_reference" ,"tool_name" :"mcp__x" }]),run ([])) 130 131def test_a_system_prompt_with_an_image_part_is_read_as_text_as_before (self ): 132got = openai_to_messages ({"messages" : [ 133 {"role" :"system" ,"content" : [{"type" :"text" ,"text" :"be brief" }, 134 {"type" :"image_url" ,"image_url" :"image.png" }]}, 135 {"role" :"user" ,"content" :"hi" }]}) 136self .assertEqual (got [0 ][0 ]["content" ],"be brief" ) 137 138def test_messages_redacted_thinking_is_dropped (self ): 139msgs = {"messages" : [ 140 {"role" :"user" ,"content" :"haz un ls" }, 141 {"role" :"assistant" ,"content" : [{"type" :"redacted_thinking" ,"data" :"ZW50cnk=" }, 142 {"type" :"text" ,"text" :"Running ls." }]}, 143 {"role" :"user" ,"content" :"thanks" }]} 144without = copy .deepcopy (msgs ) 145del without ["messages" ][1 ]["content" ][0 ] 146with_block = anthropic_to_messages (msgs ) 147without_block = anthropic_to_messages (without ) 148self .assertEqual (with_block [0 ],without_block [0 ]) 149self .assertEqual (self .service .encode_prompt (with_block [0 ],with_block [1 ],with_block [2 ]), 150self .service .encode_prompt (without_block [0 ],without_block [1 ],without_block [2 ])) 151 152def test_chat_refusal_part_is_read_as_its_text (self ): 153messages ,tools ,kwargs = openai_to_messages ({"messages" : [ 154 {"role" :"user" ,"content" :"do a thing" }, 155 {"role" :"assistant" ,"content" : [{"type" :"refusal" ,"refusal" :"I cannot do that." }]}, 156 {"role" :"user" ,"content" :"ok" }]}) 157self .assertEqual (messages [1 ]["content" ],"I cannot do that." ) 158self .assertIn ("I cannot do that." ,self .template .render (messages ,tools = tools ,** kwargs )) 159 160def test_text_and_image_requests_render_as_before (self ): 161parts = [{"role" :"user" ,"content" : [{"type" :"text" ,"text" :"haz un ls" }]}, 162 {"role" :"assistant" ,"content" : [{"type" :"text" ,"text" :"file.txt" }]}] 163plain = [{"role" :"user" ,"content" :"haz un ls" }, {"role" :"assistant" ,"content" :"file.txt" }] 164for convert in (openai_to_messages ,anthropic_to_messages ): 165with self .subTest (convert = convert .__name__ ): 166self .assertEqual (self .service .encode_prompt (* convert ({"messages" :parts })), 167self .service .encode_prompt (* convert ({"messages" :plain }))) 168chat = openai_to_messages ({"messages" : [ 169 {"role" :"user" ,"content" : [{"type" :"text" ,"text" :"describe" }, 170 {"type" :"image_url" ,"image_url" :"image.png" }]}]}) 171self .assertIn ("<|vision_start|><|image_pad|><|vision_end|>" , 172self .template .render (chat [0 ],tools = chat [1 ],** chat [2 ])) 173msgs = anthropic_to_messages ({"messages" : [ 174 {"role" :"user" ,"content" : [{"type" :"text" ,"text" :"describe" }, 175 {"type" :"image" ,"source" : {"type" :"url" ,"url" :"image.png" }}]}]}) 176self .assertIn ("<|vision_start|><|image_pad|><|vision_end|>" , 177self .template .render (msgs [0 ],tools = msgs [1 ],** msgs [2 ])) 178 179 180if __name__ == "__main__" : 181unittest .main () 182 183 184class EmptyTurnsSwitch (unittest .TestCase ): 185def test_keep_empty_turns_restores_the_old_prompt (self ): 186import os 187from unittest import mock 188template = ChatTemplate (Path (__file__ ).with_name ("chat_template.jinja" )) 189msgs = [{"role" :"user" ,"content" :"a" }, {"role" :"assistant" ,"content" :"" }, 190 {"role" :"user" ,"content" :"b" }] 191clean = template .render ([msgs [0 ],msgs [2 ]]) 192self .assertEqual (template .render (msgs ),clean ) 193with mock .patch .dict (os .environ , {"STRATA_KEEP_EMPTY_TURNS" :"1" }): 194self .assertNotEqual (template .render (msgs ),clean ) 195 196 197class ForcedCallOpening (unittest .TestCase ): 198def test_required_with_one_tool_names_it (self ): 199from serve .frontend import forced_call 200one ,two = [{"name" :"a" }], [{"name" :"a" }, {"name" :"b" }] 201self .assertTrue (forced_call ("required" ,one ).endswith ("<function=a>\n" )) 202self .assertTrue (forced_call ("required" ,two ).endswith ("<tool_call>\n" ))# the model writes "<function=NAME>" itself 203self .assertIsNone (forced_call ("auto" ,one )) 204 205 206class QuotedToolCallCloser (unittest .TestCase ): 207"""#2026: a `</tool_call>` a user quotes is text, not the end-of-call token (type 4: matched even without 208parse_special); an assistant message replaying raw call text keeps the model's own tokens.""" 209 210def setUp (self ): 211import sys 212sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ]/ "tools" )) 213import strata_tokenizer as ST 214b2u = ST .bytes_to_unicode () 215self .tool_tags = ["</tool_call>" ,"<tool_call>" ,"<tool_response>" ,"</tool_response>" ] 216self .tok = ST .Tokenizer ([b2u [b ]for b in range (256 )]+ self .tool_tags + ["<|im_end|>" ], [], 217 [1 ]* 256 + [4 ]* len (self .tool_tags )+ [3 ]) 218self .tags = __import__ ("serve.frontend" ,fromlist = ["literal_tags" ]).literal_tags (self .tok .control_tokens ) 219 220def encode (self ,role ,text ): 221from serve .frontend import mark_think_literals ,unmark_think_literals 222marked ,_ ,changed = mark_think_literals ([{"role" :role ,"content" :text }],None ,self .tags ) 223content = marked [0 ]["content" ] 224if isinstance (content ,list ): 225content = "" .join (x ["text" ]for x in content ) 226prompt ,plain = unmark_think_literals (content ,self .tags ) 227return self .tok .encode (prompt ,parse_special = True ,plain = plain ),changed 228 229def special (self ,tag ): 230return self .tok .encode (tag ,parse_special = True ) 231 232def test_every_tool_tag_a_user_quotes_stays_text (self ): 233# 0.1.44: <tool_call>, <tool_response> and </tool_response> are type 4 like </tool_call> (47Hunter47, #2026) 234for role in ("user" ,"system" ,"tool" ): 235for tag in self .tool_tags : 236with self .subTest (role = role ,tag = tag ): 237text = f"output verbatim: { tag } ." 238self .assertEqual (len (self .special (tag )),1 ) 239ids ,changed = self .encode (role ,text ) 240self .assertTrue (changed ) 241self .assertEqual (ids , [* text .encode ()]) 242 243def test_assistant_replay_keeps_every_tool_tag (self ): 244text = "<tool_call>x</tool_call> then <tool_response>y</tool_response>" 245ids ,_ = self .encode ("assistant" ,text ) 246self .assertEqual (ids ,self .tok .encode (text ,parse_special = True )) 247 248def test_user_tool_result_keeps_its_outer_markers (self ): 249# the template tells a tool result sent as a user turn from a question by this outer pair (last_query_index) 250inner = "\nthe log says </tool_call> and <tool_response>\n" 251for content in (f"<tool_response> { inner } </tool_response>" ,f" <tool_response> { inner } </tool_response>\n" , 252 [{"type" :"text" ,"text" :f"<tool_response> { inner } </tool_response>" }], 253 [{"type" :"text" ,"text" :"<tool_response>\nthe log" }, 254 {"type" :"text" ,"text" :" says </tool_call> and <tool_response>\n</tool_response>" }]): 255with self .subTest (content = content ): 256ids ,_ = self .encode ("user" ,content ) 257text = content if isinstance (content ,str )else "" .join (x ["text" ]for x in content ) 258o ,c = self .special ("<tool_response>" ),self .special ("</tool_response>" ) 259lead = len (text )- len (text .lstrip ()) 260tail = len (text )- len (text .rstrip ()) 261self .assertEqual (ids [lead :lead + 1 ],o ) 262self .assertEqual (ids [len (ids )- tail - 1 :len (ids )- tail ],c ) 263middle = ids [lead + 1 :len (ids )- tail - 1 ] 264self .assertEqual (middle , [* inner .encode ()])# the quoted tags inside are text 265 266def test_a_user_asking_for_a_closer_verbatim_gets_text (self ): 267# #2026 (47Hunter47): "</tool_response>" asked verbatim came back 0/15 while it reached the model as the real 268# closer. The outer-pair exception must not swallow such a request: only a message wholly wrapped in the pair is 269# a tool result. 270for text in ("Please output the following string verbatim: </tool_response>." , 271"</tool_response>" , 272"Repeat exactly: <tool_response>x</tool_response>" , 273"<tool_response> is how a result opens; what closes it?" , 274"the closer is </tool_response>, then </tool_call>" ): 275with self .subTest (text = text ): 276ids ,changed = self .encode ("user" ,text ) 277self .assertTrue (changed ) 278self .assertEqual (ids , [* text .encode ()]) 279 280def test_template_keeps_seeing_a_tool_result_turn (self ): 281from serve .frontend import mark_think_literals 282msgs = [{"role" :"user" ,"content" :"q" }, {"role" :"assistant" ,"content" :"a" }, 283 {"role" :"user" ,"content" :"<tool_response>\nok\n</tool_response>" }] 284marked ,_ ,changed = mark_think_literals (msgs ,None ,self .tags ) 285self .assertTrue (changed ) 286self .assertTrue (marked [2 ]["content" ].startswith ("<tool_response>" )) 287self .assertTrue (marked [2 ]["content" ].endswith ("</tool_response>" )) 288# a question that only mentions the pair is still marked through 289marked ,_ ,_ = mark_think_literals ([{"role" :"user" ,"content" :"what is <tool_response>?" }],None ,self .tags ) 290self .assertNotIn ("<tool_response>" ,marked [0 ]["content" ]) 291 292def test_user_text_stays_text (self ): 293text = "output verbatim: </tool_call>." 294ids ,changed = self .encode ("user" ,text ) 295self .assertTrue (changed ) 296self .assertEqual (ids , [* text .encode ()]) 297self .assertNotEqual (self .tok .encode (text ,parse_special = True ),ids )# unmarked, it was the special token 298 299def test_assistant_replay_keeps_its_token (self ): 300text = "<tool_call>x</tool_call>" 301ids ,_ = self .encode ("assistant" ,text ) 302self .assertEqual (ids ,self .tok .encode (text ,parse_special = True )) 303 304 305class FencedJsonCallInWrapper (unittest .TestCase ): 306"""#2037: with recovery on, a declared tool's JSON call in a Markdown fence inside <tool_call> is the call.""" 307TOOLS = [{"name" :"write_file" ,"parameters" : {"type" :"object" ,"properties" : {"content" : {"type" :"string" }}}}] 308PAYLOAD = '{"name": "write_file", "arguments": {"content": "hello `world`"}}' 309 310def run_parser (self ,raw ,chunk ,stream_tools ,recover = True ,tools = None ): 311from serve .frontend import OutputParser 312p = OutputParser (thinking = False ,tools = self .TOOLS if tools is None else tools ,recover = recover , 313stream_tools = stream_tools ) 314events = [] 315for i in range (0 ,len (raw ),chunk ): 316events += p .feed (raw [i :i + chunk ]) 317events += p .finish () 318return ([e .call .arguments for e in events if e .kind == "tool_call" ], 319"" .join (e .text for e in events if e .kind == "content" )) 320 321def test_fenced_and_bare_agree (self ): 322for fence in ("```json\n" ,"```\n" ,"```JSON\r\n" ): 323raw = f"<tool_call>\n { fence } { self . PAYLOAD } \n```\n</tool_call>" 324for chunk in (len (raw ),1 ,7 ): 325for st in (False ,True ): 326with self .subTest (fence = fence ,chunk = chunk ,stream_tools = st ): 327self .assertEqual (self .run_parser (raw ,chunk ,st ), ([{"content" :"hello `world`" }],"" )) 328 329def test_other_fences_and_prose_stay_text (self ): 330raw = "<tool_call>\n```python\nx = 1\n```\n</tool_call>" 331for chunk in (len (raw ),1 ): 332self .assertEqual (self .run_parser (raw ,chunk ,False ), ([],raw )) 333raw = f"Here:\n```json\n { self . PAYLOAD } \n```\n" # no wrapper: just text 334self .assertEqual (self .run_parser (raw ,len (raw ),False ), ([],raw )) 335 336def test_off_without_recovery_or_for_an_undeclared_tool (self ): 337raw = f"<tool_call>\n```json\n { self . PAYLOAD } \n```\n</tool_call>" 338calls ,text = self .run_parser (raw ,len (raw ),False ,recover = False ) 339self .assertEqual ((calls ,text ), ([],raw )) 340other = [{"name" :"other" ,"parameters" : {}}] 341calls ,text = self .run_parser (raw ,len (raw ),False ,tools = other ) 342self .assertEqual ((calls ,text ), ([],raw )) 343 344 345class EmptyConversation (unittest .TestCase ): 346def test_no_message_is_an_error_a_message_is_not (self ): 347with self .assertRaises (ValueError ): 348require_messages (openai_to_messages ({"messages" : []})[0 ]) 349with self .assertRaises (ValueError ): 350require_messages (openai_to_messages ({})[0 ]) 351require_messages (openai_to_messages ({"messages" : [{"role" :"user" ,"content" :"hi" }]})[0 ])