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(gateway): serve /v1/responses as a translation onto chat completions (#1017)
Krisztian Gajdarc32eeabe92f1
diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex ecf28dd0b..b311552de 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -155,7 +155,7 @@ Generation is a supported fourth primitive. Strict allow-list parsing on the Ope|--------|------|-------------|| POST | `/v1/chat/completions` | OpenAI Chat Completions (streaming + non-streaming, `n`, `best_of`, `tools`, `response_format`, `lora_adapter`) || POST | `/v1/completions` | OpenAI legacy Completions (raw `prompt`, streaming + non-streaming, single-candidate) |-| POST | `/v1/responses` | OpenAI Responses API MVP (stateless single-turn, non-streaming) |+| POST | `/v1/responses` | OpenAI Responses API, translated onto chat completions (streaming + non-streaming, function and custom tools, `text.format`, `reasoning.effort`; stateless: `previous_response_id`, `store: true` and hosted tools are refused) || POST | `/v1/generate/{*model}` | SIE-native generate (full `GenerateParams` envelope, streaming + non-streaming) |Common headers:diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 5aa89c436..d01c2d3b2 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -47,6 +47,7 @@ Key terms used throughout this document:- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**. `dimensions` is accepted only when it equals the model's native dense width and otherwise rejected with **`400 unsupported_field`**, the same rule as the single-node server. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.- `POST /v1/messages` — Anthropic Messages compatibility surface (`handlers::messages`). The handler validates the body in Anthropic terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Message, chat SSE chunks into Messages events, and every error into the Anthropic envelope `{"type":"error","error":{"type","message"},"request_id"}` with the status the chat route chose. Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. Unknown fields fail with `400 <field>: Extra inputs are not permitted`; `metadata`, every `cache_control`, `thinking.display: "summarized"`, tool `eager_input_streaming` and the `anthropic-beta` header are accepted and have no effect, and `metadata` is never logged or forwarded. `thinking` `enabled` or `adaptive` sets the chat request's `include_reasoning`, and reasoning comes back as `thinking` blocks with an opaque signature. `output_config.effort` sets the chat request's `reasoning_effort`, and a model that does not accept the value answers `400 output_config.effort: Extra inputs are not permitted`, the wording clients that drop the field recover from. Usage reports `prompt_tokens - cached_tokens` as `input_tokens` and the cached part as `cache_read_input_tokens`, so the two add up to the chat route's prompt tokens. A stream sends `message_start` with zero usage when the chat stream opens, the authoritative usage on `message_delta`, a `ping` whenever nothing was sent for 10 seconds, and a mid-stream failure as an `error` event without `message_stop`. Dropping the response body drops the chat body, so a client disconnect cancels the generation as on chat. The Anthropic error envelope is also an outer middleware, `anthropic_error_envelope`, applied to `/v1/messages` and every path below it, so auth refusals, unknown sub-paths such as `/v1/messages/count_tokens` (not served) and the method check take the same shape; a composition that adds admission layers applies it outermost. `messages_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/anthropic_messages/` pin the request translation, the buffered answer, the event sequence, the error mapping, and the tool-calling and image-input refusals both chat routes give before any engine runs.+ - `POST /v1/responses` — OpenAI Responses compatibility surface (`handlers::responses`), built the same way as `/v1/messages`: the handler validates the body in Responses terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Response, chat SSE chunks into Responses events, and a chat error into the same OpenAI error envelope, keeping its status, `Retry-After` and `X-SIE-Error-Code` and renaming `error.param` to the Responses field (`tools[i].function.name` to `tools[i].name`, `max_completion_tokens` to `max_output_tokens`, `reasoning_effort` to `reasoning.effort`, `response_format` to `text.format`). Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. `instructions` and the leading `system` and `developer` messages form one system message; `function_call` and `custom_tool_call` items join the adjacent assistant text in one chat assistant message, their outputs become `tool` messages, and `reasoning` items are dropped. Function tools pass through; a custom tool becomes a function with one string `input`, and calls to it come back as `custom_tool_call` items. `text.format` becomes `response_format` and `reasoning.effort` becomes `reasoning_effort`; reasoning is not returned. Responses are not stored: `store: true`, `previous_response_id`, `conversation` and `background: true` are refused with `400 unsupported_field`, as are hosted tools and item types, and the `/v1/responses/{id}` routes are not served. Unknown fields fail with `400 <field>: Extra inputs are not permitted`. A stream sends `response.created` and `response.in_progress` when the chat stream opens, then item, content-part, text and argument events, each with a `sequence_number`, then `response.completed` or `response.incomplete` with the full Response; a mid-stream failure is `response.failed` and ends the stream. The chat route's SSE comment heartbeats pass through until the terminal event, and dropping the response body drops the chat body. `handlers::proxy::responses_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/openai_responses/` pin the request translation, the buffered answer, the event sequence and the error mapping.2. Gateway resolves the request to a model, a bundle, a machine profile, a logical API pool, and the backing queue pool using its in-memory registry.3. Gateway ordinarily publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item. A capped logical batch pool instead targets one assigned worker on `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.4. A matching worker consumes the work item, verifies its logical pool assignment when `admission_pool` differs from its physical queue pool, and executes inference.@@ -555,6 +556,7 @@ Inference (queue-only):- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI JSON compatibility layer over encode (string or list of strings); see §2.- `POST /v1/messages` — Anthropic Messages compatibility layer over chat completions; see §2. `POST /v1/messages/count_tokens` is not served (`404 not_found_error`).+- `POST /v1/responses` — OpenAI Responses compatibility layer over chat completions; see §2. The `/v1/responses/{id}` routes are not served (`404`).Config (read-side only):diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex f6c763498..be4539dc2 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -4286,63 +4286,40 @@},"ResponsesRequest": {"additionalProperties": false,- "description": "OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).\n\n**Strict allow-list**: unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.\n- ``previous_response_id`` — rejected with 400 ``unsupported_field``\n (Responses MVP is stateless single-turn).\n- ``reasoning`` — rejected with 400 ``unsupported_field``.\n- ``background`` — rejected with 400 ``unsupported_field``.\n- ``metadata`` — rejected with 400 ``unsupported_field``.\n- ``instructions`` — rejected with 400 ``unsupported_field``.\n- ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on\n Responses is deferred; use ``stream: false`` or omit).\n- Multimodal ``image_url`` / ``input_image`` content parts on the array\n form — rejected with 400 ``unsupported_field``: the Responses surface is\n text-only. (Vision input is supported on ``/v1/chat/completions``.)",+ "description": "OpenAI Responses request, as accepted by ``POST /v1/responses``.\n\nThe request is translated into a ``/v1/chat/completions`` request and\nserved by the chat route, so every chat limit and check applies, and a\nchat refusal names the Responses field (``tools[i].name``,\n``max_output_tokens``, ``reasoning.effort``, ``text.format``). A field\nsent as ``null`` is treated as absent.\n\nResponses are not stored: ``store: true`` and a non-null\n``previous_response_id`` or ``conversation`` fail with ``400\nunsupported_field`` and the message ``<field>: SIE does not store\nresponses; send the full conversation in input``. ``background: true``,\na ``truncation`` other than ``disabled`` and an ``include`` entry other\nthan ``reasoning.encrypted_content`` fail the same way. ``prompt``,\n``max_tool_calls``, ``top_logprobs``, ``stream_options`` and every other\nfield outside this set fail with ``<field>: Extra inputs are not\npermitted``. ``client_metadata``, ``reasoning.summary``,\n``reasoning.generate_summary`` and ``text.verbosity`` are accepted and\nhave no effect.","properties": {+ "background": {+ "description": "Accepted only ``false``.",+ "type": [+ "boolean",+ "null"+ ]+ },+ "client_metadata": {+ "description": "Accepted and ignored."+ },+ "conversation": {+ "description": "Accepted only `null`: responses are not stored.",+ "type": "null"+ },+ "include": {+ "description": "Accepted only with ``reasoning.encrypted_content`` entries, which\nhave no effect.",+ "items": {+ "type": "string"+ },+ "type": [+ "array",+ "null"+ ]+ },"input": {- "description": "Either a string prompt OR an array of `{role, content}` messages (array-input support). Array form: `role` is one of `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" normalizes to \"system\"). `content` is a string or an array of `text`, `input_text`, or `output_text` parts; image parts (`image_url` / `input_image`) reject with 400 unsupported_field. The array must not be empty.",+ "description": "A string, sent as one user message, or a non-empty list of items: messages (`role` `user`, `assistant`, `system` or `developer`, with string content or `input_text`, `output_text` and `text` parts, and base64 `data:` `input_image` parts in user messages), `function_call`, `custom_tool_call`, their `*_output` items, and `reasoning` items, which do not reach the model. Item `id` and `status` are ignored. Other item and part types are refused.","oneOf": [{"type": "string"},{"items": {- "additionalProperties": false,- "properties": {- "content": {- "oneOf": [- {- "type": "string"- },- {- "items": {- "additionalProperties": false,- "properties": {- "text": {- "type": "string"- },- "type": {- "enum": [- "text",- "input_text",- "output_text"- ],- "type": "string"- }- },- "required": [- "type",- "text"- ],- "type": "object"- },- "type": "array"- }- ]- },- "role": {- "enum": [- "system",- "user",- "assistant",- "developer"- ],- "type": "string"- }- },- "required": [- "role",- "content"- ],"type": "object"},"minItems": 1,@@ -4350,57 +4327,124 @@}]},+ "instructions": {+ "description": "Prepended to the leading ``system`` and ``developer`` messages as\none system message.",+ "type": [+ "string",+ "null"+ ]+ },"max_output_tokens": {- "description": "Maximum number of generated tokens. Defaults to 16 when absent or null.",- "maximum": 4294967295,+ "description": "Output token limit, at least 1 and at most the serving profile's\n``max_output_tokens``. Absent: the chat route's default.",+ "format": "int32","minimum": 1,"type": ["integer","null"]},+ "metadata": {+ "description": "Passed to the chat route."+ },"model": {+ "description": "The model id, used as on ``/v1/chat/completions`` (``model`` or\n``model:profile``, or an operator alias).","minLength": 1,"type": "string"},+ "parallel_tool_calls": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "previous_response_id": {+ "description": "Accepted only `null`: responses are not stored.",+ "type": "null"+ },+ "prompt_cache_key": {+ "description": "Passed to the chat route.",+ "type": [+ "string",+ "null"+ ]+ },+ "reasoning": {+ "description": "``effort`` becomes the chat ``reasoning_effort``. Reasoning is not\nreturned."+ },+ "safety_identifier": {+ "description": "Passed to the chat route.",+ "type": [+ "string",+ "null"+ ]+ },"seed": {- "description": "Optional signed 64-bit per-request sampling seed. Reproducibility is best effort, not guaranteed, and depends on the active generation backend and deployment configuration. Non-integer or out-of-range values reject with 400 invalid_request.",+ "description": "Checked as on ``/v1/chat/completions``.","format": "int64",- "maximum": 9223372036854775807,- "minimum": -9223372036854775808,"type": ["integer","null"]},+ "service_tier": {+ "description": "Passed to the chat route.",+ "type": [+ "string",+ "null"+ ]+ },+ "store": {+ "description": "Accepted only ``false``.",+ "type": [+ "boolean",+ "null"+ ]+ },"stream": {- "description": "Accepted only as `false` (or absent). `true` rejects with 400 unsupported_field because Responses SSE is not supported yet.",- "enum": [- false,- null- ],+ "description": "Server-sent events: ``response.created``, ``response.in_progress``,\noutput item, content part, text and call-argument events, then\n``response.completed`` or ``response.incomplete`` with the full\nResponse. Every event carries ``sequence_number``. A failure after\nthe stream opened is ``response.failed``, and the stream then ends.","type": ["boolean","null"]},"temperature": {- "description": "Sampling temperature representable by the worker runtime.",- "format": "float",- "maximum": 3.4028234663852886e+38,- "minimum": 0,+ "description": "Checked as on ``/v1/chat/completions``.",+ "format": "double","type": ["number","null"]},+ "text": {+ "description": "``format`` ``text``, ``json_object`` or ``json_schema`` (``name``,\n``schema``, ``strict``, ``description``) becomes the chat\n``response_format``."+ },+ "tool_choice": {+ "description": "``auto``, ``none``, ``required``, or ``{\"type\": \"function\" |\n\"custom\", \"name\"}`` naming a declared tool."+ },+ "tools": {+ "description": "``function`` tools (``name``, ``description``, ``parameters``,\n``strict`` only ``false``) and ``custom`` tools (``name``,\n``description``, ``format``, which is not enforced), at most 64,\nnames matching ``^[a-zA-Z0-9_-]{1,64}$``. Hosted tool types are\nrefused."+ },"top_p": {- "description": "Nucleus sampling. Finite number in ``(0, 1]``.",- "format": "float",+ "description": "Checked as on ``/v1/chat/completions``.",+ "format": "double","type": ["number","null"]+ },+ "truncation": {+ "description": "Accepted only ``disabled``.",+ "type": [+ "string",+ "null"+ ]+ },+ "user": {+ "description": "Passed to the chat route.",+ "type": [+ "string",+ "null"+ ]}},"required": [@@ -4409,6 +4453,104 @@],"type": "object"},+ "ResponsesResponse": {+ "additionalProperties": false,+ "description": "Response answered by ``POST /v1/responses`` without ``stream``.",+ "properties": {+ "created_at": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "error": {+ "description": "Always ``null``."+ },+ "id": {+ "description": "``resp-`` followed by the gateway request id.",+ "type": "string"+ },+ "incomplete_details": {+ "description": "``{\"reason\": \"max_output_tokens\" | \"content_filter\"}`` when\n``incomplete``."+ },+ "model": {+ "description": "The model the request named.",+ "type": "string"+ },+ "object": {+ "description": "Always ``response``.",+ "type": "string"+ },+ "output": {+ "description": "A ``message`` item with one ``output_text`` part when the model\nwrote text, then one ``function_call`` or ``custom_tool_call`` item\nper tool call."+ },+ "parallel_tool_calls": {+ "description": "As the request sent it, ``true`` when absent."+ },+ "status": {+ "description": "``completed`` or ``incomplete``.",+ "type": "string"+ },+ "store": {+ "description": "Always ``false``.",+ "type": "boolean"+ },+ "tool_choice": {+ "description": "As the request sent it, ``auto`` when absent."+ },+ "usage": {+ "$ref": "#/components/schemas/ResponsesUsage"+ }+ },+ "required": [+ "id",+ "object",+ "created_at",+ "model",+ "status",+ "store",+ "parallel_tool_calls",+ "tool_choice",+ "output",+ "usage"+ ],+ "type": "object"+ },+ "ResponsesUsage": {+ "additionalProperties": false,+ "description": "Token usage of a Response, from the chat route's usage.",+ "properties": {+ "input_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "input_tokens_details": {+ "description": "``cached_tokens``: prompt tokens served from the prefix cache."+ },+ "output_tokens": {+ "description": "Includes reasoning tokens.",+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "output_tokens_details": {+ "description": "``reasoning_tokens``."+ },+ "total_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "input_tokens",+ "input_tokens_details",+ "output_tokens",+ "output_tokens_details",+ "total_tokens"+ ],+ "type": "object"+ },"ScoreEntry": {"properties": {"item_id": {@@ -8757,9 +8899,33 @@},"/v1/responses": {"post": {- "description": "OpenAI Responses API (MVP). Strict allow-list parser: unknown top-level fields reject with 400 `unsupported_field`. `input` is either a string prompt OR an array of `{role, content}` messages. Known-rejected fields: `tools`, `tool_choice`, `previous_response_id`, `reasoning`, `background`, `metadata`, `instructions` — each rejects with 400 `unsupported_field`. `stream: true` is rejected (Responses SSE is deferred). Multimodal image content parts reject with 400 `unsupported_field` on the array form.",+ "description": "OpenAI Responses API. The request is translated into a /v1/chat/completions request, served by the chat route with all of its limits, and the answer is translated back. Buffered and streaming answers are supported. Function and custom tools are supported; hosted tools are refused. Responses are not stored: previous_response_id, conversation, store: true and background: true are refused, and the /v1/responses/{id} routes are not served.","operationId": "proxy_responses","parameters": [+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },{"description": "Require local serving through a current worker execution fence. A selected remote profile returns 400; no verified local worker returns retryable 503. Duplicate or other values return 400.","in": "header",@@ -8788,134 +8954,16 @@"content": {"application/json": {"schema": {- "additionalProperties": false,- "properties": {- "created_at": {- "type": "integer"- },- "id": {- "type": "string"- },- "model": {- "type": "string"- },- "object": {- "const": "response",- "type": "string"- },- "output": {- "items": {- "additionalProperties": false,- "properties": {- "content": {- "items": {- "additionalProperties": false,- "properties": {- "annotations": {- "items": {- "type": "object"- },- "type": "array"- },- "text": {- "type": "string"- },- "type": {- "const": "output_text",- "type": "string"- }- },- "required": [- "type",- "text",- "annotations"- ],- "type": "object"- },- "type": "array"- },- "id": {- "type": "string"- },- "role": {- "const": "assistant",- "type": "string"- },- "status": {- "const": "completed",- "type": "string"- },- "type": {- "const": "message",- "type": "string"- }- },- "required": [- "type",- "id",- "role",- "status",- "content"- ],- "type": "object"- },- "type": "array"- },- "status": {- "const": "completed",- "type": "string"- },- "usage": {- "additionalProperties": false,- "properties": {- "input_tokens": {- "minimum": 0,- "type": "integer"- },- "input_tokens_details": {- "additionalProperties": false,- "properties": {- "cached_tokens": {- "minimum": 0,- "type": "integer"- }- },- "required": [- "cached_tokens"- ],- "type": "object"- },- "output_tokens": {- "minimum": 0,- "type": "integer"- },- "total_tokens": {- "minimum": 0,- "type": "integer"- }- },- "required": [- "input_tokens",- "output_tokens",- "total_tokens"- ],- "type": "object"- }- },- "required": [- "id",- "object",- "created_at",- "model",- "status",- "output",- "usage"- ],- "type": "object"+ "$ref": "#/components/schemas/ResponsesResponse"+ }+ },+ "text/event-stream": {+ "schema": {+ "type": "string"}}},- "description": "Response object",+ "description": "Response, or a text/event-stream of Responses events when stream is true","headers": {"X-Inference-Time": {"description": "Worker-reported inference time in milliseconds",@@ -9100,7 +9148,6 @@}}},- "summary": "`/v1/responses` — OpenAI Responses API (MVP, stateless single-turn).","tags": ["inference"]diff --git a/packages/sie_gateway/src/handlers/mod.rs b/packages/sie_gateway/src/handlers/mod.rsindex dc5547077..1d2d89da2 100644--- a/packages/sie_gateway/src/handlers/mod.rs+++ b/packages/sie_gateway/src/handlers/mod.rs@@ -7,6 +7,7 @@ pub mod messages;pub mod models;pub mod pools;pub mod proxy;+pub mod responses;pub mod serving_disclosure;pub mod sse;pub mod systemone;diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 4ca7c027f..f80a62ee2 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -53,6 +53,9 @@ use super::serving_disclosure::{UnansweredBeforeDeadline,};+#[allow(unused_imports)]+pub use crate::handlers::responses::responses_dispatch_inputs;+const GATEWAY_VERSION: &str = env!("CARGO_PKG_VERSION");/// The ONE ingress bound every JSON body-bearing route accepts.@@ -10600,687 +10603,10 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response&model_name,&model_name,params.stream,- ) {- return response;- }-- let ResolvedRoute {- dispatch_model,- require_execution_authority_v1,- fallback_reason,- physical_lane,- bundle,- gpu,- engine,- admission_pool,- effective_pool,- effective_machine_profile,- bundle_config_hash,- model_revision,- work_publisher: work_publisher_arc,- token_id,- content_length,- } = match resolve_generation_route(- &state,- &hdr,- &bundle,- ¶ms.model,- &model_name,- &model_name,- GenerationRequestIntent::Default,- &explicit_bundle_override,- &parts.extensions,- !native_request_has_profile_selector(&body_bytes, false),- (params.max_new_tokens, "max_tokens"),- metric_labels_slot.as_ref(),- )- .await- {- Ok(r) => r,- Err(resp) => return resp,- };- let start = Instant::now();-- // Copied out BEFORE the params are consumed into `WorkParams` below.- let requested_model = params.model.clone();- let stream = params.stream;- let stream_include_usage = params.stream_include_usage;- let mut work_params = params.into_work_params();- work_params.require_execution_authority_v1 = require_execution_authority_v1;- work_params.fallback_reason = fallback_reason;-- // SSE streaming → emit `text_completion` chunks. Single-candidate- // (completions rejects n>1), so no per-candidate interleave.- if stream {- return super::sse::build_sse_response(super::sse::SseParams {- prefetch_first_output: parts- .extensions- .get::<FallbackAttempt>()- .is_some_and(FallbackAttempt::active),- local_serving_model: FallbackAttempt::defer_local_stream(&parts.extensions),- state: state.as_ref(),- work_publisher: work_publisher_arc,- physical_lane: physical_lane.clone(),- requested_model,- model: model_name.clone(),- // /v1/completions does not accept grammar, so it never routes:- // dispatch == display.- dispatch_model: dispatch_model.clone(),- bundle: bundle.clone(),- engine: engine.clone(),- gpu: effective_machine_profile.clone(),- pool: effective_pool.clone(),- admission_pool: admission_pool.clone(),- bundle_config_hash: bundle_config_hash.clone(),- work_params,- endpoint: super::sse::SseEndpoint::Completion {- include_usage: stream_include_usage,- },- route: RouteKind::Compatibility,- })- .await;- }-- let driver = run_streaming_generate(- &state,- work_publisher_arc,- &physical_lane,- &requested_model,- &model_name,- &dispatch_model,- &bundle,- &engine,- &effective_machine_profile,- &effective_pool,- &admission_pool,- &bundle_config_hash,- &work_params,- RouteKind::Compatibility,- )- .await;-- let StreamingDriverOk {- outcome,- request_id,- publish_elapsed,- wait_elapsed,- } = match driver {- Ok(ok) => ok,- Err(err) => return build_streaming_error_response(&err),- };- let elapsed = start.elapsed();-- let body_bytes = match build_text_completion_body(&model_name, &request_id, &outcome) {- Ok(b) => b,- Err(resp) => return resp,- };-- state.registry.record_request("queue").await;- emit_audit_log(AuditEntry {- event: "proxy_request".to_string(),- method: "POST".to_string(),- endpoint: "completions".to_string(),- status: 200,- token_id,- model: model_name.clone(),- pool: effective_pool.clone(),- gpu: gpu.clone(),- worker: format!("queue:{request_id}"),- latency_ms: elapsed.as_millis() as u64,- body_bytes: content_length,- });-- let mut response = Response::builder()- .status(StatusCode::OK)- .body(Body::from(body_bytes))- .unwrap();- let h = response.headers_mut();- h.insert(- HeaderName::from_static("content-type"),- HeaderValue::from_static("application/json"),- );- h.insert(- HeaderName::from_static("x-sie-version"),- HeaderValue::from_static(GATEWAY_VERSION),- );- insert_buffered_generation_model_revision_header(- h,- model_revision.as_deref(),- &bundle_config_hash,- &outcome,- );- insert_stream_execution_identity_header(h, &outcome);- insert_stream_execution_binding_header(h, &outcome);- if let Ok(val) = HeaderValue::from_str(&request_id) {- h.insert(HeaderName::from_static("x-sie-request-id"), val);- }- insert_duration_header(h, "x-queue-publish-time", publish_elapsed);- insert_duration_header(h, "x-queue-wait-time", wait_elapsed);- response-}--/// Parsed, validated `/v1/responses` (OpenAI Responses API) request. MVP scope:-/// a single string `input` (raw prompt continuation), non-streaming.-struct ResponsesParams {- model: String,- /// Either a raw string prompt or a list of role/content messages.- input: publisher::GenerateInput,- max_new_tokens: u32,- temperature: Option<f32>,- top_p: Option<f32>,- seed: Option<i64>,-}--impl ResponsesParams {- /// The EXACT `WorkParams` a validated `/v1/responses` body dispatches with.- /// Extracted (not copied) for the same reason as- /// [`ChatRequestParams::into_work_params`] — see #2435.- fn into_work_params(self) -> publisher::WorkParams {- publisher::WorkParams {- generate: Some(publisher::GenerateParams {- input: self.input,- max_new_tokens: self.max_new_tokens,- temperature: self.temperature,- top_p: self.top_p,- seed: self.seed,- ..Default::default()- }),- ..Default::default()- }- }-}--enum ResponsesParamsResult {- Ok(ResponsesParams),- Err(Response),-}--/// The `(model, WorkParams)` a `/v1/responses` body dispatches with. See-/// [`chat_completions_dispatch_inputs`], including the `dead_code` note.-#[allow(clippy::result_large_err, dead_code)]-pub fn responses_dispatch_inputs(- body: &serde_json::Value,-) -> Result<(String, publisher::WorkParams), Response> {- match responses_params_from_json(body) {- ResponsesParamsResult::Ok(params) => {- let model = params.model.clone();- Ok((model, params.into_work_params()))- }- ResponsesParamsResult::Err(response) => Err(response),- }-}--/// Parse + validate a `/v1/responses` body. MVP: a string `input` or a-/// list of role/content messages, non-streaming. Out of scope: tools,-/// stateful threading (`previous_response_id`), reasoning, background,-/// metadata, instructions, multimodal content parts.-///-/// Validation is strict (H2 hardening): unrecognized top-level fields,-/// known-out-of-scope fields, missing roles, non-text content parts,-/// and present-but-wrong-type sampler / token-cap values all surface as-/// 400 rather than being silently coerced or dropped.-fn responses_params_from_json(body: &serde_json::Value) -> ResponsesParamsResult {- let bad = |msg: &str, param: Option<&str>, code: &'static str| {- ResponsesParamsResult::Err(- (- StatusCode::BAD_REQUEST,- Json(json_openai_error(- msg.to_string(),- oai_type::INVALID_REQUEST,- param,- code,- )),- )- .into_response(),- )- };- let Some(obj) = body.as_object() else {- return bad(- "request body must be a JSON object",- None,- oai_code::INVALID_REQUEST,- );- };-- // -- explicit reject-list: known-out-of-scope Responses fields. The- // Responses MVP is a stateless, single-turn, text-only- // surface. Anything else surfaces as ``unsupported_field`` so SDKs- // that target the wider OpenAI Responses spec fail loudly rather- // than silently losing context.- for &fname in &[- "previous_response_id",- "tools",- "tool_choice",- "reasoning",- "background",- "metadata",- "instructions",- ] {- if obj.contains_key(fname) {- return bad(- &format!("'{fname}' is not supported by this endpoint"),- Some(fname),- oai_code::UNSUPPORTED_FIELD,- );- }- }-- let model = match obj.get("model").and_then(|v| v.as_str()) {- Some(m) if !m.is_empty() => m.to_string(),- _ => {- return bad(- "field \"model\" is required",- Some("model"),- oai_code::INVALID_REQUEST,- )- }- };-- // The stateless Responses MVP accepts ordinary text messages only.- // Tool outputs require the wider Responses item/tool contract, which is- // explicitly out of scope here. ``developer`` normalizes to ``system``.- const ALLOWED_ROLES: &[&str] = &["system", "user", "assistant", "developer"];-- let input = match obj.get("input") {- Some(serde_json::Value::String(s)) => {- publisher::GenerateInput::Prompt { prompt: s.clone() }- }- // Responses array input: a list of {role, content} items. content- // is a string or a list of text parts; non-text parts reject.- Some(serde_json::Value::Array(items)) => {- if items.is_empty() {- return bad(- "'input' array must not be empty",- Some("input"),- oai_code::INVALID_REQUEST,- );- }- let mut messages: Vec<publisher::ChatMessage> = Vec::with_capacity(items.len());- for (i, item) in items.iter().enumerate() {- let Some(o) = item.as_object() else {- return bad(- &format!("input[{i}] must be an object"),- Some("input"),- oai_code::INVALID_REQUEST,- );- };- for key in o.keys() {- if !matches!(key.as_str(), "role" | "content") {- let param = format!("input[{i}].{key}");- return bad(- &format!("'{param}' is not supported by this endpoint"),- Some(¶m),- oai_code::UNSUPPORTED_FIELD,- );- }- }- let role = match o.get("role").and_then(|v| v.as_str()) {- Some("developer") => "system".to_string(),- Some(r) if ALLOWED_ROLES.contains(&r) => r.to_string(),- Some(other) => {- return bad(- &format!(- "input[{i}].role must be one of {ALLOWED_ROLES:?}, got {other:?}"- ),- Some(&format!("input[{i}].role")),- oai_code::INVALID_REQUEST,- );- }- None => {- return bad(- &format!("input[{i}].role is required and must be a string"),- Some(&format!("input[{i}].role")),- oai_code::INVALID_REQUEST,- );- }- };- let content = match o.get("content") {- Some(serde_json::Value::String(s)) => s.clone(),- Some(serde_json::Value::Array(parts)) => {- // Strict validation: each part must be a text part- // with a string ``text`` field. Non-text parts- // (image_url / input_image / etc.) reject;- // missing-or-non-string ``text`` rejects.- let mut text = String::new();- for (j, p) in parts.iter().enumerate() {- let Some(part_obj) = p.as_object() else {- return bad(- &format!("input[{i}].content[{j}] must be an object"),- Some(&format!("input[{i}].content[{j}]")),- oai_code::INVALID_REQUEST,- );- };- for key in part_obj.keys() {- if !matches!(key.as_str(), "type" | "text") {- let param = format!("input[{i}].content[{j}].{key}");- return bad(- &format!("'{param}' is not supported by this endpoint"),- Some(¶m),- oai_code::UNSUPPORTED_FIELD,- );- }- }- let ptype = match part_obj.get("type").and_then(|v| v.as_str()) {- Some(t) => t,- None => {- return bad(- &format!(- "input[{i}].content[{j}].type is required and must be a string"- ),- Some(&format!("input[{i}].content[{j}].type")),- oai_code::INVALID_REQUEST,- );- }- };- if !matches!(ptype, "text" | "input_text" | "output_text") {- return bad(- &format!(- "input[{i}].content[{j}]: unsupported content part type '{ptype}'"- ),- Some(&format!("input[{i}].content[{j}].type")),- oai_code::UNSUPPORTED_FIELD,- );- }- match part_obj.get("text") {- Some(serde_json::Value::String(t)) => text.push_str(t),- Some(_) => {- return bad(- &format!("input[{i}].content[{j}].text must be a string"),- Some(&format!("input[{i}].content[{j}].text")),- oai_code::INVALID_REQUEST,- );- }- None => {- return bad(- &format!(- "input[{i}].content[{j}].text is required for text content parts"- ),- Some(&format!("input[{i}].content[{j}].text")),- oai_code::INVALID_REQUEST,- );- }- }- }- text- }- _ => {- return bad(- &format!("input[{i}].content must be a string or text parts"),- Some(&format!("input[{i}].content")),- oai_code::INVALID_REQUEST,- );- }- };- messages.push(publisher::ChatMessage {- role,- content,- tool_calls: None,- tool_call_id: None,- // Responses-API path is text-only for now; vision arrives- // via /v1/chat/completions (the cut-your-bill skill surface).- images: None,- content_parts: None,- videos: None,- });- }- publisher::GenerateInput::Messages { messages }- }- _ => {- return bad(- "field \"input\" is required (a string or a list of messages)",- Some("input"),- oai_code::INVALID_REQUEST,- );- }- };-- // ``stream`` must be a boolean when present. ``true`` is rejected- // (streaming responses unimplemented); non-bool values reject as- // a type error rather than silently coercing.- match obj.get("stream") {- None | Some(serde_json::Value::Null) | Some(serde_json::Value::Bool(false)) => {}- Some(serde_json::Value::Bool(true)) => {- return bad(- "streaming is not yet supported on /v1/responses; use stream:false",- Some("stream"),- oai_code::UNSUPPORTED_FIELD,- );- }- Some(_) => {- return bad(- "'stream' must be a boolean",- Some("stream"),- oai_code::INVALID_REQUEST,- );- }- }-- // Responses uses ``max_output_tokens``; default to 16 to mirror completions.- let max_new_tokens = match obj.get("max_output_tokens") {- None | Some(serde_json::Value::Null) => 16u32,- Some(v) => match v.as_u64() {- Some(n) if (1..=u32::MAX as u64).contains(&n) => n as u32,- _ => {- return bad(- "'max_output_tokens' must be a positive integer",- Some("max_output_tokens"),- oai_code::INVALID_REQUEST,- )- }- },- };-- // -- samplers: reject present-but-invalid values rather than silently- // dropping them on the floor.- let temperature = match obj.get("temperature") {- None | Some(serde_json::Value::Null) => None,- Some(v) => match v.as_f64() {- Some(f) if f.is_finite() && f >= 0.0 && f <= f32::MAX as f64 => Some(f as f32),- _ => {- return bad(- "'temperature' must be a finite number >= 0",- Some("temperature"),- oai_code::INVALID_REQUEST,- );- }- },- };- let top_p = match obj.get("top_p") {- None | Some(serde_json::Value::Null) => None,- Some(v) => match v.as_f64() {- Some(f) if f.is_finite() && f > 0.0 && f <= 1.0 => Some(f as f32),- _ => {- return bad(- "'top_p' must be a number in (0, 1]",- Some("top_p"),- oai_code::INVALID_REQUEST,- );- }- },- };- let seed = match parse_seed_field(obj.get("seed")) {- Ok(seed) => seed,- Err(resp) => return ResponsesParamsResult::Err(resp),- };-- // -- allow-list: anything else surfaces as ``unsupported_field``.- const ACCEPTED: &[&str] = &[- "model",- "input",- "max_output_tokens",- "temperature",- "top_p",- "seed",- "stream",- ];- for key in obj.keys() {- if !ACCEPTED.contains(&key.as_str()) {- return bad(- &format!("'{key}' is not supported by this endpoint"),- Some(key),- oai_code::UNSUPPORTED_FIELD,- );- }- }-- ResponsesParamsResult::Ok(ResponsesParams {- model,- input,- max_new_tokens,- temperature,- top_p,- seed,- })-}--/// Responses-API usage block. `input_tokens_details.cached_tokens` appears-/// only when the worker reported a prefix-cache count.-fn responses_usage(usage: &crate::queue::streaming::UsageBlock) -> Value {- let mut body = json!({- "input_tokens": usage.prompt_tokens,- "output_tokens": usage.completion_tokens,- "total_tokens": usage.total_tokens,- });- if let Some(cached) = usage.cached_prompt_tokens() {- body["input_tokens_details"] = json!({ "cached_tokens": cached });- }- body-}--/// Build the OpenAI Responses `response` body from the aggregated outcome.-#[allow(clippy::result_large_err)]-fn build_responses_body(- model: &str,- request_id: &str,- outcome: &crate::queue::streaming::StreamOutcome,-) -> Result<Vec<u8>, Response> {- let Some(usage) = outcome.usage.as_ref() else {- return Err((- StatusCode::INTERNAL_SERVER_ERROR,- Json(json_openai_error(- "worker terminal chunk omitted required 'usage' block",- oai_type::SERVER_ERROR,- None,- oai_code::MALFORMED_WORKER_RESPONSE,- )),- )- .into_response());- };- let created = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_secs())- .unwrap_or(0);- let body = json!({- "id": format!("resp-{}", request_id),- "object": "response",- "created_at": created,- "model": model,- "status": "completed",- "output": [{- "type": "message",- "id": format!("msg-{}", request_id),- "role": "assistant",- "status": "completed",- "content": [{- "type": "output_text",- "text": outcome.text,- "annotations": [],- }],- }],- "usage": responses_usage(usage),- });- Ok(serde_json::to_vec(&body).unwrap_or_default())-}--#[utoipa::path(- post,- path = "/v1/responses",- tag = "inference",- description = "OpenAI Responses API (MVP): string input, non-streaming.",- responses(- (status = 200, description = "Response object"),- (status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),- (status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),- (status = 413, description = "Request body is too large", body = crate::openapi::OpenAIErrorEnvelope),- (status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),- (status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),- )-)]-/// `/v1/responses` — OpenAI Responses API (MVP). String `input` → raw-prompt-/// generation via the shared resolve+drive helpers; `response`-shaped body.-pub async fn proxy_responses(State(state): State<Arc<AppState>>, mut req: Request) -> Response {- if let Some(response) = invalid_remote_header_response("generate", req.headers()) {- return response;- }- let disclosure = ServingDisclosure::install(&mut req);- let fallback = FallbackAttempt::install(&mut req);- let mut response = proxy_responses_inner(state, req).await;- disclosure.stamp(response.status(), response.headers_mut());- fallback.finish(response)-}--async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {- check_sdk_version(req.headers());- let metric_labels_slot = req- .extensions()- .get::<telemetry::MetricLabelsSlot>()- .cloned();-- let max_responses_body = compat_request_body_limit("/v1/responses");- let hdr = req.headers().clone();- let (parts, body) = req.into_parts(); // keep extensions (caller identity) for the #1841 gate- let body_bytes = match to_bytes(body, max_responses_body).await {- Ok(b) => b,- Err(e) => {- let (status, _, message) = request_body_error(&e, max_responses_body);- return (- status,- Json(json_openai_error(- message,- oai_type::INVALID_REQUEST,- None,- oai_code::INVALID_REQUEST,- )),- )- .into_response();- }- };- let body_json: serde_json::Value = match serde_json::from_slice(&body_bytes) {- Ok(v) => v,- Err(e) => {- return (- StatusCode::BAD_REQUEST,- Json(json_openai_error(- format!("invalid JSON: {e}"),- oai_type::INVALID_REQUEST,- None,- oai_code::INVALID_REQUEST,- )),- )- .into_response();- }- };-- let params = match responses_params_from_json(&body_json) {- ResponsesParamsResult::Ok(p) => p,- ResponsesParamsResult::Err(resp) => return resp,- };-- let (model_name, bundle) =- match resolve_model_and_bundle(&state, ¶ms.model, &parts.extensions) {- Ok(mb) => mb,- Err(resp) => return resp,- };- ServingDisclosure::record(&state, &parts.extensions, &model_name);- if let Some(response) =- unsupported_operation_response(&state, "chat", "generate", &model_name, &model_name)- {+ ) {return response;}- let (explicit_bundle_override, _) =- resolve_model_spec_with_aliases(&state.config.model_aliases, ¶ms.model, |model| {- state.model_registry.resolve_canonical_model_name(model)- });+let ResolvedRoute {dispatch_model,require_execution_authority_v1,@@ -11308,7 +10634,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {&explicit_bundle_override,&parts.extensions,!native_request_has_profile_selector(&body_bytes, false),- (params.max_new_tokens, "max_output_tokens"),+ (params.max_new_tokens, "max_tokens"),metric_labels_slot.as_ref(),).await@@ -11318,11 +10644,46 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {};let start = Instant::now();+ // Copied out BEFORE the params are consumed into `WorkParams` below.let requested_model = params.model.clone();+ let stream = params.stream;+ let stream_include_usage = params.stream_include_usage;let mut work_params = params.into_work_params();work_params.require_execution_authority_v1 = require_execution_authority_v1;work_params.fallback_reason = fallback_reason;+ // SSE streaming → emit `text_completion` chunks. Single-candidate+ // (completions rejects n>1), so no per-candidate interleave.+ if stream {+ return super::sse::build_sse_response(super::sse::SseParams {+ prefetch_first_output: parts+ .extensions+ .get::<FallbackAttempt>()+ .is_some_and(FallbackAttempt::active),+ local_serving_model: FallbackAttempt::defer_local_stream(&parts.extensions),+ state: state.as_ref(),+ work_publisher: work_publisher_arc,+ physical_lane: physical_lane.clone(),+ requested_model,+ model: model_name.clone(),+ // /v1/completions does not accept grammar, so it never routes:+ // dispatch == display.+ dispatch_model: dispatch_model.clone(),+ bundle: bundle.clone(),+ engine: engine.clone(),+ gpu: effective_machine_profile.clone(),+ pool: effective_pool.clone(),+ admission_pool: admission_pool.clone(),+ bundle_config_hash: bundle_config_hash.clone(),+ work_params,+ endpoint: super::sse::SseEndpoint::Completion {+ include_usage: stream_include_usage,+ },+ route: RouteKind::Compatibility,+ })+ .await;+ }+let driver = run_streaming_generate(&state,work_publisher_arc,@@ -11340,6 +10701,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {RouteKind::Compatibility,).await;+let StreamingDriverOk {outcome,request_id,@@ -11351,7 +10713,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {};let elapsed = start.elapsed();- let body_bytes = match build_responses_body(&model_name, &request_id, &outcome) {+ let body_bytes = match build_text_completion_body(&model_name, &request_id, &outcome) {Ok(b) => b,Err(resp) => return resp,};@@ -11360,7 +10722,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {emit_audit_log(AuditEntry {event: "proxy_request".to_string(),method: "POST".to_string(),- endpoint: "responses".to_string(),+ endpoint: "completions".to_string(),status: 200,token_id,model: model_name.clone(),@@ -16621,6 +15983,7 @@ pub async fn proxy_moderations() -> Response {#[cfg(test)]mod tests {use super::*;+ use crate::handlers::responses::proxy_responses;use crate::handlers::test_support::{TestGateway, HYBRID_GENERATE_MODEL, LOCAL_LANE, REMOTE_LANE,};@@ -29623,32 +28986,15 @@ mod tests {}}- // ── /v1/responses ────────────────────────────────────────────────-- fn _responses_body_min(model: &str) -> serde_json::Value {- serde_json::json!({"model": model, "input": "Tell me a joke"})- }-- async fn _responses_err(body: serde_json::Value) -> serde_json::Value {- let resp = match responses_params_from_json(&body) {- ResponsesParamsResult::Ok(_) => panic!("expected Err"),- ResponsesParamsResult::Err(r) => r,- };- let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)- .await- .unwrap();- serde_json::from_slice(&bytes).unwrap()- }-/// `temperature` on every generation body parser (chat, completions,- /// responses, native generate; streaming and non-streaming share them):+ /// native generate; streaming and non-streaming share them):/// any finite number >= 0 is accepted, as the worker accepts it, and a/// negative, non-finite-looking or non-numeric value is a 400 naming the/// param and the range.#[tokio::test]async fn test_temperature_range_is_the_same_on_every_generation_parser() {type Accepted = fn(&serde_json::Value) -> Option<f32>;- let parsers: [(&str, serde_json::Value, Accepted); 4] =+ let parsers: [(&str, serde_json::Value, Accepted); 3] =[("chat", _chat_body_min("m"), |body| {_expect_chat_ok(body.clone()).temperature@@ -29659,14 +29005,6 @@ mod tests {CompletionsParamsResult::Err(_) => panic!("completions refused {body}"),}}),- (- "responses",- _responses_body_min("m"),- |body| match responses_params_from_json(body) {- ResponsesParamsResult::Ok(p) => p.temperature,- ResponsesParamsResult::Err(_) => panic!("responses refused {body}"),- },- ),("generate",json!({"prompt": "hi", "max_new_tokens": 8}),@@ -29675,11 +29013,6 @@ mod tests {];for (route, base, accepted) in parsers {for stream in [false, true] {- // Responses refuses `stream: true` on its own; the sampler- // check is the same either way.- if route == "responses" && stream {- continue;- }for (value, want) in [(json!(0), 0.0_f32),(json!(0.0), 0.0),@@ -29706,7 +29039,6 @@ mod tests {let err = match route {"chat" => _expect_chat_err(body).await,"completions" => _completions_err(body).await,- "responses" => _responses_err(body).await,_ => _expect_generate_err(&body).await,};assert_eq!(err["error"]["param"], "temperature", "{route} {value}");@@ -29720,426 +29052,6 @@ mod tests {}}- #[tokio::test]- async fn test_responses_shared_request_conformance_vectors() {- let raw = include_str!(- "../../../../conformance/openai_generation/responses_request_vectors.json"- );- let vectors: serde_json::Value = serde_json::from_str(raw).expect("valid conformance JSON");-- for case in vectors["accepted"].as_array().expect("accepted vectors") {- let name = case["name"].as_str().expect("case name");- let params = match responses_params_from_json(&case["body"]) {- ResponsesParamsResult::Ok(params) => params,- ResponsesParamsResult::Err(_) => panic!("accepted case {name:?} was rejected"),- };- let (prompt, messages) = match params.input {- publisher::GenerateInput::Prompt { prompt } => {- (Some(prompt), serde_json::Value::Null)- }- publisher::GenerateInput::Messages { messages } => (- None,- serde_json::Value::Array(- messages- .into_iter()- .map(|message| {- serde_json::json!({- "role": message.role,- "content": message.content,- })- })- .collect(),- ),- ),- };- let mut observed = serde_json::json!({- "model": params.model,- "prompt": prompt,- "messages": messages,- "max_output_tokens": params.max_new_tokens,- "temperature": params.temperature,- "top_p": params.top_p,- "seed": params.seed,- });- let mut expected = case["expected"].clone();- for field in ["temperature", "top_p"] {- match (observed[field].as_f64(), expected[field].as_f64()) {- (Some(left), Some(right)) => assert!(- (left - right).abs() <= f32::EPSILON as f64,- "accepted case {name:?} field {field:?}: {left} != {right}"- ),- (None, None) if observed[field].is_null() && expected[field].is_null() => {}- _ => panic!("accepted case {name:?} field {field:?} differs"),- }- observed- .as_object_mut()- .expect("observed object")- .remove(field);- expected- .as_object_mut()- .expect("expected object")- .remove(field);- }- assert_eq!(observed, expected, "accepted case {name:?}");- }-- for case in vectors["rejected"].as_array().expect("rejected vectors") {- let name = case["name"].as_str().expect("case name");- let error = _responses_err(case["body"].clone()).await;- assert_eq!(- error["error"]["param"], case["param"],- "rejected case {name:?}"- );- assert_eq!(- error["error"]["code"], case["code"],- "rejected case {name:?}"- );- }- }-- #[test]- fn test_responses_params_ok_string_input() {- match responses_params_from_json(&_responses_body_min("m")) {- ResponsesParamsResult::Ok(p) => {- assert_eq!(p.model, "m");- assert_eq!(p.max_new_tokens, 16);- match p.input {- publisher::GenerateInput::Prompt { prompt } => {- assert_eq!(prompt, "Tell me a joke")- }- publisher::GenerateInput::Messages { .. } => panic!("expected Prompt"),- }- }- ResponsesParamsResult::Err(_) => panic!("expected Ok"),- }- }-- #[tokio::test]- async fn test_responses_missing_input() {- let v = _responses_err(serde_json::json!({"model": "m"})).await;- assert_eq!(v["error"]["param"], "input");- }-- #[test]- fn test_responses_accepts_array_input_as_messages() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([- {"role": "user", "content": "hi"},- {"role": "assistant", "content": [{"type": "output_text", "text": "hello "}, {"type": "output_text", "text": "there"}]},- ]);- match responses_params_from_json(&body) {- ResponsesParamsResult::Ok(p) => match p.input {- publisher::GenerateInput::Messages { messages } => {- assert_eq!(messages.len(), 2);- assert_eq!(messages[0].role, "user");- assert_eq!(messages[0].content, "hi");- assert_eq!(messages[1].content, "hello there"); // text parts concatenated- }- publisher::GenerateInput::Prompt { .. } => panic!("expected Messages"),- },- ResponsesParamsResult::Err(_) => panic!("expected Ok"),- }- }-- #[tokio::test]- async fn test_responses_rejects_empty_array_input() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "input");- }-- #[tokio::test]- async fn test_responses_rejects_stream() {- let mut body = _responses_body_min("m");- body["stream"] = serde_json::json!(true);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "stream");- }-- // ── /v1/responses H2 hardening ───────────────────────────────────- //- // Strict allow-list + present-but-wrong-type rejection. These cases- // previously silently coerced or dropped — they must now 400.-- #[tokio::test]- async fn test_responses_rejects_previous_response_id() {- let mut body = _responses_body_min("m");- body["previous_response_id"] = serde_json::json!("resp-abc");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "previous_response_id");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_tools() {- let mut body = _responses_body_min("m");- body["tools"] = serde_json::json!([{"type": "function"}]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "tools");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_tool_choice() {- let mut body = _responses_body_min("m");- body["tool_choice"] = serde_json::json!("auto");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "tool_choice");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_reasoning() {- let mut body = _responses_body_min("m");- body["reasoning"] = serde_json::json!({"effort": "high"});- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "reasoning");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_background() {- let mut body = _responses_body_min("m");- body["background"] = serde_json::json!(true);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "background");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_metadata() {- let mut body = _responses_body_min("m");- body["metadata"] = serde_json::json!({"k": "v"});- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "metadata");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_instructions() {- let mut body = _responses_body_min("m");- body["instructions"] = serde_json::json!("be terse");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "instructions");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_unknown_top_level_field() {- let mut body = _responses_body_min("m");- body["foo_bar"] = serde_json::json!(1);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "foo_bar");- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_non_bool_stream_string() {- let mut body = _responses_body_min("m");- body["stream"] = serde_json::json!("true");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "stream");- assert_eq!(v["error"]["code"], "invalid_request");- }-- #[tokio::test]- async fn test_responses_rejects_non_bool_stream_int() {- let mut body = _responses_body_min("m");- body["stream"] = serde_json::json!(1);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "stream");- }-- #[tokio::test]- async fn test_responses_rejects_input_image_part() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([- {"role": "user", "content": [{"type": "input_image", "image_url": "data:image/png;base64,..."}]},- ]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_unknown_content_part_type() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([- {"role": "user", "content": [{"type": "audio", "data": "..."}]},- ]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["code"], "unsupported_field");- }-- #[tokio::test]- async fn test_responses_rejects_missing_text_on_text_part() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([- {"role": "user", "content": [{"type": "input_text"}]},- ]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["code"], "invalid_request");- }-- #[tokio::test]- async fn test_responses_rejects_non_string_text_on_text_part() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([- {"role": "user", "content": [{"type": "input_text", "text": 42}]},- ]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["code"], "invalid_request");- }-- #[tokio::test]- async fn test_responses_rejects_missing_role_on_input_message() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([{"content": "hi"}]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["code"], "invalid_request");- assert!(v["error"]["param"].as_str().unwrap().ends_with(".role"));- }-- #[tokio::test]- async fn test_responses_rejects_invalid_role_on_input_message() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([{"role": "alien", "content": "hi"}]);- let v = _responses_err(body).await;- assert_eq!(v["error"]["code"], "invalid_request");- }-- #[test]- fn test_responses_accepts_developer_role_as_system() {- let mut body = _responses_body_min("m");- body["input"] = serde_json::json!([{"role": "developer", "content": "be helpful"}]);- match responses_params_from_json(&body) {- ResponsesParamsResult::Ok(p) => match p.input {- publisher::GenerateInput::Messages { messages } => {- assert_eq!(messages[0].role, "system");- }- _ => panic!("expected Messages"),- },- ResponsesParamsResult::Err(_) => panic!("expected Ok"),- }- }-- #[tokio::test]- async fn test_responses_rejects_string_temperature() {- let mut body = _responses_body_min("m");- body["temperature"] = serde_json::json!("0.5");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "temperature");- }-- #[tokio::test]- async fn test_responses_rejects_top_p_out_of_range() {- let mut body = _responses_body_min("m");- body["top_p"] = serde_json::json!(1.5);- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "top_p");- }-- #[tokio::test]- async fn test_responses_rejects_string_seed() {- let mut body = _responses_body_min("m");- body["seed"] = serde_json::json!("42");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "seed");- }-- #[test]- fn test_responses_preserves_negative_seed() {- let mut body = _responses_body_min("m");- body["seed"] = serde_json::json!(-1);- match responses_params_from_json(&body) {- ResponsesParamsResult::Ok(params) => assert_eq!(params.seed, Some(-1)),- ResponsesParamsResult::Err(_) => panic!("expected Ok"),- }- }-- #[tokio::test]- async fn test_responses_rejects_string_max_output_tokens() {- let mut body = _responses_body_min("m");- body["max_output_tokens"] = serde_json::json!("16");- let v = _responses_err(body).await;- assert_eq!(v["error"]["param"], "max_output_tokens");- }-- #[test]- fn test_responses_accepts_null_temperature() {- // Explicit null must not 400 — it is treated as "absent".- let mut body = _responses_body_min("m");- body["temperature"] = serde_json::Value::Null;- match responses_params_from_json(&body) {- ResponsesParamsResult::Ok(p) => assert!(p.temperature.is_none()),- ResponsesParamsResult::Err(_) => panic!("expected Ok"),- }- }-- #[test]- fn test_build_responses_body_shape() {- let outcome = crate::queue::streaming::StreamOutcome {- text: "a joke".to_string(),- finish_reason: "stop".to_string(),- usage: Some(crate::queue::streaming::UsageBlock {- upstream_usage: None,- gpu_second: None,- images: None,- prompt_tokens_details: None,- prompt_tokens: 5,- completion_tokens: 7,- total_tokens: 12,- }),- attempt_id: "att".to_string(),- ttft_ms: None,- tpot_ms: None,- error: None,- origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,- tool_calls: None,- logprobs: None,- candidates: Vec::new(),- executed_bundle_config_hash: None,- execution_identity_sha256: None,- execution_binding_sha256: None,- reasoning: Default::default(),- };- let bytes = build_responses_body("m", "req-1", &outcome).expect("ok");- let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();- assert_eq!(v["object"], "response");- assert_eq!(v["status"], "completed");- assert!(v["id"].as_str().unwrap().starts_with("resp-"));- assert_eq!(v["output"][0]["type"], "message");- assert_eq!(v["output"][0]["content"][0]["type"], "output_text");- assert_eq!(v["output"][0]["content"][0]["text"], "a joke");- assert_eq!(v["usage"]["input_tokens"], 5);- assert_eq!(v["usage"]["output_tokens"], 7);- assert!(v["usage"].get("input_tokens_details").is_none());- }-- #[test]- fn test_responses_usage_reports_cached_input_tokens() {- let usage = crate::queue::streaming::UsageBlock {- upstream_usage: None,- gpu_second: None,- images: None,- prompt_tokens_details: Some(crate::queue::streaming::PromptTokensDetails {- cached_tokens: 4,- }),- prompt_tokens: 5,- completion_tokens: 7,- total_tokens: 12,- };- assert_eq!(- responses_usage(&usage),- serde_json::json!({- "input_tokens": 5,- "output_tokens": 7,- "total_tokens": 12,- "input_tokens_details": {"cached_tokens": 4},- })- );- }-/// ``n=0`` rejects as invalid_request (must be positive).#[tokio::test]async fn test_chat_params_from_json_rejects_n_zero() {@@ -32720,6 +31632,7 @@ mod governed_bridge_route_tests {#[cfg(test)]mod unsupported_operation_tests {use super::*;+ use crate::handlers::responses::proxy_responses;use crate::handlers::test_support::{TestGateway, HYBRID_GENERATE_MODEL, LOCAL_ENCODE_MODEL};/// A score-only model.diff --git a/packages/sie_gateway/src/handlers/responses.rs b/packages/sie_gateway/src/handlers/responses.rsnew file mode 100644index 000000000..f7e3fe6b4--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses.rs@@ -0,0 +1,192 @@+//! `POST /v1/responses`: the OpenAI Responses API as a translation onto+//! `/v1/chat/completions`.+//!+//! The request is validated and translated into a chat completions body+//! ([`request`]), the gateway's own chat handler serves it in process on the+//! same task, and its answer is translated back: a chat completion into a+//! Response ([`response`]), chat SSE chunks into Responses events+//! ([`stream`]), and a chat error into the same OpenAI error with the field+//! renamed ([`error`]). Every chat gate, limit, timeout and metering point+//! therefore applies unchanged. Responses are not stored, so the+//! `/v1/responses/{id}` routes are not served.++mod error;+mod request;+mod response;+pub mod schema;+mod stream;+#[cfg(test)]+mod tests;++use std::sync::Arc;+use std::time::{SystemTime, UNIX_EPOCH};++use axum::body::{to_bytes, Body};+use axum::extract::{Request, State};+use axum::http::{header, Method, StatusCode};+use axum::response::{IntoResponse, Response};+use serde_json::Value;++use crate::handlers::proxy::{+ buffer_compat_response_body, chat_completions_dispatch_inputs, compat_request_body_limit,+ is_openai_compat_forwarded_header, is_openai_compat_inner_request_header, proxy_chat,+ request_body_error, CompatResponseBody,+};+use crate::http_error::GatewayOwnedFault;+use crate::queue::publisher;+use crate::server::AppState;++use self::error::{responses_error_response, ResponsesError};+use self::response::{chat_completion_to_response, ResponseShell};++fn request_id(response: &Response) -> String {+ response+ .headers()+ .get("x-sie-request-id")+ .and_then(|value| value.to_str().ok())+ .unwrap_or_default()+ .to_string()+}++fn now() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|elapsed| elapsed.as_secs())+ .unwrap_or(0)+}++#[utoipa::path(+ post,+ path = "/v1/responses",+ tag = "inference",+ description = "OpenAI Responses API. The request is translated into a \+ /v1/chat/completions request, served by the chat route with all of its \+ limits, and the answer is translated back. Buffered and streaming answers \+ are supported. Function and custom tools are supported; hosted tools are \+ refused. Responses are not stored: previous_response_id, conversation, \+ store: true and background: true are refused, and the /v1/responses/{id} \+ routes are not served.",+ request_body = crate::handlers::responses::schema::ResponsesRequest,+ params(+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override")+ ),+ responses(+ (status = 200, description = "Response, or a text/event-stream of Responses events when stream is true", content(+ (crate::handlers::responses::schema::ResponsesResponse = "application/json"),+ (String = "text/event-stream"),+ )),+ (status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 413, description = "Request body is too large", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),+ )+)]+pub async fn proxy_responses(State(state): State<Arc<AppState>>, request: Request) -> Response {+ let (parts, body) = request.into_parts();+ let limit = compat_request_body_limit("/v1/responses");+ let bytes = match to_bytes(body, limit).await {+ Ok(bytes) => bytes,+ Err(error) => {+ let (status, _, message) = request_body_error(&error, limit);+ return ResponsesError::request(status, message).into_response();+ }+ };+ let body: Value = match serde_json::from_slice(&bytes) {+ Ok(body) => body,+ Err(error) => {+ return ResponsesError::request(+ StatusCode::BAD_REQUEST,+ format!("invalid JSON: {error}"),+ )+ .into_response()+ }+ };+ let translation = match request::responses_to_chat(&body) {+ Ok(translation) => translation,+ Err(error) => return error.into_response(),+ };+ let Ok(chat_bytes) = serde_json::to_vec(&translation.chat) else {+ return ResponsesError::internal("failed to build the chat request").into_response();+ };+ let mut builder = Request::builder()+ .method(Method::POST)+ .uri("/v1/chat/completions")+ .version(parts.version);+ for (name, value) in parts.headers.iter() {+ if is_openai_compat_inner_request_header(name.as_str()) {+ builder = builder.header(name, value);+ }+ }+ builder = builder.header(header::CONTENT_TYPE, "application/json");+ let Ok(mut inner) = builder.body(Body::from(chat_bytes)) else {+ return ResponsesError::internal("failed to build the chat request").into_response();+ };+ *inner.extensions_mut() = parts.extensions;++ let answer = proxy_chat(State(state), inner).await;+ if !answer.status().is_success() {+ return responses_error_response(answer).await;+ }+ let shell = ResponseShell::new(translation.echo, request_id(&answer), now());+ if translation.stream {+ let (mut parts, body) = answer.into_parts();+ parts.headers.remove(header::CONTENT_LENGTH);+ let machine = stream::StreamMachine::new(shell);+ return Response::from_parts(parts, stream::stream_body(body, machine));+ }+ buffered_response(answer, &shell).await+}++async fn buffered_response(answer: Response, shell: &ResponseShell) -> Response {+ let (parts, body) = answer.into_parts();+ let translated = match buffer_compat_response_body(body).await {+ CompatResponseBody::Buffered(bytes) => serde_json::from_slice::<Value>(&bytes)+ .map_err(|_| "the chat completion is not valid JSON".to_string())+ .and_then(|chat| chat_completion_to_response(&chat, shell))+ .map_err(|reason| ("translate_chat_response", reason)),+ CompatResponseBody::TooLarge { .. } | CompatResponseBody::Unreadable => Err((+ "read_chat_response",+ "failed to read the chat completion".to_string(),+ )),+ };+ let (mut response, fault) = match translated {+ Ok(translated) => (+ (StatusCode::OK, axum::Json(translated)).into_response(),+ None,+ ),+ Err((stage, reason)) => (+ ResponsesError::internal(reason).into_response(),+ Some(stage),+ ),+ };+ for (name, value) in parts.headers.iter() {+ if is_openai_compat_forwarded_header(name.as_str()) {+ response.headers_mut().insert(name.clone(), value.clone());+ }+ }+ *response.extensions_mut() = parts.extensions;+ match fault {+ Some(stage) => GatewayOwnedFault::new(stage).mark(response),+ None => response,+ }+}++/// The `(model, WorkParams)` a `/v1/responses` body dispatches with: the+/// translation composed with the chat seam, so an estimate or an admission+/// check prices and admits exactly what the chat route would run.+///+/// A translation refusal is the Responses error answer; a chat refusal is+/// the chat route's own.+///+/// `dead_code`-allowed because the `sie-gateway` binary compiles this module+/// tree independently of the library, and only a downstream composition+/// calls this seam.+#[allow(clippy::result_large_err, dead_code)]+pub fn responses_dispatch_inputs(+ body: &Value,+) -> Result<(String, publisher::WorkParams), Response> {+ let translation = request::responses_to_chat(body).map_err(ResponsesError::into_response)?;+ chat_completions_dispatch_inputs(&translation.chat)+}diff --git a/packages/sie_gateway/src/handlers/responses/error.rs b/packages/sie_gateway/src/handlers/responses/error.rsnew file mode 100644index 000000000..7e625c9fc--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses/error.rs@@ -0,0 +1,155 @@+//! Errors on `/v1/responses`, in the OpenAI envelope+//! `{"error":{"message","type","param","code"}}` the chat route already uses.+//!+//! A translation refusal names the field as the caller sent it. A chat error+//! keeps its status, headers, extensions and body; only `error.param` is+//! renamed from the chat field to the Responses field it was translated from.++use axum::body::{to_bytes, Body};+use axum::http::{header, HeaderValue, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::Json;+use hyper::body::Body as _;+use serde_json::Value;++use crate::http_error::{json_openai_error, openai_code, openai_type};++const MAX_ERROR_BODY: usize = 1024 * 1024;++/// An error decided in Responses terms.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ResponsesError {+ pub status: StatusCode,+ pub error_type: &'static str,+ pub code: &'static str,+ pub param: Option<String>,+ pub message: String,+}++impl ResponsesError {+ fn refusal(code: &'static str, param: String, reason: &str) -> Self {+ Self {+ status: StatusCode::BAD_REQUEST,+ error_type: openai_type::INVALID_REQUEST,+ code,+ message: format!("{param}: {reason}"),+ param: Some(param),+ }+ }++ pub(crate) fn invalid(param: impl Into<String>, reason: &str) -> Self {+ Self::refusal(openai_code::INVALID_REQUEST, param.into(), reason)+ }++ pub(crate) fn unsupported(param: impl Into<String>, reason: &str) -> Self {+ Self::refusal(openai_code::UNSUPPORTED_FIELD, param.into(), reason)+ }++ pub(crate) fn extra(param: impl Into<String>) -> Self {+ Self::unsupported(param, "Extra inputs are not permitted")+ }++ pub(crate) fn required(param: impl Into<String>) -> Self {+ Self::invalid(param, "Field required")+ }++ /// A refusal of the request as a whole, before any field is read.+ pub(crate) fn request(status: StatusCode, message: impl Into<String>) -> Self {+ Self {+ status,+ error_type: openai_type::INVALID_REQUEST,+ code: openai_code::INVALID_REQUEST,+ param: None,+ message: message.into(),+ }+ }++ pub(crate) fn internal(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::INTERNAL_SERVER_ERROR,+ error_type: openai_type::SERVER_ERROR,+ code: openai_code::MALFORMED_WORKER_RESPONSE,+ param: None,+ message: message.into(),+ }+ }++ pub(crate) fn into_response(self) -> Response {+ (+ self.status,+ Json(json_openai_error(+ self.message,+ self.error_type,+ self.param.as_deref(),+ self.code,+ )),+ )+ .into_response()+ }+}++/// The Responses name of a field a chat error names.+pub(crate) fn responses_param(param: &str) -> String {+ match param {+ "max_completion_tokens" => return "max_output_tokens".to_string(),+ "reasoning_effort" => return "reasoning.effort".to_string(),+ "response_format" => return "text.format".to_string(),+ _ => {}+ }+ if let Some(field) = param+ .strip_prefix("response_format.json_schema.")+ .filter(|field| !field.is_empty())+ {+ return format!("text.format.{field}");+ }+ if let Some((index, field)) = param+ .strip_prefix("tools[")+ .and_then(|rest| rest.split_once("].function."))+ {+ if !index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()) && !field.is_empty()+ {+ return format!("tools[{index}].{field}");+ }+ }+ param.to_string()+}++/// A non-2xx chat answer as `/v1/responses` returns it. A body too large to+/// rewrite passes through as it is.+pub(crate) async fn responses_error_response(response: Response) -> Response {+ let (mut parts, body) = response.into_parts();+ if body.size_hint().lower() > MAX_ERROR_BODY as u64 {+ return Response::from_parts(parts, body);+ }+ parts.headers.remove(header::CONTENT_LENGTH);+ let Ok(bytes) = to_bytes(body, MAX_ERROR_BODY).await else {+ parts.headers.insert(+ header::CONTENT_TYPE,+ HeaderValue::from_static("application/json"),+ );+ let unreadable = json_openai_error(+ "the chat route's error answer could not be read",+ openai_type::SERVER_ERROR,+ None,+ openai_code::TRANSPORT_FAILURE,+ );+ return Response::from_parts(parts, Body::from(unreadable.to_string()));+ };+ let renamed = serde_json::from_slice::<Value>(&bytes)+ .ok()+ .and_then(|mut answer| {+ let param = answer.get_mut("error")?.get_mut("param")?;+ let chat_param = param.as_str()?;+ let renamed = responses_param(chat_param);+ if renamed == chat_param {+ return None;+ }+ *param = Value::String(renamed);+ serde_json::to_vec(&answer).ok()+ });+ let body = match renamed {+ Some(renamed) => Body::from(renamed),+ None => Body::from(bytes),+ };+ Response::from_parts(parts, body)+}diff --git a/packages/sie_gateway/src/handlers/responses/request.rs b/packages/sie_gateway/src/handlers/responses/request.rsnew file mode 100644index 000000000..a2fb46734--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses/request.rs@@ -0,0 +1,869 @@+//! Request translation: an OpenAI Responses body into a chat completions+//! body.+//!+//! Validation happens here only where the chat route cannot name the field+//! the caller sent: the request shape, input items, content parts and tool+//! types. Sampling values, tool names and the tool count are the chat route's+//! to check. The accepted-but-inert set is `store: false`, `background:+//! false`, `truncation: "disabled"`, `include` of+//! `reasoning.encrypted_content`, `client_metadata`, `reasoning.summary`,+//! `reasoning.generate_summary` and `text.verbosity`.++use serde_json::{json, Map, Value};++use super::error::ResponsesError;+use super::response::Echo;++const STATELESS: &str = "SIE does not store responses; send the full conversation in input";+const ENCRYPTED_REASONING: &str = "reasoning.encrypted_content";+const PASSED_THROUGH: [&str; 5] = [+ "metadata",+ "prompt_cache_key",+ "user",+ "safety_identifier",+ "service_tier",+];+const TEXT_PART_KEYS: [&str; 2] = ["type", "text"];+const OUTPUT_TEXT_PART_KEYS: [&str; 4] = ["type", "text", "annotations", "logprobs"];+const IMAGE_PART_KEYS: [&str; 4] = ["type", "image_url", "file_id", "detail"];++/// A translated request.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct ChatTranslation {+ pub chat: Value,+ pub stream: bool,+ pub echo: Echo,+}++type Result<T> = std::result::Result<T, ResponsesError>;++fn object<'a>(value: &'a Value, path: &str) -> Result<&'a Map<String, Value>> {+ value+ .as_object()+ .ok_or_else(|| ResponsesError::invalid(path, "Input should be a valid dictionary"))+}++fn only_keys(map: &Map<String, Value>, allowed: &[&str], path: &str) -> Result<()> {+ match map.keys().find(|key| !allowed.contains(&key.as_str())) {+ Some(key) => Err(ResponsesError::extra(format!("{path}.{key}"))),+ None => Ok(()),+ }+}++fn present<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {+ map.get(key).filter(|value| !value.is_null())+}++fn string<'a>(map: &'a Map<String, Value>, key: &str, path: &str) -> Result<&'a str> {+ match present(map, key) {+ None => Err(ResponsesError::required(format!("{path}.{key}"))),+ Some(Value::String(value)) => Ok(value),+ Some(_) => Err(ResponsesError::invalid(+ format!("{path}.{key}"),+ "Input should be a valid string",+ )),+ }+}++/// Message content: adjacent texts joined, empty texts dropped, images kept+/// in order.+#[derive(Default)]+struct Parts {+ items: Vec<Part>,+}++enum Part {+ Text(String),+ Image(String),+}++impl Parts {+ fn text(&mut self, text: &str) {+ if text.is_empty() {+ return;+ }+ if let Some(Part::Text(last)) = self.items.last_mut() {+ last.push_str(text);+ } else {+ self.items.push(Part::Text(text.to_string()));+ }+ }++ fn image(&mut self, url: String) {+ self.items.push(Part::Image(url));+ }++ fn into_content(self) -> Value {+ if self.items.iter().all(|part| matches!(part, Part::Text(_))) {+ let text: String = self+ .items+ .into_iter()+ .map(|part| match part {+ Part::Text(text) => text,+ Part::Image(_) => String::new(),+ })+ .collect();+ return Value::String(text);+ }+ Value::Array(+ self.items+ .into_iter()+ .map(|part| match part {+ Part::Text(text) => json!({"type": "text", "text": text}),+ Part::Image(url) => json!({"type": "image_url", "image_url": {"url": url}}),+ })+ .collect(),+ )+ }+}++/// Translate a Responses body into a chat completions body.+pub(crate) fn responses_to_chat(body: &Value) -> Result<ChatTranslation> {+ let Some(body) = body.as_object() else {+ return Err(ResponsesError::invalid(+ "body",+ "Input should be a valid dictionary",+ ));+ };+ for (key, value) in body {+ match key.as_str() {+ "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" => {}+ "store" => match value {+ Value::Null | Value::Bool(false) => {}+ Value::Bool(true) => return Err(ResponsesError::unsupported("store", STATELESS)),+ _ => {+ return Err(ResponsesError::invalid(+ "store",+ "Input should be a valid boolean",+ ))+ }+ },+ "previous_response_id" | "conversation" => {+ if !value.is_null() {+ return Err(ResponsesError::unsupported(key.as_str(), STATELESS));+ }+ }+ "background" => match value {+ Value::Null | Value::Bool(false) => {}+ Value::Bool(true) => {+ return Err(ResponsesError::unsupported(+ "background",+ "background responses are not supported",+ ))+ }+ _ => {+ return Err(ResponsesError::invalid(+ "background",+ "Input should be a valid boolean",+ ))+ }+ },+ "truncation" => match value {+ Value::Null => {}+ Value::String(truncation) if truncation == "disabled" => {}+ _ => {+ return Err(ResponsesError::unsupported(+ "truncation",+ "only \"disabled\" is supported",+ ))+ }+ },+ "include" => include(value)?,+ other => return Err(ResponsesError::extra(other)),+ }+ }++ let model = match present(body, "model") {+ None => return Err(ResponsesError::required("model")),+ Some(Value::String(model)) if !model.is_empty() => model.clone(),+ Some(Value::String(_)) => {+ return Err(ResponsesError::invalid(+ "model",+ "String should have at least 1 character",+ ))+ }+ Some(_) => {+ return Err(ResponsesError::invalid(+ "model",+ "Input should be a valid string",+ ))+ }+ };+ let input = match present(body, "input") {+ None => return Err(ResponsesError::required("input")),+ Some(Value::Array(items)) if items.is_empty() => {+ return Err(ResponsesError::invalid(+ "input",+ "List should have at least 1 item",+ ))+ }+ Some(input @ (Value::String(_) | Value::Array(_))) => input,+ Some(_) => {+ return Err(ResponsesError::invalid(+ "input",+ "Input should be a valid string or list",+ ))+ }+ };+ let instructions = match present(body, "instructions") {+ None => None,+ Some(Value::String(instructions)) => Some(instructions.as_str()),+ Some(_) => {+ return Err(ResponsesError::invalid(+ "instructions",+ "Input should be a valid string",+ ))+ }+ };+ let max_output_tokens = max_output_tokens(present(body, "max_output_tokens"))?;+ let stream = match present(body, "stream") {+ None => false,+ Some(Value::Bool(stream)) => *stream,+ Some(_) => {+ return Err(ResponsesError::invalid(+ "stream",+ "Input should be a valid boolean",+ ))+ }+ };+ let effort = reasoning(present(body, "reasoning"))?;+ let response_format = text(present(body, "text"))?;+ let (tools, names, custom_tools) = tools(present(body, "tools"))?;+ let tool_choice = tool_choice(present(body, "tool_choice"), &names)?;+ let messages = messages(input, instructions)?;++ let mut chat = Map::new();+ chat.insert("model".into(), json!(model));+ chat.insert("messages".into(), Value::Array(messages));+ if let Some(tokens) = max_output_tokens {+ chat.insert("max_completion_tokens".into(), json!(tokens));+ }+ for key in ["temperature", "top_p", "seed"] {+ if let Some(value) = present(body, key) {+ chat.insert(key.into(), value.clone());+ }+ }+ chat.insert("stream".into(), json!(stream));+ if stream {+ chat.insert("stream_options".into(), json!({"include_usage": true}));+ }+ if !tools.is_empty() {+ chat.insert("tools".into(), Value::Array(tools));+ }+ if let Some(tool_choice) = tool_choice {+ chat.insert("tool_choice".into(), tool_choice);+ }+ if let Some(parallel) = present(body, "parallel_tool_calls") {+ chat.insert("parallel_tool_calls".into(), parallel.clone());+ }+ if let Some(response_format) = response_format {+ chat.insert("response_format".into(), response_format);+ }+ for key in PASSED_THROUGH {+ if let Some(value) = present(body, key) {+ chat.insert(key.into(), value.clone());+ }+ }+ chat.insert("include_reasoning".into(), json!(false));+ if let Some(effort) = effort {+ chat.insert("reasoning_effort".into(), effort.clone());+ }+ let echo = Echo {+ model,+ parallel_tool_calls: present(body, "parallel_tool_calls")+ .cloned()+ .unwrap_or(json!(true)),+ tool_choice: present(body, "tool_choice")+ .cloned()+ .unwrap_or(json!("auto")),+ custom_tools,+ };+ Ok(ChatTranslation {+ chat: Value::Object(chat),+ stream,+ echo,+ })+}++fn include(value: &Value) -> Result<()> {+ let entries = match value {+ Value::Null => return Ok(()),+ Value::Array(entries) => entries,+ _ => {+ return Err(ResponsesError::invalid(+ "include",+ "Input should be a valid list",+ ))+ }+ };+ for (index, entry) in entries.iter().enumerate() {+ if entry.as_str() == Some(ENCRYPTED_REASONING) {+ continue;+ }+ let shown = match entry {+ Value::String(entry) => entry.clone(),+ other => other.to_string(),+ };+ return Err(ResponsesError::unsupported(+ format!("include[{index}]"),+ &format!("'{shown}' is not supported"),+ ));+ }+ Ok(())+}++fn max_output_tokens(value: Option<&Value>) -> Result<Option<u64>> {+ let Some(value) = value else {+ return Ok(None);+ };+ match value.as_u64() {+ Some(tokens) if (1..=u64::from(u32::MAX)).contains(&tokens) => Ok(Some(tokens)),+ Some(0) => Err(ResponsesError::invalid(+ "max_output_tokens",+ "Input should be greater than or equal to 1",+ )),+ None if value.as_i64().is_some() => Err(ResponsesError::invalid(+ "max_output_tokens",+ "Input should be greater than or equal to 1",+ )),+ _ => Err(ResponsesError::invalid(+ "max_output_tokens",+ "Input should be a valid integer",+ )),+ }+}++/// The chat `reasoning_effort`, passed as sent for the chat route to check.+fn reasoning(value: Option<&Value>) -> Result<Option<&Value>> {+ let Some(value) = value else {+ return Ok(None);+ };+ let reasoning = object(value, "reasoning")?;+ only_keys(+ reasoning,+ &["effort", "summary", "generate_summary"],+ "reasoning",+ )?;+ Ok(present(reasoning, "effort"))+}++/// The chat `response_format` for `text.format`.+fn text(value: Option<&Value>) -> Result<Option<Value>> {+ let Some(value) = value else {+ return Ok(None);+ };+ let text = object(value, "text")?;+ only_keys(text, &["format", "verbosity"], "text")?;+ let Some(format) = present(text, "format") else {+ return Ok(None);+ };+ let format = object(format, "text.format")?;+ let kind = match present(format, "type") {+ None => return Err(ResponsesError::required("text.format.type")),+ Some(Value::String(kind)) => kind.as_str(),+ Some(_) => {+ return Err(ResponsesError::invalid(+ "text.format.type",+ "Input should be a valid string",+ ))+ }+ };+ let allowed: &[&str] = match kind {+ "text" | "json_object" => &["type"],+ "json_schema" => &["type", "name", "schema", "strict", "description"],+ _ => {+ return Err(ResponsesError::unsupported(+ "text.format.type",+ &format!("'{kind}' is not supported"),+ ))+ }+ };+ only_keys(format, allowed, "text.format")?;+ match kind {+ "text" => Ok(None),+ "json_object" => Ok(Some(json!({"type": "json_object"}))),+ _ => {+ let mut schema = Map::new();+ for key in ["name", "schema", "strict", "description"] {+ if let Some(value) = present(format, key) {+ schema.insert(key.into(), value.clone());+ }+ }+ Ok(Some(+ json!({"type": "json_schema", "json_schema": Value::Object(schema)}),+ ))+ }+ }+}++/// The chat tools, the declared tool names, and the names of the custom+/// tools.+fn tools(value: Option<&Value>) -> Result<(Vec<Value>, Vec<String>, Vec<String>)> {+ let Some(value) = value else {+ return Ok((Vec::new(), Vec::new(), Vec::new()));+ };+ let Some(items) = value.as_array() else {+ return Err(ResponsesError::invalid(+ "tools",+ "Input should be a valid list",+ ));+ };+ let mut tools = Vec::with_capacity(items.len());+ let mut names = Vec::with_capacity(items.len());+ let mut custom_tools = Vec::new();+ for (index, item) in items.iter().enumerate() {+ let path = format!("tools[{index}]");+ let tool = object(item, &path)?;+ let custom = match present(tool, "type") {+ None => return Err(ResponsesError::required(format!("{path}.type"))),+ Some(Value::String(kind)) if kind == "function" => false,+ Some(Value::String(kind)) if kind == "custom" => true,+ Some(Value::String(kind)) => {+ return Err(ResponsesError::unsupported(+ format!("{path}.type"),+ &format!("'{kind}' tools are not supported; send function or custom tools"),+ ))+ }+ Some(_) => {+ return Err(ResponsesError::invalid(+ format!("{path}.type"),+ "Input should be a valid string",+ ))+ }+ };+ if custom {+ only_keys(tool, &["type", "name", "description", "format"], &path)?;+ } else {+ only_keys(+ tool,+ &["type", "name", "description", "parameters", "strict"],+ &path,+ )?;+ match present(tool, "strict") {+ None | Some(Value::Bool(false)) => {}+ Some(Value::Bool(true)) => {+ return Err(ResponsesError::unsupported(+ format!("{path}.strict"),+ "strict function schemas are not supported",+ ))+ }+ Some(_) => {+ return Err(ResponsesError::invalid(+ format!("{path}.strict"),+ "Input should be a valid boolean",+ ))+ }+ }+ }+ let mut function = Map::new();+ for key in ["name", "description"] {+ if let Some(value) = present(tool, key) {+ function.insert(key.into(), value.clone());+ }+ }+ if custom {+ function.insert(+ "parameters".into(),+ json!({+ "type": "object",+ "properties": {"input": {"type": "string"}},+ "required": ["input"],+ "additionalProperties": false,+ }),+ );+ } else if let Some(parameters) = present(tool, "parameters") {+ function.insert("parameters".into(), parameters.clone());+ }+ tools.push(json!({"type": "function", "function": Value::Object(function)}));+ if let Some(name) = tool.get("name").and_then(Value::as_str) {+ names.push(name.to_string());+ if custom {+ custom_tools.push(name.to_string());+ }+ }+ }+ Ok((tools, names, custom_tools))+}++fn tool_choice(value: Option<&Value>, names: &[String]) -> Result<Option<Value>> {+ let Some(value) = value else {+ return Ok(None);+ };+ let choice = match value {+ Value::String(mode) => {+ return match mode.as_str() {+ "auto" | "none" if names.is_empty() => Ok(None),+ "auto" | "none" | "required" => Ok(Some(value.clone())),+ _ => Err(ResponsesError::invalid(+ "tool_choice",+ "Input should be 'auto', 'none' or 'required'",+ )),+ }+ }+ Value::Object(choice) => choice,+ _ => {+ return Err(ResponsesError::invalid(+ "tool_choice",+ "Input should be a valid string or dictionary",+ ))+ }+ };+ match present(choice, "type") {+ None => return Err(ResponsesError::required("tool_choice.type")),+ Some(Value::String(kind)) if kind == "function" || kind == "custom" => {}+ Some(Value::String(kind)) => {+ return Err(ResponsesError::unsupported(+ "tool_choice.type",+ &format!("'{kind}' is not supported"),+ ))+ }+ Some(_) => {+ return Err(ResponsesError::invalid(+ "tool_choice.type",+ "Input should be a valid string",+ ))+ }+ }+ only_keys(choice, &["type", "name"], "tool_choice")?;+ let name = string(choice, "name", "tool_choice")?;+ if !names.iter().any(|declared| declared == name) {+ return Err(ResponsesError::invalid(+ "tool_choice.name",+ &format!("tool '{name}' is not declared in tools"),+ ));+ }+ Ok(Some(+ json!({"type": "function", "function": {"name": name}}),+ ))+}++/// The chat messages, built item by item.+///+/// Consecutive assistant output (assistant messages and calls) becomes one+/// chat assistant message. The images of a run of tool outputs become one+/// user message after the run, joined by the user message that follows it.+#[derive(Default)]+struct Builder {+ out: Vec<Value>,+ system: Vec<String>,+ past_leading_system: bool,+ assistant: Option<(String, Vec<Value>)>,+ tool_images: Option<Vec<String>>,+}++impl Builder {+ fn flush_assistant(&mut self) {+ let Some((text, calls)) = self.assistant.take() else {+ return;+ };+ if calls.is_empty() {+ self.out.push(json!({"role": "assistant", "content": text}));+ } else {+ let content = if text.is_empty() {+ Value::Null+ } else {+ json!(text)+ };+ self.out+ .push(json!({"role": "assistant", "content": content, "tool_calls": calls}));+ }+ }++ fn take_tool_images(&mut self) -> Parts {+ let mut parts = Parts::default();+ for url in self.tool_images.take().into_iter().flatten() {+ parts.image(url);+ }+ parts+ }++ fn flush_tool_images(&mut self) {+ let images = self.take_tool_images();+ if !images.items.is_empty() {+ self.out+ .push(json!({"role": "user", "content": images.into_content()}));+ }+ }++ fn assistant(&mut self) -> &mut (String, Vec<Value>) {+ self.assistant.get_or_insert_with(Default::default)+ }++ fn item(&mut self, item: &Value, path: &str) -> Result<()> {+ let item = object(item, path)?;+ let kind = match present(item, "type") {+ None if !item.contains_key("role") => {+ return Err(ResponsesError::required(format!("{path}.role")))+ }+ None => "message",+ Some(Value::String(kind)) => kind.as_str(),+ Some(_) => {+ return Err(ResponsesError::invalid(+ format!("{path}.type"),+ "Input should be a valid string",+ ))+ }+ };+ let allowed: &[&str] = match kind {+ "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" | "custom_tool_call_output" => {+ &["type", "id", "status", "call_id", "output"]+ }+ "reasoning" => &[+ "type",+ "id",+ "status",+ "summary",+ "content",+ "encrypted_content",+ ],+ _ => {+ return Err(ResponsesError::unsupported(+ format!("{path}.type"),+ &format!("items of type '{kind}' are not supported"),+ ))+ }+ };+ only_keys(item, allowed, path)?;+ match kind {+ "reasoning" => Ok(()),+ "message" => self.message(item, path),+ "function_call" | "custom_tool_call" => {+ self.past_leading_system = true;+ self.flush_tool_images();+ let call_id = string(item, "call_id", path)?;+ let name = string(item, "name", path)?;+ let arguments = if kind == "function_call" {+ string(item, "arguments", path)?.to_string()+ } else {+ json!({"input": string(item, "input", path)?}).to_string()+ };+ self.assistant().1.push(json!({+ "id": call_id,+ "type": "function",+ "function": {"name": name, "arguments": arguments},+ }));+ Ok(())+ }+ _ => {+ self.past_leading_system = true;+ self.flush_assistant();+ let call_id = string(item, "call_id", path)?;+ let (text, images) = tool_output(present(item, "output"), path)?;+ self.out.push(json!({+ "role": "tool",+ "tool_call_id": call_id,+ "content": text,+ }));+ self.tool_images.get_or_insert_with(Vec::new).extend(images);+ Ok(())+ }+ }+ }++ fn message(&mut self, item: &Map<String, Value>, path: &str) -> Result<()> {+ let role = match present(item, "role") {+ None => return Err(ResponsesError::required(format!("{path}.role"))),+ Some(Value::String(role))+ if matches!(role.as_str(), "user" | "assistant" | "system" | "developer") =>+ {+ role.as_str()+ }+ Some(_) => {+ return Err(ResponsesError::invalid(+ format!("{path}.role"),+ "Input should be 'user', 'assistant', 'system' or 'developer'",+ ))+ }+ };+ let parts = content(item, role, path)?;+ match role {+ "system" | "developer" => {+ let text = parts.into_content();+ if !self.past_leading_system {+ self.system+ .push(text.as_str().unwrap_or_default().to_string());+ return Ok(());+ }+ self.flush_assistant();+ self.flush_tool_images();+ self.out.push(json!({"role": "system", "content": text}));+ }+ "assistant" => {+ self.past_leading_system = true;+ self.flush_tool_images();+ let text = parts.into_content();+ self.assistant()+ .0+ .push_str(text.as_str().unwrap_or_default());+ }+ _ => {+ self.past_leading_system = true;+ self.flush_assistant();+ let mut merged = self.take_tool_images();+ merged.items.extend(parts.items);+ self.out+ .push(json!({"role": "user", "content": merged.into_content()}));+ }+ }+ Ok(())+ }+}++fn messages(input: &Value, instructions: Option<&str>) -> Result<Vec<Value>> {+ let mut builder = Builder::default();+ if let Some(instructions) = instructions.filter(|text| !text.is_empty()) {+ builder.system.push(instructions.to_string());+ }+ match input {+ Value::String(text) => builder.out.push(json!({"role": "user", "content": text})),+ items => {+ for (index, item) in items.as_array().into_iter().flatten().enumerate() {+ builder.item(item, &format!("input[{index}]"))?;+ }+ }+ }+ builder.flush_assistant();+ builder.flush_tool_images();+ if !builder.system.is_empty() {+ builder.out.insert(+ 0,+ json!({"role": "system", "content": builder.system.join("\n\n")}),+ );+ }+ Ok(builder.out)+}++fn part_type<'a>(part: &'a Map<String, Value>, path: &str) -> Result<&'a str> {+ match present(part, "type") {+ None => Err(ResponsesError::required(format!("{path}.type"))),+ Some(Value::String(kind)) => Ok(kind),+ Some(_) => Err(ResponsesError::invalid(+ format!("{path}.type"),+ "Input should be a valid string",+ )),+ }+}++/// The text of a text part, or `None` when the part is not a text part.+fn text_part(part: &Map<String, Value>, kind: &str, path: &str) -> Result<Option<String>> {+ let allowed: &[&str] = match kind {+ "input_text" | "text" => &TEXT_PART_KEYS,+ "output_text" => &OUTPUT_TEXT_PART_KEYS,+ _ => return Ok(None),+ };+ only_keys(part, allowed, path)?;+ Ok(Some(string(part, "text", path)?.to_string()))+}++fn image_part(part: &Map<String, Value>, path: &str) -> Result<String> {+ only_keys(part, &IMAGE_PART_KEYS, path)?;+ if present(part, "file_id").is_some() {+ return Err(ResponsesError::unsupported(+ format!("{path}.file_id"),+ "only base64 data: URLs are supported",+ ));+ }+ let url = string(part, "image_url", path)?;+ if !url.starts_with("data:") {+ return Err(ResponsesError::unsupported(+ format!("{path}.image_url"),+ "only base64 data: URLs are supported",+ ));+ }+ Ok(url.to_string())+}++fn unsupported_part(path: &str, kind: &str) -> ResponsesError {+ ResponsesError::unsupported(+ format!("{path}.type"),+ &format!("parts of type '{kind}' are not supported"),+ )+}++fn content(item: &Map<String, Value>, role: &str, path: &str) -> Result<Parts> {+ let mut parts = Parts::default();+ let items = match present(item, "content") {+ None => return Err(ResponsesError::required(format!("{path}.content"))),+ Some(Value::String(text)) => {+ parts.text(text);+ return Ok(parts);+ }+ Some(Value::Array(items)) => items,+ Some(_) => {+ return Err(ResponsesError::invalid(+ format!("{path}.content"),+ "Input should be a valid string or list",+ ))+ }+ };+ for (index, part) in items.iter().enumerate() {+ let part_path = format!("{path}.content[{index}]");+ let part = object(part, &part_path)?;+ let kind = part_type(part, &part_path)?;+ if let Some(text) = text_part(part, kind, &part_path)? {+ parts.text(&text);+ } else if kind == "input_image" {+ if role != "user" {+ return Err(ResponsesError::unsupported(+ format!("{part_path}.type"),+ "parts of type 'input_image' are only supported in user messages",+ ));+ }+ parts.image(image_part(part, &part_path)?);+ } else {+ return Err(unsupported_part(&part_path, kind));+ }+ }+ Ok(parts)+}++/// The text and the images of a tool output.+fn tool_output(output: Option<&Value>, path: &str) -> Result<(String, Vec<String>)> {+ let items = match output {+ None => return Err(ResponsesError::required(format!("{path}.output"))),+ Some(Value::String(text)) => return Ok((text.clone(), Vec::new())),+ Some(Value::Array(items)) => items,+ Some(_) => {+ return Err(ResponsesError::invalid(+ format!("{path}.output"),+ "Input should be a valid string or list",+ ))+ }+ };+ let mut text = String::new();+ let mut images = Vec::new();+ for (index, part) in items.iter().enumerate() {+ let part_path = format!("{path}.output[{index}]");+ let part = object(part, &part_path)?;+ let kind = part_type(part, &part_path)?;+ if let Some(part_text) = text_part(part, kind, &part_path)? {+ text.push_str(&part_text);+ } else if kind == "input_image" {+ images.push(image_part(part, &part_path)?);+ } else {+ return Err(unsupported_part(&part_path, kind));+ }+ }+ Ok((text, images))+}diff --git a/packages/sie_gateway/src/handlers/responses/response.rs b/packages/sie_gateway/src/handlers/responses/response.rsnew file mode 100644index 000000000..718b462a6--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses/response.rs@@ -0,0 +1,210 @@+//! Buffered response translation: a chat completion into a Response.++use serde_json::{json, Map, Value};++/// What a Response repeats from its request.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct Echo {+ pub model: String,+ pub parallel_tool_calls: Value,+ pub tool_choice: Value,+ /// Names of the declared custom tools, whose calls come back as+ /// `custom_tool_call` items.+ pub custom_tools: Vec<String>,+}++/// The parts of a Response that do not depend on the answer.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct ResponseShell {+ echo: Echo,+ request_id: String,+ created_at: u64,+}++impl ResponseShell {+ pub(crate) fn new(echo: Echo, request_id: String, created_at: u64) -> Self {+ Self {+ echo,+ request_id,+ created_at,+ }+ }++ pub(crate) fn is_custom(&self, name: &str) -> bool {+ self.echo.custom_tools.iter().any(|custom| custom == name)+ }++ pub(crate) fn message_id(&self) -> String {+ format!("msg-{}", self.request_id)+ }++ pub(crate) fn later_message_id(&self, output_index: u64) -> String {+ format!("msg-{}-{output_index}", self.request_id)+ }++ pub(crate) fn call_id(&self, custom: bool, position: u64) -> String {+ let prefix = if custom { "ctc" } else { "fc" };+ format!("{prefix}-{}-{position}", self.request_id)+ }++ /// A `function_call` or `custom_tool_call` item. `value` is the+ /// arguments of a function call or the input of a custom-tool call.+ pub(crate) fn call_item(+ &self,+ position: u64,+ call_id: &str,+ name: &str,+ value: &str,+ status: &str,+ ) -> Value {+ let custom = self.is_custom(name);+ let (kind, field) = if custom {+ ("custom_tool_call", "input")+ } else {+ ("function_call", "arguments")+ };+ let mut item = Map::new();+ item.insert("type".into(), json!(kind));+ item.insert("id".into(), json!(self.call_id(custom, position)));+ item.insert("call_id".into(), json!(call_id));+ item.insert("name".into(), json!(name));+ item.insert(field.into(), json!(value));+ item.insert("status".into(), json!(status));+ Value::Object(item)+ }++ pub(crate) fn object(+ &self,+ status: &str,+ incomplete_details: Value,+ error: Value,+ output: &[Value],+ usage: Value,+ ) -> Value {+ json!({+ "id": format!("resp-{}", self.request_id),+ "object": "response",+ "created_at": self.created_at,+ "model": self.echo.model,+ "status": status,+ "incomplete_details": incomplete_details,+ "error": error,+ "store": false,+ "parallel_tool_calls": self.echo.parallel_tool_calls,+ "tool_choice": self.echo.tool_choice,+ "output": output,+ "usage": usage,+ })+ }+}++/// A `message` item. An item still in progress has no content yet.+pub(crate) fn message_item(id: &str, text: &str, status: &str) -> Value {+ let content = if status == "completed" {+ json!([{"type": "output_text", "text": text, "annotations": []}])+ } else {+ json!([])+ };+ json!({+ "type": "message",+ "id": id,+ "role": "assistant",+ "status": status,+ "content": content,+ })+}++/// The input a custom-tool call carries: the string `input` of its+/// arguments, or the arguments as sent when they hold none.+pub(crate) fn custom_input(arguments: &str) -> String {+ match serde_json::from_str::<Value>(arguments) {+ Ok(Value::Object(fields)) => match fields.get("input") {+ Some(Value::String(input)) => input.clone(),+ _ => arguments.to_string(),+ },+ _ => arguments.to_string(),+ }+}++/// The Response `status` and `incomplete_details` for a chat+/// `finish_reason`.+pub(crate) fn status_for(finish_reason: Option<&str>) -> (&'static str, Value) {+ match finish_reason {+ Some("length") => ("incomplete", json!({"reason": "max_output_tokens"})),+ Some("content_filter") => ("incomplete", json!({"reason": "content_filter"})),+ _ => ("completed", Value::Null),+ }+}++/// Responses usage from a chat usage block, with absent details counted+/// as 0.+pub(crate) fn responses_usage(usage: &Value) -> Option<Value> {+ let prompt = usage.get("prompt_tokens")?.as_u64()?;+ let completion = usage.get("completion_tokens")?.as_u64()?;+ let total = usage.get("total_tokens")?.as_u64()?;+ let detail = |pointer: &str| usage.pointer(pointer).and_then(Value::as_u64).unwrap_or(0);+ Some(json!({+ "input_tokens": prompt,+ "input_tokens_details": {"cached_tokens": detail("/prompt_tokens_details/cached_tokens")},+ "output_tokens": completion,+ "output_tokens_details": {"reasoning_tokens": detail("/completion_tokens_details/reasoning_tokens")},+ "total_tokens": total,+ }))+}++/// Translate a chat completion into a Response.+pub(crate) fn chat_completion_to_response(+ chat: &Value,+ shell: &ResponseShell,+) -> Result<Value, String> {+ let choice = chat+ .get("choices")+ .and_then(Value::as_array)+ .and_then(|choices| choices.first())+ .ok_or("chat completion has no choices")?;+ let message = choice+ .get("message")+ .ok_or("chat completion choice has no message")?;+ let mut output = Vec::new();+ if let Some(text) = message+ .get("content")+ .and_then(Value::as_str)+ .filter(|text| !text.is_empty())+ {+ output.push(message_item(&shell.message_id(), text, "completed"));+ }+ for (position, call) in message+ .get("tool_calls")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .enumerate()+ {+ let call_id = call+ .get("id")+ .and_then(Value::as_str)+ .ok_or("tool call has no id")?;+ let function = call.get("function").ok_or("tool call has no function")?;+ let name = function+ .get("name")+ .and_then(Value::as_str)+ .ok_or("tool call has no name")?;+ let arguments = function+ .get("arguments")+ .and_then(Value::as_str)+ .unwrap_or("");+ let value = if shell.is_custom(name) {+ custom_input(arguments)+ } else {+ arguments.to_string()+ };+ output.push(shell.call_item(position as u64, call_id, name, &value, "completed"));+ }+ let (status, incomplete_details) =+ status_for(choice.get("finish_reason").and_then(Value::as_str));+ let usage = chat+ .get("usage")+ .and_then(responses_usage)+ .unwrap_or(Value::Null);+ Ok(shell.object(status, incomplete_details, Value::Null, &output, usage))+}diff --git a/packages/sie_gateway/src/handlers/responses/schema.rs b/packages/sie_gateway/src/handlers/responses/schema.rsnew file mode 100644index 000000000..24ad3d3ae--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses/schema.rs@@ -0,0 +1,192 @@+//! OpenAPI shapes of the OpenAI Responses surface.++use serde::{Deserialize, Serialize};+use serde_json::Value;+use utoipa::openapi::schema::{ArrayBuilder, ObjectBuilder, OneOfBuilder, Schema, Type};+use utoipa::openapi::RefOr;+use utoipa::ToSchema;++fn input_schema() -> RefOr<Schema> {+ OneOfBuilder::new()+ .description(Some(+ "A string, sent as one user message, or a non-empty list of items: messages \+ (`role` `user`, `assistant`, `system` or `developer`, with string content or \+ `input_text`, `output_text` and `text` parts, and base64 `data:` `input_image` \+ parts in user messages), `function_call`, `custom_tool_call`, their `*_output` \+ items, and `reasoning` items, which do not reach the model. Item `id` and \+ `status` are ignored. Other item and part types are refused.",+ ))+ .item(ObjectBuilder::new().schema_type(Type::String))+ .item(+ ArrayBuilder::new()+ .items(ObjectBuilder::new().schema_type(Type::Object))+ .min_items(Some(1)),+ )+ .into()+}++fn null_only() -> RefOr<Schema> {+ ObjectBuilder::new()+ .schema_type(Type::Null)+ .description(Some("Accepted only `null`: responses are not stored."))+ .into()+}++/// OpenAI Responses request, as accepted by ``POST /v1/responses``.+///+/// The request is translated into a ``/v1/chat/completions`` request and+/// served by the chat route, so every chat limit and check applies, and a+/// chat refusal names the Responses field (``tools[i].name``,+/// ``max_output_tokens``, ``reasoning.effort``, ``text.format``). A field+/// sent as ``null`` is treated as absent.+///+/// Responses are not stored: ``store: true`` and a non-null+/// ``previous_response_id`` or ``conversation`` fail with ``400+/// unsupported_field`` and the message ``<field>: SIE does not store+/// responses; send the full conversation in input``. ``background: true``,+/// a ``truncation`` other than ``disabled`` and an ``include`` entry other+/// than ``reasoning.encrypted_content`` fail the same way. ``prompt``,+/// ``max_tool_calls``, ``top_logprobs``, ``stream_options`` and every other+/// field outside this set fail with ``<field>: Extra inputs are not+/// permitted``. ``client_metadata``, ``reasoning.summary``,+/// ``reasoning.generate_summary`` and ``text.verbosity`` are accepted and+/// have no effect.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct ResponsesRequest {+ /// The model id, used as on ``/v1/chat/completions`` (``model`` or+ /// ``model:profile``, or an operator alias).+ #[schema(min_length = 1)]+ pub model: String,+ #[schema(schema_with = input_schema)]+ pub input: Value,+ /// Prepended to the leading ``system`` and ``developer`` messages as+ /// one system message.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub instructions: Option<String>,+ /// Output token limit, at least 1 and at most the serving profile's+ /// ``max_output_tokens``. Absent: the chat route's default.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(minimum = 1)]+ pub max_output_tokens: Option<u32>,+ /// Checked as on ``/v1/chat/completions``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub temperature: Option<f64>,+ /// Checked as on ``/v1/chat/completions``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub top_p: Option<f64>,+ /// Checked as on ``/v1/chat/completions``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub seed: Option<i64>,+ /// Server-sent events: ``response.created``, ``response.in_progress``,+ /// output item, content part, text and call-argument events, then+ /// ``response.completed`` or ``response.incomplete`` with the full+ /// Response. Every event carries ``sequence_number``. A failure after+ /// the stream opened is ``response.failed``, and the stream then ends.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub stream: Option<bool>,+ /// ``function`` tools (``name``, ``description``, ``parameters``,+ /// ``strict`` only ``false``) and ``custom`` tools (``name``,+ /// ``description``, ``format``, which is not enforced), at most 64,+ /// names matching ``^[a-zA-Z0-9_-]{1,64}$``. Hosted tool types are+ /// refused.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tools: Option<Value>,+ /// ``auto``, ``none``, ``required``, or ``{"type": "function" |+ /// "custom", "name"}`` naming a declared tool.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tool_choice: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parallel_tool_calls: Option<bool>,+ /// ``effort`` becomes the chat ``reasoning_effort``. Reasoning is not+ /// returned.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reasoning: Option<Value>,+ /// ``format`` ``text``, ``json_object`` or ``json_schema`` (``name``,+ /// ``schema``, ``strict``, ``description``) becomes the chat+ /// ``response_format``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text: Option<Value>,+ /// Passed to the chat route.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub metadata: Option<Value>,+ /// Passed to the chat route.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub prompt_cache_key: Option<String>,+ /// Passed to the chat route.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub user: Option<String>,+ /// Passed to the chat route.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub safety_identifier: Option<String>,+ /// Passed to the chat route.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub service_tier: Option<String>,+ /// Accepted only ``false``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub store: Option<bool>,+ /// Accepted only ``false``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub background: Option<bool>,+ /// Accepted only ``disabled``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub truncation: Option<String>,+ /// Accepted only with ``reasoning.encrypted_content`` entries, which+ /// have no effect.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub include: Option<Vec<String>>,+ /// Accepted and ignored.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub client_metadata: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(schema_with = null_only)]+ pub previous_response_id: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(schema_with = null_only)]+ pub conversation: Option<Value>,+}++/// Token usage of a Response, from the chat route's usage.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct ResponsesUsage {+ pub input_tokens: u64,+ /// ``cached_tokens``: prompt tokens served from the prefix cache.+ pub input_tokens_details: Value,+ /// Includes reasoning tokens.+ pub output_tokens: u64,+ /// ``reasoning_tokens``.+ pub output_tokens_details: Value,+ pub total_tokens: u64,+}++/// Response answered by ``POST /v1/responses`` without ``stream``.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct ResponsesResponse {+ /// ``resp-`` followed by the gateway request id.+ pub id: String,+ /// Always ``response``.+ pub object: String,+ pub created_at: u64,+ /// The model the request named.+ pub model: String,+ /// ``completed`` or ``incomplete``.+ pub status: String,+ /// ``{"reason": "max_output_tokens" | "content_filter"}`` when+ /// ``incomplete``.+ pub incomplete_details: Option<Value>,+ /// Always ``null``.+ pub error: Option<Value>,+ /// Always ``false``.+ pub store: bool,+ /// As the request sent it, ``true`` when absent.+ pub parallel_tool_calls: Value,+ /// As the request sent it, ``auto`` when absent.+ pub tool_choice: Value,+ /// A ``message`` item with one ``output_text`` part when the model+ /// wrote text, then one ``function_call`` or ``custom_tool_call`` item+ /// per tool call.+ pub output: Value,+ pub usage: ResponsesUsage,+}diff --git a/packages/sie_gateway/src/handlers/responses/stream.rs b/packages/sie_gateway/src/handlers/responses/stream.rsnew file mode 100644index 000000000..6f64da7b9--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses/stream.rs@@ -0,0 +1,560 @@+//! Streaming translation: chat completion chunks in, Responses events out.+//!+//! [`StreamMachine`] is pure: it turns each chat SSE `data` payload into the+//! events it implies. [`stream_body`] drives it over the chat route's SSE body+//! and passes the chat route's comment heartbeats through until the terminal+//! event. Dropping the returned body drops the chat body with it, so a client+//! that goes away cancels the generation the same way a chat client does. A+//! `response.failed` event ends the body the same way, so a stream the+//! translation cannot follow stops generating.++use std::collections::VecDeque;+use std::convert::Infallible;++use axum::body::Body;+use bytes::Bytes;+use futures_util::StreamExt;+use serde_json::{json, Map, Value};++use super::response::{custom_input, message_item, responses_usage, status_for, ResponseShell};++pub(crate) const FAILED: &str = "response.failed";+const SERVER_ERROR: &str = "server_error";++/// One Responses SSE event.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct Event {+ pub name: &'static str,+ pub data: Value,+}++impl Event {+ pub(crate) fn encode(&self) -> Bytes {+ Bytes::from(format!("event: {}\ndata: {}\n\n", self.name, self.data))+ }+}++#[derive(Debug)]+struct OpenText {+ output_index: u64,+ item_id: String,+ text: String,+}++#[derive(Debug)]+struct OpenCall {+ chat_index: u64,+ position: u64,+ output_index: u64,+ call_id: String,+ name: String,+ custom: bool,+ arguments: String,+}++/// The chat-chunk to Responses-event state machine. At most one output item+/// is open at a time, and output indices are contiguous from 0.+#[derive(Debug)]+pub(crate) struct StreamMachine {+ shell: ResponseShell,+ sequence: u64,+ output: Vec<Value>,+ next_index: u64,+ text: Option<OpenText>,+ call: Option<OpenCall>,+ calls: u64,+ closed_calls: Vec<u64>,+ finish_reason: Option<String>,+ usage: Option<Value>,+ started: bool,+ done: bool,+}++impl StreamMachine {+ pub(crate) fn new(shell: ResponseShell) -> Self {+ Self {+ shell,+ sequence: 0,+ output: Vec::new(),+ next_index: 0,+ text: None,+ call: None,+ calls: 0,+ closed_calls: Vec::new(),+ finish_reason: None,+ usage: None,+ started: false,+ done: false,+ }+ }++ /// Whether the terminal event has been produced.+ pub(crate) fn is_done(&self) -> bool {+ self.done+ }++ fn event(&mut self, name: &'static str, payload: Value) -> Event {+ let mut data = Map::new();+ data.insert("type".into(), json!(name));+ data.insert("sequence_number".into(), json!(self.sequence));+ if let Value::Object(fields) = payload {+ data.extend(fields);+ }+ self.sequence += 1;+ Event {+ name,+ data: Value::Object(data),+ }+ }++ /// `response.created` and `response.in_progress`, sent as soon as the+ /// chat stream opens.+ pub(crate) fn start(&mut self) -> Vec<Event> {+ if self.started {+ return Vec::new();+ }+ self.started = true;+ let response = self+ .shell+ .object("in_progress", Value::Null, Value::Null, &[], Value::Null);+ vec![+ self.event("response.created", json!({"response": response})),+ self.event("response.in_progress", json!({"response": response})),+ ]+ }++ /// Feed one chat SSE `data` payload.+ pub(crate) fn on_data(&mut self, data: &str) -> Vec<Event> {+ let mut events = self.start();+ if self.done {+ return events;+ }+ if data == "[DONE]" {+ self.finish(&mut events);+ return events;+ }+ let Ok(chunk) = serde_json::from_str::<Value>(data) else {+ self.fail(+ &mut events,+ json!(SERVER_ERROR),+ json!("the generation stream sent a malformed chunk"),+ );+ return events;+ };+ if let Some(error) = chunk.get("error").filter(|error| error.is_object()) {+ let code = error.get("code").cloned().unwrap_or(Value::Null);+ let message = error.get("message").cloned().unwrap_or(Value::Null);+ self.fail(&mut events, code, message);+ return events;+ }+ if let Some(choice) = chunk+ .get("choices")+ .and_then(Value::as_array)+ .and_then(|choices| choices.first())+ {+ let delta = choice.get("delta").unwrap_or(&Value::Null);+ if let Some(text) = delta+ .get("content")+ .and_then(Value::as_str)+ .filter(|text| !text.is_empty())+ {+ self.text_delta(text, &mut events);+ }+ for call in delta+ .get("tool_calls")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ {+ if let Err(message) = self.tool_call(call, &mut events) {+ self.fail(&mut events, json!(SERVER_ERROR), json!(message));+ return events;+ }+ }+ if let Some(finish_reason) = choice.get("finish_reason").and_then(Value::as_str) {+ self.close_text(&mut events);+ self.close_call(&mut events);+ self.finish_reason = Some(finish_reason.to_string());+ }+ }+ if let Some(usage) = chunk.get("usage").filter(|usage| usage.is_object()) {+ self.usage = Some(usage.clone());+ }+ events+ }++ /// The chat stream ended. A stream that reported a finish completes;+ /// any other ending fails.+ pub(crate) fn on_end(&mut self) -> Vec<Event> {+ let mut events = self.start();+ if !self.done {+ self.finish(&mut events);+ }+ events+ }++ /// The chat stream broke before it ended.+ pub(crate) fn on_transport_error(&mut self) -> Vec<Event> {+ let mut events = self.start();+ if !self.done {+ self.fail(+ &mut events,+ json!(SERVER_ERROR),+ json!("the generation stream ended unexpectedly"),+ );+ }+ events+ }++ fn finish(&mut self, events: &mut Vec<Event>) {+ if self.finish_reason.is_none() {+ self.fail(+ events,+ json!(SERVER_ERROR),+ json!("the generation stream ended without a finish reason"),+ );+ return;+ }+ self.close_text(events);+ self.close_call(events);+ let (status, incomplete_details) = status_for(self.finish_reason.as_deref());+ let name = if status == "completed" {+ "response.completed"+ } else {+ "response.incomplete"+ };+ let usage = self+ .usage+ .as_ref()+ .and_then(responses_usage)+ .unwrap_or(Value::Null);+ let response =+ self.shell+ .object(status, incomplete_details, Value::Null, &self.output, usage);+ let event = self.event(name, json!({"response": response}));+ events.push(event);+ self.done = true;+ }++ fn fail(&mut self, events: &mut Vec<Event>, code: Value, message: Value) {+ let response = self.shell.object(+ "failed",+ Value::Null,+ json!({"code": code, "message": message}),+ &self.output,+ Value::Null,+ );+ let event = self.event(FAILED, json!({"response": response}));+ events.push(event);+ self.done = true;+ }++ fn text_delta(&mut self, text: &str, events: &mut Vec<Event>) {+ self.close_call(events);+ if self.text.is_none() {+ let output_index = self.next_index;+ self.next_index += 1;+ let item_id = if output_index == 0 {+ self.shell.message_id()+ } else {+ self.shell.later_message_id(output_index)+ };+ let added = self.event(+ "response.output_item.added",+ json!({+ "output_index": output_index,+ "item": message_item(&item_id, "", "in_progress"),+ }),+ );+ let part = self.event(+ "response.content_part.added",+ json!({+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "part": {"type": "output_text", "text": "", "annotations": []},+ }),+ );+ events.extend([added, part]);+ self.text = Some(OpenText {+ output_index,+ item_id,+ text: String::new(),+ });+ }+ let Some(open) = self.text.as_mut() else {+ return;+ };+ open.text.push_str(text);+ let payload = json!({+ "item_id": open.item_id,+ "output_index": open.output_index,+ "content_index": 0,+ "delta": text,+ });+ let event = self.event("response.output_text.delta", payload);+ events.push(event);+ }++ fn close_text(&mut self, events: &mut Vec<Event>) {+ let Some(open) = self.text.take() else {+ return;+ };+ let item = message_item(&open.item_id, &open.text, "completed");+ let text_done = self.event(+ "response.output_text.done",+ json!({+ "item_id": open.item_id,+ "output_index": open.output_index,+ "content_index": 0,+ "text": open.text,+ }),+ );+ let part_done = self.event(+ "response.content_part.done",+ json!({+ "item_id": open.item_id,+ "output_index": open.output_index,+ "content_index": 0,+ "part": {"type": "output_text", "text": open.text, "annotations": []},+ }),+ );+ let item_done = self.event(+ "response.output_item.done",+ json!({"output_index": open.output_index, "item": item}),+ );+ events.extend([text_done, part_done, item_done]);+ self.output.push(item);+ }++ fn tool_call(&mut self, call: &Value, events: &mut Vec<Event>) -> Result<(), &'static str> {+ let chat_index = call.get("index").and_then(Value::as_u64).unwrap_or(0);+ let function = call.get("function").unwrap_or(&Value::Null);+ let is_open = self.call.as_ref().map(|open| open.chat_index) == Some(chat_index);+ if !is_open && !self.closed_calls.contains(&chat_index) {+ let (Some(call_id), Some(name)) = (+ call.get("id").and_then(Value::as_str),+ function.get("name").and_then(Value::as_str),+ ) else {+ return Err("a tool call arrived without its id and name");+ };+ self.close_text(events);+ self.close_call(events);+ let open = OpenCall {+ chat_index,+ position: self.calls,+ output_index: self.next_index,+ call_id: call_id.to_string(),+ name: name.to_string(),+ custom: self.shell.is_custom(name),+ arguments: String::new(),+ };+ self.calls += 1;+ self.next_index += 1;+ let item =+ self.shell+ .call_item(open.position, &open.call_id, &open.name, "", "in_progress");+ let added = self.event(+ "response.output_item.added",+ json!({"output_index": open.output_index, "item": item}),+ );+ events.push(added);+ self.call = Some(open);+ }+ let Some(fragment) = function+ .get("arguments")+ .and_then(Value::as_str)+ .filter(|fragment| !fragment.is_empty())+ else {+ return Ok(());+ };+ let Some(open) = self+ .call+ .as_mut()+ .filter(|open| open.chat_index == chat_index)+ else {+ return Err("tool call arguments arrived after another output item started");+ };+ open.arguments.push_str(fragment);+ if open.custom {+ return Ok(());+ }+ let payload = json!({+ "item_id": self.shell.call_id(false, open.position),+ "output_index": open.output_index,+ "delta": fragment,+ });+ let event = self.event("response.function_call_arguments.delta", payload);+ events.push(event);+ Ok(())+ }++ fn close_call(&mut self, events: &mut Vec<Event>) {+ let Some(open) = self.call.take() else {+ return;+ };+ let item_id = self.shell.call_id(open.custom, open.position);+ let value = if open.custom {+ let input = custom_input(&open.arguments);+ let delta = self.event(+ "response.custom_tool_call_input.delta",+ json!({"item_id": item_id, "output_index": open.output_index, "delta": input}),+ );+ let done = self.event(+ "response.custom_tool_call_input.done",+ json!({"item_id": item_id, "output_index": open.output_index, "input": input}),+ );+ events.extend([delta, done]);+ input+ } else {+ let done = self.event(+ "response.function_call_arguments.done",+ json!({+ "item_id": item_id,+ "output_index": open.output_index,+ "arguments": open.arguments,+ }),+ );+ events.push(done);+ open.arguments+ };+ let item = self.shell.call_item(+ open.position,+ &open.call_id,+ &open.name,+ &value,+ "completed",+ );+ let done = self.event(+ "response.output_item.done",+ json!({"output_index": open.output_index, "item": item}),+ );+ events.push(done);+ self.output.push(item);+ self.closed_calls.push(open.chat_index);+ }+}++/// One SSE frame of the chat stream.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum Frame {+ /// The joined `data` lines of an event.+ Data(String),+ /// A frame with comment lines only, as `:<text>`.+ Comment(String),+}++/// Splits an SSE byte stream into frames.+#[derive(Debug, Default)]+pub(crate) struct FrameParser {+ buffer: Vec<u8>,+}++impl FrameParser {+ pub(crate) fn push(&mut self, bytes: &[u8]) -> Vec<Frame> {+ self.buffer+ .extend(bytes.iter().copied().filter(|byte| *byte != b'\r'));+ let mut frames = Vec::new();+ while let Some(end) = self.buffer.windows(2).position(|window| window == b"\n\n") {+ let raw: Vec<u8> = self.buffer.drain(..end + 2).collect();+ let raw = String::from_utf8_lossy(&raw);+ let mut data: Option<String> = None;+ let mut comment: Option<&str> = None;+ for line in raw.split('\n') {+ if line.starts_with(':') {+ comment.get_or_insert(line);+ continue;+ }+ let Some(rest) = line.strip_prefix("data:") else {+ continue;+ };+ let rest = rest.strip_prefix(' ').unwrap_or(rest);+ match data.as_mut() {+ Some(data) => {+ data.push('\n');+ data.push_str(rest);+ }+ None => data = Some(rest.to_string()),+ }+ }+ match (data, comment) {+ (Some(data), _) => frames.push(Frame::Data(data)),+ (None, Some(comment)) => frames.push(Frame::Comment(comment.to_string())),+ (None, None) => {}+ }+ }+ frames+ }+}++struct Driver {+ inner: axum::body::BodyDataStream,+ parser: FrameParser,+ machine: StreamMachine,+ pending: VecDeque<Bytes>,+ finished: bool,+}++impl Driver {+ fn queue(&mut self, events: Vec<Event>) {+ self.pending.extend(events.iter().map(Event::encode));+ }++ fn frames(&mut self, bytes: &[u8]) {+ for frame in self.parser.push(bytes) {+ match frame {+ Frame::Comment(comment) if !self.machine.is_done() => {+ self.pending+ .push_back(Bytes::from(format!("{comment}\n\n")));+ }+ Frame::Comment(_) => {}+ Frame::Data(payload) => {+ let events = self.machine.on_data(&payload);+ let failed = events.iter().any(|event| event.name == FAILED);+ self.queue(events);+ if failed {+ self.finished = true;+ return;+ }+ }+ }+ }+ }+}++/// The Responses SSE body for a chat SSE body.+pub(crate) fn stream_body(inner: Body, mut machine: StreamMachine) -> Body {+ let start = machine.start();+ let mut driver = Driver {+ inner: inner.into_data_stream(),+ parser: FrameParser::default(),+ machine,+ pending: VecDeque::new(),+ finished: false,+ };+ driver.queue(start);+ let stream = futures_util::stream::unfold(driver, |mut driver| async move {+ loop {+ if let Some(bytes) = driver.pending.pop_front() {+ return Some((Ok::<Bytes, Infallible>(bytes), driver));+ }+ if driver.finished {+ return None;+ }+ match driver.inner.next().await {+ Some(Ok(bytes)) => driver.frames(&bytes),+ Some(Err(_)) => {+ let events = driver.machine.on_transport_error();+ driver.queue(events);+ driver.finished = true;+ }+ None => {+ let events = driver.machine.on_end();+ driver.queue(events);+ driver.finished = true;+ }+ }+ }+ });+ Body::from_stream(stream)+}diff --git a/packages/sie_gateway/src/handlers/responses/tests.rs b/packages/sie_gateway/src/handlers/responses/tests.rsnew file mode 100644index 000000000..afe439c7d--- /dev/null+++ b/packages/sie_gateway/src/handlers/responses/tests.rs@@ -0,0 +1,1102 @@+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::Duration;++use axum::body::{to_bytes, Body};+use axum::extract::{Request, State};+use axum::http::{HeaderName, HeaderValue, Method, StatusCode};+use axum::response::Response;+use bytes::Bytes;+use futures_util::StreamExt;+use serde_json::{json, Value};+use tower::ServiceExt;++use super::error::{responses_error_response, ResponsesError};+use super::proxy_responses;+use super::request::responses_to_chat;+use super::response::{chat_completion_to_response, Echo, ResponseShell};+use super::stream::{stream_body, Frame, FrameParser, StreamMachine};+use crate::handlers::proxy::{+ chat_completions_dispatch_inputs, compat_request_body_limit, responses_dispatch_inputs,+};+use crate::handlers::test_support::{TestGateway, HYBRID_GENERATE_MODEL, LOCAL_LANE};++const CODER_MODEL: &str = "\+sie_id: acme/coder+hf_id: acme/coder+tasks:+ generate:+ max_output_tokens: 64+ capabilities:+ tools: true+profiles:+ default:+ adapter_path: sie_server.adapters.sglang:SGLangAdapter+ max_batch_tokens: 8192+";++fn vectors(name: &str) -> Value {+ let path = format!(+ "{}/../../conformance/openai_responses/{name}",+ env!("CARGO_MANIFEST_DIR")+ );+ serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap()+}++fn shell_for(request: &Value, request_id: &str) -> ResponseShell {+ let echo = responses_to_chat(request).unwrap().echo;+ ResponseShell::new(echo, request_id.to_string(), 0)+}++fn responses_request(body: Value) -> Request {+ Request::builder()+ .method(Method::POST)+ .uri("/v1/responses")+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap()+}++async fn json_body(response: Response) -> Value {+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap()+}++/// The events of an SSE body, and how many comment frames it carried.+fn parse_events(bytes: &[u8]) -> (Vec<Value>, usize) {+ let text = String::from_utf8(bytes.to_vec()).unwrap();+ let mut comments = 0;+ let mut events = Vec::new();+ for frame in text.split("\n\n").filter(|frame| !frame.trim().is_empty()) {+ if frame.lines().all(|line| line.starts_with(':')) {+ comments += 1;+ continue;+ }+ let mut name = "";+ let mut data = Value::Null;+ for line in frame.lines() {+ if let Some(rest) = line.strip_prefix("event: ") {+ name = rest;+ } else if let Some(rest) = line.strip_prefix("data: ") {+ data = serde_json::from_str(rest).unwrap();+ }+ }+ assert_eq!(data["type"], name, "event name and data type agree");+ events.push(json!({"event": name, "data": data}));+ }+ (events, comments)+}++async fn events_of(response: Response) -> Vec<Value> {+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ parse_events(&bytes).0+}++fn event_names(events: &[Value]) -> Vec<String> {+ events+ .iter()+ .map(|event| event["event"].as_str().unwrap().to_string())+ .collect()+}++fn assert_refusal(error: &ResponsesError, expect: &Value, name: &str) {+ assert_eq!(+ u64::from(error.status.as_u16()),+ expect["status"].as_u64().unwrap(),+ "{name}"+ );+ assert_eq!(error.error_type, expect["type"], "{name}");+ assert_eq!(error.code, expect["code"], "{name}");+ assert_eq!(error.param.as_deref(), expect["param"].as_str(), "{name}");+ assert_eq!(error.message, expect["message"], "{name}");+}++#[test]+fn request_vectors_translate_onto_the_chat_body() {+ let vectors = vectors("request_vectors.json");+ for case in vectors["accepted"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let translation =+ responses_to_chat(&case["body"]).unwrap_or_else(|error| panic!("{name}: {error:?}"));+ assert_eq!(translation.chat, case["chat"], "{name}");+ assert!(+ chat_completions_dispatch_inputs(&translation.chat).is_ok(),+ "{name}: the chat route accepts the translation"+ );+ }+ for case in vectors["rejected"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let error = responses_to_chat(&case["body"]).expect_err(name);+ assert_refusal(&error, &case["expect"], name);+ }+}++#[test]+fn every_captured_codex_request_translates_or_is_refused_as_expected() {+ let fixture = vectors("codex_requests.json");+ let requests = fixture["requests"].as_array().unwrap();+ assert!(!requests.is_empty());+ for case in requests {+ let name = case["name"].as_str().unwrap();+ let expect = &case["expect"];+ match responses_to_chat(&case["body"]) {+ Ok(translation) => {+ let summary = &expect["chat"];+ assert!(summary.is_object(), "{name}: expected a refusal");+ let chat = &translation.chat;+ let messages = chat["messages"].as_array().unwrap();+ let roles: Vec<&Value> = messages.iter().map(|message| &message["role"]).collect();+ let expected_roles: Vec<&Value> =+ summary["roles"].as_array().unwrap().iter().collect();+ assert_eq!(roles, expected_roles, "{name}");+ let image_parts = messages+ .iter()+ .filter_map(|message| message["content"].as_array())+ .flatten()+ .filter(|part| part["type"] == "image_url")+ .count();+ assert_eq!(+ image_parts as u64,+ summary["image_parts"].as_u64().unwrap(),+ "{name}"+ );+ assert_eq!(+ chat["tools"].as_array().map_or(0, Vec::len) as u64,+ summary["tool_count"].as_u64().unwrap(),+ "{name}"+ );+ for key in [+ "stream",+ "tool_choice",+ "parallel_tool_calls",+ "include_reasoning",+ "reasoning_effort",+ ] {+ assert_eq!(+ chat.get(key).unwrap_or(&Value::Null),+ summary.get(key).unwrap_or(&Value::Null),+ "{name}: {key}"+ );+ }+ assert!(+ chat_completions_dispatch_inputs(chat).is_ok(),+ "{name}: the chat route accepts the translation"+ );+ }+ Err(error) => {+ assert!(+ expect["refused"].is_object(),+ "{name}: unexpected refusal {}",+ error.message+ );+ assert_refusal(&error, &expect["refused"], name);+ }+ }+ }+}++#[test]+fn response_vectors_translate_the_chat_completion() {+ let vectors = vectors("response_vectors.json");+ for case in vectors["translated"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ assert_eq!(case["request"]["model"], case["model"], "{name}");+ let shell = shell_for(&case["request"], case["request_id"].as_str().unwrap());+ let response = chat_completion_to_response(&case["chat"], &shell)+ .unwrap_or_else(|error| panic!("{name}: {error}"));+ assert_eq!(response, case["response"], "{name}");+ }+}++#[test]+fn a_chat_completion_the_translation_cannot_read_is_a_fault() {+ let shell = shell_for(&json!({"model": "m", "input": "x"}), "r");+ for chat in [+ json!({}),+ json!({"choices": []}),+ json!({"choices": [{"index": 0}]}),+ json!({"choices": [{"message": {"tool_calls": [{"function": {"name": "f"}}]}}]}),+ ] {+ assert!(+ chat_completion_to_response(&chat, &shell).is_err(),+ "{chat}"+ );+ }+}++fn stream_frames(case: &Value) -> Vec<String> {+ case["frames"]+ .as_array()+ .unwrap()+ .iter()+ .map(|frame| match frame {+ Value::String(text) => text.clone(),+ other => other.to_string(),+ })+ .collect()+}++#[test]+fn stream_vectors_drive_the_state_machine() {+ let vectors = vectors("stream_vectors.json");+ for case in vectors["streams"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let mut machine = StreamMachine::new(shell_for(+ &case["request"],+ case["request_id"].as_str().unwrap(),+ ));+ let mut events = machine.start();+ for frame in stream_frames(case) {+ events.extend(machine.on_data(&frame));+ }+ events.extend(machine.on_end());+ let got: Vec<Value> = events+ .iter()+ .map(|event| json!({"event": event.name, "data": event.data}))+ .collect();+ assert_eq!(&Value::Array(got), &case["events"], "{name}");+ }+}++#[tokio::test]+async fn stream_vectors_survive_the_sse_body_split_at_any_byte() {+ let vectors = vectors("stream_vectors.json");+ for case in vectors["streams"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let mut sse = String::from(":\n\n");+ for frame in stream_frames(case) {+ sse.push_str(&format!("data: {frame}\n\n"));+ sse.push_str(": keep-alive\n\n");+ }+ let bytes = sse.into_bytes();+ let pieces: Vec<Result<Bytes, std::io::Error>> = bytes+ .chunks(7)+ .map(|chunk| Ok(Bytes::copy_from_slice(chunk)))+ .collect();+ let inner = Body::from_stream(futures_util::stream::iter(pieces));+ let machine = StreamMachine::new(shell_for(+ &case["request"],+ case["request_id"].as_str().unwrap(),+ ));+ let collected = to_bytes(stream_body(inner, machine), usize::MAX)+ .await+ .unwrap();+ let (events, comments) = parse_events(&collected);+ assert_eq!(&Value::Array(events), &case["events"], "{name}");+ assert!(comments >= 1, "{name}: heartbeats pass through");+ let text = String::from_utf8(collected.to_vec()).unwrap();+ let terminal = text.rfind("event: response.").unwrap();+ assert!(+ !text[terminal..].contains("\n\n:"),+ "{name}: nothing follows the terminal event"+ );+ assert!(!text.contains("[DONE]"), "{name}");+ }+}++#[test]+fn frame_parser_joins_multi_line_data_and_keeps_comments() {+ let mut parser = FrameParser::default();+ assert_eq!(+ parser.push(b": keep-alive\r\n\r\ndata: {\"a\""),+ vec![Frame::Comment(": keep-alive".to_string())]+ );+ assert_eq!(+ parser.push(b":1}\r\n\r\nevent: x\ndata: one\ndata: two\n\n:\n\n"),+ vec![+ Frame::Data("{\"a\":1}".to_string()),+ Frame::Data("one\ntwo".to_string()),+ Frame::Comment(":".to_string()),+ ]+ );+}++#[tokio::test]+async fn error_vectors_keep_the_chat_error_with_the_responses_param() {+ let vectors = vectors("error_vectors.json");+ for case in vectors["errors"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let mut response = Response::new(Body::from(case["body"].to_string()));+ *response.status_mut() =+ StatusCode::from_u16(case["status"].as_u64().unwrap() as u16).unwrap();+ for (header, value) in case+ .get("headers")+ .and_then(Value::as_object)+ .into_iter()+ .flatten()+ {+ response.headers_mut().insert(+ HeaderName::from_bytes(header.as_bytes()).unwrap(),+ HeaderValue::from_str(value.as_str().unwrap()).unwrap(),+ );+ }+ let translated = responses_error_response(response).await;+ let expect = &case["expect"];+ assert_eq!(+ u64::from(translated.status().as_u16()),+ expect["status"].as_u64().unwrap(),+ "{name}"+ );+ for (header, value) in expect+ .get("headers")+ .and_then(Value::as_object)+ .into_iter()+ .flatten()+ {+ assert_eq!(+ translated+ .headers()+ .get(header.as_str())+ .map(|value| value.to_str().unwrap()),+ value.as_str(),+ "{name}: {header}"+ );+ }+ for header in expect+ .get("absent_headers")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ {+ assert!(+ translated.headers().get(header.as_str().unwrap()).is_none(),+ "{name}: {header}"+ );+ }+ assert_eq!(json_body(translated).await, expect["body"], "{name}");+ }+}++#[tokio::test]+async fn an_inner_error_keeps_its_response_extensions() {+ let mut response = Response::new(Body::from(+ json!({"error": {"message": "failed", "type": "server_error", "param": "max_completion_tokens", "code": "x"}})+ .to_string(),+ ));+ *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;+ let response = crate::http_error::GatewayOwnedFault::new("stage").mark(response);+ let translated = responses_error_response(response).await;+ assert_eq!(+ translated+ .extensions()+ .get::<crate::http_error::GatewayOwnedFault>()+ .map(|fault| fault.stage),+ Some("stage")+ );+ assert_eq!(+ json_body(translated).await["error"]["param"],+ "max_output_tokens"+ );+}++#[tokio::test]+async fn an_inner_error_body_that_cannot_be_rewritten_is_not_emptied() {+ let oversized = json!({"error": {"message": "x".repeat(2 * 1024 * 1024), "param": "max_completion_tokens"}}).to_string();+ let mut response = Response::new(Body::from(oversized.clone()));+ *response.status_mut() = StatusCode::FORBIDDEN;+ let passed = responses_error_response(response).await;+ assert_eq!(passed.status(), StatusCode::FORBIDDEN);+ let bytes = to_bytes(passed.into_body(), usize::MAX).await.unwrap();+ assert_eq!(bytes, oversized.as_bytes());++ let broken = futures_util::stream::iter([+ Ok::<Bytes, std::io::Error>(Bytes::from_static(b"{\"error\":")),+ Err(std::io::Error::other("reset")),+ ]);+ let mut response = Response::new(Body::from_stream(broken));+ *response.status_mut() = StatusCode::SERVICE_UNAVAILABLE;+ response+ .headers_mut()+ .insert("retry-after", HeaderValue::from_static("5"));+ let unreadable = responses_error_response(response).await;+ assert_eq!(unreadable.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(unreadable.headers()["retry-after"], "5");+ assert_eq!(unreadable.headers()["content-type"], "application/json");+ let body = json_body(unreadable).await;+ assert_eq!(body["error"]["code"], "transport_failure");+ assert_eq!(body["error"]["type"], "server_error");+}++#[tokio::test]+async fn a_translation_fault_keeps_the_serving_headers() {+ let mut answer = Response::new(Body::from("not json"));+ answer+ .headers_mut()+ .insert("x-sie-request-id", HeaderValue::from_static("request-9"));+ answer+ .headers_mut()+ .insert("x-sie-served-by", HeaderValue::from_static("local"));+ let fault = super::buffered_response(answer, &plain_shell()).await;+ assert_eq!(fault.status(), StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(fault.headers()["x-sie-request-id"], "request-9");+ assert_eq!(fault.headers()["x-sie-served-by"], "local");+ assert_eq!(+ fault+ .extensions()+ .get::<crate::http_error::GatewayOwnedFault>()+ .map(|fault| fault.stage),+ Some("translate_chat_response")+ );+ assert_eq!(+ json_body(fault).await["error"]["message"],+ "the chat completion is not valid JSON"+ );+}++#[derive(Clone, Copy)]+enum Step {+ Role,+ Text(&'static str),+ ToolStart(u64, &'static str),+ ToolArgs(u64),+ Finish(&'static str),+ Usage,+ Error,+ Malformed,+ Done,+}++fn step_frame(step: Step) -> String {+ let chunk = |delta: Value, finish: Value| {+ json!({"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}).to_string()+ };+ match step {+ Step::Role => chunk(json!({"role": "assistant"}), Value::Null),+ Step::Text(text) => chunk(json!({"content": text}), Value::Null),+ Step::ToolStart(index, name) => chunk(+ json!({"tool_calls": [{"index": index, "id": format!("c{index}"), "type": "function", "function": {"name": name, "arguments": ""}}]}),+ Value::Null,+ ),+ Step::ToolArgs(index) => chunk(+ json!({"tool_calls": [{"index": index, "function": {"arguments": "{\"input\":\"x\"}"}}]}),+ Value::Null,+ ),+ Step::Finish(reason) => chunk(json!({}), json!(reason)),+ Step::Usage => json!({"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}}).to_string(),+ Step::Error => json!({"choices": [], "error": {"message": "m", "type": "server_error", "param": null, "code": "RESOURCE_EXHAUSTED"}}).to_string(),+ Step::Malformed => "{not json".to_string(),+ Step::Done => "[DONE]".to_string(),+ }+}++/// Every event sequence opens with `response.created` and+/// `response.in_progress`, numbers its events from 0 without gaps, has at+/// most one open output item with contiguous output indices, sends item+/// events only to the open item and with that item's kind, and ends with+/// exactly one terminal event and nothing after it. A completed or+/// incomplete response has closed every item it added, and every terminal+/// response lists exactly the items done so far.+fn assert_event_grammar(events: &[Value], context: &str) {+ let names = event_names(events);+ assert_eq!(+ names[..2],+ ["response.created", "response.in_progress"],+ "{context}"+ );+ let mut open: Option<(Value, Value, String)> = None;+ let mut next_index = 0;+ let mut done = Vec::new();+ let mut terminal = None;+ for (position, event) in events.iter().enumerate() {+ let data = &event["data"];+ assert_eq!(data["sequence_number"], position as u64, "{context}");+ assert!(+ terminal.is_none(),+ "{context}: event after the end at {position}"+ );+ let name = event["event"].as_str().unwrap();+ let item_kind =+ match name {+ "response.created" | "response.in_progress" => {+ assert!(position < 2, "{context}");+ continue;+ }+ "response.output_item.added" => {+ assert!(open.is_none(), "{context}: two open items");+ assert_eq!(data["output_index"], next_index, "{context}");+ assert_eq!(data["item"]["status"], "in_progress", "{context}");+ next_index += 1;+ open = Some((+ data["output_index"].clone(),+ data["item"]["id"].clone(),+ data["item"]["type"].as_str().unwrap().to_string(),+ ));+ continue;+ }+ "response.output_item.done" => {+ let (index, id, kind) = open.take().expect("done without an open item");+ assert_eq!(data["output_index"], index, "{context}");+ assert_eq!(data["item"]["id"], id, "{context}");+ assert_eq!(data["item"]["type"], kind.as_str(), "{context}");+ assert_eq!(data["item"]["status"], "completed", "{context}");+ done.push(data["item"].clone());+ continue;+ }+ "response.completed" | "response.incomplete" | "response.failed" => {+ if name != "response.failed" {+ assert!(open.is_none(), "{context}: {name} with an open item");+ }+ assert_eq!(+ data["response"]["output"],+ Value::Array(done.clone()),+ "{context}"+ );+ terminal = Some(name);+ continue;+ }+ "response.content_part.added"+ | "response.output_text.delta"+ | "response.output_text.done"+ | "response.content_part.done" => "message",+ "response.function_call_arguments.delta"+ | "response.function_call_arguments.done" => "function_call",+ "response.custom_tool_call_input.delta"+ | "response.custom_tool_call_input.done" => "custom_tool_call",+ other => panic!("{context}: unexpected event {other}"),+ };+ let (index, id, kind) = open.clone().expect("item event without an open item");+ assert_eq!(kind, item_kind, "{context}: {name}");+ assert_eq!(data["output_index"], index, "{context}");+ assert_eq!(data["item_id"], id, "{context}");+ }+ assert!(terminal.is_some(), "{context}: no terminal event");+}++#[test]+fn any_chat_chunk_sequence_yields_a_well_formed_event_sequence() {+ let alphabet = [+ Step::Role,+ Step::Text("a"),+ Step::Text(" "),+ Step::ToolStart(0, "f"),+ Step::ToolStart(1, "patch"),+ Step::ToolStart(2, "f"),+ Step::ToolArgs(0),+ Step::ToolArgs(1),+ Step::ToolArgs(2),+ Step::Finish("stop"),+ Step::Finish("tool_calls"),+ Step::Finish("length"),+ Step::Usage,+ Step::Error,+ Step::Malformed,+ Step::Done,+ ];+ let echo = Echo {+ model: "m".to_string(),+ parallel_tool_calls: json!(true),+ tool_choice: json!("auto"),+ custom_tools: vec!["patch".to_string()],+ };+ let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;+ for round in 0..4000 {+ let length = (round % 14) + 1;+ let mut steps = Vec::with_capacity(length);+ for _ in 0..length {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ steps.push(alphabet[(seed % alphabet.len() as u64) as usize]);+ }+ let mut machine = StreamMachine::new(ResponseShell::new(echo.clone(), "x".to_string(), 0));+ let mut events = machine.start();+ for step in &steps {+ events.extend(machine.on_data(&step_frame(*step)));+ }+ events.extend(if round % 5 == 0 {+ machine.on_transport_error()+ } else {+ machine.on_end()+ });+ let events: Vec<Value> = events+ .iter()+ .map(|event| json!({"event": event.name, "data": event.data}))+ .collect();+ assert_event_grammar(&events, &format!("round {round}"));+ }+}++struct DropFlag(Arc<AtomicBool>);++impl Drop for DropFlag {+ fn drop(&mut self) {+ self.0.store(true, Ordering::SeqCst);+ }+}++fn plain_shell() -> ResponseShell {+ shell_for(&json!({"model": "m", "input": "x", "stream": true}), "r")+}++#[tokio::test]+async fn a_failed_event_ends_the_body_and_drops_the_chat_body() {+ let dropped = Arc::new(AtomicBool::new(false));+ let flag = DropFlag(Arc::clone(&dropped));+ let malformed = futures_util::stream::iter([Ok::<Bytes, std::io::Error>(Bytes::from_static(+ b"data: {not json\n\n",+ ))]);+ let inner_stream = malformed+ .chain(futures_util::stream::pending())+ .map(move |item| {+ let _keep = &flag;+ item+ });+ let body = stream_body(+ Body::from_stream(inner_stream.boxed()),+ StreamMachine::new(plain_shell()),+ );+ let collected = tokio::time::timeout(Duration::from_secs(5), to_bytes(body, usize::MAX))+ .await+ .expect("the body ends after the failed event")+ .unwrap();+ let events = parse_events(&collected).0;+ assert_eq!(+ event_names(&events),+ [+ "response.created",+ "response.in_progress",+ "response.failed"+ ]+ );+ assert_eq!(+ events[2]["data"]["response"]["error"],+ json!({"code": "server_error", "message": "the generation stream sent a malformed chunk"})+ );+ assert!(dropped.load(Ordering::SeqCst));+}++fn run_steps(steps: &[Step]) -> Vec<super::stream::Event> {+ let mut machine = StreamMachine::new(plain_shell());+ let mut events = machine.start();+ for step in steps {+ events.extend(machine.on_data(&step_frame(*step)));+ }+ events.extend(machine.on_end());+ events+}++#[test]+fn tool_call_deltas_the_translation_cannot_place_fail_the_response() {+ let cases = [+ (+ vec![Step::ToolStart(0, "f"), Step::Text("a"), Step::ToolArgs(0)],+ "tool call arguments arrived after another output item started",+ ),+ (+ vec![+ Step::ToolStart(0, "f"),+ Step::ToolStart(1, "f"),+ Step::ToolArgs(0),+ ],+ "tool call arguments arrived after another output item started",+ ),+ (+ vec![Step::ToolArgs(0)],+ "a tool call arrived without its id and name",+ ),+ ];+ for (steps, message) in cases {+ let events = run_steps(&steps);+ let terminal = events.last().unwrap();+ assert_eq!(terminal.name, "response.failed", "{message}");+ assert_eq!(+ terminal.data["response"]["error"],+ json!({"code": "server_error", "message": message})+ );+ }+}++#[test]+fn a_closed_call_delta_without_arguments_is_ignored() {+ let events = run_steps(&[+ Step::ToolStart(0, "f"),+ Step::Text("a"),+ Step::ToolStart(0, "f"),+ Step::Text("b"),+ Step::Finish("stop"),+ Step::Usage,+ Step::Done,+ ]);+ let terminal = events.last().unwrap();+ assert_eq!(terminal.name, "response.completed");+ let output = &terminal.data["response"]["output"];+ assert_eq!(output[0]["type"], "function_call");+ assert_eq!(output[1]["id"], "msg-r-1");+ assert_eq!(output[1]["content"][0]["text"], "ab");+}++#[tokio::test]+async fn a_broken_chat_stream_fails_the_response() {+ let broken = futures_util::stream::iter([+ Ok::<Bytes, std::io::Error>(Bytes::from_static(+ b"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"a\"}}]}\n\n",+ )),+ Err(std::io::Error::other("reset")),+ ]);+ let body = stream_body(Body::from_stream(broken), StreamMachine::new(plain_shell()));+ let events = parse_events(&to_bytes(body, usize::MAX).await.unwrap()).0;+ let last = events.last().unwrap();+ assert_eq!(last["event"], "response.failed");+ assert_eq!(+ last["data"]["response"]["error"],+ json!({"code": "server_error", "message": "the generation stream ended unexpectedly"})+ );+}++#[tokio::test]+async fn dropping_the_responses_body_drops_the_chat_body() {+ let dropped = Arc::new(AtomicBool::new(false));+ let flag = DropFlag(Arc::clone(&dropped));+ let inner_stream =+ futures_util::stream::pending::<Result<Bytes, std::io::Error>>().map(move |item| {+ let _keep = &flag;+ item+ });+ let body = stream_body(+ Body::from_stream(inner_stream.boxed()),+ StreamMachine::new(plain_shell()),+ );+ let mut data = body.into_data_stream();+ let first = data.next().await.unwrap().unwrap();+ assert!(String::from_utf8_lossy(&first).starts_with("event: response.created"));+ assert!(!dropped.load(Ordering::SeqCst));+ drop(data);+ assert!(dropped.load(Ordering::SeqCst));+}++async fn chat_gateway(models: &[&str], loaded: &[&str]) -> TestGateway {+ let gateway = TestGateway::new(models).await;+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, loaded)+ .await;+ gateway+}++fn settle_created_at(response: &mut Value) {+ assert!(+ response["created_at"].as_u64().is_some_and(|at| at > 0),+ "{response}"+ );+ response["created_at"] = json!(0);+}++#[tokio::test]+async fn a_buffered_response_is_served_by_the_chat_route() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ responses_request(json!({+ "model": "acme/chat",+ "instructions": "Be brief.",+ "input": [{"role": "user", "content": [{"type": "input_text", "text": "hi"}]}],+ "store": false,+ "include": ["reasoning.encrypted_content"],+ "client_metadata": {"session_id": "s"},+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["x-sie-request-id"], "request-1");+ assert_eq!(response.headers()["content-type"], "application/json");+ let mut body = json_body(response).await;+ settle_created_at(&mut body);+ assert_eq!(+ body,+ json!({+ "id": "resp-request-1",+ "object": "response",+ "created_at": 0,+ "model": "acme/chat",+ "status": "completed",+ "incomplete_details": null,+ "error": null,+ "store": false,+ "parallel_tool_calls": true,+ "tool_choice": "auto",+ "output": [{+ "type": "message",+ "id": "msg-request-1",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": "ok", "annotations": []}],+ }],+ "usage": {+ "input_tokens": 1,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 1,+ "output_tokens_details": {"reasoning_tokens": 0},+ "total_tokens": 2,+ },+ })+ );+ let dispatched = gateway.dispatcher.dispatched();+ assert_eq!(dispatched.len(), 1);+ assert_eq!(dispatched[0].endpoint, "generate");+ assert_eq!(dispatched[0].model, "acme/chat");+}++#[tokio::test]+async fn a_streamed_response_is_served_by_the_chat_route() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ responses_request(json!({"model": "acme/chat", "input": "hi", "stream": true})),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["content-type"], "text/event-stream");+ assert_eq!(response.headers()["x-sie-request-id"], "request-1");+ assert!(response.headers().get("content-length").is_none());+ let events = events_of(response).await;+ assert_eq!(+ event_names(&events),+ [+ "response.created",+ "response.in_progress",+ "response.output_item.added",+ "response.content_part.added",+ "response.output_text.delta",+ "response.output_text.done",+ "response.content_part.done",+ "response.output_item.done",+ "response.completed",+ ]+ );+ assert_event_grammar(&events, "served stream");+ let mut completed = events[8]["data"]["response"].clone();+ settle_created_at(&mut completed);+ assert_eq!(completed["id"], "resp-request-1");+ assert_eq!(completed["status"], "completed");+ assert_eq!(completed["output"][0]["id"], "msg-request-1");+ assert_eq!(completed["output"][0]["content"][0]["text"], "ok");+ assert_eq!(completed["usage"]["total_tokens"], 2);+}++#[tokio::test]+async fn a_worker_failure_after_output_is_a_failed_event() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ gateway.dispatcher.fail_stream(true);+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ responses_request(json!({"model": "acme/chat", "input": "hi", "stream": true})),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let events = events_of(response).await;+ assert_eq!(+ event_names(&events),+ [+ "response.created",+ "response.in_progress",+ "response.output_item.added",+ "response.content_part.added",+ "response.output_text.delta",+ "response.failed",+ ]+ );+ let failed = &events[5]["data"]["response"];+ assert_eq!(failed["status"], "failed");+ assert_eq!(failed["output"], json!([]));+ assert!(failed["error"]["code"].is_string(), "{failed}");+ assert!(failed["error"]["message"].is_string(), "{failed}");+}++#[tokio::test]+async fn chat_refusals_name_the_responses_field() {+ let gateway = chat_gateway(+ &[HYBRID_GENERATE_MODEL, CODER_MODEL],+ &["acme/chat", "acme/coder"],+ )+ .await;+ let function =+ |name: &str| json!({"type": "function", "name": name, "parameters": {"type": "object"}});+ let cases = [+ (+ json!({"model": "acme/missing", "input": "hi"}),+ StatusCode::NOT_FOUND,+ "model",+ ),+ (+ json!({"model": "acme/chat", "input": "hi", "tools": [function("t")]}),+ StatusCode::BAD_REQUEST,+ "tools",+ ),+ (+ json!({"model": "acme/coder", "input": "hi", "max_output_tokens": 100}),+ StatusCode::BAD_REQUEST,+ "max_output_tokens",+ ),+ (+ json!({"model": "acme/coder", "input": "hi", "tools": [function("ok"), function("two words")]}),+ StatusCode::BAD_REQUEST,+ "tools[1].name",+ ),+ ];+ for (body, status, param) in cases {+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ responses_request(body.clone()),+ )+ .await;+ assert_eq!(response.status(), status, "{body}");+ let answer = json_body(response).await;+ assert_eq!(answer["error"]["param"], param, "{body}: {answer}");+ assert!(answer["error"]["code"].is_string(), "{body}");+ }+ assert!(gateway.dispatcher.dispatched().is_empty());+}++#[tokio::test]+async fn a_translation_refusal_publishes_nothing() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ responses_request(json!({+ "model": "acme/chat",+ "input": "hi",+ "previous_response_id": "resp-1",+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert_eq!(+ json_body(response).await,+ json!({"error": {+ "message": "previous_response_id: SIE does not store responses; send the full conversation in input",+ "type": "invalid_request_error",+ "param": "previous_response_id",+ "code": "unsupported_field",+ }})+ );+ assert!(gateway.dispatcher.dispatched().is_empty());+}++#[tokio::test]+async fn capacity_is_a_retryable_refusal_before_the_stream_opens() {+ for stream in [false, true] {+ let gateway = TestGateway::new(&[HYBRID_GENERATE_MODEL]).await;+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ responses_request(json!({"model": "acme/chat", "input": "hi", "stream": stream})),+ )+ .await;+ assert_eq!(+ response.status(),+ StatusCode::SERVICE_UNAVAILABLE,+ "stream={stream}"+ );+ assert!(+ response.headers().get("retry-after").is_some(),+ "stream={stream}"+ );+ assert!(+ response.headers().get("x-sie-error-code").is_some(),+ "stream={stream}"+ );+ let body = json_body(response).await;+ assert!(body["error"]["code"].is_string(), "stream={stream}: {body}");+ }+}++#[tokio::test]+async fn the_router_serves_responses_and_no_stored_response_routes() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let mut config = (*gateway.state.config).clone();+ config.auth_mode = "token".to_string();+ config.auth_tokens = vec!["secret".to_string()];+ let router = crate::server::create_router(Arc::clone(&gateway.state), Arc::new(config));+ let body = json!({"model": "acme/chat", "input": "hi"});++ let unauthenticated = router+ .clone()+ .oneshot(responses_request(body.clone()))+ .await+ .unwrap();+ assert_eq!(unauthenticated.status(), StatusCode::UNAUTHORIZED);++ let authorized = |method: Method, uri: &str, body: &Value| {+ Request::builder()+ .method(method)+ .uri(uri)+ .header("authorization", "Bearer secret")+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap()+ };+ let served = router+ .clone()+ .oneshot(authorized(Method::POST, "/v1/responses", &body))+ .await+ .unwrap();+ assert_eq!(served.status(), StatusCode::OK);+ assert_eq!(+ json_body(served).await["output"][0]["content"][0]["text"],+ "ok"+ );+ for (method, uri) in [+ (Method::GET, "/v1/responses/resp-request-1"),+ (Method::POST, "/v1/responses/resp-request-1/cancel"),+ (Method::POST, "/v1/responses/input_tokens"),+ (Method::POST, "/v1/responses/compact"),+ ] {+ let answer = router+ .clone()+ .oneshot(authorized(method, uri, &body))+ .await+ .unwrap();+ assert_eq!(answer.status(), StatusCode::NOT_FOUND, "{uri}");+ }+ let wrong_method = router+ .oneshot(authorized(Method::GET, "/v1/responses", &Value::Null))+ .await+ .unwrap();+ assert_eq!(wrong_method.status(), StatusCode::METHOD_NOT_ALLOWED);+}++#[test]+fn dispatch_inputs_compose_the_translation_with_the_chat_seam() {+ let (model, params) = responses_dispatch_inputs(&json!({+ "model": "acme/chat",+ "max_output_tokens": 48,+ "input": "hi",+ }))+ .unwrap();+ assert_eq!(model, "acme/chat");+ assert_eq!(params.generate.as_ref().unwrap().max_new_tokens, 48);+ let refused = responses_dispatch_inputs(&json!({"model": "acme/chat"})).unwrap_err();+ assert_eq!(refused.status(), StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn unreadable_bodies_are_refused_in_the_openai_envelope() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let limit = compat_request_body_limit("/v1/responses");+ for (body, status, message) in [+ (+ Body::from("x".repeat(limit + 1)),+ StatusCode::PAYLOAD_TOO_LARGE,+ format!("Request body too large (max {limit} bytes)"),+ ),+ (+ Body::from("{"),+ StatusCode::BAD_REQUEST,+ "invalid JSON: EOF while parsing an object at line 1 column 1".to_string(),+ ),+ ] {+ let response = proxy_responses(+ State(Arc::clone(&gateway.state)),+ Request::builder()+ .method(Method::POST)+ .uri("/v1/responses")+ .body(body)+ .unwrap(),+ )+ .await;+ assert_eq!(response.status(), status);+ let answer = json_body(response).await;+ assert_eq!(answer["error"]["message"], message);+ assert_eq!(answer["error"]["type"], "invalid_request_error");+ assert_eq!(answer["error"]["code"], "invalid_request");+ }+ assert!(gateway.dispatcher.dispatched().is_empty());+}diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rsindex ffc6e546d..c20e0afe2 100644--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs@@ -1587,8 +1587,9 @@ mod tests {use crate::handlers::proxy::{proxy_chat, proxy_completions, proxy_openai_embeddings, proxy_request, proxy_rerank,- proxy_rerank_v2, proxy_responses,+ proxy_rerank_v2,};+ use crate::handlers::responses::proxy_responses;use crate::handlers::test_support::{Dispatched, TestGateway, HYBRID_ENCODE_MODEL, HYBRID_EXTRACT_MODEL, HYBRID_GENERATE_MODEL,LOCAL_ENCODE_MODEL, LOCAL_LANE, REMOTE_ENCODE_MODEL, REMOTE_LANE,diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 132d977ed..ba61bb3b6 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -61,7 +61,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {crate::handlers::proxy::proxy_generate,crate::handlers::proxy::proxy_chat,crate::handlers::proxy::proxy_completions,- crate::handlers::proxy::proxy_responses,+ crate::handlers::responses::proxy_responses,crate::handlers::messages::proxy_messages,crate::handlers::proxy::proxy_moderations,docs_ui@@ -150,7 +150,6 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {ChatCompletionChoiceMessage,ChatCompletionUsage,CompletionsRequest,- ResponsesRequest,OpenAIErrorBody,OpenAIErrorEnvelope,crate::handlers::messages::schema::MessagesRequest,@@ -159,6 +158,9 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {crate::handlers::messages::schema::MessagesUsage,crate::handlers::messages::schema::AnthropicErrorBody,crate::handlers::messages::schema::AnthropicErrorEnvelope,+ crate::handlers::responses::schema::ResponsesRequest,+ crate::handlers::responses::schema::ResponsesResponse,+ crate::handlers::responses::schema::ResponsesUsage,PoolListResponse,crate::types::pool::PoolSpec,crate::types::pool::PoolStatus,@@ -483,10 +485,8 @@ fn patch_chat_completion_schema(value: &mut Value) {patch_chat_request_schema(value);patch_chat_message_schema(value);patch_completions_request_schema(value);- patch_responses_request_schema(value);patch_chat_completion_paths(value);patch_completions_path(value);- patch_responses_path(value);}fn patch_generate_request_schema(value: &mut Value) {@@ -1065,118 +1065,6 @@ fn patch_completions_request_schema(value: &mut Value) {);}-fn patch_responses_request_schema(value: &mut Value) {- let Some(schema) = value- .get_mut("components")- .and_then(|components| components.get_mut("schemas"))- .and_then(|schemas| schemas.get_mut("ResponsesRequest"))- else {- return;- };- schema["additionalProperties"] = json!(false);- let Some(properties) = schema- .get_mut("properties")- .and_then(|properties| properties.as_object_mut())- else {- return;- };- if let Some(model) = properties.get_mut("model") {- model["minLength"] = json!(1);- }- // input: either a string OR an array of {role, content} messages.- properties.insert(- "input".to_string(),- json!({- "description": "Either a string prompt OR an array of `{role, content}` messages \- (array-input support). Array form: `role` is one of \- `\"system\" | \"user\" | \"assistant\" | \"developer\"` \- (\"developer\" normalizes to \"system\"). `content` is a string or \- an array of `text`, `input_text`, or `output_text` parts; image parts \- (`image_url` / `input_image`) reject with 400 unsupported_field. The \- array must not be empty.",- "oneOf": [- {"type": "string"},- {- "type": "array",- "minItems": 1,- "items": {- "type": "object",- "additionalProperties": false,- "required": ["role", "content"],- "properties": {- "role": {- "type": "string",- "enum": ["system", "user", "assistant", "developer"],- },- "content": {- "oneOf": [- {"type": "string"},- {- "type": "array",- "items": {- "type": "object",- "additionalProperties": false,- "required": ["type", "text"],- "properties": {- "type": {- "type": "string",- "enum": ["text", "input_text", "output_text"],- },- "text": {"type": "string"},- },- },- },- ],- },- },- },- },- ],- }),- );- properties.insert(- "max_output_tokens".to_string(),- json!({- "description": "Maximum number of generated tokens. Defaults to 16 when absent or null.",- "type": ["integer", "null"],- "minimum": 1,- "maximum": u32::MAX,- }),- );- properties.insert(- "temperature".to_string(),- json!({- "description": "Sampling temperature representable by the worker runtime.",- "type": ["number", "null"],- "format": "float",- "minimum": 0,- "maximum": f32::MAX,- }),- );- properties.insert(- "stream".to_string(),- json!({- "description": "Accepted only as `false` (or absent). `true` rejects with 400 \- unsupported_field because Responses SSE is not supported yet.",- "type": ["boolean", "null"],- "enum": [false, null],- }),- );- properties.insert(- "seed".to_string(),- json!({- "description": "Optional signed 64-bit per-request sampling seed. \- Reproducibility is best effort, not guaranteed, and depends on the \- active generation backend and deployment configuration. Non-integer \- or out-of-range values reject with 400 invalid_request.",- "type": ["integer", "null"],- "format": "int64",- "minimum": i64::MIN,- "maximum": i64::MAX,- }),- );-}-fn patch_chat_completion_paths(value: &mut Value) {let Some(op) = value.get_mut("paths")@@ -1250,123 +1138,6 @@ fn patch_completions_path(value: &mut Value) {}}-fn patch_responses_path(value: &mut Value) {- let Some(post) = value- .get_mut("paths")- .and_then(|paths| paths.get_mut("/v1/responses"))- .and_then(|path_item| path_item.get_mut("post"))- else {- return;- };- if let Some(op_obj) = post.as_object_mut() {- op_obj.insert(- "description".to_string(),- json!(- "OpenAI Responses API (MVP). Strict allow-list parser: \- unknown top-level fields reject with 400 \- `unsupported_field`. `input` is either a string prompt OR an array of \- `{role, content}` messages. \- Known-rejected fields: `tools`, `tool_choice`, `previous_response_id`, \- `reasoning`, `background`, `metadata`, `instructions` — each rejects \- with 400 `unsupported_field`. `stream: true` is rejected (Responses SSE \- is deferred). Multimodal image content parts reject with 400 \- `unsupported_field` on the array form."- ),- );- op_obj.insert(- "summary".to_string(),- json!("`/v1/responses` — OpenAI Responses API (MVP, stateless single-turn)."),- );- let request_body = op_obj- .entry("requestBody".to_string())- .or_insert_with(|| json!({}));- if let Some(request_body) = request_body.as_object_mut() {- request_body.insert("required".to_string(), json!(true));- request_body.insert(- "content".to_string(),- json!({- "application/json": {- "schema": {"$ref": "#/components/schemas/ResponsesRequest"}- }- }),- );- }- if let Some(success) = op_obj- .get_mut("responses")- .and_then(|responses| responses.get_mut("200"))- .and_then(|response| response.as_object_mut())- {- success.insert(- "content".to_string(),- json!({- "application/json": {- "schema": {- "type": "object",- "additionalProperties": false,- "required": ["id", "object", "created_at", "model", "status", "output", "usage"],- "properties": {- "id": {"type": "string"},- "object": {"type": "string", "const": "response"},- "created_at": {"type": "integer"},- "model": {"type": "string"},- "status": {"type": "string", "const": "completed"},- "output": {- "type": "array",- "items": {- "type": "object",- "additionalProperties": false,- "required": ["type", "id", "role", "status", "content"],- "properties": {- "type": {"type": "string", "const": "message"},- "id": {"type": "string"},- "role": {"type": "string", "const": "assistant"},- "status": {"type": "string", "const": "completed"},- "content": {- "type": "array",- "items": {- "type": "object",- "additionalProperties": false,- "required": ["type", "text", "annotations"],- "properties": {- "type": {"type": "string", "const": "output_text"},- "text": {"type": "string"},- "annotations": {- "type": "array",- "items": {"type": "object"},- },- },- },- },- },- },- },- "usage": {- "type": "object",- "additionalProperties": false,- "required": ["input_tokens", "output_tokens", "total_tokens"],- "properties": {- "input_tokens": {"type": "integer", "minimum": 0},- "output_tokens": {"type": "integer", "minimum": 0},- "total_tokens": {"type": "integer", "minimum": 0},- "input_tokens_details": {- "type": "object",- "additionalProperties": false,- "required": ["cached_tokens"],- "properties": {- "cached_tokens": {"type": "integer", "minimum": 0},- },- },- },- },- },- }- }- }),- );- }- }-}-/// Duplicate ``application/json`` schemas to the msgpack media types accepted by queue inference.fn inject_inference_msgpack_content(paths: &mut serde_json::Map<String, Value>) {for path in [@@ -2608,52 +2379,6 @@ pub struct CompletionsRequest {pub n: Option<u32>,}-/// OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).-///-/// **Strict allow-list**: unknown fields reject with 400-/// ``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.-///-/// **Known-rejected fields**:-/// - ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.-/// - ``previous_response_id`` — rejected with 400 ``unsupported_field``-/// (Responses MVP is stateless single-turn).-/// - ``reasoning`` — rejected with 400 ``unsupported_field``.-/// - ``background`` — rejected with 400 ``unsupported_field``.-/// - ``metadata`` — rejected with 400 ``unsupported_field``.-/// - ``instructions`` — rejected with 400 ``unsupported_field``.-/// - ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on-/// Responses is deferred; use ``stream: false`` or omit).-/// - Multimodal ``image_url`` / ``input_image`` content parts on the array-/// form — rejected with 400 ``unsupported_field``: the Responses surface is-/// text-only. (Vision input is supported on ``/v1/chat/completions``.)-#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct ResponsesRequest {- pub model: String,- /// Either a string prompt OR an array of ``{role, content}`` messages- /// (array-input support). Array form: ``role`` is one of- /// ``"system" | "user" | "assistant" | "developer"``.- /// ``content`` is a string or an array of text-only content parts; image- /// parts reject.- pub input: Value,- /// Defaults to 16 (mirroring completions) when absent. Positive integer.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub max_output_tokens: Option<u32>,- /// Sampling temperature. Finite number ``>= 0``.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub temperature: Option<f32>,- /// Nucleus sampling. Finite number in ``(0, 1]``.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub top_p: Option<f32>,- /// Optional signed 64-bit per-request sampling seed. Reproducibility is- /// best effort, not guaranteed, and backend/deployment-specific.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub seed: Option<i64>,- /// Accepted only as ``false`` (or absent). ``true`` rejects with 400- /// ``unsupported_field`` (Responses SSE is deferred).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub stream: Option<bool>,-}-/// OpenAI-shaped error body used by ``/v1/generate/{model}`` and/// ``/v1/chat/completions``.#[derive(Debug, Serialize, Deserialize, ToSchema)]@@ -3999,47 +3724,47 @@ mod tests {fn openapi_json_documents_strict_responses_contract() {let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();let request = &spec["components"]["schemas"]["ResponsesRequest"];-assert_eq!(request["additionalProperties"], false);+ assert_eq!(request["required"], json!(["model", "input"]));assert_eq!(request["properties"]["model"]["minLength"], 1);assert_eq!(request["properties"]["max_output_tokens"]["minimum"], 1);+ let input = &request["properties"]["input"]["oneOf"];+ assert_eq!(input[0]["type"], "string");+ assert_eq!(input[1]["type"], "array");+ assert_eq!(input[1]["minItems"], 1);+ for stored in ["previous_response_id", "conversation"] {+ assert_eq!(request["properties"][stored]["type"], "null", "{stored}");+ }+ for refused in ["prompt", "stream_options"] {+ assert!(request["properties"].get(refused).is_none(), "{refused}");+ }+ for closed in ["ResponsesResponse", "ResponsesUsage"] {+ assert_eq!(+ spec["components"]["schemas"][closed]["additionalProperties"], false,+ "{closed}"+ );+ }++ let operation = &spec["paths"]["/v1/responses"]["post"];assert_eq!(- request["properties"]["max_output_tokens"]["maximum"],- u32::MAX+ operation["requestBody"]["content"]["application/json"]["schema"]["$ref"],+ "#/components/schemas/ResponsesRequest");- let message = &request["properties"]["input"]["oneOf"][1]["items"];- assert_eq!(message["additionalProperties"], false);- assert!(!message["properties"]["role"]["enum"]- .as_array()- .unwrap()- .iter()- .any(|role| role == "tool"));- let part = &message["properties"]["content"]["oneOf"][1]["items"];- assert_eq!(part["additionalProperties"], false);- assert_eq!(part["required"], json!(["type", "text"]));- assert!(part["properties"]["type"]["enum"]- .as_array()- .unwrap()- .iter()- .any(|part_type| part_type == "output_text"));-- let response = &spec["paths"]["/v1/responses"]["post"]["responses"]["200"]["content"]- ["application/json"]["schema"];- assert_eq!(response["additionalProperties"], false);- assert_eq!(response["properties"]["object"]["const"], "response");assert_eq!(- response["properties"]["output"]["items"]["properties"]["content"]["items"]- ["properties"]["type"]["const"],- "output_text"+ operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],+ "#/components/schemas/ResponsesResponse");assert_eq!(- response["properties"]["usage"]["required"],- json!(["input_tokens", "output_tokens", "total_tokens"])+ operation["responses"]["200"]["content"]["text/event-stream"]["schema"]["type"],+ "string");- assert!(spec["paths"]["/v1/responses"]["post"]["responses"]- .as_object()- .unwrap()- .contains_key("413"));+ for status in ["400", "404", "413", "503"] {+ assert_eq!(+ operation["responses"][status]["content"]["application/json"]["schema"]["$ref"],+ "#/components/schemas/OpenAIErrorEnvelope",+ "{status}"+ );+ }}#[test]diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex ef8aa2200..39e1b6f77 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -7,7 +7,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};use crate::config::Config;use crate::handlers::{- audio, config_api, decisions, health, messages, models, pools, proxy, systemone,+ audio, config_api, decisions, health, messages, models, pools, proxy, responses, systemone,};use crate::middleware::audit::AuditLayer;use crate::middleware::auth::AuthLayer;@@ -643,8 +643,8 @@ pub fn create_router_core(.route("/v1/chat/completions", post(proxy::proxy_chat))// OpenAI legacy Completions — raw-prompt continuation (non-streaming)..route("/v1/completions", post(proxy::proxy_completions))- // OpenAI Responses API (MVP: string input, non-streaming).- .route("/v1/responses", post(proxy::proxy_responses))+ // OpenAI Responses API, translated onto chat completions.+ .route("/v1/responses", post(responses::proxy_responses))// Anthropic Messages API, translated onto chat completions..route("/v1/messages", post(messages::proxy_messages))// OpenAI moderations surface — registered but not implemented (501)