diff --git a/README.md b/README.md index 0959ca85..0501eba2 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,8 @@ Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). You can **About** with the settings and addresses. - **Your apps and coding agents:** add an "OpenAI-compatible" provider with base URL **`http://127.0.0.1:8080/v1`**, any API key and any model name. Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages` (Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). Codex CLI and other Responses API apps: `/v1/responses` + ([setup](docs/DETAILS.md#the-responses-api-and-codex-cli)). - **Thinking:** choose **off, low, medium or high** in the chat menu or your app's "reasoning effort". Off is fastest; high is best for hard questions. - **Pictures:** say yes to "Images?" in setup, then click **Picture** in the chat, or attach them in your app diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md index 48fd1429..8b6e1bb9 100644 --- a/docs/AI_SETUP.md +++ b/docs/AI_SETUP.md @@ -168,6 +168,8 @@ line when it is ready; the engine log is `strata-.log` in the Strata fold - **Any OpenAI-compatible app or agent:** base URL `http://127.0.0.1:8080/v1`, any API key (or the configured one), any model name. - **Anthropic-compatible apps:** `http://127.0.0.1:8080/v1/messages`. +- **Codex CLI and other Responses API apps:** `http://127.0.0.1:8080/v1/responses` (stateless; Codex's + `config.toml`: [DETAILS.md](DETAILS.md#the-responses-api-and-codex-cli)). - **Claude Code:** `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`, `ANTHROPIC_MODEL` set to a Claude model name it knows (Strata ignores the name), and any `ANTHROPIC_AUTH_TOKEN` (or the configured key). - **Thinking level:** `"reasoning_effort": "none" | "low" | "medium" | "high"` (default high). diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9d2cc704..1c732c5b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -435,6 +435,7 @@ The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or | --- | --- | | OpenAI Chat Completions (stream and non-stream, tools) | `POST /v1/chat/completions` | | Anthropic Messages (stream and non-stream, tools) | `POST /v1/messages` | +| OpenAI Responses (stream and non-stream, tools; stateless, [below](#the-responses-api-and-codex-cli)) | `POST /v1/responses` | | Model list / health | `GET /v1/models`, `GET /models`, `GET /health` | | Model properties | `GET /props` (also accepts `?model=`) | | What the model is doing right now | `GET /status`, `GET /slots` (single slot, busy or idle) | @@ -520,6 +521,7 @@ print(r.choices[0].message.content) - **Claude Code** (Strata 0.1.17 or newer): set `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` and `ANTHROPIC_MODEL` to a Claude model name it knows (it refuses names it doesn't; Strata ignores the name), plus any `ANTHROPIC_AUTH_TOKEN` (or your `api_key`, if you set one). +- **Codex CLI** (0.1.39): see [the Responses API](#the-responses-api-and-codex-cli) below. - **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. A request whose `max_tokens` would run past the context is refused too (400); agents that always ask for their full output cap can instead get it shortened to the room left: add `"fit_max_tokens": true` to `strata-.json` (or pass @@ -631,6 +633,65 @@ without penalties, so more of its guesses are now rejected. Requests without pen --- +### The Responses API and Codex CLI + +`POST /v1/responses` (0.1.39, #451) speaks OpenAI's newer Responses API, which Codex CLI uses (it no longer +speaks Chat Completions). It runs on the same path as `/v1/chat/completions`, so the thinking levels, the thinking +budget, the conversation cache and the same API key, Host and Origin checks apply. + +It is **stateless**: nothing is stored, so the client sends the whole conversation in `input` every time (Codex does, +with `store: false`). `previous_response_id`, `conversation`, `background` and the retrieve/delete/cancel endpoints +are refused with an error that says so. + +| Request | What Strata does | +| --- | --- | +| `input` as a string, or as items | `message` items (`user`, `assistant`, `system`, `developer`; text and images), `reasoning`, `function_call`, `function_call_output`, `custom_tool_call(_output)` | +| `instructions` | The system message (with leading `developer` messages; later ones become user messages, as on the chat path) | +| `tools` | `function` tools, `namespace` tools (the model sees `namespace.name`; calls come back with `namespace` and `name`), `custom` tools (one free-form `input` string). Hosted tools (`web_search`, `file_search`, ...) are left out: the model cannot run them | +| `tool_choice` | `"none"` hides the tools; anything else lets the model choose (it cannot be forced) | +| `reasoning.effort` | `none`/`minimal`, `low`, `medium`, `high`/`xhigh`; without it the model's default (high) | +| `max_output_tokens` | The output cap (thinking included). Running out ends the response `incomplete` (`max_output_tokens`) | +| `text.format` | `json_schema` and `json_object` use the [JSON response formats](#json-response-formats) (checked, not constrained) | +| `temperature`, `top_p`, `reasoning_budget_tokens`, ... | As on the chat path | + +The model's thinking comes back as a `reasoning` output item with `reasoning_text` content (streamed as +`response.reasoning_text.delta`). This model writes no separate summaries, so `summary` is empty. With +`"include": ["reasoning.encrypted_content"]` the item also carries `encrypted_content`: an opaque string (base64, not +encrypted; the client already holds the text). Send the reasoning items back with the rest of the conversation, as +Codex does: their thinking goes back into the prompt, so it matches what the model wrote and the conversation cache +is reused. + +With `"stream": true` the events are the official ones, in order: `response.created`, `response.in_progress`, then +for each output item `response.output_item.added`, its deltas (`response.reasoning_text.delta`, +`response.output_text.delta`, `response.function_call_arguments.delta`), its `...done` events and +`response.output_item.done`, and at the end `response.completed`, `response.incomplete` or `response.failed`. +While a long prompt is read, a `response.in_progress` event goes out every 15 s, which Codex counts as activity. +Errors before the answer starts have the Responses form (`{"error": {"message", "type", "param", "code"}}`); after +it started they arrive as `response.failed`. + +**Codex CLI.** In `~/.codex/config.toml` (Windows: `%USERPROFILE%\.codex\config.toml`): + +```toml +model = "strata" # any name; Strata answers with its model +model_provider = "strata" +model_context_window = 32768 # the context you chose in setup: Codex compacts before it gets there +show_raw_agent_reasoning = true # show the model's thinking (it writes no summaries) +# model_reasoning_effort = "medium" # none, low, medium or high; default: the model's (high) + +[model_providers.strata] +name = "Strata (local)" +base_url = "http://127.0.0.1:8080/v1" +wire_api = "responses" +stream_idle_timeout_ms = 600000 # a first, long prompt can take minutes to read +# env_key = "STRATA_API_KEY" # only if the server has an api_key: the variable holding it +``` + +Then run `codex` (or `codex exec "..."`) as usual. Codex warns `Model metadata for ... not found` for a local model +name; that is expected. Measured with Codex CLI 0.160.0 and Q2_0 on an RTX 5070: its first prompt (instructions and +tool descriptions) was 9,443 tokens, read in 10 s; in a tool loop, each later turn reused about 96% of the prompt from +the cache and read only the new part in 1-2 s. On Windows, Codex's sandbox rejected every shell command in that test +until it was started with `-c 'windows.sandbox="unelevated"'` (a Codex setting, not Strata's). + ## Tools from MCP servers The chat page can give the model tools from [MCP](https://modelcontextprotocol.io) servers, as LM Studio and Claude diff --git a/serve/responses.py b/serve/responses.py new file mode 100644 index 00000000..4a017c38 --- /dev/null +++ b/serve/responses.py @@ -0,0 +1,538 @@ +"""serve/responses.py - #451: OpenAI's Responses API (POST /v1/responses), stateless, on the chat path. + +A Responses request becomes the same template messages, tools and kwargs a Chat Completions request does, runs through +the same Service.run, and its events (reasoning, text, tool calls) come back as Responses output items and typed SSE +events. Nothing is stored: the client sends the whole conversation in `input` every time (`store: false`, as Codex CLI +does), including the reasoning, message and function_call items of earlier answers. + +Codex CLI is the first client. What it needs, and what this does: + * `instructions` and `developer` messages -> the system message (leading ones merged, so the prompt start is stable + and the conversation cache holds across turns); + * function tools, also inside `namespace` tools (Codex's MCP and agent tools: the model sees `namespace.name`) and + `custom` tools (a free-form `input` string); hosted tools (web search, ...) are left out, the model cannot run them; + * reasoning items: the model's thinking is returned as `reasoning_text` content (no summaries: this model does not + write them, see docs/DETAILS.md) and, when `include` asks for `reasoning.encrypted_content`, also as an opaque + `encrypted_content` string (base64, not encrypted: the client already holds the text). Either form sent back is + put into the conversation again, so the prompt matches what the model wrote and the cache is reused; + * the official event order: response.created, response.in_progress, response.output_item.added, deltas, + ...done events, response.output_item.done, and response.completed / response.incomplete / response.failed. + +Based on #630 by CC-David-CC (the item/event assembler, namespace tools, call_id ordering of tool results). +""" +from __future__ import annotations + +import base64 +import copy +import json +import time +import uuid + +from serve.frontend import Event, _late_system_to_user, _parts_of, effort_kwargs + +ENCRYPTED_PREFIX = "strata.r1:" # our own reasoning replay strings; others' are ignored +HOSTED_TOOLS = ("web_search", "web_search_preview", "file_search", "computer_use_preview", "computer_use", + "code_interpreter", "image_generation", "local_shell", "mcp", "tool_search") + + +class ResponsesError(ValueError): + """A request error in the Responses format: {"error": {"message", "type", "param", "code"}}.""" + + def __init__(self, message, param=None, code=None, status=400, kind="invalid_request_error"): + super().__init__(message) + self.param, self.code, self.status, self.kind = param, code, status, kind + + def body(self): + return error_body(str(self), self.kind, self.param, self.code) + + +def error_body(message, kind="invalid_request_error", param=None, code=None) -> dict: + return {"error": {"message": message, "type": kind, "param": param, "code": code}} + + +def new_id(prefix: str) -> str: + return f"{prefix}_{uuid.uuid4().hex}" + + +# ------------------------------------------------------------------------------------------------ request -> chat +def _content(content, param): + """A message's (or a tool output's) content -> the template's form: a string, or text and image parts.""" + if content is None: + return "" + if isinstance(content, str): + return content + if not isinstance(content, list): + raise ResponsesError("expected a string or an array of content parts", param) + parts = [] + for j, part in enumerate(content): + if isinstance(part, str): + parts.append({"type": "text", "text": part}) + continue + if not isinstance(part, dict): + raise ResponsesError("expected a content part object", f"{param}[{j}]") + kind = part.get("type") + if kind in ("input_text", "output_text", "text", "summary_text", "reasoning_text"): + parts.append({"type": "text", "text": part.get("text") or ""}) + elif kind == "refusal": + parts.append({"type": "text", "text": part.get("refusal") or ""}) + elif kind in ("input_image", "image_url"): + if not part.get("image_url"): + raise ResponsesError("only images given as image_url (a data: or http(s) URL) are supported; " + "this server keeps no files", f"{param}[{j}]", "unsupported_parameter") + parts.append({"type": "input_image", "image_url": part["image_url"]}) + else: + raise ResponsesError(f"content parts of type {kind!r} are not supported (text and images are)", + f"{param}[{j}].type", "unsupported_parameter") + return _parts_of(parts) + + +def _reasoning_text(item, param) -> str: + """The thinking a reasoning item carries: its reasoning_text content, else our own encrypted_content. A summary + alone, or another server's encrypted_content, carries none that can go back into the prompt.""" + texts = [p.get("text") or "" for p in item.get("content") or [] if isinstance(p, dict) + and p.get("type") in ("reasoning_text", "text")] + if texts: + return "".join(texts) + enc = item.get("encrypted_content") + if isinstance(enc, str) and enc.startswith(ENCRYPTED_PREFIX): + try: + return json.loads(base64.b64decode(enc[len(ENCRYPTED_PREFIX):], validate=True).decode("utf-8"))["text"] + except (ValueError, KeyError, TypeError, UnicodeError): + raise ResponsesError("this reasoning item's encrypted_content is damaged", param + ".encrypted_content", + "invalid_encrypted_content") from None + return "" + + +def _arguments(raw, param) -> dict: + """A function_call's arguments (a JSON string) -> the mapping the template renders. Arguments that are not a JSON + object (a call the output ended inside) are kept as text rather than refusing the whole conversation.""" + if isinstance(raw, dict): + return raw + if raw is None or (isinstance(raw, str) and not raw.strip()): + return {} + if not isinstance(raw, str): + raise ResponsesError("function_call arguments must be a JSON string", param) + try: + value = json.loads(raw) + except ValueError: + return {"arguments": raw} + return value if isinstance(value, dict) else {"arguments": value} + + +def _tool_output(item, param): + out = item.get("output") + if isinstance(out, dict): # some clients send a JSON result as an object + return json.dumps(out, ensure_ascii=False) + return out if isinstance(out, str) else _content(out, param + ".output") + + +def input_messages(req: dict) -> list[dict]: + """`instructions` + `input` -> the chat template's messages.""" + messages = [] + instructions = req.get("instructions") + if instructions not in (None, ""): + messages.append({"role": "system", "content": _content(instructions, "instructions") + if not isinstance(instructions, str) else instructions}) + items = req.get("input") + if items is None: + raise ResponsesError("input is required: a string or an array of input items", "input", "missing_required_parameter") + if isinstance(items, str): + items = [{"type": "message", "role": "user", "content": items}] + if not isinstance(items, list): + raise ResponsesError("input must be a string or an array of input items", "input") + thinking = [] # reasoning waiting for the assistant turn it belongs to + open_turn = None # the assistant message the next function_call joins + + def turn(content=""): + nonlocal open_turn + open_turn = {"role": "assistant", "content": content} + if thinking: + open_turn["reasoning_content"] = "".join(thinking) + thinking.clear() + messages.append(open_turn) + return open_turn + + for i, item in enumerate(items): + param = f"input[{i}]" + if not isinstance(item, dict): + raise ResponsesError("expected an input item object", param) + kind = item.get("type") or ("message" if "role" in item else None) + if kind == "message": + role = item.get("role") + if role not in ("user", "assistant", "system", "developer"): + raise ResponsesError(f"unknown message role {role!r}", param + ".role") + content = _content(item.get("content"), param + ".content") + if role == "assistant": + turn(content if isinstance(content, str) else "".join( + p.get("text", "") for p in content if p.get("type") == "text")) + else: + open_turn = None + thinking.clear() + messages.append({"role": "system" if role == "developer" else role, "content": content}) + elif kind == "reasoning": + text = _reasoning_text(item, param) + if text: + if open_turn is not None and (open_turn.get("tool_calls") or open_turn["content"]): + open_turn = None # thinking starts a new model turn + thinking.append(text) + elif kind in ("function_call", "custom_tool_call"): + name = item.get("name") + if not isinstance(name, str) or not name: + raise ResponsesError("a function_call needs a name", param + ".name") + if item.get("namespace"): + name = f"{item['namespace']}.{name}" + if kind == "function_call": + args = _arguments(item.get("arguments"), param + ".arguments") + else: + args = {"input": item.get("input") if isinstance(item.get("input"), str) else ""} + target = open_turn if open_turn is not None and not thinking else turn() + target.setdefault("tool_calls", []).append({"function": {"name": name, "arguments": args}, + "_call_id": item.get("call_id")}) + elif kind in ("function_call_output", "custom_tool_call_output"): + messages.append({"role": "tool", "content": _tool_output(item, param), "_call_id": item.get("call_id")}) + open_turn = None + thinking.clear() + elif kind == "item_reference": + raise ResponsesError("item references need stored responses, and this server keeps none: send the items " + "themselves", param, "unsupported_parameter") + else: + raise ResponsesError(f"input items of type {kind!r} are not supported", param + ".type", + "unsupported_parameter") + _order_tool_results(messages) + # leading system/developer messages (Codex: instructions, then its developer message) become one system message + # at the start; later ones become user messages in place, as on the chat path + lead = 0 + while lead < len(messages) and messages[lead]["role"] == "system" and isinstance(messages[lead]["content"], str): + lead += 1 + if lead > 1: + messages[:lead] = [{"role": "system", "content": "\n\n".join(m["content"] for m in messages[:lead])}] + return _late_system_to_user(messages) + + +def _order_tool_results(messages): + """The template places tool results by position: each run of tool messages is put in the order of the calls of + the assistant turn before it (a client may send the results in the order they finished), then the private call + ids are dropped.""" + i = 0 + while i < len(messages): + if messages[i]["role"] != "tool": + i += 1 + continue + j = i + while j < len(messages) and messages[j]["role"] == "tool": + j += 1 + prev = messages[i - 1] if i else {} + order = [c.get("_call_id") for c in prev.get("tool_calls") or []] + rank = {cid: k for k, cid in enumerate(order) if cid} + messages[i:j] = sorted(messages[i:j], key=lambda m: rank.get(m.get("_call_id"), len(order))) + i = j + for m in messages: + m.pop("_call_id", None) + for c in m.get("tool_calls") or []: + c.pop("_call_id", None) + + +def request_tools(req: dict): + """-> (template tools or None, {template name: (namespace, name, kind)}, names of hosted tools left out).""" + tools, names, skipped = [], {}, [] + given = req.get("tools") or [] + if not isinstance(given, list): + raise ResponsesError("tools must be an array", "tools") + + def add(tool, param, namespace=None, ns_description=""): + kind = tool.get("type") + name = tool.get("name") + if not isinstance(name, str) or not name: + raise ResponsesError("a tool needs a name", param + ".name") + flat = f"{namespace}.{name}" if namespace else name + description = tool.get("description") or "" + if ns_description: + description = ns_description + ("\n\n" + description if description else "") + if kind == "function": + params = tool.get("parameters") or {"type": "object", "properties": {}} + else: # custom: free-form text, maybe in a grammar the model reads + fmt = tool.get("format") or {} + if isinstance(fmt, dict) and fmt.get("type") == "grammar" and fmt.get("definition"): + description += f"\n\nThe input must follow this {fmt.get('syntax', '')} grammar:\n{fmt['definition']}" + params = {"type": "object", "properties": {"input": {"type": "string", "description": "the raw input"}}, + "required": ["input"]} + tools.append({"name": flat, "description": description, "parameters": params}) + names[flat] = (namespace, name, kind) + + for i, tool in enumerate(given): + param = f"tools[{i}]" + if not isinstance(tool, dict): + raise ResponsesError("expected a tool object", param) + kind = tool.get("type") + if kind in ("function", "custom"): + add(tool, param) + elif kind == "namespace": + for j, member in enumerate(tool.get("tools") or []): + if not isinstance(member, dict) or member.get("type", "function") not in ("function", "custom"): + raise ResponsesError("a namespace holds function tools", f"{param}.tools[{j}]") + add({"type": "function", **member}, f"{param}.tools[{j}]", tool.get("name"), + tool.get("description") or "") + elif kind in HOSTED_TOOLS or isinstance(kind, str): + skipped.append(kind) # the model cannot run OpenAI's hosted tools: left out + else: + raise ResponsesError("a tool needs a type", param + ".type") + choice = req.get("tool_choice") + if choice == "none": + return None, names, skipped + return tools or None, names, skipped + + +def text_format(req: dict): + """`text.format` -> the chat path's response_format (None: plain text).""" + text = req.get("text") + if text is None: + return None + if not isinstance(text, dict): + raise ResponsesError("text must be an object", "text") + fmt = text.get("format") + if fmt is None: + return None + if not isinstance(fmt, dict): + raise ResponsesError("text.format must be an object", "text.format") + kind = fmt.get("type") + if kind in (None, "text"): + return None + if kind == "json_object": + return {"type": "json_object"} + if kind == "json_schema": + spec = {k: fmt[k] for k in ("name", "schema", "strict", "description") if k in fmt} + return {"type": "json_schema", "json_schema": spec} + raise ResponsesError("text.format.type must be text, json_object or json_schema", "text.format.type") + + +def check_request(req: dict) -> None: + """What this stateless server cannot do, refused before anything runs.""" + if req.get("previous_response_id"): + raise ResponsesError("this server keeps no responses (stateless): send the whole conversation in input " + "instead of previous_response_id", "previous_response_id", "unsupported_parameter") + if req.get("conversation"): + raise ResponsesError("this server keeps no conversations (stateless): send the whole conversation in input", + "conversation", "unsupported_parameter") + if req.get("background"): + raise ResponsesError("background responses are not supported: use stream or wait for the answer", + "background", "unsupported_parameter") + if req.get("prompt"): + raise ResponsesError("stored prompt templates are not supported: send instructions and input", + "prompt", "unsupported_parameter") + n = req.get("max_output_tokens") + if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < 1): + raise ResponsesError("max_output_tokens must be a positive whole number", "max_output_tokens") + reasoning = req.get("reasoning") + if reasoning is not None and not isinstance(reasoning, dict): + raise ResponsesError("reasoning must be an object", "reasoning") + + +def template_kwargs(req: dict, shared: dict) -> dict: + effort = (req.get("reasoning") or {}).get("effort") + if effort is None: + effort = shared.get("reasoning_effort") # the Chat settings shared with apps, as on the chat path + try: + return effort_kwargs(effort) + except ValueError as e: + raise ResponsesError(str(e), "reasoning.effort") from None + + +# ------------------------------------------------------------------------------------------------ output +class Assembler: + """One response: its output items and its typed events, built from Service.run's events. The non-streaming + answer is the `response` of the last event, so both modes are the same items.""" + + def __init__(self, req: dict, model: str, prompt_tokens: int, names: dict, encrypted: bool, + json_mode: bool = False): + self.names, self.encrypted, self.json_mode = names, encrypted, json_mode + self.prompt_tokens = prompt_tokens + self.seq = 0 + self.item = None # the open output item + self.json_text = [] # structured output: the answer, held until it is checked + reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} + self.response = { + "id": new_id("resp"), "object": "response", "created_at": int(time.time()), "status": "in_progress", + "background": False, "error": None, "incomplete_details": None, + "instructions": req.get("instructions"), "max_output_tokens": req.get("max_output_tokens"), + "model": model, "output": [], "parallel_tool_calls": req.get("parallel_tool_calls", True), + "previous_response_id": None, + "reasoning": {"effort": reasoning.get("effort"), "summary": reasoning.get("summary")}, + "store": False, "temperature": req.get("temperature"), + "text": req.get("text") if isinstance(req.get("text"), dict) else {"format": {"type": "text"}}, + "tool_choice": req.get("tool_choice", "auto"), "tools": req.get("tools") or [], + "top_p": req.get("top_p"), "truncation": "disabled", "usage": None, "user": None, + "metadata": req.get("metadata") or {}} + + # --- events + def event(self, kind, **data) -> dict: + e = {"type": kind, "sequence_number": self.seq, **data} + self.seq += 1 + return e + + def snapshot(self) -> dict: + return copy.deepcopy(self.response) + + def start(self) -> list[dict]: + return [self.event("response.created", response=self.snapshot()), + self.event("response.in_progress", response=self.snapshot())] + + def in_progress(self) -> dict: + """A keep-alive a client counts as activity (SSE comments are not events: Codex's idle timer ignores them).""" + return self.event("response.in_progress", response=self.snapshot()) + + def _open(self, item) -> list[dict]: + self.response["output"].append(item) + self.item = item + out = [self.event("response.output_item.added", output_index=self.index, item=copy.deepcopy(item))] + if item["type"] == "message": + part = {"type": "output_text", "text": "", "annotations": [], "logprobs": []} + item["content"].append(part) + out.append(self.event("response.content_part.added", item_id=item["id"], output_index=self.index, + content_index=0, part=copy.deepcopy(part))) + return out + + @property + def index(self) -> int: + return len(self.response["output"]) - 1 + + def close(self, status="completed") -> list[dict]: + item, self.item = self.item, None + if item is None: + return [] + at, out = self.response["output"].index(item), [] + item["status"] = status + if item["type"] == "message": + part = item["content"][0] + out += [self.event("response.output_text.done", item_id=item["id"], output_index=at, content_index=0, + text=part["text"], logprobs=[]), + self.event("response.content_part.done", item_id=item["id"], output_index=at, content_index=0, + part=copy.deepcopy(part))] + elif item["type"] == "reasoning": + text = item["content"][0]["text"] + out.append(self.event("response.reasoning_text.done", item_id=item["id"], output_index=at, + content_index=0, text=text)) + if self.encrypted: + item["encrypted_content"] = ENCRYPTED_PREFIX + base64.b64encode( + json.dumps({"text": text}, ensure_ascii=False).encode("utf-8")).decode("ascii") + elif item["type"] == "function_call": + out.append(self.event("response.function_call_arguments.done", item_id=item["id"], output_index=at, + name=item["name"], arguments=item["arguments"])) + elif item["type"] == "custom_tool_call": + out.append(self.event("response.custom_tool_call_input.done", item_id=item["id"], output_index=at, + input=item["input"])) + out.append(self.event("response.output_item.done", output_index=at, item=copy.deepcopy(item))) + return out + + def feed(self, ev: Event) -> list[dict]: + out = [] + kind = ev.kind + if kind == "reasoning": + if not ev.text: + return out + if self.item is None or self.item["type"] != "reasoning": + out += self.close() + out += self._open({"id": new_id("rs"), "type": "reasoning", "status": "in_progress", "summary": [], + "content": [{"type": "reasoning_text", "text": ""}]}) + self.item["content"][0]["text"] += ev.text + out.append(self.event("response.reasoning_text.delta", item_id=self.item["id"], output_index=self.index, + content_index=0, delta=ev.text)) + elif kind == "content": + if not ev.text: + return out + if self.json_mode: # sent once it is checked (finish) + out += self.close() + self.json_text.append(ev.text) + return out + if self.item is None or self.item["type"] != "message": + out += self.close() + out += self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", + "role": "assistant", "content": []}) + self.item["content"][0]["text"] += ev.text + out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index, + content_index=0, delta=ev.text, logprobs=[])) + elif kind == "tool_start": + out += self.close() + out += self._open(self._call_item(ev)) + elif kind == "tool_args": + item = self.item + if item is None or item.get("call_id") != ev.call.id: + return out + if item["type"] == "function_call": # a custom tool's input is sent whole, at its end + item["arguments"] += ev.text + out.append(self.event("response.function_call_arguments.delta", item_id=item["id"], + output_index=self.index, delta=ev.text)) + elif kind == "tool_call": + item = self.item + if item is None or item.get("call_id") != ev.call.id: # a call that was not announced while written + out += self.close() + out += self._open(self._call_item(ev)) + item = self.item + if item["type"] == "function_call": + item["arguments"] = json.dumps(ev.call.arguments, ensure_ascii=False) + out.append(self.event("response.function_call_arguments.delta", item_id=item["id"], + output_index=self.index, delta=item["arguments"])) + if item["type"] == "custom_tool_call": + value = ev.call.arguments.get("input") if isinstance(ev.call.arguments, dict) else None + item["input"] = value if isinstance(value, str) else json.dumps(ev.call.arguments, ensure_ascii=False) + out.append(self.event("response.custom_tool_call_input.delta", item_id=item["id"], + output_index=self.index, delta=item["input"])) + out += self.close() + return out + + def _call_item(self, ev: Event) -> dict: + namespace, name, kind = self.names.get(ev.call.name, (None, ev.call.name, "function")) + if kind == "custom": + item = {"id": new_id("ctc"), "type": "custom_tool_call", "status": "in_progress", "call_id": ev.call.id, + "name": name, "input": ""} + else: + item = {"id": new_id("fc"), "type": "function_call", "status": "in_progress", "call_id": ev.call.id, + "name": name, "arguments": ""} + if namespace: + item["namespace"] = namespace + return item + + def finish(self, done: dict, validate=None) -> list[dict]: + """The end: close what is open, then response.completed (or .incomplete when max_output_tokens ran out). + `validate(text, finish)` checks a structured answer and returns its text (or raises).""" + length = done.get("finish") == "length" + # a call still open was cut off (its tool_call never came, #211): incomplete, whatever the finish + unfinished = self.item is not None and self.item["type"] in ("function_call", "custom_tool_call") + out = self.close("incomplete" if length or unfinished else "completed") + if self.json_mode: + text = validate("".join(self.json_text), done.get("finish")) + out += self._open({"id": new_id("msg"), "type": "message", "status": "in_progress", "role": "assistant", + "content": []}) + self.item["content"][0]["text"] = text + out.append(self.event("response.output_text.delta", item_id=self.item["id"], output_index=self.index, + content_index=0, delta=text, logprobs=[])) + out += self.close() + n = done.get("completion_tokens", 0) + prompt = done.get("prompt_tokens", self.prompt_tokens) + self.response["usage"] = { + "input_tokens": prompt, "input_tokens_details": {"cached_tokens": min(done.get("reused") or 0, prompt)}, + "output_tokens": n, "output_tokens_details": {"reasoning_tokens": done.get("reasoning_tokens", 0)}, + "total_tokens": prompt + n} + if length: + self.response["status"] = "incomplete" + self.response["incomplete_details"] = {"reason": "max_output_tokens"} + return out + [self.event("response.incomplete", response=self.snapshot())] + self.response["status"] = "completed" + self.response["completed_at"] = int(time.time()) + return out + [self.event("response.completed", response=self.snapshot())] + + def failed(self, message: str, code: str = "server_error") -> dict: + """response.failed: an error after the stream started (the HTTP status is already sent).""" + if self.item is not None: + self.item["status"] = "incomplete" + self.item = None + self.response["status"] = "failed" + self.response["error"] = {"code": code, "message": message} + return self.event("response.failed", response=self.snapshot()) + + +def collect(events) -> dict: + """The non-streaming answer: the final response object.""" + last = None + for e in events: + if e is not None: + last = e + return last["response"] diff --git a/serve/server.py b/serve/server.py index fb1dbbcd..21aa6e38 100644 --- a/serve/server.py +++ b/serve/server.py @@ -55,6 +55,8 @@ from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_mess from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve.winjob import contain # noqa: E402 from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 +from serve import responses as responses_api # noqa: E402 +from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" @@ -1321,7 +1323,7 @@ class Service: "cache_max_tokens": ctx, "context": {"native": ctx, "max_positions": ctx}, "concurrency": {"serving": 1, "requested": 1}, # one request at a time; more wait their turn - "dialects": ["/v1/chat/completions", "/v1/messages"], + "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"], "vision": {"enabled": images, "available": images, "error": None}, "activity": {"requests": totals["requests"] + int(busy), "in_flight": int(busy) + int(s.get("queued") or 0), "last_request_at": int(last_at) if last_at else None}, @@ -1436,6 +1438,7 @@ class Service: sampling = {**defaults, **req_values} parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True) detok, n, finish = Detokenizer(self.tok), 0, "length" + thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) timings, before = None, None # this request's timings; the engine's `last` before it raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb = getattr(self.embeddings, "path", None) @@ -1485,6 +1488,7 @@ class Service: break raw_ids.append(t) seg.append(t) + thinking_n += parser.state == "reasoning" evs = parser.feed(detok.push(t)) self._note(n, evs) last_print = self._progress(last_print) @@ -1531,6 +1535,7 @@ class Service: for t in extra: n += 1 raw_ids.append(t) + thinking_n += parser.state == "reasoning" evs = parser.feed(detok.push(t)) self._note(n, evs) for ev in evs: @@ -1607,7 +1612,7 @@ class Service: for ev in parser.finish(): yield "event", ev yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), - "timings": timings} + "timings": timings, "reasoning_tokens": thinking_n} def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int: @@ -2250,6 +2255,10 @@ def make_handler(svc: Service): req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") if not isinstance(req, dict): raise ValueError("send a JSON object") + if path.startswith("/v1/responses/"): # retrieve/delete/cancel/compact: nothing is stored + self._json(404, responses_error_body("this server keeps no responses (stateless); send the " + "whole conversation to POST /v1/responses", code="not_found")) + return if path in ("/v1/load", "/v1/unload"): if not self._own_page("the model can be loaded or unloaded"): return @@ -2274,9 +2283,11 @@ def make_handler(svc: Service): result = "loaded" self._json(200, {"status": result, **svc.v1_status()}) return - if path in ("/v1/chat/completions", "/v1/messages"): + if path in ("/v1/chat/completions", "/v1/messages", "/v1/responses"): self.record = svc.begin_request(path, req) - if path == "/v1/chat/completions": + if path == "/v1/responses": + self._responses(req) + elif path == "/v1/chat/completions": self._openai(req) elif path == "/v1/messages": self._anthropic(req) @@ -2285,7 +2296,10 @@ def make_handler(svc: Service): else: self._json(404, {"error": {"message": "not found"}}) except ValueError as e: - self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + if path == "/v1/responses": + self._json(400, responses_error_body(str(e))) + else: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) except ModelBusy as e: self._json(409, {"error": {"type": "model_busy", "message": str(e)}}) except StructuredOutputError as e: @@ -2415,6 +2429,11 @@ def make_handler(svc: Service): delta = item["choices"][0]["delta"] content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "") usage, timings = item.get("usage"), item.get("timings") + elif api == "responses": + kind = item["type"] + content = item["delta"] if kind == "response.output_text.delta" else "" + reasoning = item["delta"] if kind == "response.reasoning_text.delta" else "" + usage, timings = (item.get("response") or {}).get("usage"), None else: _, event = item delta = event.get("delta", {}) @@ -2490,6 +2509,127 @@ def make_handler(svc: Service): self._note(error=err["error"]) self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + def _responses(self, req): + """#451: POST /v1/responses - OpenAI's Responses API, stateless (serve/responses.py), on the chat path. + Errors use the Responses format; once the stream has started they arrive as a response.failed event.""" + try: + ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req) + except ResponsesError as e: + return self._json(e.status, e.body()) + except ModelBusy as e: + return self._json(409, responses_error_body(str(e), "server_error", code="model_busy")) + except (GpuBusy, EngineStarting, EngineStuck, EngineDied) as e: + return self._json(503, responses_error_body(str(e), "server_error", code="server_error")) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 + + def check(text, finish): + return validated_json(text, validator, finish) + + def events(): + yield from asm.start() + done = None + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + elif kind == "event": + yield from asm.feed(x) + elif kind == "done": + done = x + if done is not None and done["finish"] != "cancel" and not cancel.is_set(): + yield from asm.finish(done, check) + items = self._capture(events(), "responses") + if not req.get("stream"): + try: + result = responses_api.collect(items) + except StructuredOutputError as e: + return self._json(502, responses_error_body(str(e), "server_error", + code="structured_output_failed")) + except EngineDied as e: + return self._json(503, responses_error_body(f"{e}; the next request restarts it", "server_error", + code="server_error")) + except ValueError as e: # the engine's ERR line + return self._json(500, responses_error_body(str(e), "server_error", code="server_error")) + return self._json(200, result) + self._sse() + last = time.monotonic() + + def send(e): + self.wfile.write(f"event: {e['type']}\n".encode() + b"data: " + + json.dumps(e, ensure_ascii=False).encode() + b"\n\n") + + try: + for e in items: + if e is None: + # Codex's idle timeout (5 minutes by default) counts events, not SSE comments: while a long + # prompt is read, a response.in_progress every 15 s tells it the server is still working + if time.monotonic() - last >= 15: + send(asm.in_progress()) + last = time.monotonic() + else: + self.wfile.write(b": keep-alive\n\n") + else: + send(e) + last = time.monotonic() + self.wfile.flush() + except OSError: + self._note(outcome="disconnected") + cancel.set() # client went away: stop the engine + items.close() + except EngineDied as e: # mid-stream: response.failed, then the stream ends + self._responses_failed(asm, f"{e}; the next request restarts it", "server_error", send) + except StructuredOutputError as e: + self._responses_failed(asm, str(e), "structured_output_failed", send) + except ValueError as e: # the engine's ERR after the stream started + self._responses_failed(asm, str(e), "server_error", send) + + def _responses_failed(self, asm, message, code, send): + e = asm.failed(message, code) + self._note(error=e["response"]["error"]) + try: + send(e) + self.wfile.flush() + except OSError: + pass + + def _responses_prepare(self, req): + responses_api.check_request(req) + messages = responses_api.input_messages(req) + tools, names, skipped = responses_api.request_tools(req) + kw = responses_api.template_kwargs(req, svc.shared) + try: + messages, validator = prepare_format(responses_api.text_format(req), messages) + except ValueError as e: + raise ResponsesError(str(e).replace("response_format", "text.format"), "text.format") from None + if validator is not None and tools: + raise ResponsesError("a JSON text.format with tools is not supported", "text.format", + "unsupported_parameter") + noted = svc.__dict__.setdefault("hosted_tools_noted", set()) # said once per tool, not per request + if set(skipped) - noted: + print(f"[strata] /v1/responses: left out the hosted tools {', '.join(sorted(set(skipped) - noted))} " + f"(this server cannot run them)", flush=True) + noted.update(skipped) + if req.get("max_output_tokens") is None and "max_tokens" in svc.shared: # the shared Chat settings + req = {**req, "max_output_tokens": svc.shared["max_tokens"]} + try: + svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + except ValueError as e: + raise ResponsesError(str(e), "reasoning_budget_tokens") from None + svc.load() + try: + ids, thinking, max_new = svc.prepare(messages, tools, kw, req.get("max_output_tokens") or 0) + except ResponsesError: + raise + except ValueError as e: # too long for the context, an image without vision + raise ResponsesError(str(e), "input", "context_length_exceeded" if "context" in str(e) else None) \ + from None + _debug_req("responses", req, messages, tools, max_new, thinking, len(ids)) + include = req.get("include") if isinstance(req.get("include"), list) else [] + asm = responses_api.Assembler(req, svc.model_for(req), len(ids), names, + "reasoning.encrypted_content" in include, validator is not None) + # the request is also the sampling dict, as on the chat path (temperature, top_p, top_k, seed, ...) + return ids, thinking, tools, max_new, asm, validator, req + def _count_tokens(self, req): """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would read for the same request, rendered and tokenized - the model does not run.""" diff --git a/serve/test_responses.py b/serve/test_responses.py new file mode 100644 index 00000000..2bae9869 --- /dev/null +++ b/serve/test_responses.py @@ -0,0 +1,361 @@ +"""serve/test_responses.py - #451: the Responses API (POST /v1/responses) against the mock engine (no GPU, no pack). + + python -m unittest serve.test_responses -v +""" +from __future__ import annotations + +import base64 +import contextlib +import http.client +import io +import json +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.responses import (ENCRYPTED_PREFIX, ResponsesError, input_messages, request_tools, # noqa: E402 + template_kwargs, text_format) +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +TEMPLATE = ChatTemplate(ROOT / "serve/chat_template.jinja") + +CALL = ("Let me look.\n\n\nChecking.\n\n\n\n\ncat a.txt\n" + "\n\n") +ANSWER = "Read it.\n\n\nThe file says before." +TOOLS = [{"type": "function", "name": "exec_command", "description": "Runs a command.", "strict": False, + "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]}}] + + +# ------------------------------------------------------------------------------------------------ parsing +class Parsing(unittest.TestCase): + def test_a_string_input_is_one_user_message(self): + self.assertEqual(input_messages({"input": "hi", "instructions": "Be brief."}), + [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}]) + + def test_leading_developer_messages_join_the_system_message_later_ones_become_user(self): + msgs = input_messages({"instructions": "I", "input": [ + {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "D1"}, + {"type": "input_text", "text": "D2"}]}, + {"role": "user", "content": "u"}, + {"type": "message", "role": "developer", "content": "late"}]}) + self.assertEqual(msgs, [{"role": "system", "content": "I\n\nD1D2"}, {"role": "user", "content": "u"}, + {"role": "user", "content": "late"}]) + + def test_codex_history_becomes_one_assistant_turn_per_answer(self): + items = [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "edit it"}]}, + {"type": "reasoning", "id": "rs_1", "summary": [], + "content": [{"type": "reasoning_text", "text": "look first"}]}, + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Looking."}]}, + {"type": "function_call", "id": "fc_1", "call_id": "c1", "name": "exec_command", + "arguments": "{\"cmd\":\"cat a\"}"}, + {"type": "function_call", "id": "fc_2", "call_id": "c2", "name": "spawn_agent", + "namespace": "multi_agent_v1", "arguments": "{}"}, + # results in the order they finished, not the order of the calls + {"type": "function_call_output", "call_id": "c2", "output": "agent"}, + {"type": "function_call_output", "call_id": "c1", + "output": [{"type": "input_text", "text": "before"}]}, + {"type": "reasoning", "id": "rs_2", "summary": [{"type": "summary_text", "text": "s"}], + "content": [{"type": "reasoning_text", "text": "now write"}]}, + {"type": "function_call", "call_id": "c3", "name": "exec_command", "arguments": "{\"cmd\":\"w\"}"}, + {"type": "function_call_output", "call_id": "c3", "output": "ok"}] + self.assertEqual(input_messages({"input": items}), [ + {"role": "user", "content": "edit it"}, + {"role": "assistant", "content": "Looking.", "reasoning_content": "look first", "tool_calls": [ + {"function": {"name": "exec_command", "arguments": {"cmd": "cat a"}}}, + {"function": {"name": "multi_agent_v1.spawn_agent", "arguments": {}}}]}, + {"role": "tool", "content": "before"}, {"role": "tool", "content": "agent"}, + {"role": "assistant", "content": "", "reasoning_content": "now write", "tool_calls": [ + {"function": {"name": "exec_command", "arguments": {"cmd": "w"}}}]}, + {"role": "tool", "content": "ok"}]) + + def test_reasoning_comes_back_from_our_encrypted_content_and_foreign_tokens_are_ignored(self): + enc = ENCRYPTED_PREFIX + base64.b64encode(json.dumps({"text": "hidden"}).encode()).decode() + for item, want in (({"encrypted_content": enc, "summary": []}, "hidden"), + ({"encrypted_content": "gAAAAAB-someone-elses", "summary": []}, None)): + msgs = input_messages({"input": [{"role": "user", "content": "q"}, {"type": "reasoning", **item}, + {"role": "assistant", "content": "a"}]}) + self.assertEqual(msgs[1].get("reasoning_content"), want) + with self.assertRaises(ResponsesError) as e: + input_messages({"input": [{"type": "reasoning", "encrypted_content": ENCRYPTED_PREFIX + "!!"}]}) + self.assertEqual(e.exception.param, "input[0].encrypted_content") + + def test_bad_arguments_from_a_cut_off_call_do_not_refuse_the_conversation(self): + msgs = input_messages({"input": [{"role": "user", "content": "q"}, + {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{\"a"}, + {"type": "function_call_output", "call_id": "c", "output": "x"}]}) + self.assertEqual(msgs[1]["tool_calls"][0]["function"]["arguments"], {"arguments": "{\"a"}) + + def test_unsupported_items_are_named(self): + for items, param in (([{"type": "item_reference", "id": "msg_1"}], "input[0]"), + ([{"type": "web_search_call"}], "input[0].type"), + ([{"role": "user", "content": [{"type": "input_file", "file_id": "f"}]}], + "input[0].content[0].type"), + ([{"role": "robot", "content": "x"}], "input[0].role")): + with self.assertRaises(ResponsesError) as e: + input_messages({"input": items}) + self.assertEqual(e.exception.param, param) + with self.assertRaises(ResponsesError): + input_messages({}) + + def test_tools_namespaces_custom_and_hosted(self): + tools, names, skipped = request_tools({"tools": [ + *TOOLS, {"type": "namespace", "name": "mcp_fs", "description": "Files.", + "tools": [{"type": "function", "name": "read", "parameters": {"type": "object"}}]}, + {"type": "custom", "name": "apply_patch", "description": "Patch.", + "format": {"type": "grammar", "syntax": "lark", "definition": "start: \"x\""}}, + {"type": "web_search"}]}) + self.assertEqual([t["name"] for t in tools], ["exec_command", "mcp_fs.read", "apply_patch"]) + self.assertEqual(tools[1]["description"], "Files.") + self.assertIn("start: \"x\"", tools[2]["description"]) + self.assertEqual(names["mcp_fs.read"], ("mcp_fs", "read", "function")) + self.assertEqual(names["apply_patch"], (None, "apply_patch", "custom")) + self.assertEqual(skipped, ["web_search"]) + self.assertIsNone(request_tools({"tools": TOOLS, "tool_choice": "none"})[0]) + + def test_effort_and_text_format(self): + self.assertEqual(template_kwargs({"reasoning": {"effort": "minimal"}}, {}), {"enable_thinking": False}) + self.assertEqual(template_kwargs({"reasoning": {"effort": "high"}}, {}), {"reasoning_effort": "xhigh"}) + self.assertEqual(template_kwargs({"reasoning": {"summary": "auto"}}, {}), {}) # Codex: the default + self.assertEqual(template_kwargs({}, {"reasoning_effort": "low"}), {"reasoning_effort": "low"}) + with self.assertRaises(ResponsesError): + template_kwargs({"reasoning": {"effort": "huge"}}, {}) + self.assertEqual(text_format({"text": {"format": {"type": "json_schema", "name": "n", "schema": {}}}}), + {"type": "json_schema", "json_schema": {"name": "n", "schema": {}}}) + self.assertIsNone(text_format({"text": {"format": {"type": "text"}}})) + + +# ------------------------------------------------------------------------------------------------ over HTTP +class Server(unittest.TestCase): + script = ANSWER + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, self.script, max_context=16384) + self.svc = Service(self.engine, self.tok, TEMPLATE) + self.httpd = serve(self.svc, port=0) + self.port = self.httpd.server_address[1] + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, body, path="/v1/responses", headers=None): + """(status, parsed body: a dict, or the list of SSE events of a stream).""" + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + try: + with contextlib.redirect_stdout(io.StringIO()): + c.request("POST", path, body=json.dumps(body).encode(), + headers={"Content-Type": "application/json", **(headers or {})}) + r = c.getresponse() + raw = r.read().decode() + if r.getheader("Content-Type") == "text/event-stream": + events = [] + for block in raw.split("\n\n"): + lines = block.strip().splitlines() + if not lines or lines[0].startswith(":"): + continue + name = lines[0][len("event: "):] + data = json.loads(lines[1][len("data: "):]) + self.assertEqual(name, data["type"]) + events.append(data) + return r.status, events + return r.status, json.loads(raw) + finally: + c.close() + + + +class OverHttp(Server): + def test_non_streaming_text_with_reasoning(self): + code, r = self.post({"model": "m", "input": "hi", "store": False}) + self.assertEqual(code, 200) + self.assertEqual((r["object"], r["status"], r["error"]), ("response", "completed", None)) + rs, msg = r["output"] + self.assertEqual(rs["type"], "reasoning") + self.assertEqual(rs["content"], [{"type": "reasoning_text", "text": "Read it.\n"}]) + self.assertEqual(rs["summary"], []) + self.assertNotIn("encrypted_content", rs) + self.assertEqual(msg["type"], "message") + self.assertEqual(msg["content"][0]["text"], "The file says before.") + u = r["usage"] + self.assertEqual(u["output_tokens"], len(self.tok.encode(ANSWER)) + 1) # + the end-of-turn token + self.assertEqual(u["output_tokens_details"]["reasoning_tokens"], len("Read it.\n")) + self.assertEqual(u["total_tokens"], u["input_tokens"] + u["output_tokens"]) + self.assertEqual(r["store"], False) + + def test_stream_event_order(self): + code, events = self.post({"model": "m", "input": "hi", "stream": True, + "include": ["reasoning.encrypted_content"]}) + self.assertEqual(code, 200) + types = [e["type"] for e in events] + deltas_r = types.count("response.reasoning_text.delta") + deltas_t = types.count("response.output_text.delta") + self.assertGreater(deltas_r, 0) + self.assertGreater(deltas_t, 0) + self.assertEqual(types, ["response.created", "response.in_progress", + "response.output_item.added", *["response.reasoning_text.delta"] * deltas_r, + "response.reasoning_text.done", "response.output_item.done", + "response.output_item.added", "response.content_part.added", + *["response.output_text.delta"] * deltas_t, + "response.output_text.done", "response.content_part.done", + "response.output_item.done", "response.completed"]) + self.assertEqual([e["sequence_number"] for e in events], list(range(len(events)))) + final = events[-1]["response"] + self.assertEqual(final["status"], "completed") + rs, msg = final["output"] + self.assertEqual([e["item"]["id"] for e in events if e["type"] == "response.output_item.done"], + [rs["id"], msg["id"]]) + self.assertEqual("".join(e["delta"] for e in events if e["type"] == "response.output_text.delta"), + msg["content"][0]["text"]) + self.assertTrue(rs["encrypted_content"].startswith(ENCRYPTED_PREFIX)) + # the encrypted_content alone brings the thinking back into the prompt + replay = input_messages({"input": [{"role": "user", "content": "hi"}, + {"type": "reasoning", "summary": [], "encrypted_content": + rs["encrypted_content"]}, msg]}) + self.assertEqual(replay[1]["reasoning_content"], "Read it.\n") + + def test_max_output_tokens_ends_incomplete(self): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": 5}) + self.assertEqual(code, 200) + self.assertEqual(r["status"], "incomplete") + self.assertEqual(r["incomplete_details"], {"reason": "max_output_tokens"}) + self.assertEqual(r["output"][0]["status"], "incomplete") + code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": 5, "stream": True}) + self.assertEqual(events[-1]["type"], "response.incomplete") + + def test_effort_none_does_not_think(self): + self.engine.scripts = [self.tok.encode("Hello.<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + code, r = self.post({"model": "m", "input": "hi", "reasoning": {"effort": "none"}}) + self.assertEqual([o["type"] for o in r["output"]], ["message"]) + self.assertIn("\n\n", self.tok.decode(self.engine.last_prompt)) + + def test_errors_use_the_responses_format(self): + for body, param in (({"model": "m"}, "input"), ({"model": "m", "input": "x", "previous_response_id": "r"}, + "previous_response_id"), + ({"model": "m", "input": "x", "reasoning": {"effort": "huge"}}, "reasoning.effort")): + code, r = self.post(body) + self.assertEqual(code, 400) + self.assertEqual(set(r["error"]), {"message", "type", "param", "code"}) + self.assertEqual(r["error"]["param"], param) + code, r = self.post({}, path="/v1/responses/resp_123/cancel") + self.assertEqual(code, 404) + self.assertEqual(r["error"]["code"], "not_found") + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + c.request("POST", "/v1/responses", body=b"{not json", headers={"Content-Type": "application/json"}) + r = c.getresponse() + err = json.loads(r.read())["error"] + c.close() + self.assertEqual((r.status, err["type"], err["param"]), (400, "invalid_request_error", None)) + + def test_too_long_for_the_context(self): + code, r = self.post({"model": "m", "input": "x" * 20000}) + self.assertEqual(code, 400) + self.assertEqual(r["error"]["code"], "context_length_exceeded") + + def test_api_key_and_foreign_pages(self): + self.svc.api_key = "s3cret" + self.assertEqual(self.post({"model": "m", "input": "hi"})[0], 401) + self.assertEqual(self.post({"model": "m", "input": "hi"}, headers={"Authorization": "Bearer s3cret"})[0], 200) + self.svc.api_key = None + code, r = self.post({"model": "m", "input": "hi"}, headers={"Origin": "https://evil.example.com"}) + self.assertEqual(code, 403) + + def test_json_schema_text_format(self): + self.engine.scripts = [self.tok.encode("\n\n{\"n\": 3}<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + fmt = {"type": "json_schema", "name": "num", "strict": True, + "schema": {"type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]}} + code, r = self.post({"model": "m", "input": "a number", "text": {"format": fmt}}) + self.assertEqual(code, 200, r) + self.assertEqual(r["output"][-1]["content"][0]["text"], "{\"n\":3}") + code, events = self.post({"model": "m", "input": "a number", "text": {"format": fmt}, "stream": True}) + self.assertEqual([e["delta"] for e in events if e["type"] == "response.output_text.delta"], ["{\"n\":3}"]) + self.assertEqual(events[-1]["type"], "response.completed") + # an answer that fails the schema + bad = {**fmt, "schema": {**fmt["schema"], "properties": {"n": {"type": "string"}}}} + code, r = self.post({"model": "m", "input": "a number", "text": {"format": bad}}) + self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed")) + code, events = self.post({"model": "m", "input": "a number", "text": {"format": bad}, "stream": True}) + self.assertEqual(events[-1]["type"], "response.failed") + self.assertEqual(events[-1]["response"]["error"]["code"], "structured_output_failed") + + def test_monitor_and_status(self): + self.svc.api_monitor = True + self.post({"model": "m", "input": "hi", "stream": True}) + rec = self.svc.request_records()[0] + self.assertEqual(rec["path"], "/v1/responses") + full = self.svc.request_records(rec["id"]) + self.assertEqual(full["output"], "The file says before.") + self.assertEqual(full["reasoning"], "Read it.\n") + self.assertIn("/v1/responses", self.svc.v1_status()["dialects"]) + + +class ToolRoundTrip(Server): + script = [CALL, ANSWER] + + def test_function_call_round_trip(self): + user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is in a.txt?"}]} + code, events = self.post({"model": "m", "instructions": "You are a coding agent.", "input": [user], + "tools": TOOLS, "store": False, "stream": True, + "include": ["reasoning.encrypted_content"], "reasoning": {"summary": "auto"}, + "parallel_tool_calls": True, "tool_choice": "auto"}) + self.assertEqual(code, 200) + first_prompt = self.tok.decode(self.engine.last_prompt) + types = [e["type"] for e in events] + n_args = types.count("response.function_call_arguments.delta") + self.assertGreater(n_args, 0) + call_part = types[types.index("response.output_text.done") + 2:] + self.assertEqual(call_part, ["response.output_item.done", "response.output_item.added", + *["response.function_call_arguments.delta"] * n_args, + "response.function_call_arguments.done", "response.output_item.done", + "response.completed"]) + output = events[-1]["response"]["output"] + self.assertEqual([o["type"] for o in output], ["reasoning", "message", "function_call"]) + fc = output[2] + self.assertEqual((fc["name"], json.loads(fc["arguments"]), fc["status"]), + ("exec_command", {"cmd": "cat a.txt"}, "completed")) + self.assertTrue(fc["call_id"]) + added = next(e for e in events if e["type"] == "response.output_item.added" + and e["item"]["type"] == "function_call") + self.assertEqual((added["item"]["call_id"], added["item"]["arguments"]), (fc["call_id"], "")) + # Codex sends everything back, plus the result: the prompt continues exactly where the model stopped + code, r = self.post({"model": "m", "instructions": "You are a coding agent.", "tools": TOOLS, "store": False, + "input": [user, *output, {"type": "function_call_output", "call_id": fc["call_id"], + "output": "before"}]}) + self.assertEqual(code, 200, r) + second_prompt = self.tok.decode(self.engine.last_prompt) + self.assertTrue(second_prompt.startswith(first_prompt + CALL + "<|im_end|>"), second_prompt[-600:]) + self.assertIn("\nbefore\n", second_prompt) + self.assertEqual(r["output"][-1]["content"][0]["text"], "The file says before.") + + def test_namespace_and_custom_calls_come_back_under_their_own_names(self): + self.engine.scripts = [self.tok.encode( + "\n\n\n\n\nhi\n\n" + "\n\n\n\n\n*** Begin Patch\n" + "\n\n<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + tools = [{"type": "namespace", "name": "multi_agent_v1", "description": "Agents.", "tools": [ + {"type": "function", "name": "spawn_agent", "strict": False, + "parameters": {"type": "object", "properties": {"message": {"type": "string"}}}}]}, + {"type": "custom", "name": "apply_patch", "description": "Edit files."}] + code, r = self.post({"model": "m", "input": "go", "tools": tools}) + self.assertEqual(code, 200, r) + ns, custom = r["output"] + self.assertEqual((ns["type"], ns["namespace"], ns["name"], json.loads(ns["arguments"])), + ("function_call", "multi_agent_v1", "spawn_agent", {"message": "hi"})) + self.assertEqual((custom["type"], custom["name"], custom["input"]), + ("custom_tool_call", "apply_patch", "*** Begin Patch")) + msgs = input_messages({"input": [{"role": "user", "content": "go"}, ns, custom, + {"type": "function_call_output", "call_id": ns["call_id"], "output": "1"}, + {"type": "custom_tool_call_output", "call_id": custom["call_id"], + "output": "2"}]}) + self.assertEqual([c["function"]["name"] for c in msgs[1]["tool_calls"]], + ["multi_agent_v1.spawn_agent", "apply_patch"]) + + +if __name__ == "__main__": + unittest.main()