okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1"""serve/responses.py - #451: OpenAI's Responses API (POST /v1/responses), stateless, on the chat path. 2 3A Responses request becomes the same template messages, tools and kwargs a Chat Completions request does, runs through 4the same Service.run, and its events (reasoning, text, tool calls) come back as Responses output items and typed SSE 5events. Nothing is stored: the client sends the whole conversation in `input` every time (`store: false`, as Codex CLI 6does), including the reasoning, message and function_call items of earlier answers. 7 8Codex CLI is the first client. What it needs, and what this does: 9* `instructions` and `developer` messages -> the system message (leading ones merged, so the prompt start is stable 10and the conversation cache holds across turns); 11* function tools, also inside `namespace` tools (Codex's MCP and agent tools: the model sees `namespace.name`) and 12`custom` tools (a free-form `input` string); hosted tools (web search, ...) are left out, the model cannot run them; 13* reasoning items: the model's thinking is returned as `reasoning_text` content (no summaries: this model does not 14write them, see docs/DETAILS.md) and, when `include` asks for `reasoning.encrypted_content`, also as an opaque 15`encrypted_content` string (base64, not encrypted: the client already holds the text). Either form sent back is 16put into the conversation again, so the prompt matches what the model wrote and the cache is reused; 17* the official event order: response.created, response.in_progress, response.output_item.added, deltas, 18...done events, response.output_item.done, and response.completed / response.incomplete / response.failed. 19 20Based on #630 by CC-David-CC (the item/event assembler, namespace tools, call_id ordering of tool results). 21""" 22from __future__import annotations 23 24import base64 25import copy 26import json 27import time 28import uuid 29 30from serve .frontend import Event ,_late_system_to_user ,_parts_of ,effort_kwargs 31 32ENCRYPTED_PREFIX = "strata.r1:" # our own reasoning replay strings; others' are ignored 33HOSTED_TOOLS = ("web_search" ,"web_search_preview" ,"file_search" ,"computer_use_preview" ,"computer_use" , 34"code_interpreter" ,"image_generation" ,"local_shell" ,"mcp" ,"tool_search" ) 35 36 37class ResponsesError (ValueError ): 38"""A request error in the Responses format: {"error": {"message", "type", "param", "code"}}.""" 39 40def __init__ (self ,message ,param = None ,code = None ,status = 400 ,kind = "invalid_request_error" ): 41super ().__init__ (message ) 42self .param ,self .code ,self .status ,self .kind = param ,code ,status ,kind 43 44def body (self ): 45return error_body (str (self ),self .kind ,self .param ,self .code ) 46 47 48def error_body (message ,kind = "invalid_request_error" ,param = None ,code = None )-> dict : 49return {"error" : {"message" :message ,"type" :kind ,"param" :param ,"code" :code }} 50 51 52def new_id (prefix :str )-> str : 53return f" { prefix } _ { uuid . uuid4 (). hex } " 54 55 56# ------------------------------------------------------------------------------------------------ request -> chat 57def _content (content ,param ): 58"""A message's (or a tool output's) content -> the template's form: a string, or text and image parts.""" 59if content is None : 60return "" 61if isinstance (content ,str ): 62return content 63if not isinstance (content ,list ): 64raise ResponsesError ("expected a string or an array of content parts" ,param ) 65parts = [] 66for j ,part in enumerate (content ): 67if isinstance (part ,str ): 68parts .append ({"type" :"text" ,"text" :part }) 69continue 70if not isinstance (part ,dict ): 71raise ResponsesError ("expected a content part object" ,f" { param } [ { j } ]" ) 72kind = part .get ("type" ) 73if kind in ("input_text" ,"output_text" ,"text" ,"summary_text" ,"reasoning_text" ): 74parts .append ({"type" :"text" ,"text" :part .get ("text" )or "" }) 75elif kind == "refusal" : 76parts .append ({"type" :"text" ,"text" :part .get ("refusal" )or "" }) 77elif kind in ("input_image" ,"image_url" ): 78if not part .get ("image_url" ): 79raise ResponsesError ("only images given as image_url (a data: or http(s) URL) are supported; " 80"this server keeps no files" ,f" { param } [ { j } ]" ,"unsupported_parameter" ) 81parts .append ({"type" :"input_image" ,"image_url" :part ["image_url" ]}) 82else : 83raise ResponsesError (f"content parts of type { kind !r } are not supported (text and images are)" , 84f" { param } [ { j } ].type" ,"unsupported_parameter" ) 85return _parts_of (parts ) 86 87 88def _reasoning_text (item ,param )-> str : 89"""The thinking a reasoning item carries: its reasoning_text content, else our own encrypted_content. A summary 90alone, or another server's encrypted_content, carries none that can go back into the prompt.""" 91texts = [p .get ("text" )or "" for p in item .get ("content" )or []if isinstance (p ,dict ) 92and p .get ("type" )in ("reasoning_text" ,"text" )] 93if texts : 94return "" .join (texts ) 95enc = item .get ("encrypted_content" ) 96if isinstance (enc ,str )and enc .startswith (ENCRYPTED_PREFIX ): 97try : 98return json .loads (base64 .b64decode (enc [len (ENCRYPTED_PREFIX ):],validate = True ).decode ("utf-8" ))["text" ] 99except (ValueError ,KeyError ,TypeError ,UnicodeError ): 100raise ResponsesError ("this reasoning item's encrypted_content is damaged" ,param + ".encrypted_content" , 101"invalid_encrypted_content" )from None 102return "" 103 104 105def _arguments (raw ,param )-> dict : 106"""A function_call's arguments (a JSON string) -> the mapping the template renders. Arguments that are not a JSON 107object (a call the output ended inside) are kept as text rather than refusing the whole conversation.""" 108if isinstance (raw ,dict ): 109return raw 110if raw is None or (isinstance (raw ,str )and not raw .strip ()): 111return {} 112if not isinstance (raw ,str ): 113raise ResponsesError ("function_call arguments must be a JSON string" ,param ) 114try : 115value = json .loads (raw ) 116except ValueError : 117return {"arguments" :raw } 118return value if isinstance (value ,dict )else {"arguments" :value } 119 120 121def _tool_output (item ,param ): 122out = item .get ("output" ) 123if isinstance (out ,dict ):# some clients send a JSON result as an object 124return json .dumps (out ,ensure_ascii = False ) 125return out if isinstance (out ,str )else _content (out ,param + ".output" ) 126 127 128def input_messages (req :dict )-> list [dict ]: 129"""`instructions` + `input` -> the chat template's messages.""" 130messages = [] 131instructions = req .get ("instructions" ) 132if instructions not in (None ,"" ): 133messages .append ({"role" :"system" ,"content" :_content (instructions ,"instructions" ) 134if not isinstance (instructions ,str )else instructions }) 135items = req .get ("input" ) 136if items is None : 137raise ResponsesError ("input is required: a string or an array of input items" ,"input" ,"missing_required_parameter" ) 138if isinstance (items ,str ): 139items = [{"type" :"message" ,"role" :"user" ,"content" :items }] 140if not isinstance (items ,list ): 141raise ResponsesError ("input must be a string or an array of input items" ,"input" ) 142thinking = []# reasoning waiting for the assistant turn it belongs to 143open_turn = None # the assistant message the next function_call joins 144 145def turn (content = "" ): 146nonlocal open_turn 147open_turn = {"role" :"assistant" ,"content" :content } 148if thinking : 149open_turn ["reasoning_content" ]= "" .join (thinking ) 150thinking .clear () 151messages .append (open_turn ) 152return open_turn 153 154for i ,item in enumerate (items ): 155param = f"input[ { i } ]" 156if not isinstance (item ,dict ): 157raise ResponsesError ("expected an input item object" ,param ) 158kind = item .get ("type" )or ("message" if "role" in item else None ) 159if kind == "message" : 160role = item .get ("role" ) 161if role not in ("user" ,"assistant" ,"system" ,"developer" ): 162raise ResponsesError (f"unknown message role { role !r } " ,param + ".role" ) 163content = _content (item .get ("content" ),param + ".content" ) 164if role == "assistant" : 165turn (content if isinstance (content ,str )else "" .join ( 166p .get ("text" ,"" )for p in content if p .get ("type" )== "text" )) 167else : 168open_turn = None 169thinking .clear () 170messages .append ({"role" :"system" if role == "developer" else role ,"content" :content }) 171elif kind == "reasoning" : 172text = _reasoning_text (item ,param ) 173if text : 174if open_turn is not None and (open_turn .get ("tool_calls" )or open_turn ["content" ]): 175open_turn = None # thinking starts a new model turn 176thinking .append (text ) 177elif kind in ("function_call" ,"custom_tool_call" ): 178name = item .get ("name" ) 179if not isinstance (name ,str )or not name : 180raise ResponsesError ("a function_call needs a name" ,param + ".name" ) 181if item .get ("namespace" ): 182name = f" { item [ 'namespace' ] } . { name } " 183if kind == "function_call" : 184args = _arguments (item .get ("arguments" ),param + ".arguments" ) 185else : 186args = {"input" :item .get ("input" )if isinstance (item .get ("input" ),str )else "" } 187target = open_turn if open_turn is not None and not thinking else turn () 188target .setdefault ("tool_calls" , []).append ({"function" : {"name" :name ,"arguments" :args }, 189"_call_id" :item .get ("call_id" )}) 190elif kind in ("function_call_output" ,"custom_tool_call_output" ): 191messages .append ({"role" :"tool" ,"content" :_tool_output (item ,param ),"_call_id" :item .get ("call_id" )}) 192open_turn = None 193thinking .clear () 194elif kind == "additional_tools" : 195continue # #782 (Codex): tools the client adds as an input item; see request_tools 196elif kind == "item_reference" : 197raise ResponsesError ("item references need stored responses, and this server keeps none: send the items " 198"themselves" ,param ,"unsupported_parameter" ) 199else : 200raise ResponsesError (f"input items of type { kind !r } are not supported" ,param + ".type" , 201"unsupported_parameter" ) 202_order_tool_results (messages ) 203# leading system/developer messages (Codex: instructions, then its developer message) become one system message 204# at the start; later ones become user messages in place, as on the chat path 205lead = 0 206while lead < len (messages )and messages [lead ]["role" ]== "system" and isinstance (messages [lead ]["content" ],str ): 207lead += 1 208if lead > 1 : 209messages [:lead ]= [{"role" :"system" ,"content" :"\n\n" .join (m ["content" ]for m in messages [:lead ])}] 210return _late_system_to_user (messages ) 211 212 213def _order_tool_results (messages ): 214"""The template places tool results by position: each run of tool messages is put in the order of the calls of 215the assistant turn before it (a client may send the results in the order they finished), then the private call 216ids are dropped.""" 217i = 0 218while i < len (messages ): 219if messages [i ]["role" ]!= "tool" : 220i += 1 221continue 222j = i 223while j < len (messages )and messages [j ]["role" ]== "tool" : 224j += 1 225prev = messages [i - 1 ]if i else {} 226order = [c .get ("_call_id" )for c in prev .get ("tool_calls" )or []] 227rank = {cid :k for k ,cid in enumerate (order )if cid } 228messages [i :j ]= sorted (messages [i :j ],key = lambda m :rank .get (m .get ("_call_id" ),len (order ))) 229i = j 230for m in messages : 231m .pop ("_call_id" ,None ) 232for c in m .get ("tool_calls" )or []: 233c .pop ("_call_id" ,None ) 234 235 236def request_tools (req :dict ): 237"""-> (template tools or None, {template name: (namespace, name, kind)}, names of hosted tools left out).""" 238tools ,names ,skipped = [], {}, [] 239given = req .get ("tools" )or [] 240if not isinstance (given ,list ): 241raise ResponsesError ("tools must be an array" ,"tools" ) 242# #782 (Codex v0.160): `additional_tools` input items carry more tool definitions (a `tools` array, as the request 243# has); they join the request's own, and an item without a usable array adds nothing 244extra = [t for item in (req .get ("input" )if isinstance (req .get ("input" ),list )else []) 245if isinstance (item ,dict )and item .get ("type" )== "additional_tools" and isinstance (item .get ("tools" ),list ) 246for t in item ["tools" ]] 247given = list (given )+ extra 248 249def add (tool ,param ,namespace = None ,ns_description = "" ): 250kind = tool .get ("type" ) 251name = tool .get ("name" ) 252if not isinstance (name ,str )or not name : 253raise ResponsesError ("a tool needs a name" ,param + ".name" ) 254flat = f" { namespace } . { name } " if namespace else name 255description = tool .get ("description" )or "" 256if ns_description : 257description = ns_description + ("\n\n" + description if description else "" ) 258if kind == "function" : 259params = tool .get ("parameters" )or {"type" :"object" ,"properties" : {}} 260else :# custom: free-form text, maybe in a grammar the model reads 261fmt = tool .get ("format" )or {} 262if isinstance (fmt ,dict )and fmt .get ("type" )== "grammar" and fmt .get ("definition" ): 263description += f"\n\nThe input must follow this { fmt . get ( 'syntax' , '' ) } grammar:\n { fmt [ 'definition' ] } " 264params = {"type" :"object" ,"properties" : {"input" : {"type" :"string" ,"description" :"the raw input" }}, 265"required" : ["input" ]} 266tools .append ({"name" :flat ,"description" :description ,"parameters" :params }) 267names [flat ]= (namespace ,name ,kind ) 268 269for i ,tool in enumerate (given ): 270param = f"tools[ { i } ]" 271if not isinstance (tool ,dict ): 272raise ResponsesError ("expected a tool object" ,param ) 273kind = tool .get ("type" ) 274if kind in ("function" ,"custom" ): 275add (tool ,param ) 276elif kind == "namespace" : 277for j ,member in enumerate (tool .get ("tools" )or []): 278if not isinstance (member ,dict )or member .get ("type" ,"function" )not in ("function" ,"custom" ): 279raise ResponsesError ("a namespace holds function tools" ,f" { param } .tools[ { j } ]" ) 280add ({"type" :"function" ,** member },f" { param } .tools[ { j } ]" ,tool .get ("name" ), 281tool .get ("description" )or "" ) 282elif kind in HOSTED_TOOLS or isinstance (kind ,str ): 283skipped .append (kind )# the model cannot run OpenAI's hosted tools: left out 284else : 285raise ResponsesError ("a tool needs a type" ,param + ".type" ) 286choice = req .get ("tool_choice" ) 287if choice == "none" : 288return None ,names ,skipped 289return tools or None ,names ,skipped 290 291 292def _turn_body (req :dict ): 293meta = req .get ("client_metadata" ) 294raw = meta .get ("x-codex-turn-metadata" )if isinstance (meta ,dict )else None 295try : 296turn = json .loads (raw )if isinstance (raw ,str )else None 297except ValueError : 298return None 299return turn if isinstance (turn ,dict )else None 300 301 302def _title_text (req :dict )-> str : 303"""The user line Codex asked to name, cut to the schema's 36 characters.""" 304parts = [] 305items = req .get ("input" ) 306if isinstance (items ,str ): 307items = [{"role" :"user" ,"content" :items }] 308if isinstance (items ,list ): 309for item in items : 310if not isinstance (item ,dict )or item .get ("role" )!= "user" : 311continue 312content = item .get ("content" ) 313if isinstance (content ,str ): 314parts .append (content ) 315elif isinstance (content ,list ): 316for piece in content : 317if isinstance (piece ,dict )and isinstance (piece .get ("text" ),str ): 318parts .append (piece ["text" ]) 319text = "\n" .join (parts ) 320if "User prompt:" in text : 321text = text .split ("User prompt:" ,1 )[1 ] 322line = next ((x .strip ()for x in text .splitlines ()if x .strip ()),"Untitled" ) 323line = line .strip (" \"'`" ) 324while line and line [- 1 ]in ".。!!??,,;;::" : 325line = line [:- 1 ].rstrip () 326return line [:36 ].rstrip ()or "Untitled" 327 328 329def thread_title_events (req :dict ,model :str ): 330"""Codex's thread-title turn, answered here. None when this request is not one. 331 332Codex 0.160 sends this beside the user turn: another session, no tools, the full instructions. Running it on the 333one prefix cache replaces the conversation. 334""" 335if (_turn_body (req )or {}).get ("thread_source" )!= "thread_title" : 336return None 337check_request (req ) 338text = json .dumps ({"title" :_title_text (req )},ensure_ascii = False ) 339asm = Assembler (req ,model ,0 , {},False ,json_mode = False ) 340events = asm .start () 341events += asm ._open ({"id" :new_id ("msg" ),"type" :"message" ,"status" :"in_progress" ,"role" :"assistant" , 342"content" : []}) 343asm .item ["content" ][0 ]["text" ]= text 344events .append (asm .event ("response.output_text.delta" ,item_id = asm .item ["id" ],output_index = asm .index , 345content_index = 0 ,delta = text ,logprobs = [])) 346events += asm .close () 347asm .response ["usage" ]= { 348"input_tokens" :0 ,"input_tokens_details" : {"cached_tokens" :0 }, 349"output_tokens" :0 ,"output_tokens_details" : {"reasoning_tokens" :0 }, 350"total_tokens" :0 } 351asm .response ["status" ]= "completed" 352asm .response ["completed_at" ]= int (time .time ()) 353events .append (asm .event ("response.completed" ,response = asm .snapshot ())) 354return events 355 356 357# Codex's local compaction (the context is full, or /compact) sends its conversation again with `tools: []` 358# (codex-rs/core/src/compact.rs: `Prompt { input, base_instructions, ..Default::default() }`). The template writes 359# the tools at the top of the prompt, so that prompt shares almost nothing with the one the engine holds and the whole 360# conversation is read again, at its longest. So the tools a Codex conversation's last prompt was rendered with are 361# kept, and that conversation's compaction prompt is rendered with them. Only the prompt: the parser and the response 362# get the request's own tools, which are none. Codex says what a request is and whose it is in 363# client_metadata["x-codex-turn-metadata"] (a JSON string, Codex 0.140 and later): `request_kind` and the 364# conversation's `session_id` and `thread_id` (a sub-agent shares its parent's session, not its thread; a fork gets 365# its own). `prompt_cache_key` is not used: it groups requests for caching, and Codex gives sub-agents and ephemeral 366# forks their parent's. A request without that metadata is rendered as sent and changes nothing. One entry, replaced 367# by each prompt of a Codex conversation: nothing grows, and a compaction of any other conversation finds a different 368# (session_id, thread_id) and renders its request as sent. Lost (a restart): the prompt is read again, as without it. 369_kept_prompt_tools = (None ,None )# ((session_id, thread_id), its prompt's tools as JSON or None) 370 371 372def _codex_turn (req :dict ): 373"""-> (request_kind, (session_id, thread_id)) from Codex's turn metadata; the conversation is None without both.""" 374meta = req .get ("client_metadata" ) 375raw = meta .get ("x-codex-turn-metadata" )if isinstance (meta ,dict )else None 376try : 377turn = json .loads (raw )if isinstance (raw ,str )else None 378except ValueError : 379turn = None 380if not isinstance (turn ,dict ): 381return None ,None 382conversation = (turn .get ("session_id" ),turn .get ("thread_id" )) 383return turn .get ("request_kind" ),conversation if all (isinstance (x ,str )and x for x in conversation )else None 384 385 386def prompt_tools (req :dict ,tools ): 387"""-> the tools the prompt is rendered with: request_tools' `tools`, or for a Codex compaction request without 388tools the ones its own conversation's last prompt was rendered with (so its prompt starts as that one did).""" 389kind ,conversation = _codex_turn (req ) 390owner ,kept = _kept_prompt_tools 391if kind != "compaction" or conversation is None or owner != conversation or kept is None or req .get ("tools" ): 392return tools 393return json .loads (kept )# a fresh copy: the kept one is nobody's to change 394 395 396def prompt_made (req :dict ,tools ): 397"""The prompt of `req` was rendered with `tools` and goes to the engine: a Codex request that is not a compaction 398leaves its conversation and those tools for that conversation's compaction. A thread-title turn is another 399session Codex sends beside the real one, and it does not replace this entry.""" 400global _kept_prompt_tools 401if (_turn_body (req )or {}).get ("thread_source" )== "thread_title" : 402return 403kind ,conversation = _codex_turn (req ) 404if conversation is not None and kind != "compaction" : 405_kept_prompt_tools = (conversation ,json .dumps (tools )if tools else None ) 406 407 408def text_format (req :dict ): 409"""`text.format` -> the chat path's response_format (None: plain text).""" 410text = req .get ("text" ) 411if text is None : 412return None 413if not isinstance (text ,dict ): 414raise ResponsesError ("text must be an object" ,"text" ) 415fmt = text .get ("format" ) 416if fmt is None : 417return None 418if not isinstance (fmt ,dict ): 419raise ResponsesError ("text.format must be an object" ,"text.format" ) 420kind = fmt .get ("type" ) 421if kind in (None ,"text" ): 422return None 423extra = {"repair_latex_escapes" :True }if fmt .get ("repair_latex_escapes" )is True else {}# #2893, opt-in 424if kind == "json_object" : 425return {"type" :"json_object" ,** extra } 426if kind == "json_schema" : 427spec = {k :fmt [k ]for k in ("name" ,"schema" ,"strict" ,"description" )if k in fmt } 428return {"type" :"json_schema" ,"json_schema" :spec ,** extra } 429raise ResponsesError ("text.format.type must be text, json_object or json_schema" ,"text.format.type" ) 430 431 432def check_request (req :dict )-> None : 433"""What this stateless server cannot do, refused before anything runs.""" 434if req .get ("previous_response_id" ): 435raise ResponsesError ("this server keeps no responses (stateless): send the whole conversation in input " 436"instead of previous_response_id" ,"previous_response_id" ,"unsupported_parameter" ) 437if req .get ("conversation" ): 438raise ResponsesError ("this server keeps no conversations (stateless): send the whole conversation in input" , 439"conversation" ,"unsupported_parameter" ) 440if req .get ("background" ): 441raise ResponsesError ("background responses are not supported: use stream or wait for the answer" , 442"background" ,"unsupported_parameter" ) 443if req .get ("prompt" ): 444raise ResponsesError ("stored prompt templates are not supported: send instructions and input" , 445"prompt" ,"unsupported_parameter" ) 446n = req .get ("max_output_tokens" ) 447# -1 and 0 mean no cap, as max_tokens does on the chat path (docs/DETAILS.md); anything lower is a mistake 448if n is not None and (isinstance (n ,bool )or not isinstance (n ,int )or n < - 1 ): 449raise ResponsesError ("max_output_tokens must be a whole number, 1 or more, or -1 or 0 for no cap" , 450"max_output_tokens" ) 451reasoning = req .get ("reasoning" ) 452if reasoning is not None and not isinstance (reasoning ,dict ): 453raise ResponsesError ("reasoning must be an object" ,"reasoning" ) 454 455 456def template_kwargs (req :dict ,shared :dict )-> dict : 457effort = (req .get ("reasoning" )or {}).get ("effort" ) 458if effort is None : 459effort = shared .get ("reasoning_effort" )# the Chat settings shared with apps, as on the chat path 460try : 461return effort_kwargs (effort ) 462except ValueError as e : 463raise ResponsesError (str (e ),"reasoning.effort" )from None 464 465 466# ------------------------------------------------------------------------------------------------ output 467class Assembler : 468"""One response: its output items and its typed events, built from Service.run's events. The non-streaming 469answer is the `response` of the last event, so both modes are the same items.""" 470 471def __init__ (self ,req :dict ,model :str ,prompt_tokens :int ,names :dict ,encrypted :bool , 472json_mode :bool = False ): 473self .names ,self .encrypted ,self .json_mode = names ,encrypted ,json_mode 474self .prompt_tokens = prompt_tokens 475self .seq = 0 476self .item = None # the open output item 477self .json_text = []# structured output: the answer, held until it is checked 478self .called = False # a tool call was made: this turn is not the final answer 479reasoning = req .get ("reasoning" )if isinstance (req .get ("reasoning" ),dict )else {} 480self .response = { 481"id" :new_id ("resp" ),"object" :"response" ,"created_at" :int (time .time ()),"status" :"in_progress" , 482"background" :False ,"error" :None ,"incomplete_details" :None , 483"instructions" :req .get ("instructions" ),"max_output_tokens" :req .get ("max_output_tokens" ), 484"model" :model ,"output" : [],"parallel_tool_calls" :req .get ("parallel_tool_calls" ,True ), 485"previous_response_id" :None , 486"reasoning" : {"effort" :reasoning .get ("effort" ),"summary" :reasoning .get ("summary" )}, 487"store" :False ,"temperature" :req .get ("temperature" ), 488"text" :req .get ("text" )if isinstance (req .get ("text" ),dict )else {"format" : {"type" :"text" }}, 489"tool_choice" :req .get ("tool_choice" ,"auto" ),"tools" :req .get ("tools" )or [], 490"top_p" :req .get ("top_p" ),"truncation" :"disabled" ,"usage" :None ,"user" :None , 491"metadata" :req .get ("metadata" )or {}} 492 493# --- events 494def event (self ,kind ,** data )-> dict : 495e = {"type" :kind ,"sequence_number" :self .seq ,** data } 496self .seq += 1 497return e 498 499def snapshot (self )-> dict : 500return copy .deepcopy (self .response ) 501 502def start (self )-> list [dict ]: 503return [self .event ("response.created" ,response = self .snapshot ()), 504self .event ("response.in_progress" ,response = self .snapshot ())] 505 506def in_progress (self )-> dict : 507"""A keep-alive a client counts as activity (SSE comments are not events: Codex's idle timer ignores them).""" 508return self .event ("response.in_progress" ,response = self .snapshot ()) 509 510def _open (self ,item )-> list [dict ]: 511self .response ["output" ].append (item ) 512self .item = item 513out = [self .event ("response.output_item.added" ,output_index = self .index ,item = copy .deepcopy (item ))] 514if item ["type" ]== "message" : 515part = {"type" :"output_text" ,"text" :"" ,"annotations" : [],"logprobs" : []} 516item ["content" ].append (part ) 517out .append (self .event ("response.content_part.added" ,item_id = item ["id" ],output_index = self .index , 518content_index = 0 ,part = copy .deepcopy (part ))) 519return out 520 521@property 522def index (self )-> int : 523return len (self .response ["output" ])- 1 524 525def close (self ,status = None )-> list [dict ]: 526item ,self .item = self .item ,None 527if item is None : 528return [] 529at ,out = self .response ["output" ].index (item ), [] 530item ["status" ]= status or ("incomplete" if item ["type" ]in ("function_call" ,"custom_tool_call" )else "completed" ) 531if item ["type" ]== "message" : 532part = item ["content" ][0 ] 533out += [self .event ("response.output_text.done" ,item_id = item ["id" ],output_index = at ,content_index = 0 , 534text = part ["text" ],logprobs = []), 535self .event ("response.content_part.done" ,item_id = item ["id" ],output_index = at ,content_index = 0 , 536part = copy .deepcopy (part ))] 537elif item ["type" ]== "reasoning" : 538text = item ["content" ][0 ]["text" ] 539out .append (self .event ("response.reasoning_text.done" ,item_id = item ["id" ],output_index = at , 540content_index = 0 ,text = text )) 541if self .encrypted : 542item ["encrypted_content" ]= ENCRYPTED_PREFIX + base64 .b64encode ( 543json .dumps ({"text" :text },ensure_ascii = False ).encode ("utf-8" )).decode ("ascii" ) 544elif item ["type" ]== "function_call" : 545out .append (self .event ("response.function_call_arguments.done" ,item_id = item ["id" ],output_index = at , 546name = item ["name" ],arguments = item ["arguments" ])) 547elif item ["type" ]== "custom_tool_call" : 548out .append (self .event ("response.custom_tool_call_input.done" ,item_id = item ["id" ],output_index = at , 549input = item ["input" ])) 550out .append (self .event ("response.output_item.done" ,output_index = at ,item = copy .deepcopy (item ))) 551return out 552 553def feed (self ,ev :Event )-> list [dict ]: 554out = [] 555kind = ev .kind 556if kind == "reasoning" : 557if not ev .text : 558return out 559if self .item is None or self .item ["type" ]!= "reasoning" : 560out += self .close () 561out += self ._open ({"id" :new_id ("rs" ),"type" :"reasoning" ,"status" :"in_progress" ,"summary" : [], 562"content" : [{"type" :"reasoning_text" ,"text" :"" }]}) 563self .item ["content" ][0 ]["text" ]+= ev .text 564out .append (self .event ("response.reasoning_text.delta" ,item_id = self .item ["id" ],output_index = self .index , 565content_index = 0 ,delta = ev .text )) 566elif kind == "content" : 567if not ev .text : 568return out 569if self .json_mode :# sent once it is checked (finish) 570out += self .close () 571self .json_text .append (ev .text ) 572return out 573if self .item is None or self .item ["type" ]!= "message" : 574out += self .close () 575out += self ._open ({"id" :new_id ("msg" ),"type" :"message" ,"status" :"in_progress" , 576"role" :"assistant" ,"content" : []}) 577self .item ["content" ][0 ]["text" ]+= ev .text 578out .append (self .event ("response.output_text.delta" ,item_id = self .item ["id" ],output_index = self .index , 579content_index = 0 ,delta = ev .text ,logprobs = [])) 580elif kind == "tool_start" : 581out += self .close () 582out += self ._call_started () 583out += self ._open (self ._call_item (ev )) 584elif kind == "tool_args" : 585item = self .item 586if item is None or item .get ("call_id" )!= ev .call .id : 587return out 588if item ["type" ]== "function_call" :# a custom tool's input is sent whole, at its end 589item ["arguments" ]+= ev .text 590out .append (self .event ("response.function_call_arguments.delta" ,item_id = item ["id" ], 591output_index = self .index ,delta = ev .text )) 592elif kind == "tool_call" : 593item = self .item 594if item is None or item .get ("call_id" )!= ev .call .id :# a call that was not announced while written 595out += self .close () 596out += self ._call_started () 597out += self ._open (self ._call_item (ev )) 598item = self .item 599if item ["type" ]== "function_call" : 600item ["arguments" ]= json .dumps (ev .call .arguments ,ensure_ascii = False ) 601out .append (self .event ("response.function_call_arguments.delta" ,item_id = item ["id" ], 602output_index = self .index ,delta = item ["arguments" ])) 603if item ["type" ]== "custom_tool_call" : 604value = ev .call .arguments .get ("input" )if isinstance (ev .call .arguments ,dict )else None 605item ["input" ]= value if isinstance (value ,str )else json .dumps (ev .call .arguments ,ensure_ascii = False ) 606out .append (self .event ("response.custom_tool_call_input.delta" ,item_id = item ["id" ], 607output_index = self .index ,delta = item ["input" ])) 608out += self .close ("completed" ) 609return out 610 611def _release (self ,text :str )-> list [dict ]: 612"""A held structured answer (or the words written beside a tool call) as one message item.""" 613if not text .strip (): 614return [] 615out = self ._open ({"id" :new_id ("msg" ),"type" :"message" ,"status" :"in_progress" ,"role" :"assistant" , 616"content" : []}) 617self .item ["content" ][0 ]["text" ]= text 618out .append (self .event ("response.output_text.delta" ,item_id = self .item ["id" ],output_index = self .index , 619content_index = 0 ,delta = text ,logprobs = [])) 620return out + self .close () 621 622def _call_started (self )-> list [dict ]: 623"""The first tool call of a JSON-format turn: this turn is not the final answer, so what the model wrote 624before the call goes out as it is, ahead of the call, and the schema is checked on the turn that ends in 625text (#782).""" 626out = [] 627if self .json_mode and not self .called : 628out = self ._release ("" .join (self .json_text )) 629self .json_text = [] 630self .called = True 631return out 632 633def _call_item (self ,ev :Event )-> dict : 634namespace ,name ,kind = self .names .get (ev .call .name , (None ,ev .call .name ,"function" )) 635if kind == "custom" : 636item = {"id" :new_id ("ctc" ),"type" :"custom_tool_call" ,"status" :"in_progress" ,"call_id" :ev .call .id , 637"name" :name ,"input" :"" } 638else : 639item = {"id" :new_id ("fc" ),"type" :"function_call" ,"status" :"in_progress" ,"call_id" :ev .call .id , 640"name" :name ,"arguments" :"" } 641if namespace : 642item ["namespace" ]= namespace 643return item 644 645def finish (self ,done :dict ,validate = None )-> list [dict ]: 646"""The end: close what is open, then response.completed (or .incomplete when max_output_tokens ran out). 647`validate(text, finish)` checks a structured answer and returns its text (or raises).""" 648length = done .get ("finish" )== "length" 649# a call still open was cut off (its tool_call never came, #211): incomplete, whatever the finish 650unfinished = self .item is not None and self .item ["type" ]in ("function_call" ,"custom_tool_call" ) 651out = self .close ("incomplete" if length or unfinished else "completed" ) 652if self .json_mode : 653text = "" .join (self .json_text ) 654self .json_text = [] 655if self .called : 656out += self ._release (text )# beside a tool call: as written (#782) 657else : 658out += self ._release (validate (text ,done .get ("finish" ))) 659n = done .get ("completion_tokens" ,0 ) 660prompt = done .get ("prompt_tokens" ,self .prompt_tokens ) 661self .response ["usage" ]= { 662"input_tokens" :prompt ,"input_tokens_details" : {"cached_tokens" :min (done .get ("reused" )or 0 ,prompt )}, 663"output_tokens" :n ,"output_tokens_details" : {"reasoning_tokens" :done .get ("reasoning_tokens" ,0 )}, 664"total_tokens" :prompt + n } 665if length : 666self .response ["status" ]= "incomplete" 667self .response ["incomplete_details" ]= {"reason" :"max_output_tokens" } 668return out + [self ._with_timings (self .event ("response.incomplete" ,response = self .snapshot ()),done )] 669self .response ["status" ]= "completed" 670self .response ["completed_at" ]= int (time .time ()) 671return out + [self ._with_timings (self .event ("response.completed" ,response = self .snapshot ()),done )] 672 673@staticmethod 674def _with_timings (event :dict ,done :dict )-> dict : 675"""Top-level `timings` on the final event, as /v1/chat/completions has them (#107).""" 676if done .get ("timings" ): 677event ["timings" ]= done ["timings" ] 678return event 679 680def failed (self ,message :str ,code :str = "server_error" )-> dict : 681"""response.failed: an error after the stream started (the HTTP status is already sent).""" 682if self .item is not None : 683self .item ["status" ]= "incomplete" 684self .item = None 685self .response ["status" ]= "failed" 686self .response ["error" ]= {"code" :code ,"message" :message } 687return self .event ("response.failed" ,response = self .snapshot ()) 688 689 690def collect (events )-> dict : 691"""The non-streaming answer: the final response object.""" 692last = None 693for e in events : 694if e is not None : 695last = e 696if last .get ("timings" ):# as on a whole /v1/chat/completions reply (#107) 697return {** last ["response" ],"timings" :last ["timings" ]} 698return last ["response" ]