Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(server): serve /v1/responses as a translation onto chat completions (#1016)
Krisztian Gajdare508250c2d20
diff --git a/conformance/openai_responses/README.md b/conformance/openai_responses/README.mdindex a73d5672a..b379018b2 100644--- a/conformance/openai_responses/README.md+++ b/conformance/openai_responses/README.md@@ -231,9 +231,9 @@ carries `type`, equal to the event name, and `sequence_number`, counting fromA chat error returned before the stream opens is returned as it is: the samestatus, `Retry-After` and `x-sie-error-code` headers, and OpenAI error body.-The route adds no header of its own. The only change is the `param` when it-names a chat field, which is renamed to the Responses field the caller sent;-the message keeps the chat route's wording.+The route adds no header of its own. The only change is the `param`: only the+chat params listed in the table below are renamed, to the Responses field the+caller sent. The message keeps the chat route's wording.| Chat `param` | Responses `param` ||---|---|diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 276860e31..0986c737e 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -1024,123 +1024,6 @@}}},- "/v1/responses": {- "post": {- "tags": [- "openai-compat"- ],- "summary": "Responses",- "description": "Create one stateless, text-only OpenAI Responses result.",- "operationId": "responses_v1_responses_post",- "parameters": [- {- "name": "X-SIE-MACHINE-PROFILE",- "in": "header",- "required": false,- "schema": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "title": "X-Sie-Machine-Profile"- }- },- {- "name": "X-SIE-Remote",- "in": "header",- "required": false,- "schema": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "The only accepted value is `forbid`. It keeps the request off remote upstreams: local capacity serves or refuses it, and a model served only by an upstream answers 400. Any other value answers 400.",- "title": "X-Sie-Remote"- },- "description": "The only accepted value is `forbid`. It keeps the request off remote upstreams: local capacity serves or refuses it, and a model served only by an upstream answers 400. Any other value answers 400."- }- ],- "responses": {- "200": {- "description": "Successful Response",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/OpenAIResponsesResponseModel"- }- }- }- },- "400": {- "description": "Invalid or unsupported request"- },- "404": {- "description": "Model not found"- },- "413": {- "description": "Request body or rendered input is too large"- },- "500": {- "description": "Generation failed",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"- }- }- }- },- "503": {- "description": "Model loading or temporarily unavailable",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"- }- }- }- },- "504": {- "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"- }- }- }- },- "422": {- "description": "Validation Error",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/HTTPValidationError"- }- }- }- }- },- "requestBody": {- "required": true,- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/OpenAIResponsesRequestModel"- }- }- }- }- }- },"/v1/systemone": {"post": {"tags": [@@ -2859,157 +2742,6 @@"title": "OpenAIGenerationErrorResponse","description": "Top-level OpenAI error envelope of a generation error."},- "OpenAIResponseOutputMessageModel": {- "properties": {- "type": {- "type": "string",- "const": "message",- "title": "Type"- },- "id": {- "type": "string",- "title": "Id"- },- "role": {- "type": "string",- "const": "assistant",- "title": "Role"- },- "status": {- "type": "string",- "const": "completed",- "title": "Status"- },- "content": {- "items": {- "$ref": "#/components/schemas/OpenAIResponseOutputTextModel"- },- "type": "array",- "title": "Content"- }- },- "type": "object",- "required": [- "type",- "id",- "role",- "status",- "content"- ],- "title": "OpenAIResponseOutputMessageModel"- },- "OpenAIResponseOutputTextModel": {- "properties": {- "type": {- "type": "string",- "const": "output_text",- "title": "Type"- },- "text": {- "type": "string",- "title": "Text"- },- "annotations": {- "items": {- "additionalProperties": true,- "type": "object"- },- "type": "array",- "title": "Annotations"- }- },- "type": "object",- "required": [- "type",- "text",- "annotations"- ],- "title": "OpenAIResponseOutputTextModel"- },- "OpenAIResponseUsageModel": {- "properties": {- "input_tokens": {- "type": "integer",- "minimum": 0.0,- "title": "Input Tokens"- },- "output_tokens": {- "type": "integer",- "minimum": 0.0,- "title": "Output Tokens"- },- "total_tokens": {- "type": "integer",- "minimum": 0.0,- "title": "Total Tokens"- },- "input_tokens_details": {- "anyOf": [- {- "$ref": "#/components/schemas/PromptTokensDetailsModel"- },- {- "type": "null"- }- ]- }- },- "type": "object",- "required": [- "input_tokens",- "output_tokens",- "total_tokens"- ],- "title": "OpenAIResponseUsageModel"- },- "OpenAIResponsesResponseModel": {- "properties": {- "id": {- "type": "string",- "title": "Id"- },- "object": {- "type": "string",- "const": "response",- "title": "Object"- },- "created_at": {- "type": "integer",- "title": "Created At"- },- "model": {- "type": "string",- "title": "Model"- },- "status": {- "type": "string",- "const": "completed",- "title": "Status"- },- "output": {- "items": {- "$ref": "#/components/schemas/OpenAIResponseOutputMessageModel"- },- "type": "array",- "title": "Output"- },- "usage": {- "$ref": "#/components/schemas/OpenAIResponseUsageModel"- }- },- "type": "object",- "required": [- "id",- "object",- "created_at",- "model",- "status",- "output",- "usage"- ],- "title": "OpenAIResponsesResponseModel",- "description": "One completed direct OpenAI Responses result."- },"OpenAIUsage": {"properties": {"prompt_tokens": {@@ -4879,175 +4611,6 @@"title": "OpenAICompletionRequestModel","type": "object"},- "OpenAIResponseInputContentPartModel": {- "additionalProperties": false,- "description": "One text-only content part accepted by the Responses MVP.",- "properties": {- "type": {- "enum": [- "text",- "input_text",- "output_text"- ],- "title": "Type",- "type": "string"- },- "text": {- "title": "Text",- "type": "string"- }- },- "required": [- "type",- "text"- ],- "title": "OpenAIResponseInputContentPartModel",- "type": "object"- },- "OpenAIResponseInputMessageModel": {- "additionalProperties": false,- "description": "One stateless text message accepted by the Responses MVP.",- "properties": {- "role": {- "enum": [- "system",- "user",- "assistant",- "developer"- ],- "title": "Role",- "type": "string"- },- "content": {- "anyOf": [- {- "type": "string"- },- {- "items": {- "$ref": "#/components/schemas/OpenAIResponseInputContentPartModel"- },- "type": "array"- }- ],- "title": "Content"- }- },- "required": [- "role",- "content"- ],- "title": "OpenAIResponseInputMessageModel",- "type": "object"- },- "OpenAIResponsesRequestModel": {- "additionalProperties": false,- "description": "Strict stateless, text-only subset of the OpenAI Responses API.",- "properties": {- "model": {- "description": "Generation model id",- "minLength": 1,- "title": "Model",- "type": "string"- },- "input": {- "anyOf": [- {- "type": "string"- },- {- "items": {- "$ref": "#/components/schemas/OpenAIResponseInputMessageModel"- },- "minItems": 1,- "type": "array"- }- ],- "title": "Input"- },- "max_output_tokens": {- "anyOf": [- {- "maximum": 4294967295,- "minimum": 1,- "type": "integer"- },- {- "type": "null"- }- ],- "default": 16,- "description": "Maximum generated tokens",- "title": "Max Output Tokens"- },- "temperature": {- "anyOf": [- {- "maximum": 3.4028234663852886e+38,- "minimum": 0,- "type": "number"- },- {- "type": "null"- }- ],- "default": null,- "description": "Sampling temperature override",- "title": "Temperature"- },- "top_p": {- "anyOf": [- {- "exclusiveMinimum": 0,- "maximum": 1,- "type": "number"- },- {- "type": "null"- }- ],- "default": null,- "description": "Nucleus-sampling probability override",- "title": "Top P"- },- "seed": {- "anyOf": [- {- "maximum": 9223372036854775807,- "minimum": -9223372036854775808,- "type": "integer"- },- {- "type": "null"- }- ],- "default": null,- "description": "Optional signed 64-bit sampling seed",- "format": "int64",- "title": "Seed"- },- "stream": {- "anyOf": [- {- "const": false,- "type": "boolean"- },- {- "type": "null"- }- ],- "default": null,- "description": "Responses streaming is not supported",- "title": "Stream"- }- },- "required": [- "model",- "input"- ],- "title": "OpenAIResponsesRequestModel",- "type": "object"- },"ScoreRequestModel": {"description": "Request body for score endpoint.","examples": [diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 051e10efa..37bb82563 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -167,11 +167,12 @@ _IGNORED_CHAT_FIELDS: dict[str, tuple[type, str]] = {"metadata": (dict, "an object"),"store": (bool, "a boolean"),"service_tier": (str, "a string"),+ "prompt_cache_key": (str, "a string"),}# Mirror the gateway's public chat field boundary, minus controls that require-# gateway-owned admission/routing translation (best_of, cache-# keys). Most importantly this excludes SGLang's backend/DP/custom-processor+# gateway-owned admission/routing translation (best_of,+# routing_key). Most importantly this excludes SGLang's backend/DP/custom-processor# extensions, so the public body cannot steer the managed child or execute a# client-supplied logit processor._CUDA_CHAT_FIELDS = frozenset(diff --git a/packages/sie_server/src/sie_server/api/openai_responses.py b/packages/sie_server/src/sie_server/api/openai_responses.pyindex a414c6938..407a6026a 100644--- a/packages/sie_server/src/sie_server/api/openai_responses.py+++ b/packages/sie_server/src/sie_server/api/openai_responses.py@@ -1,8 +1,12 @@-"""Direct OpenAI-compatible ``/v1/responses`` generation surface.--This is the direct-server counterpart of the gateway's stateless, text-only-Responses MVP. Both raw string input and validated message input are reduced to-one rendered prompt and executed through ``GenerationAdapter.generate``.+"""``POST /v1/responses``: the OpenAI Responses API on the single-instance server.++The request is validated and translated into a chat completions body+(:mod:`sie_server.api.responses_translation`), this server's own+``/v1/chat/completions`` serves it in process, and the answer is translated+back: a chat completion into a Response, chat SSE chunks into Responses events,+and a chat error into the same error with the field the caller sent. Every chat+gate, limit and timeout therefore applies unchanged. Responses are not stored,+so ``/v1/responses/{id}`` and the routes below it are not served."""from __future__ import annotations@@ -10,403 +14,130 @@ from __future__ import annotationsimport loggingimport timeimport uuid-from dataclasses import dataclass-from typing import Annotated, Any, cast--from fastapi import APIRouter, Depends, Header, HTTPException, Request, status-from fastapi.responses import JSONResponse-from sie_sdk.queue_types import denormalize_model_id--from sie_server.adapters._generation_base import (- GenerationAdapter,- GenerationError,- reasoning_starts_in_prompt,- resolve_reasoning_format,- suppress_thinking_blocks,- thinking_blocks_must_be_hidden,-)-from sie_server.adapters.remote.sie import SieUpstreamAdapter-from sie_server.api.generate import _render_native_messages_prompt-from sie_server.api.helpers import ModelStateChecker, check_sdk_version-from sie_server.api.openai_completions import (- _MAX_F32,- _MAX_PROMPT_BYTES,- _collect_completion,- _completion_error_response,- _CompletionError,- _from_generation_error,- _from_http_exception,- _generation_timeout_error,- _number,- _read_json_body,+from http import HTTPStatus+from typing import Annotated, Any++from fastapi import APIRouter, Depends, Header, Request+from fastapi.responses import JSONResponse, Response, StreamingResponse+from starlette.types import Receive, Scope, Send++from sie_server.api.anthropic_messages import _header_pairs, _json_answer, _read, _ResponseBody+from sie_server.api.anthropic_translation import is_forwarded_header, parse_json+from sie_server.api.openai_local import _MAX_BODY_BYTES, serve_chat_completions+from sie_server.api.responses_translation import (+ ResponsesError,+ ResponseShape,+ StreamMachine,+ chat_completion_to_response,+ responses_error,+ responses_to_chat,+ stream_events,)-from sie_server.api.routing import remote_routing, route_request-from sie_server.api.validation import validate_machine_profile_header, validate_signed_i64-from sie_server.core.runtime_options import (- GenerationTimeoutError,- apply_generation_runtime_options,- bound_generation,- resolve_generation_timeouts,-)-from sie_server.observability.tracing import tracer-from sie_server.types.openapi import OpenAIGenerationErrorResponse, OpenAIResponsesResponseModel+from sie_server.api.routing import remote_routing-router = APIRouter(prefix="/v1", tags=["openai-compat"], dependencies=[Depends(remote_routing)])logger = logging.getLogger(__name__)-_MAX_U32 = (1 << 32) - 1-_SUPPORTED_FIELDS = frozenset(- {- "model",- "input",- "max_output_tokens",- "temperature",- "top_p",- "seed",- "stream",- }-)-_KNOWN_UNSUPPORTED_FIELDS = frozenset(- {- "previous_response_id",- "tools",- "tool_choice",- "reasoning",- "background",- "metadata",- "instructions",- }-)-_ALLOWED_ROLES = frozenset({"system", "user", "assistant", "developer"})-_ALLOWED_CONTENT_TYPES = frozenset({"text", "input_text", "output_text"})---@dataclass(frozen=True, slots=True)-class _ResponsesParams:- model: str- prompt: str | None- messages: list[dict[str, str]] | None- max_output_tokens: int- temperature: float | None- top_p: float | None- seed: int | None---def _unsupported(field: str) -> _CompletionError:- return _CompletionError(- f"'{field}' is not supported by this endpoint",- param=field,- code="unsupported_field",- )+router = APIRouter(prefix="/v1", tags=["openai-compat"], dependencies=[Depends(remote_routing)])-def _parse_message_content(value: Any, *, index: int) -> str:- path = f"input[{index}].content"- if isinstance(value, str):- return value- if not isinstance(value, list):- raise _CompletionError(f"'{path}' must be a string or text parts", param=path)+def _refusal(error: ResponsesError) -> Response:+ return JSONResponse(status_code=error.status, content=error.body())- text: list[str] = []- for part_index, part in enumerate(value):- part_path = f"{path}[{part_index}]"- if not isinstance(part, dict):- raise _CompletionError(f"'{part_path}' must be an object", param=part_path)- part_obj = cast("dict[str, Any]", part)- unknown = set(part_obj) - {"type", "text"}- if unknown:- field = sorted(unknown)[0]- raise _unsupported(f"{part_path}.{field}")- part_type = part_obj.get("type")- if not isinstance(part_type, str):- raise _CompletionError(f"'{part_path}.type' is required and must be a string", param=f"{part_path}.type")- if part_type not in _ALLOWED_CONTENT_TYPES:- raise _CompletionError(- f"unsupported content part type '{part_type}'",- param=f"{part_path}.type",- code="unsupported_field",- )- part_text = part_obj.get("text")- if not isinstance(part_text, str):- raise _CompletionError(- f"'{part_path}.text' is required and must be a string",- param=f"{part_path}.text",- )- text.append(part_text)- return "".join(text)+def _server_error(message: str) -> Response:+ return _refusal(ResponsesError(message, param=None, code="server_error", status=500))-def _parse_input(value: Any) -> tuple[str | None, list[dict[str, str]] | None]:- if isinstance(value, str):- return value, None- if not isinstance(value, list) or not value:- raise _CompletionError(- 'field "input" is required (a string or a non-empty list of messages)',- param="input",- )- messages: list[dict[str, str]] = []- for index, item in enumerate(value):- path = f"input[{index}]"- if not isinstance(item, dict):- raise _CompletionError(f"'{path}' must be an object", param=path)- item_obj = cast("dict[str, Any]", item)- unknown = set(item_obj) - {"role", "content"}- if unknown:- field = sorted(unknown)[0]- raise _unsupported(f"{path}.{field}")- role = item_obj.get("role")- if not isinstance(role, str):- raise _CompletionError(f"'{path}.role' is required and must be a string", param=f"{path}.role")- if role not in _ALLOWED_ROLES:- raise _CompletionError(f"'{path}.role' is invalid", param=f"{path}.role")- messages.append(- {- "role": "system" if role == "developer" else role,- "content": _parse_message_content(item_obj.get("content"), index=index),- }- )- return None, messages+async def _error_answer(answer: Response) -> Response:+ headers, content = responses_error(_header_pairs(answer), await _read(answer))+ return _json_answer(answer.status_code, headers, content)-def _parse_params(body: dict[str, Any]) -> _ResponsesParams:- for field in _KNOWN_UNSUPPORTED_FIELDS:- if field in body:- raise _unsupported(field)- unknown = set(body) - _SUPPORTED_FIELDS- if unknown:- raise _unsupported(sorted(unknown)[0])+async def _read_body(request: Request) -> Any:+ declared = request.headers.get("content-length")+ too_large = ResponsesError("request body too large", param=None, code="INPUT_TOO_LONG", status=413)+ if declared is not None and declared.isdigit() and int(declared) > _MAX_BODY_BYTES:+ raise too_large+ raw = bytearray()+ async for chunk in request.stream():+ if len(raw) + len(chunk) > _MAX_BODY_BYTES:+ raise too_large+ raw.extend(chunk)+ try:+ return parse_json(bytes(raw))+ except (ValueError, UnicodeDecodeError):+ raise ResponsesError("body: invalid JSON", param="body", code="invalid_request") from None- model = body.get("model")- if not isinstance(model, str) or not model:- raise _CompletionError('field "model" is required', param="model")- prompt, messages = _parse_input(body.get("input"))+async def _buffered_response(answer: Response, shape: ResponseShape, request_id: str) -> Response:+ try:+ chat = parse_json(await _read(answer))+ except ValueError:+ return _server_error("the chat completion is not valid JSON")+ try:+ response = chat_completion_to_response(chat, shape, request_id, int(time.time()))+ except ValueError:+ logger.warning("a chat completion could not be translated into a Response", exc_info=True)+ return _server_error("the chat completion could not be translated")+ headers = {name: value for name, value in _header_pairs(answer) if is_forwarded_header(name)}+ return JSONResponse(content=response, headers=headers)- stream = body.get("stream")- if stream is not None and not isinstance(stream, bool):- raise _CompletionError("'stream' must be a boolean", param="stream")- if stream:- raise _unsupported("stream")- max_output_tokens = body.get("max_output_tokens", 16)- if max_output_tokens is None:- max_output_tokens = 16- if (- isinstance(max_output_tokens, bool)- or not isinstance(max_output_tokens, int)- or not (1 <= max_output_tokens <= _MAX_U32)- ):- raise _CompletionError("'max_output_tokens' must be a positive integer", param="max_output_tokens")+class _ResponsesStream(StreamingResponse):+ """A chat SSE answer served as Responses events. Ending this answer ends the chat answer."""- temperature = _number(body.get("temperature"), param="temperature", minimum=0, maximum=_MAX_F32)- top_p = _number(body.get("top_p"), param="top_p", minimum=0, maximum=1)- if top_p is not None and top_p == 0:- raise _CompletionError("'top_p' must be a number in (0, 1]", param="top_p")- try:- seed = validate_signed_i64(body.get("seed"), param="seed")- except ValueError as exc:- raise _CompletionError(str(exc), param="seed") from exc+ def __init__(self, chat: Response, machine: StreamMachine) -> None:+ self._body = _ResponseBody(chat)+ headers = {name: value for name, value in _header_pairs(chat) if name not in ("content-length", "content-type")}+ super().__init__(stream_events(self._body, machine), media_type="text/event-stream", headers=headers)- return _ResponsesParams(- model=model,- prompt=prompt,- messages=messages,- max_output_tokens=max_output_tokens,- temperature=temperature,- top_p=top_p,- seed=seed,- )+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ try:+ await super().__call__(scope, receive, send)+ finally:+ await self._body.aclose()@router.post("/responses",- response_model=OpenAIResponsesResponseModel,+ response_model=None,responses={400: {"description": "Invalid or unsupported request"},404: {"description": "Model not found"},- 413: {"description": "Request body or rendered input is too large"},- 500: {"description": "Generation failed", "model": OpenAIGenerationErrorResponse},- 503: {"description": "Model loading or temporarily unavailable", "model": OpenAIGenerationErrorResponse},- 504: {- "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",- "model": OpenAIGenerationErrorResponse,- },- },- openapi_extra={- "requestBody": {- "required": True,- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OpenAIResponsesRequestModel"}}},- }+ 413: {"description": "Request body is too large"},+ 500: {"description": "Generation failed"},+ 502: {"description": "The generation backend failed the request"},+ 503: {"description": "Model loading or temporarily unavailable; retry after Retry-After"},+ 504: {"description": "Generation timed out"},},)async def responses(http_request: Request,x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,-) -> JSONResponse:- """Create one stateless, text-only OpenAI Responses result."""+) -> Response:+ """OpenAI Responses API, served by this server's chat completions route.++ The request is translated into a ``/v1/chat/completions`` request, served+ in process with all of that route's limits, and the answer is translated+ back, as a Response or, with ``stream``, as Responses events. Responses are+ not stored: ``store``, ``previous_response_id`` and ``conversation`` are+ refused, and the caller sends the whole conversation in ``input``. Function+ and custom tools are supported. Errors use the OpenAI envelope at the status+ the chat route answers.+ """try:- validate_machine_profile_header(x_machine_profile)- check_sdk_version(http_request)- params = _parse_params(await _read_json_body(http_request))-- registry = http_request.app.state.registry- registry_key = denormalize_model_id(params.model)- with tracer.start_as_current_span("openai_responses") as span:- span.set_attribute("model", params.model)- ModelStateChecker(registry, registry_key, span).check_exists()-- config = registry.get_config(registry_key)- generate_task = getattr(config.tasks, "generate", None)- if generate_task is None:- raise _CompletionError(- f"Model '{params.model}' does not support generation",- param="model",- code="model_not_found",- )- if params.max_output_tokens > generate_task.max_output_tokens:- raise _CompletionError(- f"max_output_tokens ({params.max_output_tokens}) exceeds model cap "- f"({generate_task.max_output_tokens})",- param="max_output_tokens",- code="context_exceeded",- )-- prompt = params.prompt- if params.messages is not None:- prompt = await _render_native_messages_prompt(config, params.messages)- if prompt is None: # pragma: no cover - parser invariant- raise _CompletionError("input did not resolve to a prompt", param="input")- prompt_bytes = len(prompt.encode("utf-8"))- if prompt_bytes > _MAX_PROMPT_BYTES:- raise _CompletionError(- f"rendered input is {prompt_bytes} bytes, exceeds the limit of {_MAX_PROMPT_BYTES} bytes",- status_code=status.HTTP_413_CONTENT_TOO_LARGE,- param="input",- code="context_exceeded",- )-- runtime_params: dict[str, Any] = {- "prompt": prompt,- "max_new_tokens": params.max_output_tokens,- **{- key: value- for key, value in (- ("temperature", params.temperature),- ("top_p", params.top_p),- ("seed", params.seed),- )- if value is not None- },- }- try:- runtime_params = apply_generation_runtime_options(config, None, runtime_params)- except ValueError as exc:- raise _CompletionError(str(exc), code="invalid_request") from exc-- route = await route_request(http_request, registry_key, span)- adapter = registry.get(route.key)- registry.touch_lru(route.key)- if not isinstance(adapter, GenerationAdapter):- raise _CompletionError(- f"Model '{params.model}' adapter does not support generation",- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- param="model",- code="inference_error",- )-- generation_parameters: dict[str, Any] = {- "prompt": prompt,- "max_new_tokens": params.max_output_tokens,- "temperature": float(runtime_params.get("temperature", 1.0)),- "top_p": float(runtime_params.get("top_p", 1.0)),- "stop": runtime_params.get("stop"),- "frequency_penalty": runtime_params.get("frequency_penalty"),- "presence_penalty": runtime_params.get("presence_penalty"),- "top_k": runtime_params.get("top_k"),- "min_new_tokens": runtime_params.get("min_tokens"),- "seed": runtime_params.get("seed"),- }- try:- adapter.preflight_generate(generation_parameters, stream=False)- except GenerationError as exc:- raise _from_generation_error(exc, registry) from exc- except Exception as exc:- logger.warning("OpenAI Responses preflight failed for %s", params.model, exc_info=True)- raise _CompletionError(- "internal error during generation",- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- code="inference_error",- ) from exc-- try:- chunks = adapter.generate(**generation_parameters)- except GenerationError as exc:- raise _from_generation_error(exc, registry) from exc- if thinking_blocks_must_be_hidden(config):- reasoning_format = resolve_reasoning_format(config, adapter)- chunks = suppress_thinking_blocks(- chunks,- start_inside=not isinstance(adapter, SieUpstreamAdapter)- and reasoning_starts_in_prompt(prompt, reasoning_format),- reasoning_format=reasoning_format,- )- try:- text, terminal = await _collect_completion(- bound_generation(chunks, resolve_generation_timeouts(config, None))- )- except _CompletionError:- raise- except GenerationTimeoutError as exc:- raise _generation_timeout_error(exc, remote=route.upstream is not None) from exc- except GenerationError as exc:- raise _from_generation_error(exc, registry) from exc- except Exception as exc:- logger.warning("OpenAI Responses generation failed for %s", params.model, exc_info=True)- raise _CompletionError(- "internal error during generation",- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- code="inference_error",- ) from exc-- canonical_model = getattr(config, "name", None) or registry_key- response_id = f"resp-{uuid.uuid4().hex}"- if terminal.prompt_tokens is None or terminal.completion_tokens is None:- raise _CompletionError(- "generation terminal event omitted required usage",- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- code="malformed_worker_response",- )- prompt_tokens = terminal.prompt_tokens- completion_tokens = terminal.completion_tokens- usage: dict[str, Any] = {- "input_tokens": prompt_tokens,- "output_tokens": completion_tokens,- "total_tokens": prompt_tokens + completion_tokens,- }- if terminal.cached_tokens is not None:- usage["input_tokens_details"] = {"cached_tokens": min(terminal.cached_tokens, prompt_tokens)}- return JSONResponse(- content={- "id": response_id,- "object": "response",- "created_at": int(time.time()),- "model": canonical_model,- "status": "completed",- "output": [- {- "type": "message",- "id": f"msg-{response_id.removeprefix('resp-')}",- "role": "assistant",- "status": "completed",- "content": [{"type": "output_text", "text": text, "annotations": []}],- }- ],- "usage": usage,- },- headers=route.headers(),- )- except _CompletionError as exc:- return _completion_error_response(http_request, exc)- except HTTPException as exc:- return _completion_error_response(http_request, _from_http_exception(exc))+ translation = responses_to_chat(await _read_body(http_request))+ except ResponsesError as error:+ return _refusal(error)+ try:+ answer = await serve_chat_completions(http_request, x_machine_profile, translation.chat)+ if not HTTPStatus.OK <= answer.status_code < HTTPStatus.MULTIPLE_CHOICES:+ return await _error_answer(answer)+ request_id = next((value for name, value in _header_pairs(answer) if name == "x-sie-request-id"), None)+ request_id = request_id or uuid.uuid4().hex+ if translation.stream:+ return _ResponsesStream(answer, StreamMachine(translation.shape, request_id, int(time.time())))+ return await _buffered_response(answer, translation.shape, request_id)+ except Exception:+ logger.exception("the Responses translation of a chat answer failed")+ return _server_error("internal server error")diff --git a/packages/sie_server/src/sie_server/api/openapi.py b/packages/sie_server/src/sie_server/api/openapi.pyindex 7431308c9..1938bfa82 100644--- a/packages/sie_server/src/sie_server/api/openapi.py+++ b/packages/sie_server/src/sie_server/api/openapi.py@@ -15,7 +15,6 @@ from sie_server.types.openapi import (GenerateChunk,GenerateRequestModel,OpenAICompletionRequestModel,- OpenAIResponsesRequestModel,ScoreRequestModel,)@@ -68,7 +67,6 @@ def _add_request_body_schemas(openapi_schema: dict[str, Any]) -> None:GenerateChunk,GenerateRequestModel,OpenAICompletionRequestModel,- OpenAIResponsesRequestModel,ScoreRequestModel,]:model_name = model_class.__name__diff --git a/packages/sie_server/src/sie_server/api/responses_translation.py b/packages/sie_server/src/sie_server/api/responses_translation.pynew file mode 100644index 000000000..0f936f695--- /dev/null+++ b/packages/sie_server/src/sie_server/api/responses_translation.py@@ -0,0 +1,1102 @@+"""OpenAI Responses translation onto the chat completions wire.++A Responses request into a chat completions body, a chat completion into a+Response, chat SSE ``data`` payloads into Responses events, and a chat error+answer into the Responses error answer. The gateway serves the same+translation, and the shared vectors under ``conformance/openai_responses/`` pin+both, so a request is accepted, refused and answered the same way on+``sie-server`` and on the gateway.++Validation happens here, in Responses terms, so a refusal names the field the+caller sent. Unknown fields fail with ``<path>: Extra inputs are not+permitted``. The accepted-but-inert set is ``store: false``, ``background:+false``, ``truncation: "disabled"``, an ``include`` of only+``reasoning.encrypted_content``, ``client_metadata``, ``reasoning.summary``,+``reasoning.generate_summary`` and ``text.verbosity``.+"""++from __future__ import annotations++import re+from collections.abc import AsyncIterator, Iterable+from dataclasses import dataclass+from http import HTTPStatus+from typing import Any++from sie_server.api.anthropic_translation import json_text, parse_json++_U32_MAX = (1 << 32) - 1+_ENCRYPTED_REASONING = "reasoning.encrypted_content"+_STATELESS = "SIE does not store responses; send the full conversation in input"+_ACCEPTED_FIELDS = frozenset(+ {+ "model",+ "input",+ "instructions",+ "max_output_tokens",+ "temperature",+ "top_p",+ "seed",+ "stream",+ "tools",+ "tool_choice",+ "parallel_tool_calls",+ "reasoning",+ "text",+ "metadata",+ "prompt_cache_key",+ "user",+ "safety_identifier",+ "service_tier",+ "client_metadata",+ }+)+_PASSTHROUGH_FIELDS = ("metadata", "prompt_cache_key", "user", "safety_identifier", "service_tier")+_ITEM_KEYS = {+ "message": ("type", "id", "status", "role", "content"),+ "function_call": ("type", "id", "status", "call_id", "name", "arguments"),+ "custom_tool_call": ("type", "id", "status", "call_id", "name", "input"),+ "function_call_output": ("type", "id", "status", "call_id", "output"),+ "custom_tool_call_output": ("type", "id", "status", "call_id", "output"),+ "reasoning": ("type", "id", "status", "summary", "content", "encrypted_content"),+}+_ROLES = {"user": "user", "assistant": "assistant", "system": "system", "developer": "system"}+_TEXT_PART_KEYS = {+ "input_text": ("type", "text"),+ "text": ("type", "text"),+ "output_text": ("type", "text", "annotations", "logprobs"),+}+_IMAGE_KEYS = ("type", "image_url", "file_id", "detail")+_FUNCTION_TOOL_KEYS = ("type", "name", "description", "parameters", "strict")+_CUSTOM_TOOL_KEYS = ("type", "name", "description", "format")+_FORMAT_KEYS = {+ "text": ("type",),+ "json_object": ("type",),+ "json_schema": ("type", "name", "schema", "strict", "description"),+}+_PARAM_RENAMES = {+ "max_completion_tokens": "max_output_tokens",+ "reasoning_effort": "reasoning.effort",+ "response_format": "text.format",+}+_SCHEMA_PARAM_PREFIX = "response_format.json_schema."+_TOOL_PARAM = re.compile(r"tools\[([0-9]+)\]\.function\.(.+)")+++class ResponsesError(Exception):+ """A refusal decided in Responses terms, answered in the OpenAI error envelope."""++ def __init__(self, message: str, *, param: str | None, code: str, status: int = 400) -> None:+ super().__init__(message)+ self.status = status+ self.message = message+ self.param = param+ self.code = code++ def body(self) -> dict[str, Any]:+ error_type = "invalid_request_error" if self.status < HTTPStatus.INTERNAL_SERVER_ERROR else "server_error"+ return {"error": {"message": self.message, "type": error_type, "param": self.param, "code": self.code}}+++@dataclass(frozen=True)+class ResponseShape:+ """What a Response repeats from the request it answers."""++ model: str+ parallel_tool_calls: Any+ tool_choice: Any+ custom_tools: frozenset[str]+ """Names of the declared custom tools, whose calls come back as ``custom_tool_call`` items."""+++@dataclass(frozen=True)+class ChatTranslation:+ """A translated request."""++ chat: dict[str, Any]+ stream: bool+ shape: ResponseShape+++def _is_int(value: Any) -> bool:+ return isinstance(value, int) and not isinstance(value, bool)+++def _unsupported(param: str, reason: str) -> ResponsesError:+ return ResponsesError(f"{param}: {reason}", param=param, code="unsupported_field")+++def _invalid(param: str, reason: str) -> ResponsesError:+ return ResponsesError(f"{param}: {reason}", param=param, code="invalid_request")+++def _extra(param: str) -> ResponsesError:+ return _unsupported(param, "Extra inputs are not permitted")+++def _required(param: str) -> ResponsesError:+ return _invalid(param, "Field required")+++def _object(value: Any, path: str) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise _invalid(path, "Input should be a valid dictionary")+ return value+++def _only_keys(mapping: dict[str, Any], allowed: Iterable[str], path: str) -> None:+ allowed_keys = frozenset(allowed)+ for key in mapping:+ if key not in allowed_keys:+ raise _extra(f"{path}.{key}")+++def _string(mapping: dict[str, Any], key: str, path: str) -> str:+ value = mapping.get(key)+ if value is None:+ raise _required(f"{path}.{key}")+ if not isinstance(value, str):+ raise _invalid(f"{path}.{key}", "Input should be a valid string")+ return value+++def _type(mapping: dict[str, Any], path: str) -> str:+ kind = mapping.get("type")+ if kind is None:+ raise _required(f"{path}.type")+ if not isinstance(kind, str):+ raise _invalid(f"{path}.type", "Input should be a valid string")+ return kind+++class _Parts:+ """The content of one chat message: adjacent texts joined, empty texts dropped, images kept in order."""++ def __init__(self) -> None:+ self._items: list[tuple[str, str]] = []+ self._texts: list[str] = []++ def text(self, text: str) -> None:+ if text:+ self._texts.append(text)++ def image(self, data_uri: str) -> None:+ self._join_texts()+ self._items.append(("image", data_uri))++ def items(self) -> list[tuple[str, str]]:+ self._join_texts()+ return self._items++ def joined_text(self) -> str:+ return "".join(value for kind, value in self.items() if kind == "text")++ def content(self) -> str | list[dict[str, Any]]:+ items = self.items()+ if all(kind == "text" for kind, _ in items):+ return "".join(value for _, value in items)+ return [+ {"type": "text", "text": value} if kind == "text" else {"type": "image_url", "image_url": {"url": value}}+ for kind, value in items+ ]++ def _join_texts(self) -> None:+ if self._texts:+ self._items.append(("text", "".join(self._texts)))+ self._texts = []+++def responses_to_chat(body: Any) -> ChatTranslation:+ """Translate an OpenAI Responses body into a chat completions body.++ Raises:+ ResponsesError: The request is refused, with the Responses wording.+ """+ if not isinstance(body, dict):+ raise _invalid("body", "Input should be a valid dictionary")+ for key, value in body.items():+ _top_level_field(key, value)++ model = body.get("model")+ if model is None:+ raise _required("model")+ if not isinstance(model, str):+ raise _invalid("model", "Input should be a valid string")+ if not model:+ raise _invalid("model", "String should have at least 1 character")+ raw_input = body.get("input")+ if raw_input is None:+ raise _required("input")+ if not isinstance(raw_input, str | list):+ raise _invalid("input", "Input should be a valid string or list")+ if not raw_input and isinstance(raw_input, list):+ raise _invalid("input", "List should have at least 1 item")+ instructions = body.get("instructions")+ if instructions is not None and not isinstance(instructions, str):+ raise _invalid("instructions", "Input should be a valid string")+ max_output_tokens = _max_output_tokens(body.get("max_output_tokens"))+ stream = body.get("stream")+ if stream is None:+ stream = False+ elif not isinstance(stream, bool):+ raise _invalid("stream", "Input should be a valid boolean")+ effort = _reasoning_effort(body.get("reasoning"))+ response_format = _response_format(body.get("text"))+ tools, names, custom_tools = _tools(body.get("tools"))+ tool_choice = _tool_choice(body.get("tool_choice"), names)+ items: list[Any] = [{"role": "user", "content": raw_input}] if isinstance(raw_input, str) else raw_input+ conversation = _Conversation(instructions)+ for index, item in enumerate(items):+ conversation.add(item, f"input[{index}]")++ chat: dict[str, Any] = {"model": model, "messages": conversation.messages()}+ if max_output_tokens is not None:+ chat["max_completion_tokens"] = max_output_tokens+ for key in ("temperature", "top_p", "seed"):+ if body.get(key) is not None:+ chat[key] = body[key]+ chat["stream"] = stream+ if stream:+ chat["stream_options"] = {"include_usage": True}+ if tools:+ chat["tools"] = tools+ if tool_choice is not None:+ chat["tool_choice"] = tool_choice+ parallel_tool_calls = body.get("parallel_tool_calls")+ if parallel_tool_calls is not None:+ chat["parallel_tool_calls"] = parallel_tool_calls+ if response_format is not None:+ chat["response_format"] = response_format+ for key in _PASSTHROUGH_FIELDS:+ if body.get(key) is not None:+ chat[key] = body[key]+ chat["include_reasoning"] = False+ if effort is not None:+ chat["reasoning_effort"] = effort+ requested_choice = body.get("tool_choice")+ shape = ResponseShape(+ model=model,+ parallel_tool_calls=True if parallel_tool_calls is None else parallel_tool_calls,+ tool_choice="auto" if requested_choice is None else requested_choice,+ custom_tools=frozenset(custom_tools),+ )+ return ChatTranslation(chat=chat, stream=stream, shape=shape)+++def _top_level_field(key: str, value: Any) -> None:+ if key in _ACCEPTED_FIELDS:+ return+ if key in ("store", "background"):+ if value is None or value is False:+ return+ if value is not True:+ raise _invalid(key, "Input should be a valid boolean")+ if key == "store":+ raise _unsupported(key, _STATELESS)+ raise _unsupported(key, "background responses are not supported")+ if key in ("previous_response_id", "conversation"):+ if value is not None:+ raise _unsupported(key, _STATELESS)+ return+ if key == "truncation":+ if value is not None and value != "disabled":+ raise _unsupported(key, 'only "disabled" is supported')+ return+ if key == "include":+ _include(value)+ return+ raise _extra(key)+++def _include(value: Any) -> None:+ if value is None:+ return+ if not isinstance(value, list):+ raise _invalid("include", "Input should be a valid list")+ for index, entry in enumerate(value):+ if entry != _ENCRYPTED_REASONING:+ shown = entry if isinstance(entry, str) else json_text(entry)+ raise _unsupported(f"include[{index}]", f"'{shown}' is not supported")+++def _max_output_tokens(value: Any) -> int | None:+ if value is None:+ return None+ if _is_int(value) and 1 <= value <= _U32_MAX:+ return value+ if _is_int(value) and value < 1:+ raise _invalid("max_output_tokens", "Input should be greater than or equal to 1")+ raise _invalid("max_output_tokens", "Input should be a valid integer")+++def _reasoning_effort(value: Any) -> Any:+ if value is None:+ return None+ reasoning = _object(value, "reasoning")+ _only_keys(reasoning, ("effort", "summary", "generate_summary"), "reasoning")+ return reasoning.get("effort")+++def _response_format(value: Any) -> dict[str, Any] | None:+ if value is None:+ return None+ text = _object(value, "text")+ _only_keys(text, ("format", "verbosity"), "text")+ if text.get("format") is None:+ return None+ fmt = _object(text["format"], "text.format")+ kind = _type(fmt, "text.format")+ if kind not in _FORMAT_KEYS:+ raise _unsupported("text.format.type", f"'{kind}' is not supported")+ _only_keys(fmt, _FORMAT_KEYS[kind], "text.format")+ if kind == "text":+ return None+ if kind == "json_object":+ return {"type": "json_object"}+ schema = {key: fmt[key] for key in ("name", "schema", "strict", "description") if fmt.get(key) is not None}+ return {"type": "json_schema", "json_schema": schema}+++def _custom_tool_parameters() -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {"input": {"type": "string"}},+ "required": ["input"],+ "additionalProperties": False,+ }+++def _tools(value: Any) -> tuple[list[dict[str, Any]], list[str], list[str]]:+ """The chat tools, the declared tool names, and the names of the custom tools."""+ if value is None:+ return [], [], []+ if not isinstance(value, list):+ raise _invalid("tools", "Input should be a valid list")+ tools: list[dict[str, Any]] = []+ names: list[str] = []+ custom: list[str] = []+ for index, raw in enumerate(value):+ path = f"tools[{index}]"+ tool = _object(raw, path)+ kind = _type(tool, path)+ if kind not in ("function", "custom"):+ raise _unsupported(f"{path}.type", f"'{kind}' tools are not supported; send function or custom tools")+ if kind == "function":+ _only_keys(tool, _FUNCTION_TOOL_KEYS, path)+ strict = tool.get("strict")+ if strict is True:+ raise _unsupported(f"{path}.strict", "strict function schemas are not supported")+ if strict is not None and strict is not False:+ raise _invalid(f"{path}.strict", "Input should be a valid boolean")+ else:+ _only_keys(tool, _CUSTOM_TOOL_KEYS, path)+ function = {key: tool[key] for key in ("name", "description") if tool.get(key) is not None}+ if kind == "custom":+ function["parameters"] = _custom_tool_parameters()+ elif tool.get("parameters") is not None:+ function["parameters"] = tool["parameters"]+ tools.append({"type": "function", "function": function})+ name = tool.get("name")+ if isinstance(name, str):+ names.append(name)+ if kind == "custom":+ custom.append(name)+ return tools, names, custom+++def _tool_choice(value: Any, names: list[str]) -> Any:+ if value is None:+ return None+ if isinstance(value, str):+ if value not in ("auto", "none", "required"):+ raise _invalid("tool_choice", "Input should be 'auto', 'none' or 'required'")+ if not names and value in ("auto", "none"):+ return None+ return value+ if not isinstance(value, dict):+ raise _invalid("tool_choice", "Input should be a valid string or dictionary")+ kind = _type(value, "tool_choice")+ if kind not in ("function", "custom"):+ raise _unsupported("tool_choice.type", f"'{kind}' is not supported")+ _only_keys(value, ("type", "name"), "tool_choice")+ name = _string(value, "name", "tool_choice")+ if name not in names:+ raise _invalid("tool_choice.name", f"tool '{name}' is not declared in tools")+ return {"type": "function", "function": {"name": name}}+++class _Conversation:+ """The chat messages of a Responses ``input``, built one item at a time.++ A run of assistant output (assistant messages and tool calls) becomes one+ chat assistant message. The images of a run of tool outputs become one chat+ user message after them, joined by the user message that follows the run.+ """++ def __init__(self, instructions: str | None) -> None:+ self._out: list[dict[str, Any]] = []+ self._system: list[str] = [instructions] if instructions else []+ self._leading = True+ self._assistant_text: list[str] | None = None+ self._tool_calls: list[dict[str, Any]] = []+ self._tool_images: list[str] | None = None++ def messages(self) -> list[dict[str, Any]]:+ self._flush_assistant()+ self._flush_tool_images()+ if self._system:+ return [{"role": "system", "content": "\n\n".join(self._system)}, *self._out]+ return list(self._out)++ def add(self, raw: Any, path: str) -> None:+ item = _object(raw, path)+ kind = item.get("type")+ if kind is None:+ if "role" not in item:+ raise _required(f"{path}.role")+ kind = "message"+ if not isinstance(kind, str):+ raise _invalid(f"{path}.type", "Input should be a valid string")+ if kind not in _ITEM_KEYS:+ raise _unsupported(f"{path}.type", f"items of type '{kind}' are not supported")+ _only_keys(item, _ITEM_KEYS[kind], path)+ if kind == "reasoning":+ return+ if kind == "message":+ self._message(item, path)+ elif kind in ("function_call", "custom_tool_call"):+ self._tool_call(item, kind, path)+ else:+ self._tool_output(item, path)++ def _message(self, item: dict[str, Any], path: str) -> None:+ role = item.get("role")+ if role is None:+ raise _required(f"{path}.role")+ if not isinstance(role, str) or role not in _ROLES:+ raise _invalid(f"{path}.role", "Input should be 'user', 'assistant', 'system' or 'developer'")+ parts = _content(item, role, path)+ if _ROLES[role] == "system":+ text = parts.joined_text()+ if self._leading:+ self._system.append(text)+ return+ self._flush_assistant()+ self._flush_tool_images()+ self._out.append({"role": "system", "content": text})+ return+ self._leading = False+ if role == "assistant":+ self._flush_tool_images()+ if self._assistant_text is None:+ self._assistant_text = []+ self._assistant_text.append(parts.joined_text())+ return+ self._flush_assistant()+ if self._tool_images:+ merged = _Parts()+ for url in self._tool_images:+ merged.image(url)+ for kind, value in parts.items():+ if kind == "text":+ merged.text(value)+ else:+ merged.image(value)+ parts = merged+ self._tool_images = None+ self._out.append({"role": "user", "content": parts.content()})++ def _tool_call(self, item: dict[str, Any], kind: str, path: str) -> None:+ self._leading = False+ self._flush_tool_images()+ call_id = _string(item, "call_id", path)+ name = _string(item, "name", path)+ if kind == "function_call":+ arguments = _string(item, "arguments", path)+ else:+ arguments = json_text({"input": _string(item, "input", path)})+ if self._assistant_text is None:+ self._assistant_text = []+ self._tool_calls.append({"id": call_id, "type": "function", "function": {"name": name, "arguments": arguments}})++ def _tool_output(self, item: dict[str, Any], path: str) -> None:+ self._leading = False+ self._flush_assistant()+ call_id = _string(item, "call_id", path)+ text, images = _tool_output(item.get("output"), path)+ self._out.append({"role": "tool", "tool_call_id": call_id, "content": text})+ if self._tool_images is None:+ self._tool_images = []+ self._tool_images.extend(images)++ def _flush_assistant(self) -> None:+ if self._assistant_text is None:+ return+ text = "".join(self._assistant_text)+ if self._tool_calls:+ self._out.append({"role": "assistant", "content": text or None, "tool_calls": self._tool_calls})+ else:+ self._out.append({"role": "assistant", "content": text})+ self._assistant_text = None+ self._tool_calls = []++ def _flush_tool_images(self) -> None:+ if self._tool_images:+ parts = _Parts()+ for url in self._tool_images:+ parts.image(url)+ self._out.append({"role": "user", "content": parts.content()})+ self._tool_images = None+++def _content(item: dict[str, Any], role: str, path: str) -> _Parts:+ content = item.get("content")+ if content is None:+ raise _required(f"{path}.content")+ parts = _Parts()+ if isinstance(content, str):+ parts.text(content)+ return parts+ if not isinstance(content, list):+ raise _invalid(f"{path}.content", "Input should be a valid string or list")+ for index, raw in enumerate(content):+ part_path = f"{path}.content[{index}]"+ part = _object(raw, part_path)+ kind = _type(part, part_path)+ if kind in _TEXT_PART_KEYS:+ _only_keys(part, _TEXT_PART_KEYS[kind], part_path)+ parts.text(_string(part, "text", part_path))+ elif kind == "input_image":+ if role != "user":+ raise _unsupported(+ f"{part_path}.type", "parts of type 'input_image' are only supported in user messages"+ )+ parts.image(_image(part, part_path))+ else:+ raise _unsupported(f"{part_path}.type", f"parts of type '{kind}' are not supported")+ return parts+++def _image(part: dict[str, Any], path: str) -> str:+ _only_keys(part, _IMAGE_KEYS, path)+ if part.get("file_id") is not None:+ raise _unsupported(f"{path}.file_id", "only base64 data: URLs are supported")+ url = part.get("image_url")+ if url is None:+ raise _required(f"{path}.image_url")+ if not isinstance(url, str):+ raise _invalid(f"{path}.image_url", "Input should be a valid string")+ if not url.startswith("data:"):+ raise _unsupported(f"{path}.image_url", "only base64 data: URLs are supported")+ return url+++def _tool_output(output: Any, path: str) -> tuple[str, list[str]]:+ if output is None:+ raise _required(f"{path}.output")+ if isinstance(output, str):+ return output, []+ if not isinstance(output, list):+ raise _invalid(f"{path}.output", "Input should be a valid string or list")+ texts: list[str] = []+ images: list[str] = []+ for index, raw in enumerate(output):+ part_path = f"{path}.output[{index}]"+ part = _object(raw, part_path)+ kind = _type(part, part_path)+ if kind in _TEXT_PART_KEYS:+ _only_keys(part, _TEXT_PART_KEYS[kind], part_path)+ texts.append(_string(part, "text", part_path))+ elif kind == "input_image":+ images.append(_image(part, part_path))+ else:+ raise _unsupported(f"{part_path}.type", f"parts of type '{kind}' are not supported")+ return "".join(texts), images+++def custom_tool_input(arguments: str) -> str:+ """The input of a custom-tool call: ``arguments.input``, or the raw arguments when they carry none."""+ try:+ parsed = parse_json(arguments)+ except ValueError:+ return arguments+ if isinstance(parsed, dict) and isinstance(parsed.get("input"), str):+ return parsed["input"]+ return arguments+++def responses_usage(usage: Any) -> dict[str, Any] | None:+ """Responses usage from a chat usage block."""+ if not isinstance(usage, dict):+ return None+ counts = [usage.get(key) for key in ("prompt_tokens", "completion_tokens", "total_tokens")]+ if not all(_is_int(count) for count in counts):+ return None+ prompt_details = usage.get("prompt_tokens_details")+ completion_details = usage.get("completion_tokens_details")+ cached = prompt_details.get("cached_tokens") if isinstance(prompt_details, dict) else None+ reasoning = completion_details.get("reasoning_tokens") if isinstance(completion_details, dict) else None+ return {+ "input_tokens": counts[0],+ "input_tokens_details": {"cached_tokens": cached if _is_int(cached) else 0},+ "output_tokens": counts[1],+ "output_tokens_details": {"reasoning_tokens": reasoning if _is_int(reasoning) else 0},+ "total_tokens": counts[2],+ }+++def _status(finish_reason: Any) -> tuple[str, dict[str, str] | None]:+ if finish_reason == "length":+ return "incomplete", {"reason": "max_output_tokens"}+ if finish_reason == "content_filter":+ return "incomplete", {"reason": "content_filter"}+ return "completed", None+++def response_object(+ shape: ResponseShape,+ request_id: str,+ created_at: int,+ *,+ status: str,+ output: list[dict[str, Any]],+ usage: dict[str, Any] | None = None,+ incomplete_details: dict[str, str] | None = None,+ error: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """A Response object for the request ``shape`` describes."""+ return {+ "id": f"resp-{request_id}",+ "object": "response",+ "created_at": created_at,+ "model": shape.model,+ "status": status,+ "incomplete_details": incomplete_details,+ "error": error,+ "store": False,+ "parallel_tool_calls": shape.parallel_tool_calls,+ "tool_choice": shape.tool_choice,+ "output": output,+ "usage": usage,+ }+++def _message_item(item_id: str, text: str | None) -> dict[str, Any]:+ """A message item, ``in_progress`` and empty while ``text`` is None."""+ return {+ "type": "message",+ "id": item_id,+ "role": "assistant",+ "status": "in_progress" if text is None else "completed",+ "content": [] if text is None else [{"type": "output_text", "text": text, "annotations": []}],+ }+++def _call_item(item_id: str, call_id: str, name: str, value: str, *, custom: bool, done: bool) -> dict[str, Any]:+ if custom:+ payload = {"type": "custom_tool_call", "id": item_id, "call_id": call_id, "name": name, "input": value}+ else:+ payload = {"type": "function_call", "id": item_id, "call_id": call_id, "name": name, "arguments": value}+ return {**payload, "status": "completed" if done else "in_progress"}+++def _call_item_id(request_id: str, position: int, *, custom: bool) -> str:+ return f"{'ctc' if custom else 'fc'}-{request_id}-{position}"+++def chat_completion_to_response(chat: Any, shape: ResponseShape, request_id: str, created_at: int) -> dict[str, Any]:+ """Translate a chat completion into a Response.++ ``request_id`` names the Response and its items; ``created_at`` is its+ creation time in Unix seconds.++ Raises:+ ValueError: The chat completion cannot be translated.+ """+ choices = chat.get("choices") if isinstance(chat, dict) else None+ if not isinstance(choices, list) or not choices:+ raise ValueError("chat completion has no choices")+ choice = choices[0]+ if not isinstance(choice, dict) or not isinstance(choice.get("message"), dict):+ raise ValueError("chat completion choice has no message")+ message = choice["message"]+ output: list[dict[str, Any]] = []+ content = message.get("content")+ if isinstance(content, str) and content:+ output.append(_message_item(f"msg-{request_id}", content))+ tool_calls = message.get("tool_calls")+ for position, call in enumerate(tool_calls if isinstance(tool_calls, list) else []):+ function = call.get("function") if isinstance(call, dict) else None+ call_id = call.get("id") if isinstance(call, dict) else None+ name = function.get("name") if isinstance(function, dict) else None+ if not isinstance(call_id, str) or not isinstance(name, str):+ raise ValueError("tool call has no id or name")+ arguments = function.get("arguments") if isinstance(function, dict) else None+ arguments = arguments if isinstance(arguments, str) else ""+ custom = name in shape.custom_tools+ value = custom_tool_input(arguments) if custom else arguments+ item_id = _call_item_id(request_id, position, custom=custom)+ output.append(_call_item(item_id, call_id, name, value, custom=custom, done=True))+ status, incomplete = _status(choice.get("finish_reason"))+ return response_object(+ shape,+ request_id,+ created_at,+ status=status,+ incomplete_details=incomplete,+ output=output,+ usage=responses_usage(chat.get("usage")),+ )+++@dataclass(frozen=True)+class Event:+ """One Responses SSE event."""++ name: str+ data: dict[str, Any]++ def encode(self) -> bytes:+ return f"event: {self.name}\ndata: {json_text(self.data)}\n\n".encode()+++@dataclass+class _OpenText:+ output_index: int+ item_id: str+ text: str = ""+++@dataclass+class _OpenCall:+ chat_index: int+ position: int+ output_index: int+ item_id: str+ call_id: str+ name: str+ custom: bool+ arguments: str = ""+++class StreamMachine:+ """The chat-chunk to Responses-event state machine.++ One output item is open at a time and output indices are contiguous from 0.+ """++ def __init__(self, shape: ResponseShape, request_id: str, created_at: int) -> None:+ self._shape = shape+ self._request_id = request_id+ self._created_at = created_at+ self._sequence = 0+ self._next_index = 0+ self._output: list[dict[str, Any]] = []+ self._text: _OpenText | None = None+ self._call: _OpenCall | None = None+ self._calls = 0+ self._closed_calls: set[int] = set()+ self._finish_reason: str | None = None+ self._usage: dict[str, Any] | None = None+ self._started = False+ self.done = False+ """Whether the terminal event has been produced."""++ def start(self) -> list[Event]:+ """``response.created`` and ``response.in_progress``, sent as soon as the chat stream opens."""+ if self._started:+ return []+ self._started = True+ return [+ self._event("response.created", response=self._response("in_progress")),+ self._event("response.in_progress", response=self._response("in_progress")),+ ]++ def on_data(self, data: str) -> list[Event]:+ """Feed one chat SSE ``data`` payload."""+ events = self.start()+ if self.done:+ return events+ if data == "[DONE]":+ self._terminal(events)+ return events+ try:+ chunk = parse_json(data)+ except ValueError:+ self._fail(events, "server_error", "the generation stream sent a malformed chunk")+ return events+ if not isinstance(chunk, dict):+ chunk = {}+ error = chunk.get("error")+ if isinstance(error, dict):+ self._fail(events, error.get("code"), error.get("message"))+ return events+ usage = responses_usage(chunk.get("usage"))+ if usage is not None:+ self._usage = usage+ choices = chunk.get("choices")+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):+ return events+ choice = choices[0]+ delta = choice.get("delta") if isinstance(choice.get("delta"), dict) else {}+ text = delta.get("content")+ if isinstance(text, str) and text:+ self._text_delta(text, events)+ calls = delta.get("tool_calls")+ for call in calls if isinstance(calls, list) else []:+ problem = self._call_delta(call, events)+ if problem is not None:+ self._fail(events, "server_error", problem)+ return events+ finish_reason = choice.get("finish_reason")+ if isinstance(finish_reason, str):+ self._finish_reason = finish_reason+ self._close_text(events)+ self._close_call(events)+ return events++ def on_end(self) -> list[Event]:+ """The chat stream ended. A stream that reported a finish completes; any other ending fails."""+ events = self.start()+ if not self.done:+ self._terminal(events)+ return events++ def on_transport_error(self) -> list[Event]:+ """The chat stream broke before it ended."""+ events = self.start()+ if not self.done:+ self._fail(events, "server_error", "the generation stream ended unexpectedly")+ return events++ def _event(self, name: str, **payload: Any) -> Event:+ event = Event(name, {"type": name, "sequence_number": self._sequence, **payload})+ self._sequence += 1+ return event++ def _response(self, status: str, **fields: Any) -> dict[str, Any]:+ output = list(self._output) if status != "in_progress" else []+ return response_object(self._shape, self._request_id, self._created_at, status=status, output=output, **fields)++ def _terminal(self, events: list[Event]) -> None:+ if self._finish_reason is None:+ self._fail(events, "server_error", "the generation stream ended without a finish reason")+ return+ self._close_text(events)+ self._close_call(events)+ status, incomplete = _status(self._finish_reason)+ name = "response.completed" if status == "completed" else "response.incomplete"+ response = self._response(status, incomplete_details=incomplete, usage=self._usage)+ events.append(self._event(name, response=response))+ self.done = True++ def _fail(self, events: list[Event], code: Any, message: Any) -> None:+ response = self._response("failed", error={"code": code, "message": message})+ events.append(self._event("response.failed", response=response))+ self.done = True++ def _text_delta(self, text: str, events: list[Event]) -> None:+ self._close_call(events)+ if self._text is None:+ index = self._next_index+ self._next_index += 1+ item_id = f"msg-{self._request_id}" if self._calls == 0 else f"msg-{self._request_id}-{index}"+ self._text = _OpenText(index, item_id)+ events.append(+ self._event("response.output_item.added", output_index=index, item=_message_item(item_id, None))+ )+ events.append(+ self._event(+ "response.content_part.added",+ item_id=item_id,+ output_index=index,+ content_index=0,+ part={"type": "output_text", "text": "", "annotations": []},+ )+ )+ self._text.text += text+ events.append(+ self._event(+ "response.output_text.delta",+ item_id=self._text.item_id,+ output_index=self._text.output_index,+ content_index=0,+ delta=text,+ )+ )++ def _close_text(self, events: list[Event]) -> None:+ if self._text is None:+ return+ opened, self._text = self._text, None+ item_id, index, text = opened.item_id, opened.output_index, opened.text+ part = {"type": "output_text", "text": text, "annotations": []}+ item = _message_item(item_id, text)+ events.append(+ self._event("response.output_text.done", item_id=item_id, output_index=index, content_index=0, text=text)+ )+ events.append(+ self._event("response.content_part.done", item_id=item_id, output_index=index, content_index=0, part=part)+ )+ events.append(self._event("response.output_item.done", output_index=index, item=item))+ self._output.append(item)++ def _call_delta(self, call: Any, events: list[Event]) -> str | None:+ call = call if isinstance(call, dict) else {}+ index = call.get("index")+ chat_index = index if isinstance(index, int) and not isinstance(index, bool) else 0+ function = call.get("function")+ function = function if isinstance(function, dict) else {}+ fragment = function.get("arguments")+ fragment = fragment if isinstance(fragment, str) else ""+ if self._call is None or self._call.chat_index != chat_index:+ if chat_index in self._closed_calls:+ return "tool call arguments arrived after another output item started" if fragment else None+ call_id = call.get("id")+ name = function.get("name")+ if not isinstance(call_id, str) or not isinstance(name, str):+ return "a tool call arrived without its id and name"+ self._close_text(events)+ self._close_call(events)+ custom = name in self._shape.custom_tools+ item_id = _call_item_id(self._request_id, self._calls, custom=custom)+ self._call = _OpenCall(chat_index, self._calls, self._next_index, item_id, call_id, name, custom)+ self._calls += 1+ self._next_index += 1+ item = _call_item(item_id, call_id, name, "", custom=custom, done=False)+ events.append(self._event("response.output_item.added", output_index=self._call.output_index, item=item))+ if not fragment:+ return None+ self._call.arguments += fragment+ if not self._call.custom:+ events.append(+ self._event(+ "response.function_call_arguments.delta",+ item_id=self._call.item_id,+ output_index=self._call.output_index,+ delta=fragment,+ )+ )+ return None++ def _close_call(self, events: list[Event]) -> None:+ if self._call is None:+ return+ opened, self._call = self._call, None+ item_id, index = opened.item_id, opened.output_index+ if opened.custom:+ value = custom_tool_input(opened.arguments)+ events.append(+ self._event("response.custom_tool_call_input.delta", item_id=item_id, output_index=index, delta=value)+ )+ events.append(+ self._event("response.custom_tool_call_input.done", item_id=item_id, output_index=index, input=value)+ )+ else:+ value = opened.arguments+ events.append(+ self._event(+ "response.function_call_arguments.done", item_id=item_id, output_index=index, arguments=value+ )+ )+ item = _call_item(item_id, opened.call_id, opened.name, value, custom=opened.custom, done=True)+ events.append(self._event("response.output_item.done", output_index=index, item=item))+ self._output.append(item)+ self._closed_calls.add(opened.chat_index)+++class FrameParser:+ """Splits an SSE byte stream into its events.++ Each event is ``("data", payload)``, or ``("comment", frame)`` for an event+ that carries only comments, such as a keep-alive.+ """++ def __init__(self) -> None:+ self._buffer = bytearray()++ def push(self, chunk: bytes) -> list[tuple[str, str]]:+ self._buffer.extend(chunk.replace(b"\r", b""))+ frames: list[tuple[str, str]] = []+ while (end := self._buffer.find(b"\n\n")) >= 0:+ text = bytes(self._buffer[:end]).decode("utf-8", errors="replace")+ del self._buffer[: end + 2]+ lines = text.split("\n")+ data = [line[len("data:") :].removeprefix(" ") for line in lines if line.startswith("data:")]+ if data:+ frames.append(("data", "\n".join(data)))+ continue+ comments = [line for line in lines if line.startswith(":")]+ if comments:+ frames.append(("comment", "\n".join(comments) + "\n\n"))+ return frames+++async def stream_events(chunks: AsyncIterator[bytes], machine: StreamMachine) -> AsyncIterator[bytes]:+ """The Responses SSE body for a chat SSE body.++ The chat body's comments pass through. The terminal event ends the body+ and closes ``chunks``, so a stream that failed stops generating, as a+ client that goes away does.+ """+ parser = FrameParser()+ try:+ for event in machine.start():+ yield event.encode()+ while not machine.done:+ try:+ chunk = await anext(chunks)+ except StopAsyncIteration:+ for event in machine.on_end():+ yield event.encode()+ return+ except Exception: # noqa: BLE001 - any failure of the chat body fails the response+ for event in machine.on_transport_error():+ yield event.encode()+ return+ for kind, frame in parser.push(chunk):+ if kind == "comment":+ yield frame.encode()+ continue+ for event in machine.on_data(frame):+ yield event.encode()+ if machine.done:+ return+ finally:+ close = getattr(chunks, "aclose", None)+ if close is not None:+ await close()+++def responses_param(param: str) -> str:+ """The Responses field a chat error ``param`` names."""+ renamed = _PARAM_RENAMES.get(param)+ if renamed is not None:+ return renamed+ if param.startswith(_SCHEMA_PARAM_PREFIX) and len(param) > len(_SCHEMA_PARAM_PREFIX):+ return f"text.format.{param[len(_SCHEMA_PARAM_PREFIX) :]}"+ match = _TOOL_PARAM.fullmatch(param)+ if match is not None:+ return f"tools[{match.group(1)}].{match.group(2)}"+ return param+++def responses_error(headers: Iterable[tuple[str, str]], body: bytes) -> tuple[list[tuple[str, str]], bytes]:+ """A chat error answer as the Responses route returns it, at the same status.++ The headers are kept, ``Retry-After`` and ``x-sie-error-code`` among them,+ and so is the body, except that a ``param`` naming a chat field is renamed+ to the Responses field the caller sent.+ """+ kept = [(name.lower(), value) for name, value in headers if name.lower() != "content-length"]+ try:+ parsed = parse_json(body)+ except (ValueError, UnicodeDecodeError):+ return kept, body+ error = parsed.get("error") if isinstance(parsed, dict) else None+ if not isinstance(error, dict) or not isinstance(error.get("param"), str):+ return kept, body+ renamed = responses_param(error["param"])+ if renamed == error["param"]:+ return kept, body+ return kept, json_text({**parsed, "error": {**error, "param": renamed}}).encode()diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex 2a96c4616..75c1902dd 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -445,7 +445,6 @@ def openapi_export(from sie_server.api.models import router as models_routerfrom sie_server.api.openai_compat import router as openai_routerfrom sie_server.api.openai_completions import router as openai_completions_router- from sie_server.api.openai_responses import router as openai_responses_routerfrom sie_server.api.openapi import setup_custom_openapi_schemafrom sie_server.api.root import router as root_routerfrom sie_server.api.score import router as score_router@@ -456,8 +455,8 @@ def openapi_export(# init, model registry, telemetry, or NATS). NOTE: the direct-container convenience routes# are intentionally excluded from the committed openapi.json — the ``openai_local`` router# (/v1/chat/completions + /v1/rerank) proxies managed MLX/SGLang children for single-node- # serving, and /v1/messages is translated onto it, while the Rust gateway owns the- # published production chat and Messages contracts. The+ # serving, and /v1/messages and /v1/responses are translated onto it, while the Rust+ # gateway owns the published production chat, Messages and Responses contracts. The# SIE-native ``generate`` route is part of the worker contract and is published here.app_ = FastAPI(title="SIE Server",@@ -475,7 +474,6 @@ def openapi_export(app_.include_router(openai_audio_router)app_.include_router(openai_router)app_.include_router(openai_completions_router)- app_.include_router(openai_responses_router)app_.include_router(systemone_router)app_.include_router(decisions_router)setup_custom_openapi_schema(app_)diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.pyindex 41e0a5998..c91c3d109 100644--- a/packages/sie_server/src/sie_server/types/openapi.py+++ b/packages/sie_server/src/sie_server/types/openapi.py@@ -604,84 +604,6 @@ class OpenAICompletionResponseModel(BaseModel):usage: GenerateUsageModel-class OpenAIResponseInputContentPartModel(BaseModel):- """One text-only content part accepted by the Responses MVP."""-- type: Literal["text", "input_text", "output_text"]- text: str- model_config = {"extra": "forbid"}---class OpenAIResponseInputMessageModel(BaseModel):- """One stateless text message accepted by the Responses MVP."""-- role: Literal["system", "user", "assistant", "developer"]- content: str | list[OpenAIResponseInputContentPartModel]- model_config = {"extra": "forbid"}---class OpenAIResponsesRequestModel(BaseModel):- """Strict stateless, text-only subset of the OpenAI Responses API."""-- model: str = Field(..., min_length=1, description="Generation model id")- input: str | Annotated[list[OpenAIResponseInputMessageModel], Field(min_length=1)]- max_output_tokens: int | None = Field(- default=16,- ge=1,- le=(1 << 32) - 1,- description="Maximum generated tokens",- )- temperature: float | None = Field(- default=None,- ge=0,- le=3.4028234663852886e38,- description="Sampling temperature override",- )- top_p: float | None = Field(default=None, gt=0, le=1, description="Nucleus-sampling probability override")- seed: int | None = Field(- default=None,- ge=-(1 << 63),- le=(1 << 63) - 1,- description="Optional signed 64-bit sampling seed",- json_schema_extra={"format": "int64"},- )- stream: Literal[False] | None = Field(default=None, description="Responses streaming is not supported")- model_config = {"extra": "forbid"}---class OpenAIResponseOutputTextModel(BaseModel):- type: Literal["output_text"]- text: str- annotations: list[dict[str, Any]]---class OpenAIResponseOutputMessageModel(BaseModel):- type: Literal["message"]- id: str- role: Literal["assistant"]- status: Literal["completed"]- content: list[OpenAIResponseOutputTextModel]---class OpenAIResponseUsageModel(BaseModel):- input_tokens: int = Field(..., ge=0)- output_tokens: int = Field(..., ge=0)- total_tokens: int = Field(..., ge=0)- input_tokens_details: PromptTokensDetailsModel | None = None---class OpenAIResponsesResponseModel(BaseModel):- """One completed direct OpenAI Responses result."""-- id: str- object: Literal["response"]- created_at: int- model: str- status: Literal["completed"]- output: list[OpenAIResponseOutputMessageModel]- usage: OpenAIResponseUsageModel--class GenerateInputTooLongDetailModel(BaseModel):"""Detail returned when a generation prompt exceeds the worker limit."""diff --git a/packages/sie_server/tests/api/test_generation_timeouts.py b/packages/sie_server/tests/api/test_generation_timeouts.pyindex d8898035c..e6853fb29 100644--- a/packages/sie_server/tests/api/test_generation_timeouts.py+++ b/packages/sie_server/tests/api/test_generation_timeouts.py@@ -15,7 +15,6 @@ from sie_server.adapters._generation_base import GenerationChunkfrom sie_server.adapters.fake.adapter import FakeAdapterfrom sie_server.api.generate import router as generate_routerfrom sie_server.api.openai_completions import router as completions_router-from sie_server.api.openai_responses import router as responses_routerfrom sie_server.config.model import AdapterOptions, GenerateTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.registry import ModelRegistry@@ -67,7 +66,6 @@ def _client(adapter: FakeAdapter, runtime: dict[str, float]) -> TestClient:app = FastAPI()app.include_router(generate_router)app.include_router(completions_router)- app.include_router(responses_router)app.state.registry = registryreturn TestClient(app)@@ -83,7 +81,6 @@ def _openai_code(body: dict[str, Any]) -> str:_ROUTES: list[tuple[str, dict[str, Any], Callable[[dict[str, Any]], str]]] = [(f"/v1/generate/{_MODEL.replace('/', '__')}", {"prompt": "hello", "max_new_tokens": 8}, _native_code),("/v1/completions", {"model": _MODEL, "prompt": "hello", "max_tokens": 8}, _openai_code),- ("/v1/responses", {"model": _MODEL, "input": "hello", "max_output_tokens": 8}, _openai_code),]diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex 0036add34..98f871445 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -3107,7 +3107,12 @@ def test_mlx_messages_refuse_a_prompt_over_the_window_with_the_compaction_wordin}-_IGNORED_OPENAI_FIELDS = {"metadata": {"run": "eval-7"}, "store": True, "service_tier": "auto"}+_IGNORED_OPENAI_FIELDS = {+ "metadata": {"run": "eval-7"},+ "store": True,+ "service_tier": "auto",+ "prompt_cache_key": "session-1",+}def _chat_client_for(@@ -3120,7 +3125,7 @@ def _chat_client_for(@pytest.mark.parametrize("engine", ["cuda", "mlx"])@pytest.mark.parametrize("extra", [_IGNORED_OPENAI_FIELDS, dict.fromkeys(_IGNORED_OPENAI_FIELDS)])-def test_chat_accepts_and_drops_metadata_store_service_tier(+def test_chat_accepts_and_drops_the_ignored_openai_fields(monkeypatch: pytest.MonkeyPatch, engine: str, extra: dict[str, Any]) -> None:forwarded: list[dict[str, Any]] = []@@ -3158,9 +3163,14 @@ def test_chat_accepts_and_drops_metadata_store_service_tier(@pytest.mark.parametrize("engine", ["cuda", "mlx"])@pytest.mark.parametrize(("field", "value", "expected"),- [("metadata", "run", "an object"), ("store", "yes", "a boolean"), ("service_tier", 1, "a string")],+ [+ ("metadata", "run", "an object"),+ ("store", "yes", "a boolean"),+ ("service_tier", 1, "a string"),+ ("prompt_cache_key", 1, "a string"),+ ],)-def test_chat_rejects_wrongly_typed_metadata_store_service_tier(+def test_chat_rejects_wrongly_typed_ignored_openai_fields(monkeypatch: pytest.MonkeyPatch, engine: str, field: str, value: Any, expected: str) -> None:client = _chat_client_for(diff --git a/packages/sie_server/tests/api/test_openai_responses.py b/packages/sie_server/tests/api/test_openai_responses.pydeleted file mode 100644index a198097c4..000000000--- a/packages/sie_server/tests/api/test_openai_responses.py+++ /dev/null@@ -1,484 +0,0 @@-"""Regression tests for direct ``/v1/responses`` generation."""--from __future__ import annotations--import json-from collections.abc import AsyncIterator, Mapping-from pathlib import Path-from unittest.mock import AsyncMock, MagicMock--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient-from sie_server.adapters._generation_base import (- GenerationAdapter,- GenerationCapacityError,- GenerationChunk,- GenerationError,- GenerationUnsupportedFieldError,-)-from sie_server.adapters._spec import AdapterSpec-from sie_server.api import openai_responses-from sie_server.api.openai_completions import _CompletionError-from sie_server.config.model import AdapterOptions, GenerateTask, ModelConfig, ProfileConfig, Tasks-from sie_server.core.registry import ModelRegistry-from sie_server.types.grammar import GrammarSpec-from sie_server.types.inputs import ImageInput--_VECTORS = Path(__file__).parents[4] / "conformance" / "openai_generation" / "responses_request_vectors.json"---class _UntrustedUnsupportedFieldError(GenerationUnsupportedFieldError):- code = "SENSITIVE_UNSUPPORTED_CODE"---class _UntrustedCapacityError(GenerationCapacityError):- code = "SENSITIVE_CAPACITY_CODE"---class _FakeResponsesAdapter(GenerationAdapter):- spec = AdapterSpec(inputs=("text",), outputs=("tokens",), unload_fields=())-- def __init__(self) -> None:- self.last_call: dict[str, object] | None = None- self.preflight_call: dict[str, object] | None = None- self.preflight_error: GenerationError | None = None- self.generate_error_after_chunks: int | None = None- self.closed = False- self.text_chunks = ["hello", " world"]- self.include_usage = True- self.error_code: str | None = None- self.error_message: str | None = None- self.cached_tokens: int | None = None-- def load(self, device: str) -> None: # pragma: no cover - registry is mocked loaded- _ = device-- def preflight_generate(self, parameters: Mapping[str, object], *, stream: bool) -> None:- assert stream is False- self.preflight_call = dict(parameters)- if self.preflight_error is not None:- raise self.preflight_error-- async def generate(- self,- prompt: str,- *,- max_new_tokens: int,- temperature: float = 1.0,- top_p: float = 1.0,- stop: list[str] | None = None,- frequency_penalty: float | None = None,- presence_penalty: float | None = None,- top_k: int | None = None,- repetition_penalty: float | None = None,- min_new_tokens: int | None = None,- grammar: GrammarSpec | None = None,- seed: int | None = None,- logit_bias: dict[str, float] | None = None,- logprobs: bool = False,- top_logprobs: int | None = None,- images: list[ImageInput] | None = None,- ) -> AsyncIterator[GenerationChunk]:- self.last_call = {- "prompt": prompt,- "max_new_tokens": max_new_tokens,- "temperature": temperature,- "top_p": top_p,- "stop": stop,- "frequency_penalty": frequency_penalty,- "presence_penalty": presence_penalty,- "top_k": top_k,- "min_new_tokens": min_new_tokens,- "seed": seed,- }- _ = repetition_penalty, grammar, logit_bias, logprobs, top_logprobs, images- try:- if self.generate_error_after_chunks == 0:- raise GenerationUnsupportedFieldError("top_k")- for index, text in enumerate(self.text_chunks):- yield GenerationChunk(text_delta=text, is_first=index == 0)- if self.generate_error_after_chunks == index + 1:- raise GenerationUnsupportedFieldError("top_k")- yield GenerationChunk(- text_delta="",- done=True,- finish_reason="stop",- prompt_tokens=3 if self.include_usage else None,- completion_tokens=2 if self.include_usage else None,- cached_tokens=self.cached_tokens,- error_code=self.error_code,- error_message=self.error_message,- )- finally:- self.closed = True---def _config(*, chat_template_kwargs: dict[str, object] | None = None) -> ModelConfig:- return ModelConfig(- sie_id="Qwen/Qwen3-4B-Instruct",- hf_id="Qwen/Qwen3-4B-Instruct",- tasks=Tasks(- generate=GenerateTask(- context_length=32768,- max_output_tokens=64,- chat_template_kwargs=chat_template_kwargs or {},- )- ),- profiles={- "default": ProfileConfig(- adapter_path="test:FakeResponsesAdapter",- max_batch_tokens=8192,- kv_budget_tokens=4096,- adapter_options=AdapterOptions(- loadtime={"reasoning_parser": "qwen3"},- runtime={- "default_sampling": {- "temperature": 0.25,- "top_p": 0.8,- "top_k": 12,- "min_new_tokens": 2,- "seed": 23,- },- "stop_tokens": ["</s>"],- },- ),- )- },- )---def adapter() -> _FakeResponsesAdapter:- return _FakeResponsesAdapter()---def registry(adapter: _FakeResponsesAdapter) -> MagicMock:- reg = MagicMock(spec=ModelRegistry)- reg.has_model.return_value = True- reg.is_loaded.return_value = True- reg.is_loading.return_value = False- reg.is_unloading.return_value = False- reg.is_failed.return_value = False- reg.get_failure.return_value = None- reg.get_config.return_value = _config()- reg.get.return_value = adapter- reg.device = "cpu"- return reg---def client(registry: MagicMock) -> TestClient:- app = FastAPI()- app.include_router(openai_responses.router)- app.state.registry = registry- return TestClient(app)---def test_blocking_responses_uses_direct_adapter_and_openai_shape(- client: TestClient,- adapter: _FakeResponsesAdapter,-) -> None:- response = client.post(- "/v1/responses",- json={- "model": "Qwen/Qwen3-4B-Instruct",- "input": "Say hello",- "max_output_tokens": 8,- "temperature": 0.5,- "seed": -1,- },- )-- assert response.status_code == 200, response.text- body = response.json()- assert body["id"].startswith("resp-")- assert body["object"] == "response"- assert body["status"] == "completed"- assert body["model"] == "Qwen/Qwen3-4B-Instruct"- assert body["output"][0]["content"] == [{"type": "output_text", "text": "hello world", "annotations": []}]- assert body["usage"] == {"input_tokens": 3, "output_tokens": 2, "total_tokens": 5}- assert adapter.last_call == {- "prompt": "Say hello",- "max_new_tokens": 8,- "temperature": 0.5,- "top_p": 0.8,- "stop": ["</s>"],- "frequency_penalty": None,- "presence_penalty": None,- "top_k": 12,- "min_new_tokens": 2,- "seed": -1,- }- assert adapter.preflight_call == adapter.last_call---def test_message_input_uses_model_native_template(- client: TestClient,- adapter: _FakeResponsesAdapter,- monkeypatch: pytest.MonkeyPatch,-) -> None:- render = AsyncMock(return_value="<rendered>Hi there</rendered>")- monkeypatch.setattr(openai_responses, "_render_native_messages_prompt", render)-- response = client.post(- "/v1/responses",- json={- "model": "Qwen/Qwen3-4B-Instruct",- "input": [- {"role": "developer", "content": "Be concise"},- {- "role": "user",- "content": [- {"type": "input_text", "text": "Hi "},- {"type": "text", "text": "there"},- ],- },- ],- },- )-- assert response.status_code == 200, response.text- render.assert_awaited_once()- assert render.await_args.args[1] == [- {"role": "system", "content": "Be concise"},- {"role": "user", "content": "Hi there"},- ]- assert adapter.last_call is not None- assert adapter.last_call["prompt"] == "<rendered>Hi there</rendered>"---def test_responses_hides_family_reasoning_without_changing_usage(- client: TestClient,- registry: MagicMock,- adapter: _FakeResponsesAdapter,-) -> None:- registry.get_config.return_value = _config(chat_template_kwargs={"enable_thinking": True})- adapter.text_chunks = ["<thi", "nk>private</think>answer"]-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == 200, response.text- body = response.json()- assert body["output"][0]["content"][0]["text"] == "answer"- assert body["usage"] == {"input_tokens": 3, "output_tokens": 2, "total_tokens": 5}---def test_responses_usage_reports_cached_input_tokens(- client: TestClient,- adapter: _FakeResponsesAdapter,-) -> None:- adapter.cached_tokens = 2-- response = client.post("/v1/responses", json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"})-- assert response.status_code == 200, response.text- assert response.json()["usage"] == {- "input_tokens": 3,- "output_tokens": 2,- "total_tokens": 5,- "input_tokens_details": {"cached_tokens": 2},- }---def test_shared_responses_request_conformance_vectors() -> None:- vectors = json.loads(_VECTORS.read_text())-- for case in vectors["accepted"]:- params = openai_responses._parse_params(case["body"])- observed = {- "model": params.model,- "prompt": params.prompt,- "messages": params.messages,- "max_output_tokens": params.max_output_tokens,- "temperature": params.temperature,- "top_p": params.top_p,- "seed": params.seed,- }- assert observed == case["expected"], case["name"]-- for case in vectors["rejected"]:- with pytest.raises(_CompletionError) as exc_info:- openai_responses._parse_params(case["body"])- assert exc_info.value.param == case["param"], case["name"]- assert exc_info.value.code == case["code"], case["name"]---def test_responses_rejects_model_output_cap(client: TestClient) -> None:- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x", "max_output_tokens": 65},- )-- assert response.status_code == 400- assert response.json()["error"]["param"] == "max_output_tokens"---def test_responses_rejects_terminal_event_without_usage(- client: TestClient,- adapter: _FakeResponsesAdapter,-) -> None:- adapter.include_usage = False-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == 500- assert response.json()["error"]["code"] == "malformed_worker_response"--- ("code", "message", "expected_code", "expected_message"),- [- (- "inference_error",- "SENSITIVE_RESPONSES_RUNTIME",- "inference_error",- "internal error during generation",- ),- (- "grammar_compile_failed",- "SENSITIVE_RESPONSES_GRAMMAR",- "grammar_compile_failed",- "internal error compiling grammar",- ),- (- "empty_model_output",- "model produced no visible output",- "empty_model_output",- "model produced no visible output",- ),- (- "SENSITIVE_RESPONSES_ERROR_CODE",- "SENSITIVE_RESPONSES_ERROR_CODE",- "inference_error",- "generation terminated with an upstream error",- ),- ],-)-def test_responses_classifies_adapter_yielded_terminal_errors(- client: TestClient,- adapter: _FakeResponsesAdapter,- code: str,- message: str,- expected_code: str,- expected_message: str,-) -> None:- adapter.error_code = code- adapter.error_message = message-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == 500, response.text- assert response.json()["error"]["code"] == expected_code- assert response.json()["error"]["message"] == expected_message- if message.startswith("SENSITIVE_"):- assert message not in response.text---def test_responses_rejects_oversized_rendered_input(- client: TestClient,- monkeypatch: pytest.MonkeyPatch,-) -> None:- monkeypatch.setattr(openai_responses, "_MAX_PROMPT_BYTES", 4)-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "12345"},- )-- assert response.status_code == 413- assert response.json()["error"]["param"] == "input"- assert response.json()["error"]["code"] == "context_exceeded"---def test_responses_preflight_preserves_exact_parameter_and_skips_dispatch(- client: TestClient,- adapter: _FakeResponsesAdapter,-) -> None:- adapter.preflight_error = GenerationUnsupportedFieldError("top_k")-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == 400- assert response.json()["error"]["code"] == "unsupported_field"- assert response.json()["error"]["param"] == "top_k"- assert adapter.preflight_call is not None- assert adapter.last_call is None--- ("error", "status_code"),- [- (_UntrustedUnsupportedFieldError("top_k", "private unsupported detail"), 400),- (_UntrustedCapacityError("private capacity detail"), 503),- ],-)-def test_responses_sanitizes_untrusted_typed_error_codes(- client: TestClient,- adapter: _FakeResponsesAdapter,- error: GenerationError,- status_code: int,-) -> None:- adapter.preflight_error = error-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == status_code- assert response.json()["error"]["code"] == "inference_error"- assert "SENSITIVE_" not in response.text---def test_responses_preserves_typed_synchronous_dispatch_error(- client: TestClient,- adapter: _FakeResponsesAdapter,- monkeypatch: pytest.MonkeyPatch,-) -> None:- def refuse(**parameters: object) -> AsyncIterator[GenerationChunk]:- _ = parameters- raise GenerationUnsupportedFieldError("top_k")-- monkeypatch.setattr(adapter, "generate", refuse)-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == 400- assert response.json()["error"]["code"] == "unsupported_field"- assert response.json()["error"]["param"] == "top_k"--[email protected]("error_after", [0, 1])-def test_responses_preserves_typed_iterator_error_and_closes(- client: TestClient,- adapter: _FakeResponsesAdapter,- error_after: int,-) -> None:- adapter.generate_error_after_chunks = error_after-- response = client.post(- "/v1/responses",- json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},- )-- assert response.status_code == 400- assert response.json()["error"]["code"] == "unsupported_field"- assert response.json()["error"]["param"] == "top_k"- assert adapter.closed is Truediff --git a/packages/sie_server/tests/api/test_openai_responses_route.py b/packages/sie_server/tests/api/test_openai_responses_route.pynew file mode 100644index 000000000..9dd9d1f85--- /dev/null+++ b/packages/sie_server/tests/api/test_openai_responses_route.py@@ -0,0 +1,479 @@+"""``POST /v1/responses`` through the server's own app and chat route, on the weightless fake.++The app comes from :class:`AppFactory`, so its middleware and routers run as+``sie-server serve`` runs them. The model configs and the fake adapter come+from the catalog; only the registry is a stub. So each request is translated,+served by the real ``/v1/chat/completions`` code and translated back.+"""++from __future__ import annotations++import asyncio+import json+from collections.abc import AsyncIterator+from contextlib import AsyncExitStack+from functools import cache+from pathlib import Path+from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi.responses import JSONResponse, StreamingResponse+from fastapi.testclient import TestClient+from sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGES+from sie_server.adapters.remote._http import RemoteUpstreamError+from sie_server.api import openai_responses+from sie_server.api.lora import LeasedStreamingResponse+from sie_server.api.responses_translation import StreamMachine, responses_to_chat+from sie_server.app.app_factory import AppFactory+from sie_server.app.app_state_config import AppStateConfig+from sie_server.config.model import ModelConfig+from sie_server.core.loader import load_adapter, load_model_configs++MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+VECTORS = Path(__file__).resolve().parents[4] / "conformance" / "openai_responses"+MODEL = "sie-fake:chat"+QUESTION = "What is the weather in Paris?"+WEATHER = {+ "type": "function",+ "name": "get_weather",+ "description": "Current weather for a city.",+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},+}+APPLY_PATCH = {"type": "custom", "name": "apply_patch", "description": "Apply a patch to the workspace."}+_TERMINAL = ("response.completed", "response.incomplete", "response.failed")+++@cache+def _configs() -> dict[str, ModelConfig]:+ return load_model_configs(MODELS_DIR)+++def _registry(loading: frozenset[str] = frozenset()) -> MagicMock:+ configs = {name: _configs()[name] for name in ("sie-fake", MODEL)}+ adapters = {}+ for name, config in configs.items():+ adapter = load_adapter(config, MODELS_DIR, device="cpu")+ adapter.load("cpu")+ adapters[name] = adapter+ registry = MagicMock()+ registry.device = "cpu"+ registry.model_names = list(configs)+ registry.has_model.side_effect = configs.__contains__+ registry.get_config.side_effect = configs.__getitem__+ registry.get.side_effect = adapters.__getitem__+ registry.is_failed.return_value = False+ registry.is_unloading.return_value = False+ registry.is_loading.side_effect = loading.__contains__+ registry.is_loaded.return_value = True+ registry.adapters = adapters+ return registry+++def registry() -> MagicMock:+ return _registry()+++def _client(registry: MagicMock) -> TestClient:+ app = AppFactory.create_app(AppStateConfig(auth_mode="none"))+ app.state.registry = registry+ return TestClient(app)+++def client(registry: MagicMock) -> TestClient:+ return _client(registry)+++def _body(prompt: str = "Which is larger, 9.11 or 9.9?", **fields: Any) -> dict[str, Any]:+ return {"model": MODEL, "input": prompt, "max_output_tokens": 64, **fields}+++def _post(client: TestClient, body: dict[str, Any]) -> Any:+ return client.post("/v1/responses", json=body)+++def _chat(client: TestClient, body: dict[str, Any]) -> Any:+ return client.post("/v1/chat/completions", json=responses_to_chat(body).chat)+++def _events(response: Any) -> list[dict[str, Any]]:+ assert response.status_code == 200, response.text+ assert response.headers["content-type"].startswith("text/event-stream")+ events = []+ for frame in response.text.split("\n\n"):+ if not frame.strip() or frame.startswith(":"):+ continue+ lines = dict(line.split(": ", 1) for line in frame.splitlines())+ data = json.loads(lines["data"])+ assert data["type"] == lines["event"]+ events.append(data)+ assert [event["sequence_number"] for event in events] == list(range(len(events)))+ assert [event["type"] for event in events].count(events[-1]["type"]) == 1+ assert events[-1]["type"] in _TERMINAL+ assert "[DONE]" not in response.text+ return events+++def _chat_events(response: Any) -> list[dict[str, Any]]:+ assert response.status_code == 200, response.text+ data = [block.removeprefix("data: ") for block in response.text.split("\n\n") if block.startswith("data: ")]+ assert data[-1] == "[DONE]"+ return [json.loads(item) for item in data[:-1]]+++def _names(events: list[dict[str, Any]]) -> list[str]:+ return [event["type"] for event in events]+++def _error(response: Any, status: int) -> dict[str, Any]:+ assert response.status_code == status, response.text+ assert response.headers["content-type"] == "application/json"+ body = response.json()+ assert set(body) == {"error"}+ return body["error"]+++def _usage(chat_usage: dict[str, int]) -> dict[str, Any]:+ return {+ "input_tokens": chat_usage["prompt_tokens"],+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": chat_usage["completion_tokens"],+ "output_tokens_details": {"reasoning_tokens": 0},+ "total_tokens": chat_usage["total_tokens"],+ }+++def test_a_buffered_response_matches_the_chat_answer_to_the_same_conversation(client: TestClient) -> None:+ body = _body(+ "Reply with a word.",+ instructions="Be brief.",+ store=False,+ include=["reasoning.encrypted_content"],+ prompt_cache_key="session-1",+ client_metadata={"turn": "1"},+ reasoning={"summary": "auto"},+ text={"verbosity": "low"},+ )+ response = _post(client, body)+ chat = client.post(+ "/v1/chat/completions",+ json={+ "model": MODEL,+ "max_completion_tokens": 64,+ "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "Reply with a word."}],+ },+ ).json()++ assert response.status_code == 200, response.text+ assert response.headers["x-sie-served-by"] == "local"+ answer = response.json()+ assert answer["id"].startswith("resp-")+ assert isinstance(answer["created_at"], int)+ request_id = answer["id"].removeprefix("resp-")+ assert answer == {+ "id": f"resp-{request_id}",+ "object": "response",+ "created_at": answer["created_at"],+ "model": MODEL,+ "status": "completed",+ "incomplete_details": None,+ "error": None,+ "store": False,+ "parallel_tool_calls": True,+ "tool_choice": "auto",+ "output": [+ {+ "type": "message",+ "id": f"msg-{request_id}",+ "role": "assistant",+ "status": "completed",+ "content": [+ {"type": "output_text", "text": chat["choices"][0]["message"]["content"], "annotations": []}+ ],+ }+ ],+ "usage": _usage(chat["usage"]),+ }+++def test_a_streamed_response_matches_the_chat_stream_of_the_same_conversation(client: TestClient) -> None:+ body = _body("Reply with a word.", stream=True)+ events = _events(_post(client, body))+ chat = _chat_events(_chat(client, body))++ text = "".join(event["delta"] for event in events if event["type"] == "response.output_text.delta")+ assert _names(events)[:4] == [+ "response.created",+ "response.in_progress",+ "response.output_item.added",+ "response.content_part.added",+ ]+ assert _names(events)[-4:] == [+ "response.output_text.done",+ "response.content_part.done",+ "response.output_item.done",+ "response.completed",+ ]+ assert text == "".join(chunk["choices"][0]["delta"].get("content") or "" for chunk in chat if chunk["choices"])+ completed = events[-1]["response"]+ assert completed["status"] == "completed"+ assert completed["output"][0]["content"][0]["text"] == text+ assert completed["usage"] == _usage(chat[-1]["usage"])+++def test_a_function_tool_loop_calls_the_tool_then_answers_with_its_output(client: TestClient) -> None:+ first = _post(client, _body(QUESTION, tools=[WEATHER], tool_choice="auto"))++ assert first.status_code == 200, first.text+ [call] = first.json()["output"]+ request_id = first.json()["id"].removeprefix("resp-")+ assert call["type"] == "function_call"+ assert call["id"] == f"fc-{request_id}-0"+ assert call["call_id"].startswith("call_")+ assert call["name"] == "get_weather"+ assert json.loads(call["arguments"]) == {"city": QUESTION}+ assert call["status"] == "completed"+ assert first.json()["status"] == "completed"+ streamed = _events(_post(client, _body(QUESTION, stream=True, tools=[WEATHER], tool_choice="auto")))+ arguments = "".join(e["delta"] for e in streamed if e["type"] == "response.function_call_arguments.delta")+ [done] = [event for event in streamed if event["type"] == "response.function_call_arguments.done"]+ assert arguments == done["arguments"] == call["arguments"]+ assert streamed[-1]["response"]["output"][0]["call_id"] == call["call_id"]++ result = '{"city": "Paris", "temperature_c": 18}'+ second = _post(+ client,+ _body(+ tools=[WEATHER],+ input=[+ {"role": "user", "content": QUESTION},+ {"type": "reasoning", "id": "rs_1", "summary": []},+ {key: call[key] for key in ("type", "id", "call_id", "name", "arguments", "status")},+ {"type": "function_call_output", "call_id": call["call_id"], "output": result},+ ],+ ),+ )++ assert second.status_code == 200, second.text+ [message] = second.json()["output"]+ assert message["content"][0]["text"] == f"Tool result: {result}"+++def test_a_streamed_custom_tool_call_carries_the_decoded_input(client: TestClient) -> None:+ events = _events(_post(client, _body(QUESTION, stream=True, tools=[APPLY_PATCH])))+ added = next(event for event in events if event["type"] == "response.output_item.added")+ [done] = [event for event in events if event["type"] == "response.custom_tool_call_input.done"]++ assert added["item"]["type"] == "custom_tool_call"+ assert added["item"]["input"] == ""+ assert done["input"] == QUESTION+ assert "response.function_call_arguments.delta" not in _names(events)+ assert events[-1]["response"]["output"][0]["input"] == QUESTION+++def test_max_output_tokens_cuts_the_answer_as_incomplete(client: TestClient) -> None:+ buffered = _post(client, _body("Write a long answer.", max_output_tokens=3)).json()+ streamed = _events(_post(client, _body("Write a long answer.", max_output_tokens=3, stream=True)))++ for response in (buffered, streamed[-1]["response"]):+ assert response["status"] == "incomplete"+ assert response["incomplete_details"] == {"reason": "max_output_tokens"}+ assert response["usage"]["output_tokens"] == 3+ assert streamed[-1]["type"] == "response.incomplete"+++def test_a_body_that_is_not_json_or_is_too_large_is_refused(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ invalid = client.post("/v1/responses", content=b"{", headers={"content-type": "application/json"})+ monkeypatch.setattr(openai_responses, "_MAX_BODY_BYTES", 16)+ large = _post(client, _body())++ error = _error(invalid, 400)+ assert error["message"] == "body: invalid JSON"+ assert (error["param"], error["code"]) == ("body", "invalid_request")+ assert _error(large, 413) == {+ "message": "request body too large",+ "type": "invalid_request_error",+ "param": None,+ "code": "INPUT_TOO_LONG",+ }+++def test_a_translation_refusal_reaches_no_engine(client: TestClient, registry: MagicMock) -> None:+ registry.get.reset_mock()+ response = _post(client, _body(store=True))++ assert _error(response, 400) == {+ "message": "store: SIE does not store responses; send the full conversation in input",+ "type": "invalid_request_error",+ "param": "store",+ "code": "unsupported_field",+ }+ registry.get.assert_not_called()+++ ("body", "status", "param"),+ [+ (_body(model="sie-conformance/no-such-model"), 404, None),+ (_body(max_output_tokens=5000), 400, "max_output_tokens"),+ (_body(tools=[{**WEATHER, "name": "get weather"}]), 400, "tools[0].name"),+ (_body(reasoning={"effort": "extreme"}), 400, "reasoning.effort"),+ ],+ ids=["unknown model", "output cap", "tool name", "reasoning effort"],+)+def test_a_chat_refusal_comes_back_with_the_field_the_caller_sent(+ client: TestClient, body: dict[str, Any], status: int, param: str | None+) -> None:+ for stream in (False, True):+ chat = _chat(client, {**body, "stream": stream})+ error = _error(_post(client, {**body, "stream": stream}), status)+ assert chat.status_code == status+ assert error == {**chat.json()["error"], "param": param}+++def test_a_loading_model_answers_the_chat_error_with_its_retry_after() -> None:+ client = _client(_registry(loading=frozenset({MODEL})))+ response = _post(client, _body(stream=True))+ chat = _chat(client, _body(stream=True))++ assert _error(response, 503) == chat.json()["error"]+ assert response.json()["error"]["code"] == "MODEL_LOADING"+ assert response.headers["retry-after"] == chat.headers["retry-after"] == "5"+++ "case",+ json.loads((VECTORS / "error_vectors.json").read_text(encoding="utf-8"))["errors"],+ ids=lambda case: case["name"],+)[email protected]("stream", [False, True])+def test_an_error_vector_from_the_chat_route_is_answered_at_its_status(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, case: dict[str, Any], stream: bool+) -> None:+ async def chat_error(*_: Any) -> JSONResponse:+ return JSONResponse(status_code=case["status"], content=case["body"], headers=case.get("headers"))++ monkeypatch.setattr(openai_responses, "serve_chat_completions", chat_error)+ response = _post(client, _body(stream=stream))++ expect = case["expect"]+ assert response.status_code == expect["status"]+ assert response.headers["content-type"] == "application/json"+ for name, value in (expect.get("headers") or {}).items():+ assert response.headers[name] == value, name+ for name in expect.get("absent_headers") or []:+ assert name not in response.headers, name+ assert response.json() == expect["body"]+++def test_stored_response_routes_are_not_served(client: TestClient) -> None:+ assert client.get("/v1/responses/resp-1").status_code == 404+ assert client.post("/v1/responses/resp-1/cancel").status_code == 404+ assert client.get("/v1/responses").status_code == 405+++def _scripted_stream(adapter: Any, *, after: int, ending: str) -> None:+ original = adapter.chat_completion_stream++ async def stream(*args: Any, **kwargs: Any) -> AsyncIterator[dict[str, Any]]:+ sent = 0+ async for payload in original(*args, **kwargs):+ if sent == after:+ if ending == "fail":+ raise RemoteUpstreamError("the scripted engine failed", upstream_reason="upstream_unavailable")+ return+ sent += 1+ yield payload++ adapter.chat_completion_stream = stream+++def test_a_failure_after_output_fails_the_response(registry: MagicMock, client: TestClient) -> None:+ _scripted_stream(registry.adapters[MODEL], after=3, ending="fail")+ events = _events(_post(client, _body(stream=True)))++ assert "response.output_text.delta" in _names(events)+ assert _names(events)[-1] == "response.failed"+ failed = events[-1]["response"]+ assert failed["status"] == "failed"+ assert failed["output"] == []+ assert failed["usage"] is None+ assert failed["error"] == {"code": "upstream_error", "message": UPSTREAM_FAILURE_MESSAGES["upstream_unavailable"]}+ assert "response.completed" not in _names(events)+++def test_a_stream_ending_without_a_finish_fails_the_response(registry: MagicMock, client: TestClient) -> None:+ _scripted_stream(registry.adapters[MODEL], after=3, ending="stop")+ events = _events(_post(client, _body(stream=True)))++ assert "response.output_text.delta" in _names(events)+ assert _names(events)[-1] == "response.failed"+ assert events[-1]["response"]["error"] == {+ "code": "server_error",+ "message": "the generation stream ended without a finish reason",+ }+++class _Lease:+ def __init__(self) -> None:+ self.released = False+ self.body_closed = False++ async def body(self) -> AsyncIterator[bytes]:+ try:+ yield b'data: {"choices":[{"index":0,"delta":{"content":"x"},"finish_reason":null}]}\n\n'+ await asyncio.get_running_loop().create_future()+ finally:+ self.body_closed = True++ async def answer(self) -> LeasedStreamingResponse:+ lifetime = AsyncExitStack()+ lifetime.callback(setattr, self, "released", True)+ inner = StreamingResponse(self.body(), media_type="text/event-stream")+ return LeasedStreamingResponse(inner, lifetime)+++async def _serve(response: Any, *, fail_on: str, after: int = 0) -> list[dict[str, Any]]:+ sent: list[dict[str, Any]] = []++ async def send(message: dict[str, Any]) -> None:+ if message["type"] == fail_on and sum(m["type"] == fail_on for m in sent) >= after:+ raise OSError("the client went away")+ sent.append(message)++ async def receive() -> dict[str, Any]:+ await asyncio.get_running_loop().create_future()+ return {}++ scope = {"type": "http", "asgi": {"version": "3.0", "spec_version": "2.4"}}+ with pytest.raises(Exception): # noqa: B017, PT011 - Starlette reports the disconnect in its own type+ await asyncio.wait_for(response(scope, receive, send), 5)+ return sent+++def _machine() -> StreamMachine:+ return StreamMachine(responses_to_chat({"model": "m", "input": "x", "stream": True}).shape, "c", 0)+++async def test_a_client_that_goes_away_mid_stream_ends_the_chat_answer() -> None:+ lease = _Lease()+ stream = openai_responses._ResponsesStream(await lease.answer(), _machine())++ sent = await _serve(stream, fail_on="http.response.body", after=4)++ assert any(b"response.output_item.added" in message.get("body", b"") for message in sent)+ assert lease.body_closed+ assert lease.released+++async def test_a_stream_never_read_still_releases_the_chat_answer() -> None:+ lease = _Lease()+ stream = openai_responses._ResponsesStream(await lease.answer(), _machine())++ await _serve(stream, fail_on="http.response.start")++ assert lease.releaseddiff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.pyindex 676dcc2ac..9ad8155de 100644--- a/packages/sie_server/tests/api/test_remote_chat.py+++ b/packages/sie_server/tests/api/test_remote_chat.py@@ -22,7 +22,6 @@ from sie_server.api import openai_localfrom sie_server.api.generate import router as generate_routerfrom sie_server.api.openai_completions import router as completions_routerfrom sie_server.api.openai_local import _remote_chat_response, router-from sie_server.api.openai_responses import router as responses_routerfrom sie_server.config.model import ModelConfig, ReasoningEffortDeclarationfrom sie_server.config.upstreams import Upstream, install_upstreamsfrom sie_server.core.loader import expand_profile_variants@@ -124,7 +123,6 @@ def remote_chat(app.include_router(router)app.include_router(generate_router)app.include_router(completions_router)- app.include_router(responses_router)app.state.registry = registryrequests: list[httpx.Request] = []try:@@ -877,7 +875,6 @@ _GENERATION_SURFACES = [("chat", True),("completions", False),("completions", True),- ("responses", False),]@@ -912,8 +909,6 @@ def _generation_request(surface: str, *, stream: bool) -> tuple[str, dict[str, Areturn f"/v1/generate/{SAFE_MODEL}", {"prompt": "question", "max_new_tokens": 8, "stream": stream}if surface == "chat":return "/v1/chat/completions", {**BODY, "stream": stream, "max_tokens": 8}- if surface == "responses":- return "/v1/responses", {"model": MODEL, "input": "question", "max_output_tokens": 8}return "/v1/completions", {"model": MODEL, "prompt": "question", "max_tokens": 8, "stream": stream}@@ -986,7 +981,7 @@ def test_remote_forbid_keeps_cold_generation_off_the_bridge(remote_chat: tuple,registry.start_load_async.assert_not_awaited()[email protected]("surface", ["native", "chat", "completions", "responses"])[email protected]("surface", ["native", "chat", "completions"])def test_buffered_generation_bridge_discloses_success_and_warms_local(remote_chat: tuple, surface: str) -> None:client, adapter, _, requests = remote_chatregistry = _cold_generation_bridge(remote_chat)@@ -1062,9 +1057,7 @@ def test_invalid_generation_never_starts_a_bridge(remote_chat: tuple, surface: sregistry = _cold_generation_bridge(remote_chat)answer_with(remote_chat, json_response(200, completion()))path, body = _generation_request(surface, stream=streaming)- body[- "max_new_tokens" if surface == "native" else "max_output_tokens" if surface == "responses" else "max_tokens"- ] = 1000+ body["max_new_tokens" if surface == "native" else "max_tokens"] = 1000response = client.post(path, json=body)assert response.status_code == 400, response.textassert "X-SIE-Fallback-Reason" not in response.headers@@ -1309,7 +1302,7 @@ def test_native_upstream_prompt_reasoning_ownership_across_surfaces(remote_chat,stream = ChatStream(frames)answer_with(remote_chat, httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream))path, request = _generation_request(surface, stream=streaming)- request["input" if surface == "responses" else "prompt"] = "owned prompt<think>"+ request["prompt"] = "owned prompt<think>"response = client.post(path, json=request)assert response.status_code == 200, response.textassert "answer" in response.text@@ -1640,7 +1633,6 @@ class HangingStream(ChatStream):[("native", False, "first_chunk_timeout"),("completions", False, "first_chunk_timeout"),- ("responses", False, "first_chunk_timeout"),("rendered chat", False, "generation_timeout"),("rendered chat", True, "generation_timeout"),],diff --git a/packages/sie_server/tests/api/test_responses_translation.py b/packages/sie_server/tests/api/test_responses_translation.pynew file mode 100644index 000000000..7df7b6df1--- /dev/null+++ b/packages/sie_server/tests/api/test_responses_translation.py@@ -0,0 +1,439 @@+"""The Responses translation replays the vectors the gateway replays.++Every file under ``conformance/openai_responses/`` is read by the gateway's+tests and by these, so a request is accepted, refused and answered the same+way on both topologies. A translated request must also pass this server's own+chat validation. ``created_at`` is the one value the clock decides, so the+vectors carry ``0`` and these tests pass ``0``.+"""++from __future__ import annotations++import asyncio+import json+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import pytest+from sie_server.api.openai_local import (+ _validate_chat_message_media,+ _validate_chat_messages,+ _validate_cuda_chat_body,+)+from sie_server.api.responses_translation import (+ Event,+ FrameParser,+ ResponsesError,+ StreamMachine,+ chat_completion_to_response,+ responses_error,+ responses_to_chat,+ stream_events,+)++VECTORS = Path(__file__).resolve().parents[4] / "conformance" / "openai_responses"+++def _vectors(name: str) -> Any:+ return json.loads((VECTORS / name).read_text(encoding="utf-8"))+++def _chat_route_accepts(chat: dict[str, Any]) -> None:+ _validate_chat_messages(chat["messages"])+ _validate_chat_message_media(chat["messages"])+ _validate_cuda_chat_body(chat)+++def _frames(case: dict[str, Any]) -> list[str]:+ return [frame if isinstance(frame, str) else json.dumps(frame, ensure_ascii=False) for frame in case["frames"]]+++def _named(events: list[Event]) -> list[dict[str, Any]]:+ return [{"event": event.name, "data": event.data} for event in events]+++def _machine(case: dict[str, Any]) -> StreamMachine:+ return StreamMachine(responses_to_chat(case["request"]).shape, case["request_id"], 0)+++def _parse_body(body: bytes) -> tuple[list[dict[str, Any]], list[str]]:+ """The events of a Responses SSE body, and its comment frames."""+ events: list[dict[str, Any]] = []+ comments: list[str] = []+ for frame in body.decode().split("\n\n"):+ if not frame:+ continue+ if frame.startswith(":"):+ comments.append(frame)+ continue+ name, data = "", None+ for line in frame.splitlines():+ if line.startswith("event: "):+ name = line[len("event: ") :]+ elif line.startswith("data: "):+ data = json.loads(line[len("data: ") :])+ assert data is not None, frame+ assert data["type"] == name, frame+ events.append({"event": name, "data": data})+ return events, comments+++async def _drain(body: AsyncIterator[bytes]) -> bytes:+ return b"".join([chunk async for chunk in body])++[email protected]("case", _vectors("request_vectors.json")["accepted"], ids=lambda case: case["name"])+def test_an_accepted_request_vector_translates_onto_the_chat_body(case: dict[str, Any]) -> None:+ translation = responses_to_chat(case["body"])++ assert translation.chat == case["chat"]+ assert translation.stream is case["chat"]["stream"]+ _chat_route_accepts(translation.chat)++[email protected]("case", _vectors("request_vectors.json")["rejected"], ids=lambda case: case["name"])+def test_a_rejected_request_vector_is_refused_with_its_wording(case: dict[str, Any]) -> None:+ with pytest.raises(ResponsesError) as refused:+ responses_to_chat(case["body"])++ error = refused.value+ expect = case["expect"]+ assert error.status == expect["status"]+ assert error.body() == {+ "error": {+ "message": expect["message"],+ "type": expect["type"],+ "param": expect["param"],+ "code": expect["code"],+ }+ }++[email protected]("case", _vectors("codex_requests.json")["requests"], ids=lambda case: case["name"])+def test_a_captured_codex_request_translates_or_is_refused(case: dict[str, Any]) -> None:+ expect = case["expect"]+ if "refused" in expect:+ with pytest.raises(ResponsesError) as refused:+ responses_to_chat(case["body"])+ error = refused.value+ assert {+ "status": error.status,+ "type": error.body()["error"]["type"],+ "code": error.code,+ "param": error.param,+ "message": error.message,+ } == expect["refused"]+ return+ chat = responses_to_chat(case["body"]).chat+ summary = expect["chat"]+ assert [message["role"] for message in chat["messages"]] == summary["roles"]+ assert chat["stream"] is summary["stream"]+ assert len(chat.get("tools") or []) == summary["tool_count"]+ assert chat.get("tool_choice") == summary["tool_choice"]+ assert chat.get("parallel_tool_calls") == summary["parallel_tool_calls"]+ assert chat["include_reasoning"] is summary["include_reasoning"]+ assert chat.get("reasoning_effort") == summary.get("reasoning_effort")+ images = [+ part+ for message in chat["messages"]+ if isinstance(message["content"], list)+ for part in message["content"]+ if part["type"] == "image_url"+ ]+ assert len(images) == summary["image_parts"]+ _chat_route_accepts(chat)++[email protected]("case", _vectors("response_vectors.json")["translated"], ids=lambda case: case["name"])+def test_a_response_vector_translates_the_chat_completion(case: dict[str, Any]) -> None:+ shape = responses_to_chat(case["request"]).shape++ assert shape.model == case["model"]+ assert chat_completion_to_response(case["chat"], shape, case["request_id"], 0) == case["response"]+++ "chat",+ [+ {},+ {"choices": []},+ {"choices": [{"finish_reason": "stop"}]},+ {"choices": [{"message": {"content": "", "tool_calls": [{"function": {"name": "f"}}]}}]},+ {"choices": [{"message": {"content": "", "tool_calls": [{"id": "c", "function": {}}]}}]},+ ],+ ids=["no choices key", "no choices", "no message", "a call without an id", "a call without a name"],+)+def test_a_faulty_chat_completion_is_not_translated(chat: dict[str, Any]) -> None:+ shape = responses_to_chat({"model": "m", "input": "x"}).shape++ with pytest.raises(ValueError, match=r"^(chat completion|tool call)"):+ chat_completion_to_response(chat, shape, "r", 0)++[email protected]("case", _vectors("stream_vectors.json")["streams"], ids=lambda case: case["name"])+def test_a_stream_vector_drives_the_state_machine(case: dict[str, Any]) -> None:+ machine = _machine(case)+ events = machine.start()+ for frame in _frames(case):+ events += machine.on_data(frame)+ events += machine.on_end()++ assert _named(events) == case["events"]+ assert machine.done++[email protected]("case", _vectors("stream_vectors.json")["streams"], ids=lambda case: case["name"])+async def test_a_stream_vector_survives_the_sse_body_split_at_any_byte(case: dict[str, Any]) -> None:+ sse = "".join(f": keepalive\n\ndata: {frame}\n\n" for frame in _frames(case)).encode()++ async def chunks() -> AsyncIterator[bytes]:+ for start in range(len(sse)):+ yield sse[start : start + 1]++ events, comments = _parse_body(await _drain(stream_events(chunks(), _machine(case))))++ assert events == case["events"]+ assert comments+ assert set(comments) == {": keepalive"}+++def test_the_frame_parser_joins_multi_line_data_and_keeps_comment_frames() -> None:+ parser = FrameParser()++ assert parser.push(b': keep-alive\r\n\r\ndata: {"a"') == [("comment", ": keep-alive\n\n")]+ assert parser.push(b":1}\r\n\r\nevent: x\n: note\ndata: one\ndata: two\n\nid: 1\n\n") == [+ ("data", '{"a":1}'),+ ("data", "one\ntwo"),+ ]++[email protected]("case", _vectors("error_vectors.json")["errors"], ids=lambda case: case["name"])+def test_an_error_vector_keeps_the_answer_and_renames_the_param(case: dict[str, Any]) -> None:+ body = json.dumps(case["body"]).encode()+ sent = [*(case.get("headers") or {}).items(), ("Content-Length", str(len(body)))]++ headers, content = responses_error(sent, body)++ expect = case["expect"]+ for name, value in (expect.get("headers") or {}).items():+ assert dict(headers)[name] == value, name+ for name in expect.get("absent_headers") or []:+ assert name not in dict(headers), name+ assert "content-length" not in dict(headers)+ assert json.loads(content) == expect["body"]+++def test_a_body_that_is_not_an_openai_error_passes_unchanged() -> None:+ for body in (b"", b"not json", b'{"detail": {"code": "X", "param": "max_completion_tokens"}}', b"[]"):+ assert responses_error([("retry-after", "3")], body) == ([("retry-after", "3")], body)+++_STEPS: dict[str, str] = {+ "role": json.dumps({"choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}]}),+ "text": json.dumps({"choices": [{"index": 0, "delta": {"content": "a"}, "finish_reason": None}]}),+ **{+ f"call {index}": json.dumps(+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": index,+ "id": f"c{index}",+ "type": "function",+ "function": {"name": name, "arguments": ""},+ }+ ]+ },+ "finish_reason": None,+ }+ ]+ }+ )+ for index, name in ((0, "f"), (1, "edit"))+ },+ **{+ f"arguments {index}": json.dumps(+ {+ "choices": [+ {+ "index": 0,+ "delta": {"tool_calls": [{"index": index, "function": {"arguments": '{"input":"x"}'}}]},+ "finish_reason": None,+ }+ ]+ }+ )+ for index in (0, 1)+ },+ **{+ f"finish {reason}": json.dumps({"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]})+ for reason in ("stop", "tool_calls", "length")+ },+ "usage": json.dumps({"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}}),+ "error": json.dumps({"choices": [], "error": {"message": "m", "type": "server_error", "code": "inference_error"}}),+ "malformed": "{not json",+ "done": "[DONE]",+}+_SHAPE = responses_to_chat(+ {+ "model": "m",+ "input": "x",+ "tools": [{"type": "function", "name": "f"}, {"type": "custom", "name": "edit"}],+ }+).shape+++def _assert_event_grammar(events: list[dict[str, Any]], context: str) -> None:+ """Check the event grammar Responses clients parse.++ ``response.created`` and ``response.in_progress``, then one item at a time+ with contiguous output indices and the events of its kind, then one+ terminal event, and nothing after. Sequence numbers count from 0.+ """+ assert [event["data"]["sequence_number"] for event in events] == list(range(len(events))), context+ assert [event["event"] for event in events[:2]] == ["response.created", "response.in_progress"], context+ open_item: tuple[int, str] | None = None+ next_index = 0+ allowed = {+ "message": {+ "response.content_part.added",+ "response.output_text.delta",+ "response.output_text.done",+ "response.content_part.done",+ },+ "function_call": {"response.function_call_arguments.delta", "response.function_call_arguments.done"},+ "custom_tool_call": {"response.custom_tool_call_input.delta", "response.custom_tool_call_input.done"},+ }+ for position, event in enumerate(events[2:], start=2):+ name, data = event["event"], event["data"]+ if name in ("response.completed", "response.incomplete", "response.failed"):+ assert position == len(events) - 1, f"{context}: event after the end"+ if name != "response.failed":+ assert open_item is None, f"{context}: {name} with an open item"+ items = data["response"]["output"]+ assert [item["status"] for item in items] == ["completed"] * len(items), context+ return+ if name == "response.output_item.added":+ assert open_item is None, f"{context}: two open items"+ assert data["output_index"] == next_index, context+ next_index += 1+ open_item = (data["output_index"], data["item"]["type"])+ elif name == "response.output_item.done":+ assert open_item is not None, context+ assert (data["output_index"], data["item"]["type"]) == open_item, context+ open_item = None+ else:+ assert open_item is not None, f"{context}: {name} without an open item"+ assert name in allowed[open_item[1]], f"{context}: {name} in a {open_item[1]} item"+ assert data["output_index"] == open_item[0], context+ pytest.fail(f"{context}: no terminal event")+++def test_any_chat_chunk_sequence_yields_a_valid_event_grammar() -> None:+ alphabet = list(_STEPS)+ seed = 0x9E3779B97F4A7C15+ mask = (1 << 64) - 1+ for round_number in range(4000):+ steps = []+ for _ in range(round_number % 12 + 1):+ seed ^= (seed << 13) & mask+ seed ^= seed >> 7+ seed ^= (seed << 17) & mask+ steps.append(alphabet[seed % len(alphabet)])+ machine = StreamMachine(_SHAPE, "r", 0)+ events = machine.start()+ for step in steps:+ events += machine.on_data(_STEPS[step])+ events += machine.on_end()+ _assert_event_grammar(_named(events), f"round {round_number}: {steps}")+++ ("frames", "message"),+ [+ (["{not json"], "the generation stream sent a malformed chunk"),+ (+ [json.dumps({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0}]}, "finish_reason": None}]})],+ "a tool call arrived without its id and name",+ ),+ (+ [_STEPS["call 0"], _STEPS["call 1"], _STEPS["arguments 0"]],+ "tool call arguments arrived after another output item started",+ ),+ (+ [_STEPS["call 0"], _STEPS["text"], _STEPS["arguments 0"]],+ "tool call arguments arrived after another output item started",+ ),+ ],+ ids=["malformed chunk", "call without an id", "arguments after a later call", "arguments after text"],+)+def test_a_chat_stream_the_translation_cannot_follow_fails_the_response(frames: list[str], message: str) -> None:+ machine = StreamMachine(_SHAPE, "r", 0)+ events = machine.start()+ for frame in frames:+ events += machine.on_data(frame)++ assert events[-1].name == "response.failed"+ assert events[-1].data["response"]["error"] == {"code": "server_error", "message": message}+ assert machine.done+++class _Source:+ """A chat body that records whether it was closed."""++ def __init__(self, chunks: list[bytes], *, fail: bool = False) -> None:+ self._chunks = list(chunks)+ self._fail = fail+ self.closed = False++ def __aiter__(self) -> _Source:+ return self++ async def __anext__(self) -> bytes:+ if self._chunks:+ return self._chunks.pop(0)+ if self._fail:+ raise OSError("the chat body broke")+ await asyncio.get_running_loop().create_future()+ raise AssertionError("unreachable")++ async def aclose(self) -> None:+ self.closed = True+++async def test_a_chat_body_that_breaks_fails_the_response() -> None:+ source = _Source([b'data: {"choices":[{"index":0,"delta":{"content":"x"},"finish_reason":null}]}\n\n'], fail=True)++ events, _ = _parse_body(await asyncio.wait_for(_drain(stream_events(source, StreamMachine(_SHAPE, "r", 0))), 5))++ assert events[-1]["event"] == "response.failed"+ assert events[-1]["data"]["response"]["error"] == {+ "code": "server_error",+ "message": "the generation stream ended unexpectedly",+ }+ assert source.closed+++async def test_the_terminal_event_ends_the_body_and_closes_the_chat_body() -> None:+ source = _Source([f"data: {_STEPS['error']}\n\n".encode()])++ events, _ = _parse_body(await asyncio.wait_for(_drain(stream_events(source, StreamMachine(_SHAPE, "r", 0))), 5))++ assert [event["event"] for event in events] == ["response.created", "response.in_progress", "response.failed"]+ assert source.closed+++async def test_closing_the_responses_body_closes_the_chat_body() -> None:+ source = _Source([])+ body = stream_events(source, StreamMachine(_SHAPE, "r", 0))++ first = await anext(body)+ assert first.startswith(b"event: response.created")+ assert not source.closed+ await body.aclose()++ assert source.closeddiff --git a/packages/sie_server/tests/test_openapi_export.py b/packages/sie_server/tests/test_openapi_export.pyindex 9de942565..a010bcd79 100644--- a/packages/sie_server/tests/test_openapi_export.py+++ b/packages/sie_server/tests/test_openapi_export.py@@ -31,11 +31,11 @@ def test_openapi_has_expected_paths() -> None:"/v1/extract/{model}","/v1/generate/{model}","/v1/completions",- "/v1/responses","/v1/score/{model}","/v1/models",]:assert expected in paths, f"Missing path: {expected}"+ assert not paths & {"/v1/chat/completions", "/v1/messages", "/v1/responses"}def test_openapi_has_request_body_schemas() -> None:@@ -162,26 +162,6 @@ def test_openapi_documents_direct_completions_contract() -> None:assert response_content["text/event-stream"]["schema"]["type"] == "string"-def test_openapi_documents_direct_responses_contract() -> None:- result = runner.invoke(app, ["openapi"])- assert result.exit_code == 0, result.output- spec = json.loads(result.output)-- operation = spec["paths"]["/v1/responses"]["post"]- assert operation["requestBody"]["content"]["application/json"]["schema"] == {- "$ref": "#/components/schemas/OpenAIResponsesRequestModel"- }- schema = spec["components"]["schemas"]["OpenAIResponsesRequestModel"]- assert schema["additionalProperties"] is False- assert set(schema["required"]) == {"model", "input"}- assert schema["properties"]["max_output_tokens"]["anyOf"][0]["minimum"] == 1- assert schema["properties"]["stream"]["anyOf"][0]["const"] is False- assert operation["responses"]["200"]["content"]["application/json"]["schema"] == {- "$ref": "#/components/schemas/OpenAIResponsesResponseModel"- }- assert "413" in operation["responses"]--def test_openapi_audio_timestamp_contract() -> None:"""Audio compatibility documents word and segment timestamps."""result = runner.invoke(app, ["openapi"])