okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
36.9 KiB698 linesraw
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
10    and 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
14    write 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
16    put 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
40    def __init__(self, message, param=None, code=None, status=400, kind="invalid_request_error"):
41        super().__init__(message)
42        self.param, self.code, self.status, self.kind = param, code, status, kind
43
44    def body(self):
45        return 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:
49    return {"error": {"message": message, "type": kind, "param": param, "code": code}}
50
51
52def new_id(prefix: str) -> str:
53    return 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."""
59    if content is None:
60        return ""
61    if isinstance(content, str):
62        return content
63    if not isinstance(content, list):
64        raise ResponsesError("expected a string or an array of content parts", param)
65    parts = []
66    for j, part in enumerate(content):
67        if isinstance(part, str):
68            parts.append({"type": "text", "text": part})
69            continue
70        if not isinstance(part, dict):
71            raise ResponsesError("expected a content part object", f"{param}[{j}]")
72        kind = part.get("type")
73        if kind in ("input_text", "output_text", "text", "summary_text", "reasoning_text"):
74            parts.append({"type": "text", "text": part.get("text") or ""})
75        elif kind == "refusal":
76            parts.append({"type": "text", "text": part.get("refusal") or ""})
77        elif kind in ("input_image", "image_url"):
78            if not part.get("image_url"):
79                raise 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")
81            parts.append({"type": "input_image", "image_url": part["image_url"]})
82        else:
83            raise ResponsesError(f"content parts of type {kind!r} are not supported (text and images are)",
84                                 f"{param}[{j}].type", "unsupported_parameter")
85    return _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
90    alone, or another server's encrypted_content, carries none that can go back into the prompt."""
91    texts = [p.get("text") or "" for p in item.get("content") or [] if isinstance(p, dict)
92             and p.get("type") in ("reasoning_text", "text")]
93    if texts:
94        return "".join(texts)
95    enc = item.get("encrypted_content")
96    if isinstance(enc, str) and enc.startswith(ENCRYPTED_PREFIX):
97        try:
98            return json.loads(base64.b64decode(enc[len(ENCRYPTED_PREFIX):], validate=True).decode("utf-8"))["text"]
99        except (ValueError, KeyError, TypeError, UnicodeError):
100            raise ResponsesError("this reasoning item's encrypted_content is damaged", param + ".encrypted_content",
101                                 "invalid_encrypted_content") from None
102    return ""
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
107    object (a call the output ended inside) are kept as text rather than refusing the whole conversation."""
108    if isinstance(raw, dict):
109        return raw
110    if raw is None or (isinstance(raw, str) and not raw.strip()):
111        return {}
112    if not isinstance(raw, str):
113        raise ResponsesError("function_call arguments must be a JSON string", param)
114    try:
115        value = json.loads(raw)
116    except ValueError:
117        return {"arguments": raw}
118    return value if isinstance(value, dict) else {"arguments": value}
119
120
121def _tool_output(item, param):
122    out = item.get("output")
123    if isinstance(out, dict):                        # some clients send a JSON result as an object
124        return json.dumps(out, ensure_ascii=False)
125    return 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."""
130    messages = []
131    instructions = req.get("instructions")
132    if instructions not in (None, ""):
133        messages.append({"role": "system", "content": _content(instructions, "instructions")
134                         if not isinstance(instructions, str) else instructions})
135    items = req.get("input")
136    if items is None:
137        raise ResponsesError("input is required: a string or an array of input items", "input", "missing_required_parameter")
138    if isinstance(items, str):
139        items = [{"type": "message", "role": "user", "content": items}]
140    if not isinstance(items, list):
141        raise ResponsesError("input must be a string or an array of input items", "input")
142    thinking = []                                    # reasoning waiting for the assistant turn it belongs to
143    open_turn = None                                 # the assistant message the next function_call joins
144
145    def turn(content=""):
146        nonlocal open_turn
147        open_turn = {"role": "assistant", "content": content}
148        if thinking:
149            open_turn["reasoning_content"] = "".join(thinking)
150            thinking.clear()
151        messages.append(open_turn)
152        return open_turn
153
154    for i, item in enumerate(items):
155        param = f"input[{i}]"
156        if not isinstance(item, dict):
157            raise ResponsesError("expected an input item object", param)
158        kind = item.get("type") or ("message" if "role" in item else None)
159        if kind == "message":
160            role = item.get("role")
161            if role not in ("user", "assistant", "system", "developer"):
162                raise ResponsesError(f"unknown message role {role!r}", param + ".role")
163            content = _content(item.get("content"), param + ".content")
164            if role == "assistant":
165                turn(content if isinstance(content, str) else "".join(
166                    p.get("text", "") for p in content if p.get("type") == "text"))
167            else:
168                open_turn = None
169                thinking.clear()
170                messages.append({"role": "system" if role == "developer" else role, "content": content})
171        elif kind == "reasoning":
172            text = _reasoning_text(item, param)
173            if text:
174                if open_turn is not None and (open_turn.get("tool_calls") or open_turn["content"]):
175                    open_turn = None                 # thinking starts a new model turn
176                thinking.append(text)
177        elif kind in ("function_call", "custom_tool_call"):
178            name = item.get("name")
179            if not isinstance(name, str) or not name:
180                raise ResponsesError("a function_call needs a name", param + ".name")
181            if item.get("namespace"):
182                name = f"{item['namespace']}.{name}"
183            if kind == "function_call":
184                args = _arguments(item.get("arguments"), param + ".arguments")
185            else:
186                args = {"input": item.get("input") if isinstance(item.get("input"), str) else ""}
187            target = open_turn if open_turn is not None and not thinking else turn()
188            target.setdefault("tool_calls", []).append({"function": {"name": name, "arguments": args},
189                                                        "_call_id": item.get("call_id")})
190        elif kind in ("function_call_output", "custom_tool_call_output"):
191            messages.append({"role": "tool", "content": _tool_output(item, param), "_call_id": item.get("call_id")})
192            open_turn = None
193            thinking.clear()
194        elif kind == "additional_tools":
195            continue                                 # #782 (Codex): tools the client adds as an input item; see request_tools
196        elif kind == "item_reference":
197            raise ResponsesError("item references need stored responses, and this server keeps none: send the items "
198                                 "themselves", param, "unsupported_parameter")
199        else:
200            raise 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
205    lead = 0
206    while lead < len(messages) and messages[lead]["role"] == "system" and isinstance(messages[lead]["content"], str):
207        lead += 1
208    if lead > 1:
209        messages[:lead] = [{"role": "system", "content": "\n\n".join(m["content"] for m in messages[:lead])}]
210    return _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
215    the assistant turn before it (a client may send the results in the order they finished), then the private call
216    ids are dropped."""
217    i = 0
218    while i < len(messages):
219        if messages[i]["role"] != "tool":
220            i += 1
221            continue
222        j = i
223        while j < len(messages) and messages[j]["role"] == "tool":
224            j += 1
225        prev = messages[i - 1] if i else {}
226        order = [c.get("_call_id") for c in prev.get("tool_calls") or []]
227        rank = {cid: k for k, cid in enumerate(order) if cid}
228        messages[i:j] = sorted(messages[i:j], key=lambda m: rank.get(m.get("_call_id"), len(order)))
229        i = j
230    for m in messages:
231        m.pop("_call_id", None)
232        for c in m.get("tool_calls") or []:
233            c.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)."""
238    tools, names, skipped = [], {}, []
239    given = req.get("tools") or []
240    if not isinstance(given, list):
241        raise 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
244    extra = [t for item in (req.get("input") if isinstance(req.get("input"), list) else [])
245             if isinstance(item, dict) and item.get("type") == "additional_tools" and isinstance(item.get("tools"), list)
246             for t in item["tools"]]
247    given = list(given) + extra
248
249    def add(tool, param, namespace=None, ns_description=""):
250        kind = tool.get("type")
251        name = tool.get("name")
252        if not isinstance(name, str) or not name:
253            raise ResponsesError("a tool needs a name", param + ".name")
254        flat = f"{namespace}.{name}" if namespace else name
255        description = tool.get("description") or ""
256        if ns_description:
257            description = ns_description + ("\n\n" + description if description else "")
258        if kind == "function":
259            params = tool.get("parameters") or {"type": "object", "properties": {}}
260        else:                                        # custom: free-form text, maybe in a grammar the model reads
261            fmt = tool.get("format") or {}
262            if isinstance(fmt, dict) and fmt.get("type") == "grammar" and fmt.get("definition"):
263                description += f"\n\nThe input must follow this {fmt.get('syntax', '')} grammar:\n{fmt['definition']}"
264            params = {"type": "object", "properties": {"input": {"type": "string", "description": "the raw input"}},
265                      "required": ["input"]}
266        tools.append({"name": flat, "description": description, "parameters": params})
267        names[flat] = (namespace, name, kind)
268
269    for i, tool in enumerate(given):
270        param = f"tools[{i}]"
271        if not isinstance(tool, dict):
272            raise ResponsesError("expected a tool object", param)
273        kind = tool.get("type")
274        if kind in ("function", "custom"):
275            add(tool, param)
276        elif kind == "namespace":
277            for j, member in enumerate(tool.get("tools") or []):
278                if not isinstance(member, dict) or member.get("type", "function") not in ("function", "custom"):
279                    raise ResponsesError("a namespace holds function tools", f"{param}.tools[{j}]")
280                add({"type": "function", **member}, f"{param}.tools[{j}]", tool.get("name"),
281                    tool.get("description") or "")
282        elif kind in HOSTED_TOOLS or isinstance(kind, str):
283            skipped.append(kind)                     # the model cannot run OpenAI's hosted tools: left out
284        else:
285            raise ResponsesError("a tool needs a type", param + ".type")
286    choice = req.get("tool_choice")
287    if choice == "none":
288        return None, names, skipped
289    return tools or None, names, skipped
290
291
292def _turn_body(req: dict):
293    meta = req.get("client_metadata")
294    raw = meta.get("x-codex-turn-metadata") if isinstance(meta, dict) else None
295    try:
296        turn = json.loads(raw) if isinstance(raw, str) else None
297    except ValueError:
298        return None
299    return 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."""
304    parts = []
305    items = req.get("input")
306    if isinstance(items, str):
307        items = [{"role": "user", "content": items}]
308    if isinstance(items, list):
309        for item in items:
310            if not isinstance(item, dict) or item.get("role") != "user":
311                continue
312            content = item.get("content")
313            if isinstance(content, str):
314                parts.append(content)
315            elif isinstance(content, list):
316                for piece in content:
317                    if isinstance(piece, dict) and isinstance(piece.get("text"), str):
318                        parts.append(piece["text"])
319    text = "\n".join(parts)
320    if "User prompt:" in text:
321        text = text.split("User prompt:", 1)[1]
322    line = next((x.strip() for x in text.splitlines() if x.strip()), "Untitled")
323    line = line.strip(" \"'`")
324    while line and line[-1] in ".。!!??,,;;::":
325        line = line[:-1].rstrip()
326    return 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
332    Codex 0.160 sends this beside the user turn: another session, no tools, the full instructions. Running it on the
333    one prefix cache replaces the conversation.
334    """
335    if (_turn_body(req) or {}).get("thread_source") != "thread_title":
336        return None
337    check_request(req)
338    text = json.dumps({"title": _title_text(req)}, ensure_ascii=False)
339    asm = Assembler(req, model, 0, {}, False, json_mode=False)
340    events = asm.start()
341    events += asm._open({"id": new_id("msg"), "type": "message", "status": "in_progress", "role": "assistant",
342                         "content": []})
343    asm.item["content"][0]["text"] = text
344    events.append(asm.event("response.output_text.delta", item_id=asm.item["id"], output_index=asm.index,
345                            content_index=0, delta=text, logprobs=[]))
346    events += asm.close()
347    asm.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}
351    asm.response["status"] = "completed"
352    asm.response["completed_at"] = int(time.time())
353    events.append(asm.event("response.completed", response=asm.snapshot()))
354    return 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."""
374    meta = req.get("client_metadata")
375    raw = meta.get("x-codex-turn-metadata") if isinstance(meta, dict) else None
376    try:
377        turn = json.loads(raw) if isinstance(raw, str) else None
378    except ValueError:
379        turn = None
380    if not isinstance(turn, dict):
381        return None, None
382    conversation = (turn.get("session_id"), turn.get("thread_id"))
383    return 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
388    tools the ones its own conversation's last prompt was rendered with (so its prompt starts as that one did)."""
389    kind, conversation = _codex_turn(req)
390    owner, kept = _kept_prompt_tools
391    if kind != "compaction" or conversation is None or owner != conversation or kept is None or req.get("tools"):
392        return tools
393    return 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
398    leaves its conversation and those tools for that conversation's compaction. A thread-title turn is another
399    session Codex sends beside the real one, and it does not replace this entry."""
400    global _kept_prompt_tools
401    if (_turn_body(req) or {}).get("thread_source") == "thread_title":
402        return
403    kind, conversation = _codex_turn(req)
404    if 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)."""
410    text = req.get("text")
411    if text is None:
412        return None
413    if not isinstance(text, dict):
414        raise ResponsesError("text must be an object", "text")
415    fmt = text.get("format")
416    if fmt is None:
417        return None
418    if not isinstance(fmt, dict):
419        raise ResponsesError("text.format must be an object", "text.format")
420    kind = fmt.get("type")
421    if kind in (None, "text"):
422        return None
423    extra = {"repair_latex_escapes": True} if fmt.get("repair_latex_escapes") is True else {}   # #2893, opt-in
424    if kind == "json_object":
425        return {"type": "json_object", **extra}
426    if kind == "json_schema":
427        spec = {k: fmt[k] for k in ("name", "schema", "strict", "description") if k in fmt}
428        return {"type": "json_schema", "json_schema": spec, **extra}
429    raise 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."""
434    if req.get("previous_response_id"):
435        raise ResponsesError("this server keeps no responses (stateless): send the whole conversation in input "
436                             "instead of previous_response_id", "previous_response_id", "unsupported_parameter")
437    if req.get("conversation"):
438        raise ResponsesError("this server keeps no conversations (stateless): send the whole conversation in input",
439                             "conversation", "unsupported_parameter")
440    if req.get("background"):
441        raise ResponsesError("background responses are not supported: use stream or wait for the answer",
442                             "background", "unsupported_parameter")
443    if req.get("prompt"):
444        raise ResponsesError("stored prompt templates are not supported: send instructions and input",
445                             "prompt", "unsupported_parameter")
446    n = 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
448    if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < -1):
449        raise ResponsesError("max_output_tokens must be a whole number, 1 or more, or -1 or 0 for no cap",
450                             "max_output_tokens")
451    reasoning = req.get("reasoning")
452    if reasoning is not None and not isinstance(reasoning, dict):
453        raise ResponsesError("reasoning must be an object", "reasoning")
454
455
456def template_kwargs(req: dict, shared: dict) -> dict:
457    effort = (req.get("reasoning") or {}).get("effort")
458    if effort is None:
459        effort = shared.get("reasoning_effort")      # the Chat settings shared with apps, as on the chat path
460    try:
461        return effort_kwargs(effort)
462    except ValueError as e:
463        raise 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
469    answer is the `response` of the last event, so both modes are the same items."""
470
471    def __init__(self, req: dict, model: str, prompt_tokens: int, names: dict, encrypted: bool,
472                 json_mode: bool = False):
473        self.names, self.encrypted, self.json_mode = names, encrypted, json_mode
474        self.prompt_tokens = prompt_tokens
475        self.seq = 0
476        self.item = None                             # the open output item
477        self.json_text = []                          # structured output: the answer, held until it is checked
478        self.called = False                          # a tool call was made: this turn is not the final answer
479        reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {}
480        self.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
494    def event(self, kind, **data) -> dict:
495        e = {"type": kind, "sequence_number": self.seq, **data}
496        self.seq += 1
497        return e
498
499    def snapshot(self) -> dict:
500        return copy.deepcopy(self.response)
501
502    def start(self) -> list[dict]:
503        return [self.event("response.created", response=self.snapshot()),
504                self.event("response.in_progress", response=self.snapshot())]
505
506    def in_progress(self) -> dict:
507        """A keep-alive a client counts as activity (SSE comments are not events: Codex's idle timer ignores them)."""
508        return self.event("response.in_progress", response=self.snapshot())
509
510    def _open(self, item) -> list[dict]:
511        self.response["output"].append(item)
512        self.item = item
513        out = [self.event("response.output_item.added", output_index=self.index, item=copy.deepcopy(item))]
514        if item["type"] == "message":
515            part = {"type": "output_text", "text": "", "annotations": [], "logprobs": []}
516            item["content"].append(part)
517            out.append(self.event("response.content_part.added", item_id=item["id"], output_index=self.index,
518                                  content_index=0, part=copy.deepcopy(part)))
519        return out
520
521    @property
522    def index(self) -> int:
523        return len(self.response["output"]) - 1
524
525    def close(self, status=None) -> list[dict]:
526        item, self.item = self.item, None
527        if item is None:
528            return []
529        at, out = self.response["output"].index(item), []
530        item["status"] = status or ("incomplete" if item["type"] in ("function_call", "custom_tool_call") else "completed")
531        if item["type"] == "message":
532            part = item["content"][0]
533            out += [self.event("response.output_text.done", item_id=item["id"], output_index=at, content_index=0,
534                               text=part["text"], logprobs=[]),
535                    self.event("response.content_part.done", item_id=item["id"], output_index=at, content_index=0,
536                               part=copy.deepcopy(part))]
537        elif item["type"] == "reasoning":
538            text = item["content"][0]["text"]
539            out.append(self.event("response.reasoning_text.done", item_id=item["id"], output_index=at,
540                                  content_index=0, text=text))
541            if self.encrypted:
542                item["encrypted_content"] = ENCRYPTED_PREFIX + base64.b64encode(
543                    json.dumps({"text": text}, ensure_ascii=False).encode("utf-8")).decode("ascii")
544        elif item["type"] == "function_call":
545            out.append(self.event("response.function_call_arguments.done", item_id=item["id"], output_index=at,
546                                  name=item["name"], arguments=item["arguments"]))
547        elif item["type"] == "custom_tool_call":
548            out.append(self.event("response.custom_tool_call_input.done", item_id=item["id"], output_index=at,
549                                  input=item["input"]))
550        out.append(self.event("response.output_item.done", output_index=at, item=copy.deepcopy(item)))
551        return out
552
553    def feed(self, ev: Event) -> list[dict]:
554        out = []
555        kind = ev.kind
556        if kind == "reasoning":
557            if not ev.text:
558                return out
559            if self.item is None or self.item["type"] != "reasoning":
560                out += self.close()
561                out += self._open({"id": new_id("rs"), "type": "reasoning", "status": "in_progress", "summary": [],
562                                   "content": [{"type": "reasoning_text", "text": ""}]})
563            self.item["content"][0]["text"] += ev.text
564            out.append(self.event("response.reasoning_text.delta", item_id=self.item["id"], output_index=self.index,
565                                  content_index=0, delta=ev.text))
566        elif kind == "content":
567            if not ev.text:
568                return out
569            if self.json_mode:                       # sent once it is checked (finish)
570                out += self.close()
571                self.json_text.append(ev.text)
572                return out
573            if self.item is None or self.item["type"] != "message":
574                out += self.close()
575                out += self._open({"id": new_id("msg"), "type": "message", "status": "in_progress",
576                                   "role": "assistant", "content": []})
577            self.item["content"][0]["text"] += ev.text
578            out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index,
579                                  content_index=0, delta=ev.text, logprobs=[]))
580        elif kind == "tool_start":
581            out += self.close()
582            out += self._call_started()
583            out += self._open(self._call_item(ev))
584        elif kind == "tool_args":
585            item = self.item
586            if item is None or item.get("call_id") != ev.call.id:
587                return out
588            if item["type"] == "function_call":         # a custom tool's input is sent whole, at its end
589                item["arguments"] += ev.text
590                out.append(self.event("response.function_call_arguments.delta", item_id=item["id"],
591                                      output_index=self.index, delta=ev.text))
592        elif kind == "tool_call":
593            item = self.item
594            if item is None or item.get("call_id") != ev.call.id:     # a call that was not announced while written
595                out += self.close()
596                out += self._call_started()
597                out += self._open(self._call_item(ev))
598                item = self.item
599                if item["type"] == "function_call":
600                    item["arguments"] = json.dumps(ev.call.arguments, ensure_ascii=False)
601                    out.append(self.event("response.function_call_arguments.delta", item_id=item["id"],
602                                          output_index=self.index, delta=item["arguments"]))
603            if item["type"] == "custom_tool_call":
604                value = ev.call.arguments.get("input") if isinstance(ev.call.arguments, dict) else None
605                item["input"] = value if isinstance(value, str) else json.dumps(ev.call.arguments, ensure_ascii=False)
606                out.append(self.event("response.custom_tool_call_input.delta", item_id=item["id"],
607                                      output_index=self.index, delta=item["input"]))
608            out += self.close("completed")
609        return out
610
611    def _release(self, text: str) -> list[dict]:
612        """A held structured answer (or the words written beside a tool call) as one message item."""
613        if not text.strip():
614            return []
615        out = self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", "role": "assistant",
616                          "content": []})
617        self.item["content"][0]["text"] = text
618        out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index,
619                              content_index=0, delta=text, logprobs=[]))
620        return out + self.close()
621
622    def _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
624        before the call goes out as it is, ahead of the call, and the schema is checked on the turn that ends in
625        text (#782)."""
626        out = []
627        if self.json_mode and not self.called:
628            out = self._release("".join(self.json_text))
629            self.json_text = []
630        self.called = True
631        return out
632
633    def _call_item(self, ev: Event) -> dict:
634        namespace, name, kind = self.names.get(ev.call.name, (None, ev.call.name, "function"))
635        if kind == "custom":
636            item = {"id": new_id("ctc"), "type": "custom_tool_call", "status": "in_progress", "call_id": ev.call.id,
637                    "name": name, "input": ""}
638        else:
639            item = {"id": new_id("fc"), "type": "function_call", "status": "in_progress", "call_id": ev.call.id,
640                    "name": name, "arguments": ""}
641        if namespace:
642            item["namespace"] = namespace
643        return item
644
645    def 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)."""
648        length = done.get("finish") == "length"
649        # a call still open was cut off (its tool_call never came, #211): incomplete, whatever the finish
650        unfinished = self.item is not None and self.item["type"] in ("function_call", "custom_tool_call")
651        out = self.close("incomplete" if length or unfinished else "completed")
652        if self.json_mode:
653            text = "".join(self.json_text)
654            self.json_text = []
655            if self.called:
656                out += self._release(text)           # beside a tool call: as written (#782)
657            else:
658                out += self._release(validate(text, done.get("finish")))
659        n = done.get("completion_tokens", 0)
660        prompt = done.get("prompt_tokens", self.prompt_tokens)
661        self.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}
665        if length:
666            self.response["status"] = "incomplete"
667            self.response["incomplete_details"] = {"reason": "max_output_tokens"}
668            return out + [self._with_timings(self.event("response.incomplete", response=self.snapshot()), done)]
669        self.response["status"] = "completed"
670        self.response["completed_at"] = int(time.time())
671        return out + [self._with_timings(self.event("response.completed", response=self.snapshot()), done)]
672
673    @staticmethod
674    def _with_timings(event: dict, done: dict) -> dict:
675        """Top-level `timings` on the final event, as /v1/chat/completions has them (#107)."""
676        if done.get("timings"):
677            event["timings"] = done["timings"]
678        return event
679
680    def failed(self, message: str, code: str = "server_error") -> dict:
681        """response.failed: an error after the stream started (the HTTP status is already sent)."""
682        if self.item is not None:
683            self.item["status"] = "incomplete"
684            self.item = None
685        self.response["status"] = "failed"
686        self.response["error"] = {"code": code, "message": message}
687        return self.event("response.failed", response=self.snapshot())
688
689
690def collect(events) -> dict:
691    """The non-streaming answer: the final response object."""
692    last = None
693    for e in events:
694        if e is not None:
695            last = e
696    if last.get("timings"):                          # as on a whole /v1/chat/completions reply (#107)
697        return {**last["response"], "timings": last["timings"]}
698    return last["response"]