okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""serve/frontend.py - plan v0.3 P8: the request/response layer between API clients and the engine. 2 3Everything here is text: no model, no GPU. The engine consumes token ids and produces text deltas; this module 4 5* normalizes OpenAI Chat Completions and Anthropic Messages requests into the chat template's message form, 6* renders the model's own Jinja chat template (pack `tokenizer/chat_template.jinja`) exactly as Hugging Face 7does (checked against the pack's `chat_golden.json`, 10 cases incl. thinking and tools), 8* parses the streamed output incrementally into reasoning (`<think>...</think>`), content and tool calls in 9the template's XML form (`<tool_call><function=NAME><parameter=P>VALUE</parameter>...</function></tool_call>`), 10never emitting a partial tag to the client. 11 12Design note: plan v0.3 describes a single C++ process. The frontend is Python first because the template is Jinja 13and the formats change often; the engine boundary is token ids in, text deltas out, which keeps a later C++ port 14(or a pybind wrapper) a local change. 15""" 16from __future__import annotations 17 18import json 19import logging 20import os 21import re 22import threading 23import uuid 24from collections import OrderedDict 25from dataclasses import dataclass ,field 26from pathlib import Path 27 28import jinja2 29from jinja2 .sandbox import ImmutableSandboxedEnvironment 30 31LOGGER = logging .getLogger (__name__ ) 32 33 34# ------------------------------------------------------------------------------------------------ template 35class TemplateRequestError (jinja2 .exceptions .TemplateError ,ValueError ): 36"""The template refused the request's messages (e.g. "No user query found in messages."): a ValueError, so the 37client gets a 400 with the template's message instead of a dropped connection (#365).""" 38 39 40class ChatTemplate : 41"""The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template.""" 42 43def __init__ (self ,path :str | Path ): 44def raise_exception (message ): 45raise TemplateRequestError (message ) 46 47def tojson (x ,ensure_ascii = False ,indent = None ,separators = None ,sort_keys = False ): 48return json .dumps (x ,ensure_ascii = ensure_ascii ,indent = indent ,separators = separators ,sort_keys = sort_keys ) 49 50env = ImmutableSandboxedEnvironment (trim_blocks = True ,lstrip_blocks = True ,extensions = ["jinja2.ext.loopcontrols" ]) 51env .filters ["tojson" ]= tojson 52env .globals ["raise_exception" ]= raise_exception 53self .source = Path (path ).read_text (encoding = "utf-8" ) 54self .template = env .from_string (self .source ) 55self .caps = self ._detect_caps () 56 57def render (self ,messages :list [dict ],tools :list [dict ]| None = None ,add_generation_prompt :bool = True , 58** kwargs )-> str : 59# Do not use completed empty assistant turns as examples for the next reply. Keep the final message. 60# (#843. STRATA_KEEP_EMPTY_TURNS=1 renders them as before.) 61messages = [m for i ,m in enumerate (messages ) 62if i == len (messages )- 1 or os .environ .get ("STRATA_KEEP_EMPTY_TURNS" )== "1" or not (isinstance (m ,dict )and m .get ("role" )== "assistant" 63and not _text_of (m .get ("content" )).strip () 64and not _has_image (m .get ("content" ))and not m .get ("tool_calls" ))] 65return self .template .render (messages = messages ,tools = tools ,add_generation_prompt = add_generation_prompt , 66** kwargs ) 67 68def _detect_caps (self )-> dict [str ,bool ]: 69"""llama.cpp's capability names, checked at load time against this template and Strata's tool-call format. 70These are rendering hints, not a guarantee that the model will follow a request.""" 71def render (messages ,tools = None ): 72try : 73return self .render (messages ,tools = tools ) 74except Exception as exc :# noqa: BLE001 - a hint only: never stop the server for a probe 75# A template may reject a role or feature (a custom one may fail in any way): the feature is off, 76# discovery still answers for the others, and the start-up goes on. 77LOGGER .debug ("chat template capability probe failed: %s" ,exc ,exc_info = True ) 78return "" 79 80user = {"role" :"user" ,"content" :"strata_caps_user" } 81tools = [{"name" :f"strata_caps_call_ { i } " ,"description" :"strata_caps_description" , 82"parameters" : {"type" :"object" ,"properties" : {"arg" : {"type" :"string" }}}} 83for i in range (2 )] 84tool_prompt = render ([user ],tools ) 85 86def calls_supported (count ): 87calls = [{"name" :f"strata_caps_call_ { i } " ,"arguments" : {"arg" :f"strata_caps_arg_ { i } " }} 88for i in range (count )] 89messages = [user , {"role" :"assistant" ,"content" :"" , 90"tool_calls" : [{"function" :call }for call in calls ]}] 91replies = [f"strata_caps_result_ { i } " for i in range (count )] 92messages += [{"role" :"tool" ,"content" :reply }for reply in replies ]+ [user ] 93prompt = render (messages ,tools ) 94# Instructions include example XML and literal tag names, which are not model output. Parse only 95# complete calls to our probe functions, using the same body parser as OutputParser. 96bodies = re .findall (r"<tool_call>\s*(<function=strata_caps_call_\d+>.*?</function>)\s*</tool_call>" , 97prompt ,re .S ) 98try : 99parsed = [parse_tool_call (body )for body in bodies ] 100except ValueError : 101return False 102return [{"name" :call .name ,"arguments" :call .arguments }for call in parsed ]== calls \ 103and all (reply in prompt for reply in replies ) 104 105history = [user , {"role" :"assistant" ,"content" :"strata_caps_answer" , 106"reasoning_content" :"strata_caps_reasoning" },user ] 107return {"supports_tools" :all (s in tool_prompt for s in 108 ("strata_caps_call_0" ,"strata_caps_description" ,"<tool_call>" ,"<function=" )), 109"supports_tool_calls" :calls_supported (1 ), 110"supports_system_role" :"strata_caps_system" in render ( 111 [{"role" :"system" ,"content" :"strata_caps_system" },user ]), 112"supports_parallel_tool_calls" :calls_supported (2 ), 113"supports_preserve_reasoning" :"strata_caps_reasoning" in render (history )} 114 115 116# ------------------------------------------------------------------------------------------------ requests 117# The content-part types the readers take as text (a part with no type that has a "text" field reads as text too) 118TEXT_PARTS = ("text" ,"input_text" ,None ) 119 120 121def _text_of (content )-> str : 122if content is None : 123return "" 124if isinstance (content ,str ): 125return content 126return "" .join (part .get ("text" ,"" )for part in content if isinstance (part ,dict )and part .get ("type" )in 127TEXT_PARTS ) 128 129 130IMAGE_PARTS = ("image_url" ,"input_image" ,"image" ) 131 132# Thinking levels. The model's template knows low, medium and xhigh (its default; "high" means xhigh), and 133# enable_thinking=false for none. Clients spell these many ways; everything maps onto those four. 134EFFORT = {"none" :None ,"off" :None ,"minimal" :None ,"disabled" :None ,"false" :None , 135"low" :"low" ,"medium" :"medium" ,"high" :"xhigh" ,"xhigh" :"xhigh" ,"max" :"xhigh" ,"maximum" :"xhigh" } 136 137 138# DeepSeek-V4.1's template takes low, medium, high (its default) and max, or a whole number 1..100 (the "Reasoning 139# Effort: N" line of its prompt). use_family("deepseek41") switches the table; the other families keep the one above. 140EFFORT_DEEPSEEK = {"none" :None ,"off" :None ,"minimal" :None ,"disabled" :None ,"false" :None , 141"low" :"low" ,"medium" :"medium" ,"high" :"high" ,"xhigh" :"max" ,"max" :"max" ,"maximum" :"max" } 142_EFFORT_QWEN = dict (EFFORT ) 143_NUMERIC_EFFORT = False 144 145 146def use_family (family :str | None )-> None : 147"""The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER).""" 148global _NUMERIC_EFFORT 149EFFORT .clear () 150EFFORT .update (EFFORT_DEEPSEEK if family == "deepseek41" else _EFFORT_QWEN ) 151_NUMERIC_EFFORT = family == "deepseek41" 152 153 154def effort_kwargs (value )-> dict : 155"""A reasoning effort as given by a client -> the template's kwargs. Unknown values are a 400, not a crash.""" 156if value is None or value == "" : 157return {} 158if value is False : 159return {"enable_thinking" :False } 160if _NUMERIC_EFFORT and isinstance (value ,int )and not isinstance (value ,bool ): 161if not 1 <= value <= 100 : 162raise ValueError (f"unknown reasoning effort { value !r } : use none, low, medium, high, max or 1..100" ) 163return {"reasoning_effort" :value } 164key = str (value ).strip ().lower () 165if key not in EFFORT : 166raise ValueError (f"unknown reasoning effort { value !r } : use none, low, medium or high" 167+ (", max or 1..100" if _NUMERIC_EFFORT else "" )) 168level = EFFORT [key ] 169return {"enable_thinking" :False }if level is None else {"reasoning_effort" :level } 170 171 172def budget_effort (tokens )-> dict : 173"""Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high.""" 174try : 175n = int (tokens ) 176except (TypeError ,ValueError ): 177return {} 178return {"reasoning_effort" :"low" if n < 2048 else "medium" if n < 8192 else EFFORT ["high" ]} 179 180 181def _has_image (content )-> bool : 182return isinstance (content ,list )and any (isinstance (p ,dict )and p .get ("type" )in IMAGE_PARTS for p in content ) 183 184 185def _image_source (part :dict )-> str : 186"""An image part's source as one string: a data: URL, an http(s) URL or a local file path. 187OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style 188{"type": "input_image", "image_url": ...}; Anthropic: {"type": "image", "source": {"type": "base64", 189"media_type": ..., "data": ...}} or {"source": {"type": "url", "url": ...}}.""" 190if part .get ("type" )== "image" : 191src = part .get ("source" )or {} 192if src .get ("type" )== "base64" : 193return f"data: { src . get ( 'media_type' , 'image/png' ) } ;base64, { src . get ( 'data' , '' ) } " 194return src .get ("url" )or src .get ("path" )or "" 195url = part .get ("image_url" ) 196if isinstance (url ,dict ): 197url = url .get ("url" ) 198return url or "" 199 200 201def _parts_of (content ): 202"""Message content for the template: a string when there is no image (unchanged behaviour), otherwise the 203template's list form - text items and image items, in order - whose image items carry their source.""" 204if not _has_image (content ): 205return _text_of (content ) 206items = [] 207for part in content : 208if not isinstance (part ,dict ): 209continue 210if part .get ("type" )in IMAGE_PARTS : 211items .append ({"type" :"image" ,"source" :_image_source (part )}) 212elif part .get ("type" )in TEXT_PARTS and "text" in part : 213items .append ({"type" :"text" ,"text" :part .get ("text" ,"" )}) 214return items 215 216 217# The blocks a messages request may carry: text, the image parts, thinking, tool_use and tool_result. 218# redacted_thinking is allowed only to be dropped without an error: another server's encrypted reasoning, which 219# carries nothing this server can read - the same reason responses.py's _reasoning_text gives for another server's 220# encrypted_content. 221ANTHROPIC_BLOCKS = ("text" ,)+ IMAGE_PARTS + ("thinking" ,"tool_use" ,"tool_result" ,"redacted_thinking" ) 222 223 224def _check_parts (content ,path :str ,kinds ): 225"""A request's content parts (on chat) or content blocks (on messages), looked at while the request is converted. 226A part whose type this server does not read (a file, audio, a document, Anthropic's tool_reference, 227search_result, server_tool_use / web_search_tool_result blocks, ...) is left out of the prompt exactly as it always 228was, with a debug line: real clients (Claude Code, Codex, opencode, Cline, Continue, Open WebUI) send such parts 229next to text the model can answer from, so refusing them would break requests that work. A "refusal" part is read 230as its text, as /v1/responses does. Content that is not a list, and a part that is not an object, passes through 231unchanged.""" 232if not isinstance (content ,list ): 233return content 234out = content 235for j ,part in enumerate (content ): 236if not isinstance (part ,dict ): 237continue 238kind = part .get ("type" ) 239if kind == "refusal" : 240if out is content : 241out = list (content ) 242out [j ]= {"type" :"text" ,"text" :part .get ("refusal" )or "" } 243elif kind not in kinds : 244LOGGER .debug ("%s[%d].type: content part of type %r is not read by this server; left out of the prompt" , 245path ,j ,kind ) 246return out 247 248 249def images_of (messages :list [dict ])-> list [str ]: 250"""The image sources of the rendered conversation, in prompt order (the template renders one 251<|vision_start|><|image_pad|><|vision_end|> per image item, message by message).""" 252return [item ["source" ]for m in messages if isinstance (m .get ("content" ),list ) 253for item in m ["content" ]if item .get ("type" )== "image" ] 254 255 256# #537: a literal <think> / </think> inside a message's text is plain text, not the model's reasoning markers. The 257# tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so 258# a user quoting "</think>" used to hand the model a real end-of-reasoning token. Before the template is rendered 259# they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text. 260THINK_TAGS = {"<think>" :"\U000F0E01" ,"</think>" :"\U000F0E02" } 261# #554: the vision markers the same way. They are special tokens only where the template writes them for an image 262# item; the same strings in a message's text (an agent reading chat_template.jinja, a tool result quoting it) became 263# the same special ids, so text with <|vision_start|><|image_pad|> before a picture took that picture's embeddings 264VISION_TAGS = {"<|vision_start|>" :"\U000F0E03" ,"<|image_pad|>" :"\U000F0E04" ,"<|vision_end|>" :"\U000F0E05" , 265"<|video_pad|>" :"\U000F0E06" } 266# #2026: `</tool_call>` the same way. A user asking for the string verbatim handed the model the real end-of-call token 267# (type 4, matched everywhere); it copied that token into its answer and the reply came back empty. An assistant 268# message keeps its own: a client replaying the model's raw call text sends the tokens the model wrote. 269# 0.1.44: `<tool_call>`, `<tool_response>` and `</tool_response>` are type 4 too (ids 248058, 248066, 248070), so a quoted 270# one handed the model the real call / tool-result marker in the same way (found by 47Hunter47 in #2026). The template 271# writes the tool-result markers around a tool message itself; only the text inside a message is marked. 272TOOL_LITERAL_TAGS = {"</tool_call>" :"\U000F0E07" ,"<tool_call>" :"\U000F0E08" ,"<tool_response>" :"\U000F0E09" , 273"</tool_response>" :"\U000F0E0A" } 274LITERAL_TAGS = {** THINK_TAGS ,** VISION_TAGS ,** TOOL_LITERAL_TAGS } 275THINK_MARKS = {v :k for k ,v in LITERAL_TAGS .items ()} 276CONTROL_MARK0 = 0xF0E10 # the control tokens' marks start here, clear of the two sets above 277 278 279def literal_tags (controls )-> dict [str ,str ]: 280"""LITERAL_TAGS plus a mark for each control token's text (`controls`: the tokenizer's CONTROL literals, 281<|im_start|>, <|im_end|>, <|endoftext|>, ...). The rendered prompt is encoded with those literals parsed, so one 282written inside a message - a file an agent reads, a pasted chat template - opened or ended a turn there. Longest 283first, as the tokenizer matches them: a literal inside a longer one is not marked before it.""" 284tags = {** LITERAL_TAGS ,** {c :chr (CONTROL_MARK0 + k )for k ,c in enumerate (c for c in controls 285if c not in LITERAL_TAGS )}} 286return dict (sorted (tags .items (),key = lambda t :- len (t [0 ]))) 287 288 289def _mark (text :str ,tags :dict [str ,str ]= LITERAL_TAGS )-> str : 290for tag ,mark in tags .items (): 291text = text .replace (tag ,mark ) 292return text 293 294 295def _mark_deep (v ,tags :dict [str ,str ]= LITERAL_TAGS ): 296if isinstance (v ,str ): 297return _mark (v ,tags ) 298if isinstance (v ,dict ): 299return {k :_mark_deep (x ,tags )for k ,x in v .items ()} 300if isinstance (v ,list ): 301return [_mark_deep (x ,tags )for x in v ] 302return v 303 304 305def _has_tag (v ,tags :dict [str ,str ]= LITERAL_TAGS )-> bool : 306if isinstance (v ,str ): 307return any (tag in v for tag in tags ) 308if isinstance (v ,dict ): 309return any (_has_tag (x ,tags )for x in v .values ()) 310if isinstance (v ,list ): 311return any (_has_tag (x ,tags )for x in v ) 312return False 313 314 315_TOOL_RESULT_OPEN ,_TOOL_RESULT_CLOSE = "<tool_response>" ,"</tool_response>" 316 317 318def _keep_tool_result_wrap (content ,tags :dict [str ,str ]): 319"""A user message whose whole text is <tool_response>...</tool_response> (a client that formats a tool result the way 320the template does for a tool message) keeps that outer pair as the markers - the template tells such a turn from a 321real question by exactly that pair - and only the text inside is marked. None: not such a message.""" 322o ,c = _TOOL_RESULT_OPEN ,_TOOL_RESULT_CLOSE 323 324def wrap (text :str ,first :bool ,last :bool )-> str : 325i = text .index (o )+ len (o )if first else 0 326j = text .rindex (c )if last else len (text ) 327head = _mark (text [:i - len (o )],tags )+ o if first else "" 328tail = c + _mark (text [j + len (c ):],tags )if last else "" 329return head + _mark (text [i :j ],tags )+ tail 330 331if isinstance (content ,str ): 332body = content .strip () 333if len (body )>= len (o )+ len (c )and body .startswith (o )and body .endswith (c ): 334return wrap (content ,True ,True ) 335return None 336if not (isinstance (content ,list )and content and all (isinstance (x ,dict )and "text" in x for x in content )): 337return None 338texts = [x ["text" ]for x in content ] 339if not all (isinstance (t ,str )for t in texts ): 340return None 341body = "" .join (texts ).strip () 342if not (len (body )>= len (o )+ len (c )and body .startswith (o )and body .endswith (c )): 343return None 344if not (texts [0 ].lstrip ().startswith (o )and texts [- 1 ].rstrip ().endswith (c )): 345return None # the pair is split across parts: mark it all, as before 346if len (content )== 1 : 347return [{** content [0 ],"text" :wrap (texts [0 ],True ,True )}] 348return ([{** content [0 ],"text" :wrap (texts [0 ],True ,False )}]+ 349 [_mark_deep (x ,tags )for x in content [1 :- 1 ]]+ 350 [{** content [- 1 ],"text" :wrap (texts [- 1 ],False ,True )}]) 351 352 353def mark_think_literals (messages :list [dict ],tools :list [dict ]| None ,tags :dict [str ,str ]= LITERAL_TAGS ): 354"""#537: (messages, tools) with every literal <think> / </think> (#554: and vision marker) in their text swapped for 355LITERAL_TAGS' marks (or `tags`': literal_tags() adds the control tokens' texts), and 356whether there was one (None: no change, the same objects back - a prompt without them renders as it always did). 357An assistant message whose content opens with a whole <think>...</think> block (clients that send the reasoning 358inline) keeps that one block as the model's markers, as before.""" 359if not _has_tag (messages ,tags )and not _has_tag (tools ,tags ): 360return messages ,tools ,False 361out = [] 362own = {t :v for t ,v in tags .items ()if t not in TOOL_LITERAL_TAGS }# what an assistant message keeps as written 363for m in messages : 364m = dict (m ) 365content = m .get ("content" ) 366mine = own if m .get ("role" )== "assistant" else tags 367for k ,v in m .items (): 368if k != "role" : 369m [k ]= _mark_deep (v ,mine ) 370if m .get ("role" )== "user" : 371kept = _keep_tool_result_wrap (content ,tags ) 372if kept is not None : 373m ["content" ]= kept 374if m .get ("role" )== "assistant" and isinstance (content ,str )and content .lstrip ().startswith ("<think>" ) \ 375and "</think>" in content : 376i ,j = content .index ("<think>" )+ len ("<think>" ),content .index ("</think>" ) 377m ["content" ]= (content [:i ]+ _mark (content [i :j ],own )+ "</think>" + 378_mark (content [j + len ("</think>" ):],own )) 379out .append (m ) 380return out ,_mark_deep (tools ,tags ),True 381 382 383_THINK_MARK_RE = re .compile ("|" .join (THINK_MARKS )) 384 385 386def unmark_think_literals (prompt :str ,tags :dict [str ,str ]= LITERAL_TAGS )-> tuple [str ,list [tuple [int ,int ]]]: 387"""The rendered prompt with THINK_TAGS' marks turned back into the tags' text, and the (start, end) spans of those 388tags in it: the server encodes them as ordinary text (the tokenizer's encode_plain_spans).""" 389marks = THINK_MARKS if tags is LITERAL_TAGS else {v :k for k ,v in tags .items ()} 390if marks and all (len (k )== 1 for k in marks ): 391# one character each: a range of code points is scanned ~20x faster than their alternation (13 ms for an 392# 80K-token prompt), and a character in the range that is no mark is skipped below 393lo ,hi = min (marks ),max (marks ) 394mark_re = re .compile (f"[ { re . escape ( lo ) } - { re . escape ( hi ) } ]" ) 395else : 396mark_re = _THINK_MARK_RE if tags is LITERAL_TAGS else re .compile ("|" .join (map (re .escape ,marks ))) 397out ,spans ,pos ,n = [], [],0 ,0 398for m in mark_re .finditer (prompt ): 399tag = marks .get (m .group (0 )) 400if tag is None : 401continue 402out .append (prompt [pos :m .start ()]) 403n += m .start ()- pos 404out .append (tag ) 405spans .append ((n ,n + len (tag ))) 406n += len (tag ) 407pos = m .end () 408out .append (prompt [pos :]) 409return "" .join (out ),spans 410 411 412# Config "env_to_user" (opt-in): opencode writes its <env> block (working directory, today's date) near the START of 413# the system message, before ~40K characters of instructions and tool definitions that are the same in every session. 414# The prefix cache only reuses a prompt's start, so a new folder or a new day read all of it again (~14K tokens, 8-11 s). 415# Moved to the front of the first user message, the system turn (and the tools the template writes into it) is the same 416# for every session and the disk prefix cache restores it. The model still sees the same lines, one turn later. 417ENV_TO_USER = False 418_ENV_BLOCK = re .compile (r"(?:[^\n]*environment you are running in:\n)?<env>\n.*?\n</env>\n?" ,re .S ) 419 420 421def _env_to_user (messages :list [dict ])-> list [dict ]: 422if not ENV_TO_USER or not messages or messages [0 ].get ("role" )!= "system" : 423return messages 424sys_text = messages [0 ].get ("content" ) 425if not isinstance (sys_text ,str ): 426return messages 427m = _ENV_BLOCK .search (sys_text ) 428if m is None : 429return messages 430for i in range (1 ,len (messages )): 431if messages [i ].get ("role" )!= "user" : 432continue 433block = m .group (0 ).rstrip ("\n" ) 434c = messages [i ].get ("content" ) 435if isinstance (c ,str ): 436nc = block + "\n\n" + c 437elif isinstance (c ,list ): 438nc = [{"type" :"text" ,"text" :block + "\n\n" }]+ c 439else : 440return messages 441out = list (messages ) 442out [0 ]= dict (messages [0 ],content = sys_text [:m .start ()]+ sys_text [m .end ():]) 443out [i ]= dict (messages [i ],content = nc ) 444return out 445return messages 446 447 448def _late_system_to_user (messages :list [dict ])-> list [dict ]: 449"""The chat template takes a system message only at the start ("System message must be at the beginning"). 450Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user 451turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place: 452merging them into the first one would change the prompt's start and cost the conversation cache every turn.""" 453return [dict (m ,role = "user" )if m .get ("role" )== "system" and i > 0 else m for i ,m in enumerate (messages )] 454 455 456def _object_list (value ,name :str )-> list [dict ]: 457"""#460: a request's "messages" (or a message's "tool_calls") as a list of objects. Some clients send the array 458double-encoded, as a JSON string, which used to be iterated character by character and crashed on m.get: such a 459string is decoded. Anything that is still not a list of objects is a ValueError, which the server answers with 460a 400 naming the field. None (or no field) is an empty list, as a missing field always was.""" 461if value is None : 462return [] 463if isinstance (value ,str ): 464try : 465value = json .loads (value ) 466except ValueError : 467raise ValueError (f" { name } must be a list of objects (a string was sent that is not JSON)" )from None 468if not isinstance (value ,list )or not all (isinstance (m ,dict )for m in value ): 469raise ValueError (f" { name } must be a list of objects" ) 470return value 471 472 473_TOOL_ORDERS :"OrderedDict[frozenset, tuple]" = OrderedDict ()# a set of tool names -> the order it first came in 474_TOOL_ORDERS_LOCK = threading .Lock () 475_TOOL_ORDERS_MAX = 64 476 477 478def _stable_tool_order (tools :list [dict ],name_of )-> list [dict ]: 479"""The same set of tools comes back in the order it was first seen. Clients send their tools in the order their 480MCP servers finished registering, which can differ from one request (or one client restart) to the next, and the 481template renders the tool list before the system prompt: one swap moves the shared prefix back thousands of 482tokens and the whole conversation is read again (opencode issue 23571). A request's first sight of a tool set 483is untouched (so its prompt is byte for byte what the client sent); later requests with the same names in 484another order are put back in that first order. Duplicate names, or a single tool: left as sent.""" 485if len (tools )< 2 : 486return tools 487names = [name_of (t )for t in tools ] 488if len (set (names ))!= len (names ): 489return tools 490key = frozenset (names ) 491with _TOOL_ORDERS_LOCK : 492order = _TOOL_ORDERS .get (key ) 493if order is None : 494_TOOL_ORDERS [key ]= tuple (names ) 495while len (_TOOL_ORDERS )> _TOOL_ORDERS_MAX : 496_TOOL_ORDERS .popitem (last = False ) 497return tools 498_TOOL_ORDERS .move_to_end (key ) 499pos = {n :k for k ,n in enumerate (order )} 500return sorted (tools ,key = lambda t :pos [name_of (t )]) 501 502 503def _tool_list (value ,wrapper :str | None )-> list [dict ]: 504"""#592: a request's "tools" as a list of tool objects, each with a name - in the OpenAI shape 505{"type": "function", "function": {"name": ...}} (`wrapper` "function"; a bare {"name": ...} is still taken), or 506in the Anthropic shape {"name": ...} (`wrapper` None). A value that is not (a string such as "auto", a list of 507names, an object without a name) is a ValueError - a 400 naming the field - where it used to take the request 508thread down with no reply at all. No value (or an empty one) is no tools, as always. A tool's schema - 509"parameters" in the OpenAI shape, "input_schema" in the Anthropic one - is an object when it is there, for the 510same reason: a string or a list passed and raised later instead, on the model's first call of that tool.""" 511if not value : 512return [] 513shape = ('{"type": "function", "function": {"name": ..., "parameters": {...}}}' if wrapper else 514'{"name": ..., "input_schema": {...}}' ) 515try : 516tools = _object_list (value ,"tools" ) 517except ValueError : 518raise ValueError (f"tools must be a list of tool objects, each { shape } " )from None 519key = "parameters" if wrapper else "input_schema" 520for i ,t in enumerate (tools ): 521fn = t .get (wrapper ,t )if wrapper and t .get ("type" )== wrapper else t 522if not isinstance (fn ,dict )or not isinstance (fn .get ("name" ),str )or not fn ["name" ]: 523raise ValueError (f"tools[ { i } ] has no name: each tool must be { shape } " ) 524schema = fn .get (key ) 525if schema is not None and not isinstance (schema ,dict ): 526# it reached parse_tool_call and the stream parser as the tool's schema, whose .get("properties") raised 527# AttributeError in the request thread - after the 200 and whatever the model had said before the call 528raise ValueError (f'tools[ { i } ] ( { fn [ "name" ] } ): " { key } " must be an object (the JSON schema of its ' 529f"parameters), not { type ( schema ). __name__ } " ) 530return _stable_tool_order (tools ,lambda t : (t .get (wrapper ,t )if wrapper and t .get ("type" )== wrapper else t )["name" ]) 531 532 533def tool_arguments (raw )-> dict : 534"""A call's arguments from a client's history -> the mapping the template renders (both APIs). A JSON object 535(as text or already parsed) is used as it is; empty is {}; anything else (cut-off or malformed JSON, a list, a 536number) is kept as text under "arguments" instead of refusing the whole conversation (#510).""" 537if raw is None or (isinstance (raw ,str )and not raw .strip ()): 538return {} 539if isinstance (raw ,dict ): 540return raw 541if isinstance (raw ,str ): 542try : 543value = json .loads (raw ) 544except ValueError : 545return {"arguments" :raw } 546return value if isinstance (value ,dict )else {"arguments" :raw } 547return {"arguments" :json .dumps (raw ,ensure_ascii = False )} 548 549 550def require_messages (messages :list )-> None : 551"""A chat request with no message at all is a 400 (OpenAI: "empty array. Expected an array with minimum length 1"); the 552template would otherwise render just the assistant turn and the model would answer nothing.""" 553if not messages : 554raise ValueError ("messages must be a non-empty list: send at least one message" ) 555 556 557def _order_chat_tool_results (messages :list [dict ])-> None : 558"""The template pairs results by position, so restore call order while IDs are still available. 559 560Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their 561received order. IDs are private to this conversion and never reach the template. 562""" 563i = 0 564while i < len (messages ): 565if messages [i ]["role" ]!= "tool" : 566i += 1 567continue 568j = i + 1 569while j < len (messages )and messages [j ]["role" ]== "tool" : 570j += 1 571prev = messages [i - 1 ]if i else {} 572calls = [c .get ("_call_id" )for c in prev .get ("tool_calls" )or []]if prev .get ("role" )== "assistant" else [] 573results = [m .get ("_call_id" )for m in messages [i :j ]] 574if len (calls )== len (results )and all (isinstance (cid ,str )and cid for cid in calls + results ): 575if len (set (calls ))== len (calls )and len (set (results ))== len (results )and set (calls )== set (results ): 576rank = {cid :n for n ,cid in enumerate (calls )} 577messages [i :j ]= sorted (messages [i :j ],key = lambda m :rank [m ["_call_id" ]]) 578i = j 579for message in messages : 580message .pop ("_call_id" ,None ) 581for call in message .get ("tool_calls" )or []: 582call .pop ("_call_id" ,None ) 583 584 585def openai_to_messages (req :dict )-> tuple [list [dict ],list [dict ]| None ,dict ]: 586"""OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" 587messages = [] 588for i ,m in enumerate (_object_list (req .get ("messages" ),"messages" )): 589role = m .get ("role" ) 590if role == "developer" : 591role = "system" 592# an image is read in a user, tool or assistant message; the system prompt takes text only, as _text_of reads 593images = role in ("user" ,"tool" ,"assistant" ) 594content = _check_parts (m .get ("content" ),f"messages[ { i } ].content" , 595TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS ) 596out = {"role" :role ,"content" :_parts_of (content )if images else _text_of (content )} 597if role == "tool" : 598out ["_call_id" ]= m .get ("tool_call_id" ) 599if m .get ("reasoning_content" ): 600out ["reasoning_content" ]= m ["reasoning_content" ] 601if m .get ("tool_calls" ): 602calls = [] 603for c in _object_list (m ["tool_calls" ],"tool_calls" ): 604fn = c .get ("function" ,c ) 605if not isinstance (fn ,dict ): 606raise ValueError ("tool_calls must be a list of objects (each with a \"function\" object)" ) 607calls .append ({"function" : {"name" :fn .get ("name" ),"arguments" :tool_arguments (fn .get ("arguments" ))}, 608"_call_id" :c .get ("id" )}) 609out ["tool_calls" ]= calls 610messages .append (out ) 611_order_chat_tool_results (messages ) 612tools = [t .get ("function" ,t )if t .get ("type" )== "function" else t 613for t in _tool_list (req .get ("tools" ),"function" )]or None 614kwargs = {} 615# OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...} 616reasoning = req .get ("reasoning" )if isinstance (req .get ("reasoning" ),dict )else {} 617given = req .get ("reasoning_effort" ) 618# `false` is a level (thinking off, effort_kwargs): an `or` between the two fields dropped it 619kwargs .update (effort_kwargs (given if given is not None and given != "" else reasoning .get ("effort" ))) 620# the vLLM / llama.cpp convention: {"chat_template_kwargs": {"enable_thinking": false, "reasoning_effort": "low"}} 621for k ,v in (req .get ("chat_template_kwargs" )or {}).items (): 622if k == "enable_thinking" and not v : 623kwargs = {"enable_thinking" :False } 624elif k == "reasoning_effort" and "enable_thinking" not in kwargs : 625kwargs .update (effort_kwargs (v )) 626return _env_to_user (_late_system_to_user (messages )),tools ,kwargs 627 628 629BILLING_HEADER = "x-anthropic-billing-header:" 630 631 632def pin_billing_stamp (system :str )-> str : 633"""Claude Code starts its system prompt with `x-anthropic-billing-header: cc_version=2.1.170.bf4; 634cc_entrypoint=sdk-cli; cch=b145e;`. cch changes on EVERY request and the version's 4th part on every session, so 635the prompt changed ~22K tokens in (after the tool list) on every turn and the conversation cache could only reuse 636up to its last 16K checkpoint: half of every agent prompt was read again. Both stamps are pinned to f's, as 637llama.cpp does (ggml-org/llama.cpp#21793); only a header at the very start of the system text is touched, and 638only inside its first 160 characters.""" 639if not system .startswith (BILLING_HEADER ): 640return system 641s = list (system ) 642cch = system .find ("cch=" ,len (BILLING_HEADER )) 643if 0 <= cch <= 160 : 644v ,end = cch + 4 ,system .find (";" ,cch + 4 ) 645if end > v and end - v <= 16 : 646s [v :end ]= "f" * (end - v ) 647cv = system .find ("cc_version=" ) 648if 0 <= cv <= 160 : 649v ,end = cv + len ("cc_version=" ),system .find (";" ,cv ) 650if v < end and end - v <= 64 : 651parts = system [v :end ].split ("." ) 652if len (parts )> 3 : 653tail = v + len ("." .join (parts [:3 ]))+ 1 654s [tail :end ]= "f" * (end - tail ) 655return "" .join (s ) 656 657 658def _anthropic_tool (t :dict )-> dict : 659"""An Anthropic tool -> the template's form of it (also what the output parser reads its schema from).""" 660return {"name" :t ["name" ],"description" :t .get ("description" ,"" ),"parameters" :t .get ("input_schema" , {})} 661 662 663def anthropic_tools (req :dict )-> tuple [list [dict ]| None ,bool ]: 664"""#4663, Anthropic's tool search: (every tool the request declared, the `defer_loading` ones included, whether any 665tool is deferred). A deferred tool is callable although the prompt does not list it. A client that defers tools 666(Claude Code) holds back more than it declares - it names the rest in the conversation and runs a call for any of 667them - so with one deferred tool a call for an undeclared name is a call too (OutputParser's `deferred`).""" 668tools = _tool_list (req .get ("tools" ),None ) 669return [_anthropic_tool (t )for t in tools ]or None ,any (t .get ("defer_loading" )for t in tools ) 670 671 672def _tool_references (content ,deferred :dict ): 673"""A tool_result's tool_reference blocks (a tool search's results) -> the referenced deferred tools' definitions, 674in the form the prompt lists tools: the model sees a tool where it was loaded, and the prompt's start (its tool 675list) stays the same, so the prompt cache does too. Any other reference is left out as before (_check_parts): a 676listed tool is in the prompt already, and an old one (its MCP server gone) must not fail the rest of the session.""" 677if not isinstance (content ,list ): 678return content 679return [{"type" :"text" ,"text" :"<tools>\n" + json .dumps (deferred [p .get ("tool_name" )],ensure_ascii = False )+ "\n</tools>" } 680if isinstance (p ,dict )and p .get ("type" )== "tool_reference" and isinstance (p .get ("tool_name" ),str ) 681and p ["tool_name" ]in deferred else p 682for p in content ] 683 684 685def anthropic_to_messages (req :dict ,think_unasked :bool = True )-> tuple [list [dict ],list [dict ]| None ,dict ]: 686"""Anthropic Messages -> (template messages, template tools, template kwargs). `think_unasked`: a request 687without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False 688renders it without thinking (#278, the config's "anthropic_thinking": "on_request").""" 689declared = _tool_list (req .get ("tools" ),None ) 690# #4663: a `defer_loading` tool stays out of the prompt's tool list until a tool_reference loads it 691deferred = {t ["name" ]:_anthropic_tool (t )for t in declared if t .get ("defer_loading" )} 692messages = [] 693system = req .get ("system" ) 694if system : 695messages .append ({"role" :"system" , 696"content" :pin_billing_stamp (_text_of (_check_parts (system ,"system" ,TEXT_PARTS )))}) 697for i ,m in enumerate (_object_list (req .get ("messages" ),"messages" )): 698content = _check_parts (m .get ("content" ),f"messages[ { i } ].content" ,ANTHROPIC_BLOCKS ) 699if isinstance (content ,str ): 700messages .append ({"role" :m ["role" ],"content" :content }) 701continue 702if m .get ("role" )== "user" and _has_image (content )and not any ( 703isinstance (b ,dict )and b .get ("type" )== "tool_result" for b in content ): 704messages .append ({"role" :"user" ,"content" :_parts_of (content )}) 705continue 706text ,reasoning ,calls ,parts = [], [], [], [] 707for j ,block in enumerate (content or []): 708kind = block .get ("type" ) 709if kind == "text" : 710text .append (block .get ("text" ,"" )) 711parts .append (block ) 712elif kind in IMAGE_PARTS : 713parts .append (block ) 714elif kind == "thinking" : 715reasoning .append (block .get ("thinking" ,"" )) 716elif kind == "tool_use" : 717calls .append ({"function" : {"name" :block .get ("name" ),"arguments" :tool_arguments (block .get ("input" ))}, 718"_call_id" :block .get ("id" )}) 719elif kind == "tool_result" : 720# A tool's image (Claude Code's Read of a picture) reaches the encoder like a user's, as the OpenAI 721# path's tool messages already do; a text-only result is one string, as before. 722messages .append ({"role" :"tool" ,"content" :_parts_of (_check_parts ( 723_tool_references (block .get ("content" ),deferred ), 724f"messages[ { i } ].content[ { j } ].content" ,TEXT_PARTS + IMAGE_PARTS )), 725"_call_id" :block .get ("tool_use_id" )}) 726if text or calls or reasoning or parts : 727# an image sent beside tool results stays in this turn instead of being dropped 728out = {"role" :m ["role" ],"content" :_parts_of (parts )if _has_image (parts )else "" .join (text )} 729if reasoning : 730out ["reasoning_content" ]= "" .join (reasoning ) 731if calls : 732out ["tool_calls" ]= calls 733messages .append (out ) 734# A client may send results in the order its tools finished (Claude Code does for parallel calls) 735_order_chat_tool_results (messages ) 736tools = [_anthropic_tool (t )for t in declared if t ["name" ]not in deferred ]or None 737kwargs = {} 738# Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N}; 739# "output_config": {"effort": "low" | "medium" | "high"} 740thinking = req .get ("thinking" ) 741effort = (req .get ("output_config" )or {}).get ("effort" )if isinstance (req .get ("output_config" ),dict )else None 742# 0.1.45: Anthropic's budget_tokens is a real budget, not only a level: the thinking is closed (wrap-up, </think>, 743# the answer) after that many tokens. A reasoning_budget_tokens of the request's own wins. 744bt = thinking .get ("budget_tokens" )if isinstance (thinking ,dict )and thinking .get ("type" )!= "disabled" else None 745if isinstance (bt ,int )and not isinstance (bt ,bool )and bt > 0 and req .get ("reasoning_budget_tokens" )is None : 746req ["reasoning_budget_tokens" ]= bt 747if isinstance (thinking ,dict )and thinking .get ("type" )== "disabled" : 748kwargs ["enable_thinking" ]= False 749elif effort : 750kwargs .update (effort_kwargs (effort )) 751elif isinstance (thinking ,dict )and thinking .get ("budget_tokens" ): 752kwargs .update (budget_effort (thinking ["budget_tokens" ])) 753elif thinking is None and not req .get ("reasoning_budget_tokens" )and not think_unasked : 754# Opt-in (the config's "anthropic_thinking": "on_request"; the default thinks as 0.1.31 did, since a 755# client that never asks would otherwise lose the thinking on every turn). Anthropic's thinking is 756# opt-in there. Claude Code's helper calls (a session title, a topic check) ask for none 757# and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. 758# A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. A 759# request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before. 760kwargs ["enable_thinking" ]= False 761return _env_to_user (_late_system_to_user (messages )),tools ,kwargs 762 763 764# ------------------------------------------------------------------------------------------------ output parser 765@dataclass 766class ToolCall : 767name :str 768arguments :dict 769id :str = field (default_factory = lambda :"call_" + uuid .uuid4 ().hex [:24 ]) 770 771 772@dataclass 773class Event : 774kind :str # "reasoning" | "content" | "tool_call" 775text :str = "" 776call :ToolCall | None = None 777 778 779THINK_END = "</think>" 780CALL_START = "<tool_call>" 781CALL_END = "</tool_call>" 782 783 784PARAM_END = "</parameter>" 785FUNC_START = "<function=" 786FUNC_END = "</function>" 787# #3441: the opener a model writes when it drifts by a token inside the envelope the template documents: 788# `<=NAME>` (the word `function` dropped), `<function:NAME>`, `<function =NAME>`, or the bare `<NAME>` 789_LOOSE_OPEN = re .compile (r"<\s*(?:function\s*[=:]\s*|=\s*)?([A-Za-z0-9_.\-]+)\s*>" ) 790_PREFIX_LOOKBACK = 256 # how far before a new delta a prefixed name or a misspelt opener can start (see OutputParser._prefixed) 791# #5409: `<function=tools actio>` / `<function=tools>`; the prefixes are the ones of #4751 792_PREFIX_SPACED = re .compile (r"(<function=\s*(?:tools|functions|default_api)[ \t]+)([^<>\s]+)\s*>" ) 793_PREFIX_PART = re .compile (r"<function=\s*(?:tools|functions|default_api)[ \t]+[^<>\s]{0,80}\s*$" ) 794_PREFIX_BARE = re .compile (r"(<tool_call>\s*)<function=\s*(tools|functions|default_api)\s*>(.*?)</function>" ,re .S ) 795_PREFIX_BARE_OPEN = re .compile (r"<tool_call>\s*<function=\s*(tools|functions|default_api)\s*>(?!.*</function>)" ,re .S ) 796# #5276: `<toolcall>` / `<tool-call>` as the opener (then whitespace, `<function=NAME>`), and such an opener still arriving 797_MISSPELT_OPEN = re .compile (r"<tool-?call>(\s*)<function=(\s*[^<>\s]+\s*)>" ) 798_MISSPELT_PART = re .compile (r"<tool-?call>\s*<function=[^<>]{0,80}$|<tool-?call>\s*(?:<(?:f(?:u(?:n(?:c(?:t(?:i(?:o(?:n)?)?)?)?)?)?)?)?)?$" ) 799_LOOSE_PART = re .compile (r"<\s*(?:function[ \t]*[=:]?\s*|=\s*)?[A-Za-z0-9_.\-]*\s*$" ) 800 801 802# a quoted call's opener in a value: `<function=NAME>` and its first parameter or close; a bare FUNC_START is text 803_QUOTED_OPEN = re .compile (r"<function=[^<>\s]+>\s*(?:<parameter=|</function>)" ) 804 805 806#: #4701: how much text after a closing sequence is looked at before the value is taken as ended there (a call followed by a long sentence) 807CLOSE_LOOKAHEAD_CHARS = 1500 808 809 810def _close_verdict (after :str ,final :bool )-> str : 811"""`after` starts with `</function>` and/or `</tool_call>` right after a `</parameter>`. A file that documents the call format has those 812three tags on lines of its own inside a value (#4701), so the sequence only ends the value when what follows is the end of the turn, another 813call, or prose with no closing tag after it. "end": the value ends here; "continue": it goes on to the next `</parameter>`; "hold": not 814decidable yet (streaming): wait for more text. Bounded: the end of the turn (`final`), a new `<tool_call>`, or CLOSE_LOOKAHEAD_CHARS of 815text decide, so a call is never held longer than that.""" 816m = re .match (r"(?:</function>)?\s*</tool_call>" ,after ) 817if not m : 818tail = after [len (FUNC_END ):].lstrip ()if after .startswith (FUNC_END )else after 819if not final and CALL_END .startswith (tail ): 820return "hold" # #5040: `</tool_call>` is still arriving: a streamed view must not end the value yet 821return "end" # the call is cut, or it has no wrapper: as before 822rest = after [m .end ():].lstrip () 823if not rest : 824return "end" if final else "hold" # the usual call: the turn ends right after it 825if rest .startswith (CALL_START ): 826return "end" 827if not final and CALL_START .startswith (rest ): 828return "hold" # `<tool_c` of a second call is arriving 829if CALL_START in rest : 830return "end" # prose, then another call: this one is complete 831if PARAM_END in rest or CALL_END in rest or FUNC_END in rest : 832return "continue" # prose, then closing tags again: the text was part of the value 833if final or len (rest )> CLOSE_LOOKAHEAD_CHARS : 834return "end" 835return "hold" 836 837 838 839def param_end (text :str ,final :bool = False ,name :str | None = None ,hold :bool = True )-> int : 840"""Where a parameter value in `text` ends: the first PARAM_END followed (after whitespace) by the next 841PARAM_START or FUNC_END, or by the wrapper's CALL_END when the call's `</function>` was left out (#4427) - the 842same text inside a value (a file that documents the call format, #210) is 843part of the value. #4078: a close inside a call the value itself quotes (more _QUOTED_OPEN than FUNC_END before 844it), or one followed by the same parameter `name` again, is part of the value too. `text` starts at the value. 845-1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it).""" 846at = text .find (PARAM_END ) 847while at >= 0 : 848if len (_QUOTED_OPEN .findall (text ,0 ,at ))<= text .count (FUNC_END ,0 ,at ): 849after = text [at + len (PARAM_END ):].lstrip () 850if after .startswith (PARAM_START ): 851gt = after .find (">" ) 852if gt < 0 : 853return at if final else - 2 854if name is None or after [len (PARAM_START ):gt ].strip ()!= name : 855return at 856elif after .startswith ((FUNC_END ,CALL_END )):# #4427: the model left out its `</function>` 857verdict = _close_verdict (after ,final )if hold else "end" # hold=False: a call inside the reasoning keeps its old rule 858if verdict == "end" : 859return at 860if verdict == "hold" : 861return - 2 862elif not after or PARAM_START .startswith (after )or FUNC_END .startswith (after )or CALL_END .startswith (after ): 863return at if final else - 2 864at = text .find (PARAM_END ,at + 1 ) 865return - 1 866 867 868def call_end (text :str ,final :bool = False ,hold :bool = True )-> int : 869"""Where a tool call's body ends (#210): the `</tool_call>` after the call's own `</function>`, found by walking 870its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in 871the call format ends at the first `</tool_call>`, as before.""" 872s = text .lstrip () 873pos = len (text )- len (s ) 874if not s .startswith ("<function=" ): 875return text .find (CALL_END )if not "<function=" .startswith (s )else - 1 876gt = text .find (">" ,pos ) 877if gt < 0 : 878return - 1 879pos = gt + 1 880while True : 881rest = text [pos :] 882s = rest .lstrip () 883pos += len (rest )- len (s ) 884if s .startswith ("<parameter=" ): 885gt = text .find (">" ,pos ) 886if gt < 0 : 887return - 1 888end = param_end (text [gt + 1 :],final ,text [pos :gt ].split ("=" ,1 )[1 ].strip (),hold ) 889if end < 0 : 890return - 1 891pos = gt + 1 + end + len (PARAM_END ) 892elif s .startswith (FUNC_END ): 893rest = text [pos + len (FUNC_END ):] 894s = rest .lstrip () 895if s .startswith (CALL_END ): 896return pos + len (FUNC_END )+ len (rest )- len (s ) 897return - 1 if CALL_END .startswith (s )else text .find (CALL_END ,pos ) 898elif not s or "<parameter=" .startswith (s )or FUNC_END .startswith (s ): 899return - 1 900else : 901return text .find (CALL_END ,pos ) 902 903 904def tool_choice_of (tool_choice )-> tuple [str ,str | None ]: 905"""A client's `tool_choice` in either API's shape -> ("auto" | "none" | "required" | "named", name). OpenAI: 906"auto" / "none" / "required", {"type": "function", "function": {"name": N}} or the flat {"type": "function", 907"name": N}; Anthropic: {"type": "auto" | "any" | "none"} and {"type": "tool", "name": N}. A value it does not 908know is ("unknown", None).""" 909if tool_choice is None : 910return "auto" ,None 911if isinstance (tool_choice ,str ): 912return (tool_choice ,None )if tool_choice in ("auto" ,"none" ,"required" )else ("unknown" ,None ) 913if isinstance (tool_choice ,dict ): 914kind = tool_choice .get ("type" ) 915if kind in ("auto" ,"none" ): 916return kind ,None 917if kind in ("any" ,"required" ): 918return "required" ,None 919if kind in ("function" ,"tool" ): 920fn = tool_choice .get ("function" ) 921name = (fn .get ("name" )if isinstance (fn ,dict )else None )or tool_choice .get ("name" ) 922if isinstance (name ,str )and name : 923return "named" ,name 924return "unknown" ,None 925 926 927def forced_call (tool_choice ,tools :list [dict ]| None )-> str | None : 928"""`tool_choice` -> the text that opens the call the reply must make, or None (the model decides). 929There is no grammar here: the server writes this opening itself, so the model can only go on with a call. 930"required" / Anthropic "any": any of the tools; a named function: that one. A value it cannot honour (an 931unknown shape, a name that is not one of the tools, "required" with no tools) is logged and acts as "auto", 932not a 400: a client's odd choice must not stop its request. "none" is handled by the caller (no tools).""" 933kind ,name = tool_choice_of (tool_choice ) 934names = {t .get ("name" )for t in tools or []if isinstance (t ,dict )} 935if kind in ("auto" ,"none" ): 936return None 937if kind == "required" and len (names )== 1 :# one tool to call: name it, the model cannot invent another 938kind ,name = "named" ,next (iter (names )) 939if kind == "required" and names :# the model writes "<function=NAME>": from a written "<function=", Qwen3.8 went on with names no tool has 940return CALL_START + "\n" 941if kind == "named" and name in names : 942return CALL_START + f"\n<function= { name } >\n" 943f"[strata] tool_choice { json . dumps ( tool_choice )[: 200 ] } is not supported here (or names no tool of the " 944"request): the model decides, as with \"auto\"" ,flush = True ) 945return None 946 947 948PARAM_START = "<parameter=" 949 950 951def function_end (text :str )-> int : 952"""Where a `<function=NAME>...</function>` at the start of `text` ends (just past `</function>`), walking its 953parameters with param_end like call_end does; -1: not complete (or not in the call format).""" 954s = text .lstrip () 955pos = len (text )- len (s ) 956if not s .startswith (FUNC_START ): 957return - 1 958gt = text .find (">" ,pos ) 959if gt < 0 : 960return - 1 961pos = gt + 1 962while True : 963rest = text [pos :] 964s = rest .lstrip () 965pos += len (rest )- len (s ) 966if s .startswith (PARAM_START ): 967gt = text .find (">" ,pos ) 968if gt < 0 : 969return - 1 970end = param_end (text [gt + 1 :],name = text [pos :gt ].split ("=" ,1 )[1 ].strip (),hold = False )# a bare or unwrapped call: the old rule 971if end < 0 : 972return - 1 973pos = gt + 1 + end + len (PARAM_END ) 974elif s .startswith (FUNC_END ): 975return pos + len (FUNC_END ) 976else : 977return - 1 978 979 980_JSON_FENCE = re .compile (r"```[ \t]*(?:json)?[ \t]*\r?\n\s*" ,re .I ) 981 982 983def json_tool_call (body :str ,schemas :dict )-> ToolCall | None : 984"""`{"name": N, "arguments": {...}}` (or "parameters", or the arguments as a JSON string) of a declared tool -> its 985call; anything else -> None. #2037: the object may sit in a Markdown fence (```json ... ```).""" 986body = body .strip () 987m = _JSON_FENCE .match (body ) 988if m : 989body = body [m .end ():].rstrip () 990body = body [:- 3 ]if body .endswith ("```" )else body 991try : 992obj = json .loads (body ) 993except ValueError : 994return None 995if not isinstance (obj ,dict )or not isinstance (obj .get ("name" ),str )or obj ["name" ]not in schemas : 996return None 997args = obj .get ("arguments" ,obj .get ("parameters" , {})) 998if isinstance (args ,str ): 999try : 1000args = json .loads (args ) 1001except ValueError : 1002return None 1003if args is None : 1004args = {} 1005return ToolCall (name = obj ["name" ],arguments = args )if isinstance (args ,dict )else None 1006 1007 1008LENIENT_MAX = 1 << 20 # the longest value lenient_json will try (it is a python loop) 1009 1010 1011class _Lenient : 1012"""A JSON reader for the slips a model makes inside an array or object argument (#4427): a trailing or doubled comma, 1013single quotes and Python's True/False/None, a bare string between two members of an object (`"status": "pending", 1014"in_progress", "pending": false`), brackets left open at the end, extra closers at the end. It is only asked about 1015text json.loads has refused. It never guesses at a value: a string cut short, an unknown word, a missing colon 1016after a key, anything else raises ValueError.""" 1017 1018_WORDS = {"true" :True ,"false" :False ,"null" :None ,"True" :True ,"False" :False ,"None" :None } 1019_ESC = {'"' :'"' ,"'" :"'" ,"\\" :"\\" ,"/" :"/" ,"b" :"\b" ,"f" :"\f" ,"n" :"\n" ,"r" :"\r" ,"t" :"\t" } 1020_TOKEN = re .compile (r"[^\s,\]}:]+" ) 1021 1022def __init__ (self ,text :str ): 1023self .s ,self .i = text ,0 1024 1025def peek (self )-> str : 1026s ,n = self .s ,len (self .s ) 1027while self .i < n and s [self .i ]in " \t\r\n" : 1028self .i += 1 1029return s [self .i :self .i + 1 ] 1030 1031def string (self )-> str : 1032s ,q = self .s ,self .s [self .i ] 1033self .i += 1 1034out = [] 1035while self .i < len (s ): 1036c = s [self .i ] 1037if c == q : 1038self .i += 1 1039return "" .join (out ) 1040if c == "\\" : 1041self .i += 1 1042e = s [self .i :self .i + 1 ] 1043if e == "u" and re .fullmatch (r"[0-9a-fA-F]{4}" ,s [self .i + 1 :self .i + 5 ]): 1044out .append (chr (int (s [self .i + 1 :self .i + 5 ],16 ))) 1045self .i += 5 1046continue 1047if e not in self ._ESC : 1048raise ValueError ("bad escape" ) 1049out .append (self ._ESC [e ]) 1050else : 1051out .append (c ) 1052self .i += 1 1053raise ValueError ("string not closed" ) 1054 1055def value (self ,depth :int = 0 ): 1056if depth > 64 : 1057raise ValueError ("too deep" ) 1058c = self .peek () 1059if c == "{" : 1060return self .obj (depth + 1 ) 1061if c == "[" : 1062return self .arr (depth + 1 ) 1063if c in ('"' ,"'" ): 1064return self .string () 1065m = self ._TOKEN .match (self .s ,self .i ) 1066if not m : 1067raise ValueError ("no value" ) 1068self .i = m .end () 1069if m .group ()in self ._WORDS : 1070return self ._WORDS [m .group ()] 1071return json .loads (m .group ())# a number, or ValueError 1072 1073def obj (self ,depth :int ): 1074self .i += 1 1075out :dict = {} 1076while True : 1077c = self .peek () 1078if not c or c == "}" :# (no closer: the brackets were left open at the end) 1079self .i += 1 1080return out 1081if c == "," : 1082self .i += 1 1083continue 1084if c not in ('"' ,"'" ): 1085raise ValueError ("object member" ) 1086key = self .string () 1087if self .peek ()== ":" : 1088self .i += 1 1089out [key ]= self .value (depth ) 1090elif self .peek ()not in ("," ,"}" ,"" ):# a bare string where a member belongs is dropped 1091raise ValueError ("object member" ) 1092 1093def arr (self ,depth :int ): 1094self .i += 1 1095out :list = [] 1096while True : 1097c = self .peek () 1098if not c or c == "]" : 1099self .i += 1 1100return out 1101if c == "," : 1102self .i += 1 1103continue 1104out .append (self .value (depth )) 1105if self .peek ()not in ("," ,"]" ,"" ): 1106raise ValueError ("array element" ) 1107 1108 1109def lenient_json (text :str ): 1110"""The JSON array or object `text` was meant to be, read past the slips of _Lenient; ValueError for anything else 1111(and for text that is not an array or object). Valid JSON is not its business: callers try json.loads first.""" 1112t = text .strip () 1113m = _JSON_FENCE .match (t ) 1114if m : 1115t = t [m .end ():].rstrip () 1116t = t [:- 3 ].rstrip ()if t .endswith ("```" )else t 1117if not t .startswith (("[" ,"{" ))or len (t )> LENIENT_MAX : 1118raise ValueError ("not an array or object" ) 1119r = _Lenient (t ) 1120v = r .value () 1121if t [r .i :].strip ("]}) \t\r\n" ): 1122raise ValueError ("text after the value" ) 1123return v 1124 1125 1126def coerce_value (value :str ,declared ,notes :list | None = None ): 1127"""A non-string parameter's text -> its value by the tool's declared type: JSON when it parses; else an array or an 1128object read with lenient_json (a note says so in `notes`); else the text itself, as before. An array or object that 1129arrived as a JSON string of itself is decoded once more.""" 1130if declared == "string" : 1131return value 1132boolean = declared == "boolean" or (isinstance (declared ,list )and "boolean" in declared and "string" not in declared ) 1133if boolean and value .strip ().lower ()in ("true" ,"false" ): 1134return value .strip ().lower ()== "true" # #5979: the model's Python spelling (True / False) of a declared boolean is the boolean 1135try : 1136v = json .loads (value ) 1137except ValueError : 1138if not value .lstrip ().startswith (("[" ,"{" ,"`" ))or (isinstance (declared ,list )and "string" in declared ): 1139return value 1140try : 1141v = lenient_json (value ) 1142except (ValueError ,RecursionError ): 1143return value 1144if notes is not None : 1145notes .append ("a damaged JSON " + ("array" if isinstance (v ,list )else "object" )+ " argument was read as written" ) 1146return v 1147if isinstance (v ,str )and declared in ("array" ,"object" )and v .lstrip ().startswith (("[" ,"{" )): 1148try : 1149return json .loads (v ) 1150except ValueError : 1151return coerce_value (v ,declared ,notes ) 1152return v 1153 1154 1155def parse_tool_call (body :str ,schema :dict | None = None ,notes :list | None = None )-> ToolCall : 1156"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decoded 1157when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON 1158objects/arrays/numbers/booleans).""" 1159body = body .strip () 1160if not body .startswith ("<function=" )or ">" not in body : 1161raise ValueError ("malformed tool call: " + body [:80 ]) 1162name = body [len ("<function=" ):body .index (">" )].strip ()# `<function= capture>`: the model's stray space 1163rest = body [body .index (">" )+ 1 :] 1164props = ((schema or {}).get ("parameters" )or {}).get ("properties" )or {} 1165args = {} 1166while "<parameter=" in rest : 1167rest = rest [rest .index ("<parameter=" )+ len ("<parameter=" ):] 1168pname = rest [:rest .index (">" )] 1169rest = rest [rest .index (">" )+ 1 :] 1170end = param_end (rest ,final = True ,name = pname .strip ()) 1171value = rest [:end ]if end >= 0 else rest 1172rest = rest [end + len (PARAM_END ):]if end >= 0 else "" 1173if value .startswith ("\n" ): 1174value = value [1 :] 1175if value .endswith ("\n" ): 1176value = value [:- 1 ] 1177args [pname ]= coerce_value (value , (props .get (pname )or {}).get ("type" ),notes ) 1178return ToolCall (name = name ,arguments = args ) 1179 1180 1181RCALL_MAX = 32768 # the most of a `<tool_call>` inside the reasoning that is held while waiting for its end (#804) 1182 1183 1184class OutputParser : 1185"""Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back 1186until it is complete, so clients never see `<tool_` or `</thi`.""" 1187 1188def __init__ (self ,thinking :bool = True ,tools :list [dict ]| None = None ,stream_tools :bool = False , 1189recover :bool = False ,declared_only :bool = False ,deferred :bool = False ): 1190self .state = "reasoning" if thinking else "content" 1191self .buf = "" 1192self .lead = False 1193self .schemas = {t .get ("name" ):t for t in tools or []} 1194# #4663: the request defers tools (Anthropic's tool search, see anthropic_tools): the client holds back more tools 1195# than it declares, so a call for an undeclared name is a call too - Claude Code runs it, where text ended the turn. 1196self .deferred = deferred 1197# #804/#3075: in the answer too, a call counts only for a tool the request declared. With tools declared a 1198# call for another name stays text (the Responses spelling `namespace__tool` of a `namespace.tool` counts as 1199# that tool); `declared_only` extends the rule to a request that declared none (Chat Completions, Anthropic: 1200# the client has no tool to run). The Responses route leaves it off: a Codex compaction request keeps its 1201# conversation's tools in the prompt only, and its calls come back as before. 1202self .declared_only = declared_only 1203# A declared namespace.member tool is also accepted as namespace__member (PR #3556), 1204# namespace=member (Qwen writes the <function= tag's equals sign into the name), 1205# namespace_member (one underscore dropped), and the bare member when exactly one 1206# declared tool has it. Only an unambiguous alias counts, and an exactly declared 1207# name always wins over an alias. 1208aliases = {} 1209for name in self .schemas : 1210if isinstance (name ,str )and "." in name : 1211namespace ,member = name .rsplit ("." ,1 ) 1212for alias in (f" { namespace } __ { member } " ,f" { namespace } = { member } " , 1213f" { namespace } _ { member } " ,member ): 1214aliases .setdefault (alias ,set ()).add (name ) 1215# #3796: the same tool written with every `__` collapsed to `_` (`mcp__playwright__browser_navigate` as 1216# `mcp_playwright_browser_navigate`, the way Qwen often flattens a name) is that tool. Only a spelling of a declared 1217# name: a reordered or renamed tool (`server1_label_values` for `label_values_mcp_server1`) is not guessed. 1218for name in self .schemas : 1219if isinstance (name ,str )and "__" in name : 1220aliases .setdefault (name .replace ("__" ,"_" ),set ()).add (name ) 1221# #5281: a namespaced MCP tool (`mcp__assets__get_asset_info`) written with its last segment only (`get_asset_info`), 1222# as the bare member of a dotted name is accepted above; only when exactly one declared tool ends that way 1223last = name .rsplit ("__" ,1 )[1 ] 1224if last : 1225aliases .setdefault (last ,set ()).add (name ) 1226# #4751: a programmatic-tool-calling harness (the DeepSeek Harness's PTC mode) shows the model its tools as `tools.write(...)` 1227# inside code, and the model then writes the native call with that spelling (`tools.write`, also `functions.write`). The 1228# prefix is not part of the declared name; the same unambiguous-alias rule applies, an exactly declared name always wins. 1229for name in self .schemas : 1230if isinstance (name ,str )and name : 1231for prefix in ("tools." ,"functions." ,"default_api." ): 1232aliases .setdefault (prefix + name ,set ()).add (name ) 1233self .aliases = {alias :next (iter (names ))for alias ,names in aliases .items () 1234if len (names )== 1 and alias not in self .schemas } 1235self .unread = 0 # #3441: `<tool_call>` blocks that opened like a call and were returned as text 1236self .unread_names :list [str ]= []# the names (first few) of those that named a tool the request did not declare 1237# stream_tools: a tool call is also reported while it is being written - "tool_start" (its name and id) as 1238# soon as the name is known, then "tool_args" pieces of its JSON arguments (string parameters character by 1239# character; other types whole, once complete) - before the final "tool_call". Without it, a client sees 1240# nothing until the call is complete, which for a large file write can be many minutes. 1241self .stream_tools = stream_tools 1242# #804/#1058: calls found inside the reasoning wait here as [raw text, ToolCall | None] until the turn shows 1243# they were acts: only whitespace (or more calls) after them, then the end of the turn or `</think>`. The 1244# reasoning text before them is tracked (code fence, inline code, current line) to tell an act from a quote. 1245self .pending :list [list ]= [] 1246self .rescued = 0 # calls delivered from the reasoning 1247self .notes :list [str ]= []# #4427: what was repaired in the arguments of the calls (a damaged JSON array or object) 1248self .after_think = False # #4077: the reasoning ended at a bare `</think>` (a second one in the answer is a stray) 1249self .stray_think = 0 # ... and the strays of that kind dropped from the answer 1250self .refused = 0 # declared calls kept as reasoning text (quoted, or the turn was cut) 1251self .fence ,self .line ,self .ticks = "" ,"" ,0 1252self ._prev_blank = self ._indented = False # #4703: the line before was blank / this is inside an indented (4-space) code block 1253# recover (on in the server since 0.2.8, off for a bare OutputParser; the config's "tool_call_recovery": false turns it off): a declared tool's call written next to the template's 1254# form is the call - `<parameter=NAME>` as the opener, JSON inside <tool_call>, a bare <function=NAME> at the 1255# start of a line outside code, or a second call in the same <tool_call> (which otherwise merges into one). 1256self .recover = recover 1257self .bare = False # the call being read opened with <function= alone (no <tool_call> around it) 1258self .batch = False # the call being finished is followed by another in the same wrapper 1259self ._final = False # #4701: the turn has ended: a call held for what might follow it is decided now 1260self ._held = "" # #5276/#5409: the end of a misspelt opener or a prefixed name still arriving (see _prefixed) 1261self ._reset_scan () 1262 1263@property 1264def clean (self )-> bool : 1265"""Nothing is held back: a clean point to stop the thinking at (a parser that rewrites the model's text, as 1266serve/dsml.py's does, also counts what it holds).""" 1267return not self .buf and not self ._held 1268 1269def _ok_at (self ,p :int )-> bool : 1270"""self.buf[p] would open a call: at the start of a line, outside a code fence and inline code.""" 1271snap = self ._snap () 1272self ._track (self .buf [:p ]) 1273ok = self ._opener_ok () 1274self ._restore (snap ) 1275return ok 1276 1277def _opens_at (self ,p :int )-> bool : 1278"""self.buf[p] would open a call as `<tool_call>` does: in the reasoning at the start of a line outside code, in the answer 1279anywhere outside code (a fence, inline code, an indented block).""" 1280if self .state == "reasoning" : 1281return self ._ok_at (p ) 1282snap = self ._snap () 1283self ._track (self .buf [:p ]) 1284ok = not self ._in_code () 1285self ._restore (snap ) 1286return ok 1287 1288def _callable (self ,name :str )-> bool : 1289"""#3075: may a call for `name` be a call? A tool the request declared (or its Responses spelling); with 1290none declared, only where `declared_only` is off.""" 1291if not self .schemas : 1292return not self .declared_only 1293return name in self .schemas or name in self .aliases or self .deferred 1294 1295def _loose_open (self ,after :str ): 1296"""#3441: `after` (text after a `<tool_call>`, whitespace dropped) opens a call in a drifted form that names a 1297declared tool -> (name, length of the opener); "wait" while it may still become one; None otherwise.""" 1298m = _LOOSE_OPEN .match (after ) 1299if m : 1300name = m .group (1 ) 1301return (name ,m .end ())if self ._callable (name )else None 1302if ">" in after or "\n" in after or not after .startswith ("<" ): 1303return None 1304if _LOOSE_PART .match (after ): 1305bare = after [1 :].strip ().lstrip ("=" ).strip () 1306if after [1 :].lstrip ().startswith (("=" ,"function" )): 1307return "wait" 1308if any (k .startswith (bare )for k in list (self .schemas )+ list (self .aliases )if isinstance (k ,str )): 1309return "wait" 1310return None 1311 1312def _follower (self ,after :str )-> str : 1313"""recover: what a `<tool_call>` followed (after whitespace) by `after` opens: "call" (`<function=`), "param" 1314(a declared tool's name written as `<parameter=NAME>`), "json" (`{`), "wait" (not decided yet) or "text".""" 1315if after .startswith (FUNC_START ): 1316return "call" 1317if after .startswith (PARAM_START ): 1318gt = after .find (">" ) 1319if gt < 0 : 1320return "wait" if "\n" not in after else "text" 1321return "param" if after [len (PARAM_START ):gt ]in self .schemas else "text" 1322if after .startswith ("{" ): 1323return "json" if self .schemas else "text" 1324if after .startswith ("```" )or (after and "```" .startswith (after )): 1325# #2037: the JSON call inside a Markdown fence (```json ... ```) in the explicit wrapper 1326m = _JSON_FENCE .match (after ) 1327if m : 1328rest = after [m .end ():] 1329if rest .startswith ("{" ): 1330return "json" if self .schemas else "text" 1331return "wait" if not rest else "text" 1332return "wait" if "\n" not in after else "text" 1333if not after or FUNC_START .startswith (after )or PARAM_START .startswith (after ): 1334return "wait" 1335return "text" 1336 1337def _bare_opener (self )-> tuple [int ,bool ]: 1338"""recover: the first `<function=` in self.buf that opens a call without the wrapper (start of a line, outside 1339code, a declared tool) -> (position, decided); (-1, False) for none. A name still arriving is undecided.""" 1340p = self .buf .find (FUNC_START ) 1341while p >= 0 : 1342if self ._ok_at (p ): 1343gt = self .buf .find (">" ,p ) 1344raw_name = self .buf [p + len (FUNC_START ):gt if gt >= 0 else len (self .buf )] 1345name = raw_name .strip () 1346name = self .aliases .get (name ,name ) 1347if gt < 0 and re .fullmatch (r"\s*[^<>\s]*\s*" ,raw_name ): 1348return p ,False 1349if gt >= 0 and name in self .schemas : 1350return p ,True 1351p = self .buf .find (FUNC_START ,p + 1 ) 1352return - 1 ,False 1353 1354@property 1355def line (self )-> str : 1356"""Materialize the current line only for a decision, newline, or state snapshot.""" 1357if self ._line_blocks is not None : 1358self ._line_blocks .extend (self ._line_parts ) 1359self ._line_parts = ["" .join (self ._line_blocks )] 1360self ._line_blocks = None 1361elif len (self ._line_parts )> 1 : 1362self ._line_parts = ["" .join (self ._line_parts )] 1363return self ._line_parts [0 ]if self ._line_parts else "" 1364 1365@ line . setter 1366def line (self ,text :str ): 1367self ._line_parts = [text ]if text else [] 1368self ._line_blocks = None 1369 1370def _track (self ,text :str )-> str : 1371"""Follow the reasoning text that has gone out: the open code fence, the current line, and the backticks of 1372the current paragraph. Returns the text.""" 1373# Most token fragments stay on the current line. Fence and paragraph 1374# bookkeeping happens only when a newline completes that line. 1375if "\n" not in text : 1376if text : 1377self ._line_parts .append (text ) 1378if len (self ._line_parts )== 64 : 1379# Release small fragment objects in bounded groups. Completed 1380# blocks are never recopied until the full line is requested. 1381if self ._line_blocks is None : 1382self ._line_blocks = [] 1383self ._line_blocks .append ("" .join (self ._line_parts )) 1384self ._line_parts .clear () 1385return text 1386parts = text .split ("\n" ) 1387for k ,part in enumerate (parts ): 1388if k < len (parts )- 1 : 1389line = self .line + part if self ._line_parts or self ._line_blocks else part 1390self ._line_parts .clear () 1391self ._line_blocks = None 1392s = line .lstrip () 1393was_fenced = bool (self .fence ) 1394if self .fence : 1395# #4702: a fence is closed only by a line of at least as many of the same character as opened it (CommonMark), so a 1396# ``` example inside a ```` file stays inside it 1397run = len (s )- len (s .lstrip (self .fence [0 ])) 1398if run >= len (self .fence ): 1399self .fence = "" 1400elif s [:3 ]in ("```" ,"~~~" )and (s [0 ]* 3 )not in s [3 :]: 1401self .fence = s [0 ]* (len (s )- len (s .lstrip (s [0 ]))) 1402elif not s : 1403self .ticks = 0 1404else : 1405self .ticks += line .count ("`" ) 1406# #4703: an indented (4 spaces or a tab) code block starts after a blank line and goes on until a line that is not indented 1407if was_fenced or self .fence : 1408self ._prev_blank = self ._indented = False 1409elif not s : 1410self ._prev_blank = True 1411elif line .startswith ((" " ,"\t" )): 1412self ._indented = self ._prev_blank or self ._indented 1413self ._prev_blank = False 1414else : 1415self ._prev_blank = self ._indented = False 1416else : 1417if part : 1418self ._line_parts .append (part ) 1419return text 1420 1421def _opener_ok (self )-> bool : 1422"""The reasoning text so far puts a `<tool_call>` at the start of a line, outside a code fence and outside 1423inline code.""" 1424return not self .fence and not self .line .strip ()and self .ticks % 2 == 0 and not self ._in_indented_block () 1425 1426def _in_indented_block (self )-> bool : 1427"""#4703: the current line is part of an indented code block: four spaces or a tab, after a blank line or another such line.""" 1428return (self ._prev_blank or self ._indented )and self .line .startswith ((" " ,"\t" )) 1429 1430def _snap (self )-> tuple : 1431return (self .fence ,self .line ,self .ticks ,self ._prev_blank ,self ._indented ) 1432 1433def _restore (self ,snap :tuple )-> None : 1434self .fence ,self .line ,self .ticks ,self ._prev_blank ,self ._indented = snap 1435 1436def _reset_track (self )-> None : 1437self .fence ,self .line ,self .ticks = "" ,"" ,0 1438self ._prev_blank = self ._indented = False 1439 1440def _in_code (self )-> bool : 1441"""The text so far leaves the next character inside a code fence, inline code or an indented code block.""" 1442return bool (self .fence )or (self .ticks + self .line .count ("`" ))% 2 == 1 or self ._in_indented_block () 1443 1444def _quoted_think_end (self ,i :int )-> bool | None : 1445"""#537: the `</think>` at self.buf[i] is the model quoting the tag while it thinks, not the end of the 1446thinking: written right after a quote or backtick and followed by anything but a line break, as in `</think>` 1447or "</think>...". The end of the thinking is followed by a line break. None while the character after the 1448tag has not arrived.""" 1449before = self .buf [i - 1 ]if i else self .line [- 1 :] 1450if before not in ('"' ,"'" ,"`" ): 1451return False 1452after = self .buf [i + len (THINK_END ):] 1453if not after : 1454return None 1455return after [0 ]not in "\r\n" 1456 1457def _stray_think_at (self )-> int : 1458"""#4077: where self.buf has a `</think>` at the start of a line, in the answer of a turn whose reasoning 1459already ended at one; -1 for none. A fence or backtick is no reason to keep it: the reasoning may have left 1460one open, and the answer's own tracking of code is wrong from there on.""" 1461k = self .buf .find (THINK_END ) 1462while k >= 0 : 1463before = self .buf [:k ] 1464if not (before .rsplit ("\n" ,1 )[1 ]if "\n" in before else self .line + before ).strip (): 1465return k 1466k = self .buf .find (THINK_END ,k + 1 ) 1467return - 1 1468 1469def _release (self ,deliver :bool )-> list [Event ]: 1470"""Settle the calls waiting in self.pending: events for real calls, or all of it back as reasoning text.""" 1471out = [] 1472for raw ,call in self .pending : 1473if call is not None and deliver : 1474out .append (Event ("tool_call" ,call = call )) 1475self .rescued += 1 1476elif call is None or not deliver : 1477if call is not None : 1478self .refused += 1 1479if raw : 1480out .append (Event ("reasoning" ,self ._track (raw ))) 1481self .pending = [] 1482return out 1483 1484def _reset_scan (self ): 1485self ._call_end_checked = 0 # closing-tag search progress for the current wrapped call 1486self .sp = 0 # how much of self.buf (the call body) the scanner has consumed 1487self .ss = "name" # name -> between -> str|raw -> ... -> function_done -> done 1488self .scall = None # the ToolCall being streamed (its id is reused by the final event) 1489self .sfirst = True 1490self .sval_started = False 1491self .sdeclared = {} 1492self .spname = None 1493self .svstart = 0 1494 1495def _wrapped_call_end (self )-> int : 1496# Without a closing tag the structural walk cannot finish. Search only 1497# newly appended text plus enough overlap for a tag split across feeds. 1498# A literal closing tag inside a value needs structural disambiguation: 1499# once any candidate appears, keep the original full walk for this call. 1500# Recovery can rewrite the buffer, so it always uses the full walk. 1501if not self .recover and self ._call_end_checked >= 0 : 1502start = max (0 ,self ._call_end_checked - len (CALL_END )+ 1 ) 1503if self .buf .find (CALL_END ,start )< 0 : 1504self ._call_end_checked = len (self .buf ) 1505return - 1 1506self ._call_end_checked = - 1 1507return call_end (self .buf ,self ._final ) 1508 1509def _scan (self )-> list [Event ]: 1510"""Advance the streaming view of the call body in self.buf (see stream_tools).""" 1511out = [] 1512 1513def args (s ): 1514if s : 1515out .append (Event ("tool_args" ,s ,call = self .scall )) 1516while True : 1517rest = self .buf [self .sp :] 1518if self .ss == "name" : 1519a = rest .find ("<function=" ) 1520b = rest .find (">" ,a + 10 )if a >= 0 else - 1 1521if b < 0 : 1522return out 1523raw_name = rest [a + 10 :b ] 1524name = raw_name .strip () 1525name = self .aliases .get (name ,name ) 1526if raw_name != raw_name .strip ()and name not in self .schemas : 1527return out 1528self .scall = ToolCall (name = name ,arguments = {}) 1529props = ((self .schemas .get (name )or {}).get ("parameters" )or {}).get ("properties" )or {} 1530self .sdeclared = {k : (v or {}).get ("type" )for k ,v in props .items ()} 1531out .append (Event ("tool_start" ,call = self .scall )) 1532args ("{" ) 1533self .sp += b + 1 1534self .ss = "between" 1535elif self .ss == "between" : 1536stripped = rest .lstrip () 1537self .sp += len (rest )- len (stripped ) 1538if stripped .startswith ("<parameter=" ): 1539b = stripped .find (">" ) 1540if b < 0 : 1541return out 1542pname = stripped [11 :b ] 1543args (("" if self .sfirst else "," )+ json .dumps (pname )+ ":" ) 1544self .sfirst = False 1545self .sp += b + 1 1546self .spname = pname .strip () 1547if self .sdeclared .get (pname )== "string" : 1548args ('"' ) 1549self .ss ,self .sval_started = "str" ,False 1550else : 1551self .ss = "raw" 1552elif stripped .startswith ("</function>" ): 1553self .sp += len ("</function>" ) 1554self .ss = "function_done" 1555else : 1556return out # a tag still arriving (or trailing text): wait 1557elif self .ss == "str" : 1558if not self .sval_started : 1559if not rest : 1560return out 1561if rest [0 ]== "\n" :# the value's leading newline is not part of it 1562self .sp += 1 1563rest = rest [1 :] 1564self .sval_started = True 1565self .svstart = self .sp 1566# the walk starts at the value (a quoted call's opener counts); only a close in the new text can end it 1567end = param_end (self .buf [self .svstart :],self ._final ,name = self .spname )if PARAM_END in rest else - 1 1568end = end - (self .sp - self .svstart )if end >= 0 else end 1569if end >= 0 : 1570value = rest [:end ] 1571if value .endswith ("\n" ): 1572value = value [:- 1 ] 1573args (json .dumps (value )[1 :- 1 ]+ '"' ) 1574self .sp += end + len (PARAM_END ) 1575self .ss = "between" 1576continue 1577# an undecided </parameter> (-2) is held from its start, like a tag still arriving 1578safe = rest .find (PARAM_END )if end == - 2 else len (rest )- self ._hold (rest , (PARAM_END ,)) 1579if safe > 0 and rest [safe - 1 ]== "\n" :# may be the trailing newline before </parameter> 1580safe -= 1 1581if safe > 0 : 1582args (json .dumps (rest [:safe ])[1 :- 1 ]) 1583self .sp += safe 1584return out 1585elif self .ss == "raw" : 1586end = param_end (rest ,self ._final ,name = self .spname ) 1587if end < 0 : 1588return out 1589value = rest [:end ] 1590if value .startswith ("\n" ): 1591value = value [1 :] 1592if value .endswith ("\n" ): 1593value = value [:- 1 ] 1594v = coerce_value (value ,self .sdeclared .get (self .spname ))# the note comes with the final call (parse_tool_call) 1595args (json .dumps (v ,ensure_ascii = False )) 1596self .sp += end + len (PARAM_END ) 1597self .ss = "between" 1598else : 1599return out 1600 1601def _close_scan (self )-> list [Event ]: 1602"""Close streamed JSON only after its call boundary has been confirmed.""" 1603out = [] 1604if self .scall is None or self .ss == "done" : 1605return out 1606tail = "" 1607if self .ss == "str" : 1608tail += '"' 1609elif self .ss == "raw" : 1610tail += json .dumps (self .buf [self .sp :].strip ("\n" )) 1611tail += "}" 1612out .append (Event ("tool_args" ,tail ,call = self .scall )) 1613self .ss = "done" 1614return out 1615 1616def _hold (self ,text :str ,tags :tuple [str , ...])-> int : 1617"""Length of the longest suffix of `text` that is a proper prefix of one of `tags`.""" 1618best = 0 1619size = len (text ) 1620for tag in tags : 1621if len (tag )<= 1 : 1622continue 1623# Only a suffix beginning with the tag's first character can match. 1624# Ordinary token deltas contain no '<': one C-level search replaces 1625# checking every possible prefix. Earliest candidate is the longest. 1626start = text .find (tag [0 ],max (0 ,size - len (tag )+ 1 )) 1627while start >= 0 and size - start > best : 1628if tag .startswith (text [start :]): 1629best = size - start 1630break 1631start = text .find (tag [0 ],start + 1 ) 1632return best 1633 1634def _prefixed (self ,fresh :int )-> str : 1635"""#5409: a call written `<function=tools NAME>` (a space for the dot of `tools.NAME`) is the call NAME, and one written 1636`<function=tools>` (the bare prefix) is the one declared tool that takes the call's parameters. Rewrites the complete 1637ones in self.buf to `<function=NAME>` and returns the tail of a call still arriving, which feed() holds back until the next 1638delta. Only a declared name is ever the result; with none, or with two that fit, the text is left as it was. 1639`fresh`: the length of the text just added; only the end of the buffer (that and a little before it) can hold a new match, 1640so a long call is not scanned again with every token.""" 1641held = self ._opener (fresh ) 1642start = max (0 ,len (self .buf )- fresh - _PREFIX_LOOKBACK ) 1643buf = self .buf [start :] 1644if "<function=" in buf : 1645def spaced (m ): 1646name = m .group (2 ).strip () 1647return f"<function= { name } >" if name in self .schemas else m .group (0 ) 1648buf = _PREFIX_SPACED .sub (spaced ,buf ) 1649m = _PREFIX_PART .search (buf ) 1650if m and not held : 1651held ,buf = buf [m .start ():],buf [:m .start ()] 1652if self .recover : 1653def bare (m ): 1654body = m .group (3 ) 1655names = re .findall (r"<parameter=\s*([^<>\s]+?)\s*>" ,body ) 1656tool = None if m .group (2 )in self .schemas else self ._tool_by_params (names ) 1657return f" { m . group ( 1 ) } <function= { tool } > { body } </function>" if tool else m .group (0 ) 1658buf = _PREFIX_BARE .sub (bare ,buf ) 1659m = _PREFIX_BARE_OPEN .search (buf ) 1660if m and m .group (1 )not in self .schemas and not held and len (buf )- m .start ()<= RCALL_MAX : 1661held ,buf = buf [m .start ():],buf [:m .start ()] 1662if buf != self .buf [start :]: 1663self .buf = self .buf [:start ]+ buf 1664return held 1665 1666def _opener (self ,fresh :int )-> str : 1667"""#5276: `<toolcall>` / `<tool-call>` (the opener written as text, misspelled) followed by `<function=NAME>` of a declared 1668tool is `<tool_call>`, where a `<tool_call>` would open a call (in the reasoning the start of a line, outside code; in the 1669answer outside code). Prose that names the misspelled tag, or any other follower, is left as it was. Returns the tail of 1670an opener still arriving (held back by feed).""" 1671start = max (0 ,len (self .buf )- fresh - _PREFIX_LOOKBACK ) 1672if "<tool" not in self .buf [start :]: 1673return "" 1674buf = self .buf 1675pos ,out = start , [] 1676for m in _MISSPELT_OPEN .finditer (buf ,start ): 1677name = m .group (2 ).strip () 1678name = self .aliases .get (name ,name ) 1679if name in self .schemas and self ._opens_at (m .start ()): 1680out .append (buf [pos :m .start ()]+ CALL_START + m .group (1 )+ FUNC_START + m .group (2 )+ ">" ) 1681pos = m .end () 1682buf = buf [:start ]+ "" .join (out )+ buf [pos :]if out else buf 1683held = "" 1684m = _MISSPELT_PART .search (buf ,start ) 1685tail = buf [m .start ():]if m else "" 1686if not tail :# the opener itself still arriving: a prefix of `<toolcall>` 1687for k in range (min (len (buf ),11 ),5 ,- 1 ): 1688if any (w .startswith (buf [- k :])for w in ("<toolcall>" ,"<tool-call>" ))and buf [- k :]!= "<tool_" : 1689tail = buf [- k :] 1690break 1691if tail : 1692held ,buf = tail ,buf [:len (buf )- len (tail )] 1693self .buf = buf 1694return held 1695 1696def _tool_by_params (self ,names :list [str ])-> str | None : 1697"""The one declared tool whose properties hold every one of `names` and whose required parameters are all in them.""" 1698found = [] 1699for tname ,schema in self .schemas .items (): 1700params = (schema or {}).get ("parameters" )or {} 1701props = params .get ("properties" )or {} 1702if names and all (n in props for n in names )and all (r in names for r in params .get ("required" )or []): 1703found .append (tname ) 1704return found [0 ]if len (found )== 1 else None 1705 1706def feed (self ,delta :str )-> list [Event ]: 1707if self ._held : 1708delta ,self ._held = self ._held + delta ,"" 1709self .buf += delta 1710if self .schemas and delta : 1711self ._held = self ._prefixed (len (delta )) 1712return self ._feed () 1713 1714def _feed (self )-> list [Event ]: 1715out :list [Event ]= [] 1716while True : 1717if self .state == "rcall" : 1718# #804: a `<tool_call>` inside the reasoning, with tools declared. It is held whole (never streamed 1719# as a call) until it ends: a declared name is then a tool call, anything else stays reasoning text. 1720body = self .buf [len (CALL_START ):] 1721end ,think = call_end (body ,hold = False ),body .find (THINK_END ) 1722drop = len (CALL_END ) 1723f = function_end (body )# #4427: as in the answer, a following call opener confirms an omitted closer 1724if f >= 0 and (end < 0 or f < end )and re .match (r"<tool_call>\s*<function=\s*[^<>\s]+\s*>" ,body [f :].lstrip ()): 1725end ,drop = f ,0 1726if end >= 0 and (think < 0 or think >= end ): 1727call = None 1728try : 1729name = body [:end ].strip ()[len ("<function=" ):].split (">" ,1 )[0 ].strip () 1730name = self .aliases .get (name ,name ) 1731if self ._callable (name ): 1732call = parse_tool_call (body [:end ],self .schemas .get (name ),self .notes ) 1733call .name = name 1734except ValueError : 1735pass 1736raw = self .buf [:len (CALL_START )+ end + drop ] 1737if call is not None or self .pending : 1738self .pending .append ([raw ,call ])# settled by what follows it (see __init__) 1739else : 1740out .append (Event ("reasoning" ,self ._track (raw ))) 1741self .buf = body [end + drop :] 1742self .state = "reasoning" 1743elif think >= 0 :# the thinking ended inside it: it never was a call 1744out += self ._release (False ) 1745out .append (Event ("reasoning" ,self ._track (self .buf [:len (CALL_START )+ think ]))) 1746self .buf = body [think :] 1747self .state = "reasoning" 1748elif len (body )> RCALL_MAX :# a tag in the prose that never closes: stop holding the thinking back 1749out += self ._release (False ) 1750out .append (Event ("reasoning" ,self ._track (self .buf ))) 1751self .buf = "" 1752self .state = "reasoning" 1753else : 1754return out 1755elif self .state == "reasoning" : 1756if self .pending : 1757# calls wait for what follows: more calls or whitespace keep them, `</think>` makes them acts, 1758# any other text means they were quoted 1759stripped = self .buf .lstrip () 1760if len (stripped )< len (self .buf ): 1761self .pending [- 1 ][0 ]+= self .buf [:len (self .buf )- len (stripped )] 1762self .buf = stripped 1763if not self .buf : 1764return out 1765if self .buf .startswith (CALL_START ): 1766self .state = "rcall" 1767elif self .buf .startswith (THINK_END ): 1768out += self ._release (True ) 1769elif CALL_START .startswith (self .buf )or THINK_END .startswith (self .buf ): 1770return out 1771else : 1772out += self ._release (False ) 1773continue 1774i = self .buf .find (THINK_END ) 1775tool = self .buf .find (CALL_START )if self .schemas else - 1 1776if tool >= 0 and (i < 0 or tool < i ): 1777if tool : 1778out .append (Event ("reasoning" ,self ._track (self .buf [:tool ]))) 1779if self ._opener_ok (): 1780self .buf = self .buf [tool :] 1781self .state = "rcall" 1782else :# mid-sentence, in a fence or in inline code: a quote 1783out .append (Event ("reasoning" ,self ._track (CALL_START ))) 1784self .buf = self .buf [tool + len (CALL_START ):] 1785continue 1786if i < 0 : 1787keep = self ._hold (self .buf , (THINK_END ,CALL_START )if self .schemas else (THINK_END ,)) 1788if len (self .buf )> keep : 1789out .append (Event ("reasoning" ,self ._track (self .buf [:len (self .buf )- keep ]))) 1790self .buf = self .buf [len (self .buf )- keep :] 1791return out 1792quoted = self ._quoted_think_end (i ) 1793if quoted is None :# held like a partial tag until the character after it is here 1794if i : 1795out .append (Event ("reasoning" ,self ._track (self .buf [:i ]))) 1796self .buf = self .buf [i :] 1797return out 1798if quoted :# #537: a quoted `</think>` is reasoning text 1799out .append (Event ("reasoning" ,self ._track (self .buf [:i + len (THINK_END )]))) 1800self .buf = self .buf [i + len (THINK_END ):] 1801continue 1802if i : 1803out .append (Event ("reasoning" ,self ._track (self .buf [:i ]))) 1804self .buf = self .buf [i + len (THINK_END ):] 1805self .state ,self .lead ,self .after_think = "content" ,True ,True 1806self ._reset_track ()# the answer's own text starts here 1807elif self .state == "content" : 1808if self .lead :# newlines right after </think> or a call 1809stripped = self .buf .lstrip ("\n" ) 1810if not stripped : 1811self .buf = "" 1812return out 1813self .buf ,self .lead = stripped ,False 1814i = self .buf .find (CALL_START ) 1815stray = self ._stray_think_at ()if self .after_think else - 1 1816if stray >= 0 and (i < 0 or stray < i ): 1817# #4077: the reasoning ended at a `</think>` the model wrote while thinking (quoting the format on a 1818# line of its own), and this is the one that ends it. What came between was reasoning, already sent 1819# as the answer; the tag is dropped and the text after it starts over, so a call that follows is 1820# not taken for a quote by the code fence or backtick the reasoning left open. 1821if stray : 1822out .append (Event ("content" ,self ._track (self .buf [:stray ]))) 1823self .buf = self .buf [stray + len (THINK_END ):] 1824self ._reset_track () 1825self .lead = True 1826self .stray_think += 1 1827continue 1828b ,decided = self ._bare_opener ()if self .recover and self .schemas else (- 1 ,False ) 1829if b >= 0 and (i < 0 or b < i ): 1830# recover: <function=NAME> alone at the start of a line - the call without its <tool_call>. 1831# Until the name has arrived it is held. 1832j = b 1833while j > 0 and self .buf [j - 1 ]== "\n" : 1834j -= 1 1835if j > 0 and self .buf [:j ].strip (): 1836out .append (Event ("content" ,self ._track (self .buf [:j ]))) 1837if not decided : 1838self .buf = self .buf [j :] 1839return out 1840self .buf = self .buf [b :] 1841self .state ,self .bare = "call" ,True 1842continue 1843if i < 0 : 1844# Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped, 1845# so emitting them early would make streamed and whole outputs differ. 1846j = len (self .buf )- self ._hold (self .buf , (CALL_START ,THINK_END )if self .after_think else (CALL_START ,)) 1847if self .recover and self .schemas :# a line that may be becoming a bare <function= 1848k = self .buf .rfind ("\n" )+ 1 1849tail = self .buf [k :] 1850if tail and FUNC_START .startswith (tail )and self ._ok_at (k ): 1851j = min (j ,k ) 1852while j > 0 and self .buf [j - 1 ]== "\n" : 1853j -= 1 1854if j > 0 : 1855out .append (Event ("content" ,self ._track (self .buf [:j ]))) 1856self .buf = self .buf [j :] 1857return out 1858# #1058: an opener inside a code fence or inline code is text (a quoted example), never a call. The 1859# text before it decides, so streamed and whole outputs agree. Mid-sentence openers still count. 1860snap = self ._snap () 1861self ._track (self .buf [:i ]) 1862in_code = self ._in_code () 1863self ._restore (snap ) 1864if in_code : 1865out .append (Event ("content" ,self ._track (self .buf [:i + len (CALL_START )]))) 1866self .buf = self .buf [i + len (CALL_START ):] 1867continue 1868# A call is `<tool_call>` and then (after whitespace) `<function=`; the tag with anything else after 1869# it is prose that names the format ("I'll use a <tool_call> block") - content, not a malformed call 1870# that ends the request. Until its follower has arrived it is held, like a partial tag. 1871after = self .buf [i + len (CALL_START ):].lstrip () 1872if self .schemas and not after .startswith (FUNC_START ): 1873loose = self ._loose_open (after ) 1874if loose == "wait" :# may still become one: held like a partial tag 1875j = i 1876while j > 0 and self .buf [j - 1 ]== "\n" : 1877j -= 1 1878if j > 0 : 1879out .append (Event ("content" ,self ._track (self .buf [:j ]))) 1880self .buf = self .buf [j :] 1881return out 1882if loose :# #3441: `<=NAME>` etc. is `<function=NAME>` 1883at = len (self .buf )- len (after ) 1884self .buf = self .buf [:at ]+ FUNC_START + loose [0 ]+ ">" + after [loose [1 ]:] 1885continue 1886kind = self ._follower (after )if self .recover else None 1887if (after .startswith ("<" )and kind is None and not FUNC_START .startswith (after ) 1888and not after .startswith (FUNC_START )): 1889self .unread += 1 1890if kind in ("param" ,"json" ): 1891if i and self .buf [:i ].strip (): 1892out .append (Event ("content" ,self ._track (self .buf [:i ].rstrip ("\n" )))) 1893rest = self .buf [i + len (CALL_START ):] 1894if kind == "param" :# <parameter=NAME> as the opener: the call's <function=NAME> 1895at = len (rest )- len (after ) 1896rest = rest [:at ]+ FUNC_START + after [len (PARAM_START ):] 1897self .buf = rest 1898self .state = "call" if kind == "param" else "json" 1899continue 1900if kind == "wait" : 1901after = "" 1902is_call = re .match (r"<function=(\s*[^<>\s]+\s*)>" ,after ) 1903if is_call : 1904raw_name = is_call .group (1 ) 1905name = raw_name .strip () 1906name = self .aliases .get (name ,name ) 1907if raw_name != raw_name .strip ()and name not in self .schemas : 1908is_call = None # only declared names gain whitespace normalization 1909is_partial = FUNC_START .startswith (after )or re .fullmatch (r"<function=\s*[^<>\s]*\s*" ,after ) 1910if not is_call and not is_partial : 1911out .append (Event ("content" ,self ._track (self .buf [:i + len (CALL_START )]))) 1912self .buf = self .buf [i + len (CALL_START ):] 1913continue 1914if not is_call : 1915j = i 1916while j > 0 and self .buf [j - 1 ]== "\n" : 1917j -= 1 1918if j > 0 : 1919out .append (Event ("content" ,self ._track (self .buf [:j ]))) 1920self .buf = self .buf [j :] 1921return out 1922if self .schemas or self .declared_only : 1923# #3075: a call counts only for a declared tool; the name must be complete to tell 1924gt = after .find (">" ) 1925nl = after .find ("\n" ) 1926if gt < 0 and nl < 0 : 1927j = i 1928while j > 0 and self .buf [j - 1 ]== "\n" : 1929j -= 1 1930if j > 0 : 1931out .append (Event ("content" ,self ._track (self .buf [:j ]))) 1932self .buf = self .buf [j :] 1933return out 1934if gt >= 0 and (nl < 0 or gt < nl )and not self ._callable (after [len (FUNC_START ):gt ].strip ()): 1935self .unread += 1 # logged by the server: otherwise "the model ignored my tool" is the only clue 1936if len (self .unread_names )< 5 : 1937self .unread_names .append (after [len (FUNC_START ):gt ].strip ()[:80 ]) 1938out .append (Event ("content" ,self ._track (self .buf [:i + len (CALL_START )]))) 1939self .buf = self .buf [i + len (CALL_START ):] 1940continue 1941if i and self .buf [:i ].strip (): 1942out .append (Event ("content" ,self ._track (self .buf [:i ].rstrip ("\n" )))) 1943self .buf = self .buf [i + len (CALL_START ):] 1944self .state = "call" 1945elif self .state == "json" : 1946# recover: `{"name": ..., "arguments": {...}}` inside the wrapper is the call once its </tool_call> has 1947# arrived and it names a declared tool; anything else is the text it is 1948i = self .buf .find (CALL_END ) 1949if i < 0 : 1950return out 1951call = json_tool_call (self .buf [:i ].strip (),self .schemas ) 1952if call is None : 1953out .append (Event ("content" ,self ._track (CALL_START + self .buf [:i + len (CALL_END )]))) 1954else : 1955out .append (Event ("tool_call" ,call = call )) 1956self .buf = self .buf [i + len (CALL_END ):] 1957self .state ,self .lead = "content" ,call is not None 1958else : 1959drop = None 1960if self .bare :# no wrapper: the call ends at its </function>; a stray 1961i = function_end (self .buf )# </tool_call> after it is the wrapper's closer, dropped 1962if i >= 0 : 1963after = self .buf [i :].lstrip () 1964if after .startswith (CALL_END ): 1965drop = len (self .buf [i :])- len (after )+ len (CALL_END ) 1966elif after and not CALL_END .startswith (after ): 1967drop = 0 1968else : 1969i = self ._wrapped_call_end () 1970if i >= 0 : 1971drop = len (CALL_END ) 1972# Only a following call opener confirms an omitted wrapper closer. 1973f = function_end (self .buf ) 1974nxt = self .buf [f :].lstrip ()if f >= 0 else "" 1975if re .match (r"<tool_call>\s*<function=\s*[^<>\s]+\s*>" ,nxt ): 1976i ,drop = f ,0 1977if self .recover :# a batch in one wrapper: the next call follows </function> 1978if nxt .startswith (PARAM_START )and self ._follower (nxt )== "param" : 1979at = len (self .buf )- len (nxt ) 1980self .buf = self .buf [:at ]+ FUNC_START + nxt [len (PARAM_START ):] 1981nxt = self .buf [at :] 1982if nxt .startswith (FUNC_START ): 1983i ,drop ,self .batch = f ,0 ,True 1984if self .stream_tools : 1985if i >= 0 : 1986whole ,self .buf = self .buf ,self .buf [:i ]# scan only the body 1987final ,self ._final = self ._final ,True # #5040: its end is known, so no closing tag is still arriving 1988out += self ._scan () 1989out += self ._close_scan () 1990self .buf ,self ._final = whole ,final 1991else : 1992out += self ._scan () 1993if i < 0 or drop is None : 1994return out 1995body = self .buf [:i ] 1996self .buf = self .buf [i + drop :] 1997batch ,self .batch = self .batch ,False 1998out += self ._finish_call (body ) 1999if batch and out [- 1 ].kind == "tool_call" : 2000self .state ,self .lead = "call" ,False 2001 2002def finish (self ,reason :str | None = None )-> list [Event ]: 2003"""End of generation: flush whatever is held (an unterminated tool call is returned as content; one that was 2004already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211). `reason` is 2005how the turn ended: calls waiting from the reasoning become real calls only on a natural stop (None = stop); 2006a turn cut by max tokens (or cancelled, or failed) keeps them as reasoning text (#1058).""" 2007out = [] 2008if self ._held : 2009self .buf ,self ._held = self .buf + self ._held ,"" 2010if self .buf and self .state in ("call" ,"rcall" ): 2011self ._final = True # #4701: a call held after its closing tags (could a file's text go on?) is whole now 2012out += self .feed ("" ) 2013if self .state == "rcall" and reason in (None ,"stop" ): 2014# #4427: a call in the reasoning whose `</function>` is the end of the output (the `</tool_call>` left out) 2015# is as whole as one in the answer: it waits for the turn's end like the others 2016body = self .buf [len (CALL_START ):] 2017f = function_end (body ) 2018name = body .lstrip ()[len (FUNC_START ):].split (">" ,1 )[0 ].strip ()if f >= 0 else "" 2019name = self .aliases .get (name ,name ) 2020if f >= 0 and not body [f :].strip ()and self ._callable (name ): 2021try : 2022call = parse_tool_call (body [:f ],self .schemas .get (name ),self .notes ) 2023call .name = name 2024self .pending .append ([self .buf ,call ]) 2025self .buf ,self .state = "" ,"reasoning" 2026except ValueError : 2027pass 2028if self .pending : 2029out += self ._release (reason in (None ,"stop" )and self .state == "reasoning" and not self .buf ) 2030if self .state == "call" and self .bare and function_end (self .buf )>= 0 : 2031i = function_end (self .buf )# recover: a bare call is whole at its </function> 2032body ,rest = self .buf [:i ],self .buf [i :].strip () 2033self .buf = "" 2034out += self ._finish_call (body ) 2035if rest and not CALL_END .startswith (rest ): 2036out .append (Event ("content" ,self ._track (rest ))) 2037return out 2038if self .state == "call" and self .stream_tools and self .scall is not None : 2039out += self ._scan ()# the output ended inside a call that was already announced 2040if self .ss == "function_done" and not self .buf [self .sp :].strip ()and reason in (None ,"stop" ): 2041# A natural end immediately after </function> retains native streaming recovery. 2042out += self ._close_scan () 2043call = self .scall 2044try :# the final event carries the call's arguments, as the one _finish_call sends does 2045call = parse_tool_call (self .buf ,self .schemas .get (call .name ),self .notes ) 2046call .name ,call .id = self .scall .name ,self .scall .id 2047except ValueError : 2048pass 2049out .append (Event ("tool_call" ,call = call )) 2050elif self .ss == "function_done" : 2051out .append (Event ("content" ,self ._track (CALL_START + self .buf ))) 2052self .buf = "" 2053self ._reset_scan () 2054return out 2055if self .state == "reasoning" and self .buf == THINK_END :# the output ends on a held `</think>`: its end 2056self .buf ,self .state = "" ,"content" 2057if self .buf : 2058# an unfinished call inside the reasoning (#804) is reasoning text, never a call 2059kind = {"reasoning" :"reasoning" ,"rcall" :"reasoning" ,"content" :"content" }.get (self .state ,"content" ) 2060text = CALL_START + self .buf if self .state in ("call" ,"json" )and not self .bare else self .buf 2061out .append (Event (kind ,text )) 2062self .buf = "" 2063return out 2064 2065def _finish_call (self ,body :str )-> list [Event ]: 2066"""A whole call body in the template's form -> its tool_call event. With recover, one that still does not 2067parse is the text it is instead of an error that ends the request.""" 2068raw_name = body .strip ()[len (FUNC_START ):].split (">" ,1 )[0 ] 2069name = raw_name .strip () 2070name = self .aliases .get (name ,name ) 2071bare ,self .bare = self .bare ,False 2072try : 2073if raw_name != raw_name .strip ()and name not in self .schemas : 2074raise ValueError ("whitespace tool name is not declared" ) 2075call = parse_tool_call (body ,self .schemas .get (name ),self .notes ) 2076call .name = name 2077except ValueError : 2078if not self .recover : 2079raise 2080self ._reset_scan () 2081self .state = "content" 2082return [Event ("content" ,self ._track (body if bare else CALL_START + body + CALL_END ))] 2083if self .scall is not None : 2084call .id = self .scall .id 2085self ._reset_scan () 2086self .state ,self .lead = "content" ,True 2087return [Event ("tool_call" ,call = call )] 2088 2089 2090class JsonOutputParser (OutputParser ): 2091"""The parser for a model whose chat template tells it to write each call as JSON inside the wrapper: 2092`<tool_call>\n{"name": NAME, "arguments": {...}}\n</tool_call>` (Qwen3, Hermes). OutputParser already reads that form, but only 2093as a recovery for a model that drifted off the XML form; for a JSON template it is the form itself, so it is read whether or 2094not the server's tool_call_recovery is on. Everything else (reasoning, code fences, declared-tool rules) is OutputParser's.""" 2095 2096def __init__ (self ,thinking :bool = True ,tools :list [dict ]| None = None ,stream_tools :bool = False , 2097recover :bool = False ,declared_only :bool = False ,deferred :bool = False ): 2098super ().__init__ (thinking = thinking ,tools = tools ,stream_tools = stream_tools ,recover = True , 2099declared_only = declared_only ,deferred = deferred ) 2100 2101 2102def parser_for_template (source :str | None ): 2103"""The OutputParser class for a chat template's text, by the tool-call form the template documents (serve/toolformat.py): 2104the JSON form gets JsonOutputParser; the XML form every Strata model ships with, templates without tools, and forms nothing 2105here reads keep OutputParser (the same class as before this existed). DeepSeek's DSML parser is chosen by the model family 2106(Service.set_family), not here.""" 2107from serve import toolformat 2108return JsonOutputParser if toolformat .tool_format (source or "" )== "json" else OutputParser