diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md index 2175bb128..0aab2fbcd 100644 --- a/packages/sie_gateway/docs/architecture-guide.md +++ b/packages/sie_gateway/docs/architecture-guide.md @@ -66,7 +66,7 @@ Rules enforced on the inference path: - On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal. - When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, and `QUEUE_FULL` (a worker that cannot serve the item now, such as a remote profile whose upstream is busy, unreachable, rate capped or behind an open circuit breaker; a remote profile whose upstream model is not ready answers `MODEL_LOADING`). A remote worker answers these upstream refusals at once with the upstream's wait rather than redelivering the item. Generation workers attach the operator's validated `oom_recovery.retry_after_s` value to a `RESOURCE_EXHAUSTED` terminal chunk, and a worker may set `WorkResult.retry_after_s` on a failed item; for `RESOURCE_EXHAUSTED`, `QUEUE_FULL` and `MODEL_LOADING` failures, the gateway uses the longest worker hint that qualifies as an integer in `1..=60` seconds, ignoring other hints. If no hint qualifies, or the code is `LORA_LOADING` even when a worker provides a hint, it uses the current five-second default compiled into the gateway. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal. - When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata. -- Every successful response and every `5xx` of an inference route carries `X-SIE-Served-By` (`local` or `remote`) once routing has resolved the dispatched model, and `X-SIE-Upstream` with the upstream's name when that model's default profile uses a remote adapter (`handlers::serving_disclosure`). The value is read from the dispatched route's configuration, as `sie_server.api.helpers.serving_disclosure_headers` reads it on the single server, so a `model:remote` variant or a remote-backed model reports `remote` and the model's local profile reports `local`. Client errors carry neither header. The compatibility routes (`/v1/embeddings`, `/v1/rerank`, `/v2/rerank`, `/v1/audio/transcriptions`, `/v1/messages`) forward both through `is_openai_compat_forwarded_header`. +- Every successful response and every `5xx` of an inference route carries `X-SIE-Served-By` (`local` or `remote`) once routing has resolved the dispatched model, and `X-SIE-Upstream` with the upstream's name when that model's default profile uses a remote adapter (`handlers::serving_disclosure`). The value is read from the dispatched route's configuration, as `sie_server.api.helpers.serving_disclosure_headers` reads it on the single server, so a `model:remote` variant or a remote-backed model reports `remote` and the model's local profile reports `local`. Client errors carry neither header. The compatibility routes (`/v1/embeddings`, `/v1/rerank`, `/v2/rerank`, `/v1/audio/transcriptions`, `/v1/audio/speech`, `/v1/messages`) forward both through `is_openai_compat_forwarded_header`. Encode / extract tuning fields (`output_types`, `instruction`, `options`, `labels`, `output_schema`, `is_query`) are read **only** from the nested JSON **`params`** object (and the msgpack analogue: a top-level **`params`** map). The score path continues to read `query` / `instruction` / `options` at the top level of the request body, matching `sie_server`. @@ -78,7 +78,7 @@ before the gateway publishes the worker item, preserving the worker-side typed Gateway-generated **JSON error** bodies (validation, routing, auth, config read, pools) use a FastAPI-like envelope **`{"detail":{"code":"","message":"…", …}}`**. Extra diagnostic keys (e.g. `compatible_bundles`, `gpu`, `model`) live **inside** `detail` when present. This is intentionally **not** the same shape as SDK retry contracts, which remain **`{"error":{"code","message"}}`** for **503** retryable worker signals, SIE-native provisioning, and **`502`** **`MODEL_LOAD_FAILED`**. OpenAI-compatible provisioning uses the OpenAI error envelope. **200** success payloads keep their existing top-level shapes. -On the OpenAI-compatible routes (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions`, `/v1/moderations`, and every path below them) every error body uses the OpenAI envelope **`{"error":{"message","type","param","code"}}`**. The handlers build it themselves; refusals made outside them, such as the auth middleware's `401` and `500 GATEWAY_AUTH_MISCONFIGURED`, are re-rendered by the outer middleware `http_error::openai_error_envelope`, the twin of `anthropic_error_envelope` on `/v1/messages`. It turns a 4xx or 5xx JSON `detail` body into the OpenAI envelope: `message` is `detail.message` (or the `detail` string), `code` is `detail.code` verbatim (a string `detail` gets its status's SIE code: `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMIT`, `INVALID_REQUEST` or `INTERNAL_SERVER_ERROR`), `type` follows the status (`authentication_error` for 401, `permission_error` for 403, `rate_limit_error` for 429, `invalid_request_error` for other 4xx, `server_error` for 5xx), `param` is `detail.param` when it is a string and otherwise `null`, and every other `detail` field stays in `error`. The status, the headers (`WWW-Authenticate`, `Retry-After`, `X-SIE-Error-Code`, `X-SIE-RateLimit-*`) and the response extensions are kept. Bodies already in the OpenAI envelope, other bodies such as a validation list, answers without a body such as an unrouted `405`, non-JSON, encoded or chunked bodies, bodies of unknown length or over 1 MiB, and successes pass through; a body that fails while it is read still fails. The SIE-native routes keep `detail`. A composition that adds admission layers around the gateway's routes applies both envelope layers outermost so its refusals take the same shapes; the two never apply to the same path, and applying one twice changes nothing. +On the OpenAI-compatible routes (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions`, `/v1/audio/speech`, `/v1/moderations`, and every path below them) every error body uses the OpenAI envelope **`{"error":{"message","type","param","code"}}`**. The handlers build it themselves; refusals made outside them, such as the auth middleware's `401` and `500 GATEWAY_AUTH_MISCONFIGURED`, are re-rendered by the outer middleware `http_error::openai_error_envelope`, the twin of `anthropic_error_envelope` on `/v1/messages`. It turns a 4xx or 5xx JSON `detail` body into the OpenAI envelope: `message` is `detail.message` (or the `detail` string), `code` is `detail.code` verbatim (a string `detail` gets its status's SIE code: `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `RATE_LIMIT`, `INVALID_REQUEST` or `INTERNAL_SERVER_ERROR`), `type` follows the status (`authentication_error` for 401, `permission_error` for 403, `rate_limit_error` for 429, `invalid_request_error` for other 4xx, `server_error` for 5xx), `param` is `detail.param` when it is a string and otherwise `null`, and every other `detail` field stays in `error`. The status, the headers (`WWW-Authenticate`, `Retry-After`, `X-SIE-Error-Code`, `X-SIE-RateLimit-*`) and the response extensions are kept. Bodies already in the OpenAI envelope, other bodies such as a validation list, answers without a body such as an unrouted `405`, non-JSON, encoded or chunked bodies, bodies of unknown length or over 1 MiB, and successes pass through; a body that fails while it is read still fails. The SIE-native routes keep `detail`. A composition that adds admission layers around the gateway's routes applies both envelope layers outermost so its refusals take the same shapes; the two never apply to the same path, and applying one twice changes nothing. ## 3. Configuration Write Path @@ -1119,7 +1119,7 @@ lane. It is `false` by default and is a non-publishing hint. budget, so the SDKs still retry after it. - On the OpenAI-compatible routes (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, - `/v1/audio/transcriptions`, `/v1/messages`) and the rerank routes (`/v1/rerank`, + `/v1/audio/transcriptions`, `/v1/audio/speech`, `/v1/messages`) and the rerank routes (`/v1/rerank`, `/v2/rerank`) the ceiling is 60 seconds. The OpenAI Python client honors `Retry-After` only when it is greater than 0 and at most 60 seconds. Above that it ignores the header and retries on its own diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json index 6679dca65..970a5daab 100644 --- a/packages/sie_gateway/openapi.json +++ b/packages/sie_gateway/openapi.json @@ -3464,6 +3464,73 @@ ], "type": "object" }, + "OpenAISpeechAudio": { + "description": "The binary audio body of `POST /v1/audio/speech`. Documentation only.", + "format": "binary", + "type": "string" + }, + "OpenAISpeechRequest": { + "properties": { + "input": { + "description": "The text to speak. The model bounds its length.", + "minLength": 1, + "type": "string" + }, + "model": { + "description": "A text-to-speech model, such as `hexgrad/Kokoro-82M`.", + "type": "string" + }, + "response_format": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/OpenAISpeechResponseFormat", + "description": "Defaults to `wav`." + } + ] + }, + "speed": { + "description": "Defaults to 1.0.", + "format": "double", + "maximum": 2, + "minimum": 0.5, + "type": [ + "number", + "null" + ] + }, + "stream_format": { + "description": "Only `audio`: the whole audio in one response body.", + "pattern": "^audio$", + "type": [ + "string", + "null" + ] + }, + "voice": { + "description": "A voice id of the model, such as `af_heart`; the model's default when omitted.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "model", + "input" + ], + "type": "object" + }, + "OpenAISpeechResponseFormat": { + "description": "Audio formats of `POST /v1/audio/speech`: a WAV file, or raw 24 kHz\n16-bit little-endian mono samples.", + "enum": [ + "wav", + "pcm" + ], + "type": "string" + }, "OpenAITranscriptionRequest": { "properties": { "file": { @@ -5156,6 +5223,313 @@ ] } }, + "/v1/audio/speech": { + "post": { + "description": "OpenAI-compatible text-to-speech backed by SIE native extract. Sends `input` as one extract item to a text-to-speech model such as hexgrad/Kokoro-82M, with `voice` (a voice id of the model) and `speed` (0.5 to 2.0) as runtime options, and returns the audio as the binary body: a WAV file for response_format=wav (the default) or raw 24 kHz 16-bit little-endian mono samples for pcm. Other formats, `instructions` and streaming are rejected explicitly. The request body is bounded at 64 KiB; the model bounds the input length.", + "operationId": "proxy_openai_speech", + "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": "Client SDK version for skew warnings", + "in": "header", + "name": "X-SIE-SDK-Version", + "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", + "name": "X-SIE-Remote", + "required": false, + "schema": { + "enum": [ + "forbid" + ], + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAISpeechRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "audio/pcm": { + "schema": { + "$ref": "#/components/schemas/OpenAISpeechAudio" + } + }, + "audio/wav": { + "schema": { + "$ref": "#/components/schemas/OpenAISpeechAudio" + } + } + }, + "description": "The speech audio", + "headers": { + "X-Inference-Time": { + "description": "Worker-reported inference time in milliseconds", + "schema": { + "type": "string" + } + }, + "X-Payload-Fetch-Time": { + "description": "Worker-reported offloaded payload fetch time in milliseconds, when available", + "schema": { + "type": "string" + } + }, + "X-Postprocessing-Time": { + "description": "Worker-reported postprocessing time in milliseconds, when available", + "schema": { + "type": "string" + } + }, + "X-Queue-Publish-Time": { + "description": "Milliseconds spent publishing work to the queue", + "schema": { + "type": "string" + } + }, + "X-Queue-Time": { + "description": "Worker-reported queue time in milliseconds", + "schema": { + "type": "string" + } + }, + "X-Queue-Wait-Time": { + "description": "Milliseconds spent waiting for worker results", + "schema": { + "type": "string" + } + }, + "X-SIE-Execution-Binding-SHA256": { + "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available on buffered responses. SSE carries optional execution evidence in the successful terminal event instead of headers.", + "schema": { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + } + }, + "X-SIE-Execution-Identity-SHA256": { + "description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available on buffered responses. SSE carries optional execution evidence in the successful terminal event instead of headers.", + "schema": { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + } + }, + "X-SIE-Model-Revision": { + "description": "Executed bundle/config SHA-256, distinct from the catalog weights revision (for example, a 40-hex Hugging Face commit). Buffered responses only: present when the routing snapshot has a model revision and all successful worker results report its expected config hash. Omitted when evidence is unavailable or mismatched, and always omitted on SSE because headers precede terminal execution evidence.", + "schema": { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + } + }, + "X-SIE-Request-Id": { + "description": "Gateway request id for queue-backed inference", + "schema": { + "type": "string" + } + }, + "X-SIE-Server-Version": { + "description": "Gateway-compatible server version advertised by this gateway", + "schema": { + "type": "string" + } + }, + "X-SIE-Version": { + "description": "Gateway package version that handled the request", + "schema": { + "type": "string" + } + }, + "X-SIE-Worker": { + "description": "Logical queue worker tag that produced the response", + "schema": { + "type": "string" + } + }, + "X-Tokenization-Time": { + "description": "Worker-reported tokenization time in milliseconds, when available", + "schema": { + "type": "string" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Invalid or unsupported field, a voice or input the model refuses, or a model that does not return speech" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Missing or invalid bearer token" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Model not found" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Request body too large" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Malformed worker response or gateway internal error; gateway auth enabled but no tokens configured" + }, + "502": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Model load failed", + "headers": { + "X-SIE-Error-Code": { + "description": "SDK-stable gateway or worker error code", + "schema": { + "type": "string" + } + }, + "X-SIE-Error-Version": { + "description": "Gateway package version associated with the error envelope", + "schema": { + "type": "string" + } + }, + "X-SIE-Server-Version": { + "description": "Gateway-compatible server version advertised by this gateway", + "schema": { + "type": "string" + } + }, + "X-SIE-Version": { + "description": "Gateway package version that handled the request", + "schema": { + "type": "string" + } + } + } + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Provisioning, queue, loading, or capacity unavailable", + "headers": { + "Retry-After": { + "description": "Suggested retry delay in seconds, when retryable", + "schema": { + "type": "string" + } + }, + "X-SIE-Error-Code": { + "description": "SDK-stable gateway or worker error code", + "schema": { + "type": "string" + } + }, + "X-SIE-Server-Version": { + "description": "Gateway-compatible server version advertised by this gateway", + "schema": { + "type": "string" + } + }, + "X-SIE-Version": { + "description": "Gateway package version that handled the request", + "schema": { + "type": "string" + } + } + } + }, + "504": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIErrorEnvelope" + } + } + }, + "description": "Result channel closed" + } + }, + "tags": [ + "inference" + ] + } + }, "/v1/audio/transcriptions": { "post": { "description": "OpenAI-compatible audio transcription backed by SIE native extract. The multipart upload is bounded at 24 MiB. json, text, srt, verbose_json, and vtt responses are supported; stream=true and diarized_json are rejected explicitly.", diff --git a/packages/sie_gateway/src/handlers/mod.rs b/packages/sie_gateway/src/handlers/mod.rs index 1d2d89da2..711350905 100644 --- a/packages/sie_gateway/src/handlers/mod.rs +++ b/packages/sie_gateway/src/handlers/mod.rs @@ -9,6 +9,7 @@ pub mod pools; pub mod proxy; pub mod responses; pub mod serving_disclosure; +pub mod speech; pub mod sse; pub mod systemone; #[cfg(test)] diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs index 3e195b623..0331764a8 100644 --- a/packages/sie_gateway/src/handlers/proxy.rs +++ b/packages/sie_gateway/src/handlers/proxy.rs @@ -11925,6 +11925,17 @@ pub(crate) fn is_openai_compat_inner_request_header(name: &str) -> bool { /// text, never request content or raw upstream internals); unparseable /// bodies fall back to a generic message, never the raw bytes. pub(crate) async fn translate_inner_compat_error(resp: Response) -> Response { + translate_inner_compat_error_with_param(resp, |_, _, _| None).await +} + +/// [`translate_inner_compat_error`], with the OpenAI ``param`` chosen by +/// ``param_for`` from the status, the inner SIE code and the inner message. +/// A route uses it when it knows which of its request fields an inner refusal +/// is about. +pub(crate) async fn translate_inner_compat_error_with_param( + resp: Response, + param_for: impl FnOnce(StatusCode, &str, &str) -> Option<&'static str>, +) -> Response { // Deliberately NOT [`MAX_COMPAT_RESPONSE_BODY`]. This buffers an ERROR // envelope — a code and a sanitized message, kilobytes at the outside — so // 16 MiB is already orders of magnitude above any real body here and the @@ -11957,7 +11968,8 @@ pub(crate) async fn translate_inner_compat_error(resp: Response) -> Response { .and_then(|m| m.as_str()) .unwrap_or("internal server error") .to_string(); - let mut body = embeddings_error(&sie_code, None, message); + let param = param_for(status, &sie_code, &message); + let mut body = embeddings_error(&sie_code, param, message); // The inner `MODEL_NOT_FOUND` was built by this gateway for the same // caller, so its `suggestions` are already limited to ids that caller may // list. Carry them over; anything that is not a list of strings is dropped. diff --git a/packages/sie_gateway/src/handlers/speech.rs b/packages/sie_gateway/src/handlers/speech.rs new file mode 100644 index 000000000..143f68fc1 --- /dev/null +++ b/packages/sie_gateway/src/handlers/speech.rs @@ -0,0 +1,1090 @@ +//! OpenAI text-to-speech compatibility over native `extract`. +//! +//! `POST /v1/audio/speech` sends one `input` text as one extract item to a +//! text-to-speech model such as `hexgrad/Kokoro-82M`, with `voice` and `speed` +//! as the item's runtime options. The model answers with a base64 WAV in the +//! item's `data`; this handler returns it as the binary body, unchanged for +//! `response_format=wav` or as its raw 16-bit little-endian samples for +//! `response_format=pcm`. Other formats, `instructions` and streaming are +//! refused with a 400 that names what is supported. + +use std::sync::Arc; + +use axum::body::{to_bytes, Body}; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use base64::Engine as _; +use serde_json::{json, Map, Value}; + +use crate::http_error::{ + code as err_code, embeddings_error, json_openai_error, openai_code as oai_code, + openai_type as oai_type, GatewayOwnedFault, +}; +use crate::server::AppState; + +use super::proxy::{ + invalid_remote_header_response, is_openai_compat_forwarded_header, + is_openai_compat_inner_request_header, is_valid_compat_model_id, proxy_request, + translate_inner_compat_error_with_param, CompatibilityRoute, +}; +use super::serving_disclosure::{DeferredFallbackFinish, FallbackAttempt}; + +/// Ingress bound for the JSON speech request. +pub const MAX_SPEECH_REQUEST_BYTES: usize = 64 * 1024; +/// Bound for the native extract answer: four minutes of 24 kHz 16-bit audio is +/// about 11.5 MB of WAV, about 15.4 MB once base64-encoded. +const MAX_NATIVE_RESPONSE_BYTES: usize = 32 * 1024 * 1024; +const MIN_SPEED: f64 = 0.5; +const MAX_SPEED: f64 = 2.0; +const SUPPORTED_FIELDS: [&str; 6] = [ + "model", + "input", + "voice", + "response_format", + "speed", + "stream_format", +]; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SpeechFormat { + Wav, + Pcm, +} + +impl SpeechFormat { + fn content_type(self) -> &'static str { + match self { + Self::Wav => "audio/wav", + Self::Pcm => "audio/pcm", + } + } +} + +#[derive(Debug)] +struct SpeechRequest { + model: String, + input: String, + voice: Option, + response_format: SpeechFormat, + speed: Option, +} + +#[derive(Debug)] +struct SpeechError { + status: StatusCode, + message: String, + param: Option, + code: &'static str, +} + +impl SpeechError { + fn invalid(param: Option<&str>, message: impl Into) -> Self { + Self { + status: StatusCode::BAD_REQUEST, + message: message.into(), + param: param.map(str::to_string), + code: oai_code::INVALID_REQUEST, + } + } + + fn unsupported(param: &str, message: impl Into) -> Self { + Self { + status: StatusCode::BAD_REQUEST, + message: message.into(), + param: Some(param.to_string()), + code: oai_code::UNSUPPORTED_FIELD, + } + } + + fn payload_too_large() -> Self { + Self { + status: StatusCode::PAYLOAD_TOO_LARGE, + message: format!("request body exceeds {MAX_SPEECH_REQUEST_BYTES} bytes"), + param: None, + code: oai_code::PAYLOAD_TOO_LARGE, + } + } + + fn into_response(self) -> Response { + ( + self.status, + Json(json_openai_error( + self.message, + oai_type::INVALID_REQUEST, + self.param.as_deref(), + self.code, + )), + ) + .into_response() + } +} + +fn parse_speech_request(body: &[u8]) -> Result { + let parsed: Value = serde_json::from_slice(body) + .map_err(|_| SpeechError::invalid(None, "request body must be a JSON object"))?; + let Value::Object(fields) = parsed else { + return Err(SpeechError::invalid( + None, + "request body must be a JSON object", + )); + }; + if fields.contains_key("instructions") { + return Err(SpeechError::unsupported( + "instructions", + "field 'instructions' is not supported; control the speech with 'voice' and 'speed'", + )); + } + // Sorted so the refused field does not depend on the map's order. + let mut names: Vec<&String> = fields.keys().collect(); + names.sort(); + if let Some(name) = names + .into_iter() + .find(|name| !SUPPORTED_FIELDS.contains(&name.as_str())) + { + return Err(SpeechError::unsupported( + name, + format!( + "unsupported field '{name}'; supported fields are model, input, voice, response_format and speed" + ), + )); + } + + let model = fields + .get("model") + .and_then(Value::as_str) + .map(str::trim) + .unwrap_or_default(); + if model.is_empty() { + return Err(SpeechError::invalid( + Some("model"), + "field 'model' is required", + )); + } + if !is_valid_compat_model_id(model) { + return Err(SpeechError::invalid( + Some("model"), + "invalid model id for path", + )); + } + + let input = match fields.get("input") { + Some(Value::String(input)) if !input.trim().is_empty() => input.clone(), + _ => { + return Err(SpeechError::invalid( + Some("input"), + "field 'input' must be a non-empty string", + )) + } + }; + + let voice = match fields.get("voice") { + None | Some(Value::Null) => None, + Some(Value::String(voice)) if !voice.trim().is_empty() => Some(voice.trim().to_string()), + Some(_) => { + return Err(SpeechError::invalid( + Some("voice"), + "field 'voice' must be a non-empty string voice id", + )) + } + }; + + let response_format = match fields.get("response_format") { + None | Some(Value::Null) => SpeechFormat::Wav, + Some(Value::String(format)) if format == "wav" => SpeechFormat::Wav, + Some(Value::String(format)) if format == "pcm" => SpeechFormat::Pcm, + Some(value) => { + let message = "response_format must be wav or pcm (24 kHz 16-bit little-endian mono)"; + return Err( + if matches!(value.as_str(), Some("mp3" | "opus" | "aac" | "flac")) { + SpeechError::unsupported("response_format", message) + } else { + SpeechError::invalid(Some("response_format"), message) + }, + ); + } + }; + + let speed = match fields.get("speed") { + None | Some(Value::Null) => None, + Some(Value::Number(number)) => { + let speed = number + .as_f64() + .filter(|speed| speed.is_finite() && (MIN_SPEED..=MAX_SPEED).contains(speed)); + if speed.is_none() { + return Err(SpeechError::invalid( + Some("speed"), + format!("speed must be a number from {MIN_SPEED:.1} to {MAX_SPEED:.1}"), + )); + } + speed + } + Some(_) => { + return Err(SpeechError::invalid( + Some("speed"), + format!("speed must be a number from {MIN_SPEED:.1} to {MAX_SPEED:.1}"), + )) + } + }; + + match fields.get("stream_format") { + None | Some(Value::Null) => {} + Some(Value::String(format)) if format == "audio" => {} + Some(_) => { + return Err(SpeechError::unsupported( + "stream_format", + "streaming speech is not supported; omit stream_format or set it to 'audio'", + )); + } + } + + Ok(SpeechRequest { + model: model.to_string(), + input, + voice, + response_format, + speed, + }) +} + +/// The option of `request` that a model's refusal `message` names, if any. +/// +/// A worker reports a refused request as a code and a message, with no field, +/// so the option is found by name: `voice` or `speed` as a whole word of the +/// message, and only when the request sent that option. The server route +/// applies the same rule. +fn refused_option(message: &str, request: &SpeechRequest) -> Option<&'static str> { + let named = |name: &str| { + message + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .any(|word| word.eq_ignore_ascii_case(name)) + }; + [ + ("voice", request.voice.is_some()), + ("speed", request.speed.is_some()), + ] + .into_iter() + .find(|(name, sent)| *sent && named(name)) + .map(|(name, _)| name) +} + +/// The `param` of an inner native refusal: the option it names, or `input` +/// for a text over the model's length limit. +fn inner_refusal_param( + status: StatusCode, + code: &str, + message: &str, + request: &SpeechRequest, +) -> Option<&'static str> { + if status != StatusCode::BAD_REQUEST { + return None; + } + match code { + "INVALID_INPUT" => refused_option(message, request), + "INPUT_TOO_LONG" => Some("input"), + _ => None, + } +} + +fn native_extract_body(request: &SpeechRequest) -> Value { + let mut options = Map::new(); + if let Some(voice) = &request.voice { + options.insert("voice".to_string(), json!(voice)); + } + if let Some(speed) = request.speed { + options.insert("speed".to_string(), json!(speed)); + } + json!({ + "items": [{"text": request.input}], + "params": {"options": options}, + }) +} + +fn copy_inner_headers(inbound: &HeaderMap) -> HeaderMap { + let mut headers = HeaderMap::new(); + for (name, value) in inbound { + if is_openai_compat_inner_request_header(name.as_str()) { + headers.append(name.clone(), value.clone()); + } + } + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + headers.insert(header::ACCEPT, HeaderValue::from_static("application/json")); + headers +} + +fn copy_native_response_headers(from: &HeaderMap, to: &mut HeaderMap) { + for (name, value) in from { + if is_openai_compat_forwarded_header(name.as_str()) { + to.insert(name.clone(), value.clone()); + } + } +} + +/// The sample bytes of a 16-bit PCM WAV file. +fn pcm16_samples(wav: &[u8]) -> Result<&[u8], &'static str> { + const INVALID: &str = "extract response audio is not a valid WAV file"; + if wav.len() < 12 || &wav[0..4] != b"RIFF" || &wav[8..12] != b"WAVE" { + return Err(INVALID); + } + let mut offset = 12usize; + let mut pcm16 = false; + while offset + 8 <= wav.len() { + let id = &wav[offset..offset + 4]; + let size = + u32::from_le_bytes(wav[offset + 4..offset + 8].try_into().expect("4 bytes")) as usize; + let start = offset + 8; + let end = start.checked_add(size).ok_or(INVALID)?; + if id == b"fmt " { + let chunk = wav.get(start..end).ok_or(INVALID)?; + if chunk.len() < 16 { + return Err(INVALID); + } + let audio_format = u16::from_le_bytes([chunk[0], chunk[1]]); + let bits_per_sample = u16::from_le_bytes([chunk[14], chunk[15]]); + if audio_format != 1 || bits_per_sample != 16 { + return Err("extract response audio is not 16-bit PCM"); + } + pcm16 = true; + } else if id == b"data" { + if !pcm16 { + return Err(INVALID); + } + return wav.get(start..end).ok_or(INVALID); + } + // Chunks are padded to an even length. + offset = end.checked_add(size % 2).ok_or(INVALID)?; + } + Err(INVALID) +} + +/// The response for one native extract result, or `Err` for a result this +/// handler cannot turn into audio. +fn format_speech_response( + item: &Map, + request: &SpeechRequest, +) -> Result { + if let Some(error) = item.get("error").and_then(Value::as_object) { + // The model refused this text, for example as longer than its limit. + let message = error + .get("message") + .and_then(Value::as_str) + .unwrap_or("the model could not synthesize this input"); + // A length refusal is about the input even when its message names an option. + let param = if error.get("code").and_then(Value::as_str) == Some("INPUT_TOO_LONG") { + "input" + } else { + refused_option(message, request).unwrap_or("input") + }; + return Err(SpeechOutcome::Refused(SpeechError::invalid( + Some(param), + message, + ))); + } + let Some(data) = item.get("data").and_then(Value::as_object) else { + return Err(SpeechOutcome::Fault( + "native_response_shape", + "native extract response is missing one speech result", + )); + }; + let Some(audio) = data.get("audio") else { + return Err(SpeechOutcome::Refused(SpeechError::invalid( + Some("model"), + format!("Model '{}' did not return speech audio", request.model), + ))); + }; + let (Some(audio), Some("wav")) = (audio.as_str(), data.get("format").and_then(Value::as_str)) + else { + return Err(SpeechOutcome::Fault( + "decode_speech_audio", + "extract response is missing WAV audio", + )); + }; + let wav = base64::engine::general_purpose::STANDARD + .decode(audio) + .map_err(|_| { + SpeechOutcome::Fault( + "decode_speech_audio", + "extract response audio is not valid base64", + ) + })?; + let samples = pcm16_samples(&wav) + .map_err(|message| SpeechOutcome::Fault("decode_speech_audio", message))?; + let body = match request.response_format { + SpeechFormat::Wav => wav.clone(), + SpeechFormat::Pcm => samples.to_vec(), + }; + Ok(( + [(header::CONTENT_TYPE, request.response_format.content_type())], + body, + ) + .into_response()) +} + +/// Marks a 400 this handler built from a worker result, already in the OpenAI +/// envelope. +#[derive(Clone, Copy, Debug)] +struct OwnRefusal; + +#[derive(Debug)] +enum SpeechOutcome { + /// The request cannot be served as speech: a 400 for the client. + Refused(SpeechError), + /// A successful result this handler could not render: a gateway-owned 500. + Fault(&'static str, &'static str), +} + +#[utoipa::path( + post, + path = "/v1/audio/speech", + tag = "inference", + description = "OpenAI-compatible text-to-speech backed by SIE native extract. Sends `input` as one extract item to a text-to-speech model such as hexgrad/Kokoro-82M, with `voice` (a voice id of the model) and `speed` (0.5 to 2.0) as runtime options, and returns the audio as the binary body: a WAV file for response_format=wav (the default) or raw 24 kHz 16-bit little-endian mono samples for pcm. Other formats, `instructions` and streaming are rejected explicitly. The request body is bounded at 64 KiB; the model bounds the input length.", + request_body(content = crate::openapi::OpenAISpeechRequest, content_type = "application/json"), + params( + ("X-SIE-MACHINE-PROFILE" = Option, Header, description = "Preferred GPU or machine profile"), + ("X-SIE-Pool" = Option, Header, description = "Explicit pool routing override"), + ("X-SIE-SDK-Version" = Option, Header, description = "Client SDK version for skew warnings") + ), + responses( + (status = 200, description = "The speech audio", content( + (crate::openapi::OpenAISpeechAudio = "audio/wav"), + (crate::openapi::OpenAISpeechAudio = "audio/pcm") + )), + (status = 400, description = "Invalid or unsupported field, a voice or input the model refuses, or a model that does not return speech", body = crate::openapi::OpenAIErrorEnvelope), + (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::OpenAIErrorEnvelope), + (status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope), + (status = 413, description = "Request body too large", body = crate::openapi::OpenAIErrorEnvelope), + (status = 500, description = "Malformed worker response or gateway internal error", body = crate::openapi::OpenAIErrorEnvelope), + (status = 502, description = "Model load failed", body = crate::openapi::OpenAIErrorEnvelope), + (status = 503, description = "Provisioning, queue, loading, or capacity unavailable", body = crate::openapi::OpenAIErrorEnvelope), + (status = 504, description = "Result channel closed", body = crate::openapi::OpenAIErrorEnvelope) + ) +)] +pub async fn proxy_openai_speech(State(state): State>, req: Request) -> Response { + if let Some(response) = invalid_remote_header_response("generate", req.headers()) { + return response; + } + if req + .headers() + .get(header::CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .is_some_and(|value| value > MAX_SPEECH_REQUEST_BYTES) + { + return SpeechError::payload_too_large().into_response(); + } + + let (parts, body) = req.into_parts(); + let body = match to_bytes(body, MAX_SPEECH_REQUEST_BYTES).await { + Ok(body) => body, + Err(_) => return SpeechError::payload_too_large().into_response(), + }; + let request = match parse_speech_request(&body) { + Ok(request) => request, + Err(error) => return error.into_response(), + }; + + let body = match serde_json::to_vec(&native_extract_body(&request)) { + Ok(body) => body, + Err(_) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(embeddings_error( + err_code::INTERNAL_ERROR, + None, + "failed to serialize native extract request", + )), + ) + .into_response(); + } + }; + let uri = match format!("/v1/extract/{}", request.model).parse::() { + Ok(uri) => uri, + Err(_) => { + return SpeechError::invalid(Some("model"), "invalid model id for path").into_response() + } + }; + let mut builder = Request::builder() + .method(Method::POST) + .uri(uri) + .version(parts.version); + for (name, value) in copy_inner_headers(&parts.headers).iter() { + builder = builder.header(name, value); + } + let mut inner_request = match builder.body(Body::from(body)) { + Ok(request) => request, + Err(_) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(embeddings_error( + err_code::INTERNAL_ERROR, + None, + "failed to build native extract request", + )), + ) + .into_response(); + } + }; + *inner_request.extensions_mut() = parts.extensions; + + let fallback = FallbackAttempt::install(&mut inner_request); + inner_request + .extensions_mut() + .insert(DeferredFallbackFinish); + inner_request.extensions_mut().insert(CompatibilityRoute); + let native_response = proxy_request(State(state), inner_request, "extract").await; + let native_headers = native_response.headers().clone(); + let mut response = async { + if native_response.status() != StatusCode::OK { + return native_response; + } + // From here the worker has already run. A result this handler cannot + // render is marked as gateway-owned (see [`GatewayOwnedFault`]). + let bytes = match to_bytes(native_response.into_body(), MAX_NATIVE_RESPONSE_BYTES).await { + Ok(bytes) => bytes, + Err(_) => { + return speech_fault( + "read_native_response", + "failed to read native extract response", + ); + } + }; + let parsed: Value = match serde_json::from_slice(&bytes) { + Ok(value) => value, + Err(_) => { + return speech_fault( + "decode_native_response", + "native extract response is not valid JSON", + ); + } + }; + let item = parsed + .get("items") + .and_then(Value::as_array) + .filter(|items| items.len() == 1) + .and_then(|items| items[0].as_object()); + let Some(item) = item else { + return speech_fault( + "native_response_shape", + "native extract response is missing one speech result", + ); + }; + match format_speech_response(item, &request) { + Ok(response) => response, + Err(SpeechOutcome::Refused(error)) => { + let mut response = error.into_response(); + response.extensions_mut().insert(OwnRefusal); + response + } + Err(SpeechOutcome::Fault(stage, message)) => speech_fault(stage, message), + } + } + .await; + copy_native_response_headers(&native_headers, response.headers_mut()); + let response = fallback.finish(response); + // This handler's own refusals are already in the OpenAI envelope with their + // `param`; only inner native errors need translating. + if response.extensions().get::().is_none() + && (response.status().is_client_error() || response.status().is_server_error()) + { + translate_inner_compat_error_with_param(response, |status, code, message| { + inner_refusal_param(status, code, message, &request) + }) + .await + } else { + response + } +} + +/// A 500 for a successful worker result this handler could not render, marked +/// as gateway-owned so a metered composition does not charge for it. +fn speech_fault(stage: &'static str, message: &str) -> Response { + GatewayOwnedFault::new(stage).mark( + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(embeddings_error(err_code::INTERNAL_ERROR, None, message)), + ) + .into_response(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::handlers::test_support::{TestGateway, LOCAL_LANE}; + + /// A local text-to-speech model on the native extract primitive. + const SPEECH_MODEL: &str = "\ +sie_id: acme/speech +hf_id: acme/speech +inputs: + text: true +tasks: + extract: {} +profiles: + default: + adapter_path: sie_server.adapters.kokoro.adapter:KokoroAdapter + max_batch_tokens: 6000 +"; + + /// A mono 24 kHz 16-bit WAV with the given sample bytes and `bits` per sample. + fn wav(samples: &[u8], bits: u16) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(b"RIFF"); + out.extend_from_slice(&(36 + samples.len() as u32).to_le_bytes()); + out.extend_from_slice(b"WAVE"); + out.extend_from_slice(b"fmt "); + out.extend_from_slice(&16u32.to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&24_000u32.to_le_bytes()); + out.extend_from_slice(&(24_000u32 * u32::from(bits / 8)).to_le_bytes()); + out.extend_from_slice(&(bits / 8).to_le_bytes()); + out.extend_from_slice(&bits.to_le_bytes()); + out.extend_from_slice(b"data"); + out.extend_from_slice(&(samples.len() as u32).to_le_bytes()); + out.extend_from_slice(samples); + out + } + + fn samples() -> Vec { + (0..=255u8).cycle().take(4096).collect() + } + + fn speech_data(audio: &[u8]) -> Value { + json!({ + "audio": base64::engine::general_purpose::STANDARD.encode(audio), + "format": "wav", + "sample_rate": 24000, + "duration_ms": 85, + "voice": "af_heart", + }) + } + + fn parse(body: Value) -> Result { + parse_speech_request(&serde_json::to_vec(&body).unwrap()) + } + + async fn post(gateway: &TestGateway, body: Value) -> Response { + let request = Request::builder() + .method(Method::POST) + .uri("/v1/audio/speech") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(serde_json::to_vec(&body).unwrap())) + .unwrap(); + proxy_openai_speech(State(Arc::clone(&gateway.state)), request).await + } + + async fn served_gateway(data: Value) -> TestGateway { + let gateway = TestGateway::new(&[SPEECH_MODEL]).await; + gateway + .add_verified_worker("local-1", LOCAL_LANE, &["acme/speech"]) + .await; + gateway.dispatcher.return_extract_data(data); + gateway + } + + #[test] + fn parser_maps_openai_fields_onto_one_extract_item() { + let request = parse(json!({ + "model": "hexgrad/Kokoro-82M", + "input": "Hello there.", + "voice": "bf_emma", + "response_format": "pcm", + "speed": 1.25, + "stream_format": "audio", + })) + .unwrap(); + assert_eq!(request.response_format, SpeechFormat::Pcm); + assert_eq!( + native_extract_body(&request), + json!({ + "items": [{"text": "Hello there."}], + "params": {"options": {"voice": "bf_emma", "speed": 1.25}}, + }) + ); + + let defaults = parse(json!({"model": "hexgrad/Kokoro-82M", "input": "Hi."})).unwrap(); + assert_eq!(defaults.response_format, SpeechFormat::Wav); + assert_eq!( + native_extract_body(&defaults), + json!({"items": [{"text": "Hi."}], "params": {"options": {}}}) + ); + } + + #[test] + fn parser_refuses_unsupported_and_invalid_fields() { + for (fields, param, code) in [ + ( + json!({"response_format": "mp3"}), + "response_format", + oai_code::UNSUPPORTED_FIELD, + ), + ( + json!({"response_format": "opus"}), + "response_format", + oai_code::UNSUPPORTED_FIELD, + ), + ( + json!({"response_format": "aac"}), + "response_format", + oai_code::UNSUPPORTED_FIELD, + ), + ( + json!({"response_format": "flac"}), + "response_format", + oai_code::UNSUPPORTED_FIELD, + ), + ( + json!({"response_format": "ogg"}), + "response_format", + oai_code::INVALID_REQUEST, + ), + ( + json!({"instructions": "Calm."}), + "instructions", + oai_code::UNSUPPORTED_FIELD, + ), + ( + json!({"stream_format": "sse"}), + "stream_format", + oai_code::UNSUPPORTED_FIELD, + ), + ( + json!({"stream": true}), + "stream", + oai_code::UNSUPPORTED_FIELD, + ), + (json!({"speed": 0.25}), "speed", oai_code::INVALID_REQUEST), + (json!({"speed": 4.0}), "speed", oai_code::INVALID_REQUEST), + (json!({"speed": true}), "speed", oai_code::INVALID_REQUEST), + (json!({"speed": "1.0"}), "speed", oai_code::INVALID_REQUEST), + (json!({"voice": ""}), "voice", oai_code::INVALID_REQUEST), + (json!({"voice": 3}), "voice", oai_code::INVALID_REQUEST), + (json!({"input": ""}), "input", oai_code::INVALID_REQUEST), + (json!({"input": " "}), "input", oai_code::INVALID_REQUEST), + (json!({"input": ["a"]}), "input", oai_code::INVALID_REQUEST), + (json!({"model": ""}), "model", oai_code::INVALID_REQUEST), + ( + json!({"model": "/leading"}), + "model", + oai_code::INVALID_REQUEST, + ), + ( + json!({"model": "two..dots"}), + "model", + oai_code::INVALID_REQUEST, + ), + ( + json!({"model": "back\\slash"}), + "model", + oai_code::INVALID_REQUEST, + ), + ( + json!({"model": "query?x=1"}), + "model", + oai_code::INVALID_REQUEST, + ), + ( + json!({"model": "unicode-model-模型"}), + "model", + oai_code::INVALID_REQUEST, + ), + ] { + let mut body = json!({"model": "hexgrad/Kokoro-82M", "input": "Hello."}); + for (key, value) in fields.as_object().unwrap() { + body[key] = value.clone(); + } + let error = parse(body).unwrap_err(); + assert_eq!(error.status, StatusCode::BAD_REQUEST, "{fields}"); + assert_eq!(error.param.as_deref(), Some(param), "{fields}"); + assert_eq!(error.code, code, "{fields}"); + } + let mp3 = parse(json!({"model": "m", "input": "x", "response_format": "mp3"})).unwrap_err(); + assert!(mp3.message.contains("wav") && mp3.message.contains("pcm")); + for body in [&b"not json"[..], b"[1]", b"\"text\""] { + let error = parse_speech_request(body).unwrap_err(); + assert_eq!(error.code, oai_code::INVALID_REQUEST); + assert_eq!(error.param, None); + } + } + + #[test] + fn pcm_is_the_data_chunk_of_a_16_bit_wav() { + let samples = samples(); + assert_eq!( + pcm16_samples(&wav(&samples, 16)).unwrap(), + samples.as_slice() + ); + assert_eq!( + pcm16_samples(&wav(&samples, 8)), + Err("extract response audio is not 16-bit PCM") + ); + for invalid in [&b"RIFF-not-a-wav"[..], b"", &wav(&samples, 16)[..60]] { + assert!(pcm16_samples(invalid).is_err()); + } + // An odd-sized chunk before `fmt ` is skipped with its pad byte. + let mut padded = wav(&samples, 16); + let extra = [b'L', b'I', b'S', b'T', 3, 0, 0, 0, 1, 2, 3, 0]; + padded.splice(12..12, extra); + assert_eq!(pcm16_samples(&padded).unwrap(), samples.as_slice()); + } + + #[tokio::test] + async fn returns_wav_and_pcm_bodies_from_native_extract_audio() { + let samples = samples(); + let audio = wav(&samples, 16); + for (format, content_type, expected) in [ + (None, "audio/wav", audio.clone()), + (Some("wav"), "audio/wav", audio.clone()), + (Some("pcm"), "audio/pcm", samples.clone()), + ] { + let gateway = served_gateway(speech_data(&audio)).await; + let mut body = json!({"model": "acme/speech", "input": "Hello.", "voice": "af_heart"}); + if let Some(format) = format { + body["response_format"] = json!(format); + } + let response = post(&gateway, body).await; + assert_eq!(response.status(), StatusCode::OK, "{format:?}"); + assert_eq!(response.headers()[header::CONTENT_TYPE], content_type); + assert_eq!(response.headers()["x-sie-served-by"], "local"); + let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap(); + assert_eq!(bytes.as_ref(), expected.as_slice(), "{format:?}"); + let work = gateway.dispatcher.dispatched(); + assert_eq!(work.len(), 1); + assert_eq!(work[0].endpoint, "extract"); + } + } + + #[tokio::test] + async fn a_model_without_speech_audio_is_a_400_on_model() { + let gateway = served_gateway(json!({"text": "not audio"})).await; + let response = post(&gateway, json!({"model": "acme/speech", "input": "Hello."})).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(response.extensions().get::().is_none()); + let body = to_bytes(response.into_body(), 8192).await.unwrap(); + let body: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["error"]["param"], "model"); + assert_eq!(body["error"]["type"], "invalid_request_error"); + } + + #[tokio::test] + async fn malformed_native_audio_is_a_gateway_owned_500() { + let samples = samples(); + for data in [ + json!({"audio": "not base64!", "format": "wav"}), + json!({"audio": base64::engine::general_purpose::STANDARD.encode(wav(&samples, 16)), "format": "mp3"}), + speech_data(b"RIFF-not-a-wav"), + speech_data(&wav(&samples, 8)), + ] { + let gateway = served_gateway(data).await; + let response = post(&gateway, json!({"model": "acme/speech", "input": "Hello."})).await; + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert!(response.extensions().get::().is_some()); + let body = to_bytes(response.into_body(), 8192).await.unwrap(); + let body: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["error"]["type"], "server_error"); + } + } + + #[test] + fn an_item_refusal_is_a_400_on_input() { + // The length refusal names the speed it was measured at; it is still + // about the input, whichever options the request sent. + let item = json!({ + "data": {}, + "error": {"code": "INPUT_TOO_LONG", "message": "text has 3001 characters; the limit at speed 1 is 3000"}, + }); + for body in [ + json!({"model": "m", "input": "x"}), + json!({"model": "m", "input": "x", "speed": 1.0}), + json!({"model": "m", "input": "x", "voice": "af_heart", "speed": 1.0}), + ] { + let request = parse(body.clone()).unwrap(); + let Err(SpeechOutcome::Refused(error)) = + format_speech_response(item.as_object().unwrap(), &request) + else { + panic!("an item error must be refused"); + }; + assert_eq!(error.status, StatusCode::BAD_REQUEST); + assert_eq!(error.param.as_deref(), Some("input"), "{body}"); + assert!(error.message.contains("3000")); + } + } + + #[test] + fn a_british_voice_leaves_the_language_to_the_model() { + let request = parse(json!({"model": "m", "input": "Hi.", "voice": "bf_emma"})).unwrap(); + assert_eq!( + native_extract_body(&request), + json!({"items": [{"text": "Hi."}], "params": {"options": {"voice": "bf_emma"}}}) + ); + } + + #[test] + fn a_refusal_names_the_option_it_is_about_only_when_sent() { + let both = + parse(json!({"model": "m", "input": "x", "voice": "alloy", "speed": 1.5})).unwrap(); + let none = parse(json!({"model": "m", "input": "x"})).unwrap(); + for (message, request, param) in [ + ( + "unknown Kokoro voice 'alloy'; available voices: af_heart", + &both, + Some("voice"), + ), + ( + "speed must be a number from 0.8 to 1.2", + &both, + Some("speed"), + ), + ("Speed must be a number", &both, Some("speed")), + ("unknown Kokoro voice 'alloy'", &none, None), + ("speed must be a number", &none, None), + ("available voices: af_heart; speedy", &both, None), + ("Kokoro text-to-speech does not accept labels", &both, None), + ] { + assert_eq!(refused_option(message, request), param, "{message}"); + } + } + + #[test] + fn an_item_refusal_of_an_option_names_it() { + let request = parse(json!({"model": "m", "input": "x", "voice": "alloy"})).unwrap(); + let item = json!({ + "data": {}, + "error": {"code": "INVALID_INPUT", "message": "unknown Kokoro voice 'alloy'"}, + }); + let Err(SpeechOutcome::Refused(error)) = + format_speech_response(item.as_object().unwrap(), &request) + else { + panic!("an item error must be refused"); + }; + assert_eq!(error.param.as_deref(), Some("voice")); + } + + #[tokio::test] + async fn worker_refusals_through_the_queue_name_the_field() { + for (code, message, fields, param) in [ + ( + "INVALID_INPUT", + "unknown Kokoro voice 'alloy'; available voices: af_heart, bf_emma", + json!({"voice": "alloy"}), + Some("voice"), + ), + ( + "INVALID_INPUT", + "speed must be a number from 0.8 to 1.2", + json!({"speed": 1.5}), + Some("speed"), + ), + ( + "INPUT_TOO_LONG", + "text has 3001 characters; the limit at speed 1 is 3000", + json!({}), + Some("input"), + ), + ( + "INPUT_TOO_LONG", + "text has 3001 characters; the limit at speed 1 is 3000", + json!({"speed": 1.0}), + Some("input"), + ), + ( + "INVALID_INPUT", + "unknown Kokoro voice 'af_heart'", + json!({}), + None, + ), + ] { + let gateway = TestGateway::new(&[SPEECH_MODEL]).await; + gateway + .add_verified_worker("local-1", LOCAL_LANE, &["acme/speech"]) + .await; + gateway.dispatcher.fail_extract_items(code, message); + let mut body = json!({"model": "acme/speech", "input": "Hello."}); + body.as_object_mut() + .unwrap() + .extend(fields.as_object().unwrap().clone()); + let response = post(&gateway, body).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{message}"); + let body = to_bytes(response.into_body(), 8192).await.unwrap(); + let body: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["error"]["type"], "invalid_request_error", "{message}"); + assert_eq!(body["error"]["message"], message); + assert_eq!(body["error"]["param"].as_str(), param, "{message}"); + assert_eq!(gateway.dispatcher.dispatched().len(), 1); + } + } + + #[tokio::test] + async fn body_limits_and_remote_header_are_checked_before_dispatch() { + let gateway = TestGateway::new(&[SPEECH_MODEL]).await; + let declared = Request::builder() + .method(Method::POST) + .uri("/v1/audio/speech") + .header(header::CONTENT_TYPE, "application/json") + .header(header::CONTENT_LENGTH, MAX_SPEECH_REQUEST_BYTES + 1) + .body(Body::empty()) + .unwrap(); + let response = proxy_openai_speech(State(Arc::clone(&gateway.state)), declared).await; + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); + + let streamed = post( + &gateway, + json!({"model": "acme/speech", "input": "x".repeat(MAX_SPEECH_REQUEST_BYTES)}), + ) + .await; + assert_eq!(streamed.status(), StatusCode::PAYLOAD_TOO_LARGE); + let body = to_bytes(streamed.into_body(), 8192).await.unwrap(); + let body: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["error"]["code"], oai_code::PAYLOAD_TOO_LARGE); + + let remote = Request::builder() + .method(Method::POST) + .uri("/v1/audio/speech") + .header(header::CONTENT_TYPE, "application/json") + .header("x-sie-remote", "allow") + .body(Body::from(r#"{"model":"acme/speech","input":"x"}"#)) + .unwrap(); + let response = proxy_openai_speech(State(Arc::clone(&gateway.state)), remote).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(gateway.dispatcher.dispatched().is_empty()); + } + + #[tokio::test] + async fn speech_caps_the_provisioning_estimate() { + for (local, retry_after) in [ + (std::time::Duration::from_secs(680), "60"), + (std::time::Duration::from_secs(45), "45"), + ] { + let gateway = TestGateway::new(&[SPEECH_MODEL]).await; + gateway.dispatcher.estimate_provisioning(LOCAL_LANE, local); + let response = post(&gateway, json!({"model": "acme/speech", "input": "Hello."})).await; + assert_eq!( + response.status(), + StatusCode::SERVICE_UNAVAILABLE, + "{local:?}" + ); + assert_eq!(response.headers()["retry-after"], retry_after, "{local:?}"); + assert_eq!(response.headers()["x-sie-error-code"], "PROVISIONING"); + } + } + + #[test] + fn inner_request_is_json_with_bounded_headers() { + let mut inbound = HeaderMap::new(); + inbound.insert( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer test"), + ); + inbound.insert(header::COOKIE, HeaderValue::from_static("secret=drop")); + let inner = copy_inner_headers(&inbound); + assert_eq!(inner[header::CONTENT_TYPE], "application/json"); + assert_eq!(inner[header::ACCEPT], "application/json"); + assert_eq!(inner[header::AUTHORIZATION], "Bearer test"); + assert!(!inner.contains_key(header::COOKIE)); + } +} diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs index 235e9b663..f70dcaff4 100644 --- a/packages/sie_gateway/src/handlers/test_support.rs +++ b/packages/sie_gateway/src/handlers/test_support.rs @@ -32,7 +32,7 @@ pub(crate) const LOCAL_LANE: (&str, &str, &str) = ("default", "l4", "default"); /// The remote lane's `(pool, machine_profile, bundle)`. pub(crate) const REMOTE_LANE: (&str, &str, &str) = ("default", "cpu", "remote"); -const DEFAULT_BUNDLE: &str = "name: default\ndefault: true\nadapters:\n - sie_server.adapters.bert_flash\n - sie_server.adapters.sglang\n - sie_server.adapters.whisper.adapter\n - sie_server.adapters.gliner2.decide\n - sie_server.adapters.remote.sie\n"; +const DEFAULT_BUNDLE: &str = "name: default\ndefault: true\nadapters:\n - sie_server.adapters.bert_flash\n - sie_server.adapters.sglang\n - sie_server.adapters.whisper.adapter\n - sie_server.adapters.gliner2.decide\n - sie_server.adapters.kokoro.adapter\n - sie_server.adapters.remote.sie\n"; const REMOTE_BUNDLE: &str = "name: remote\npriority: 1\ndefault: false\nadapters:\n - sie_server.adapters.remote.sie\n"; @@ -175,6 +175,7 @@ pub(crate) struct RecordingDispatcher { generate_refused: AtomicBool, work_refused: AtomicBool, extract_data: Mutex>, + extract_failure: Mutex>, stream_error: AtomicBool, stream_mid_error: AtomicBool, stream_terminal_failure: Mutex>, @@ -342,6 +343,12 @@ impl RecordingDispatcher { *self.extract_data.lock().unwrap() = Some(data); } + /// Fail every extract item with `code` and `message`, as a worker reports + /// an input or option the model refuses. + pub(crate) fn fail_extract_items(&self, code: &'static str, message: &'static str) { + *self.extract_failure.lock().unwrap() = Some((code, message)); + } + pub(crate) fn fail_stream(&self, after_output: bool) { self.stream_error.store(true, Ordering::SeqCst); self.stream_mid_error.store(after_output, Ordering::SeqCst); @@ -401,6 +408,18 @@ fn successful_result(request_id: &str, item_index: u32, payload: serde_json::Val result } +fn failed_result(request_id: &str, item_index: u32, code: &str, message: &str) -> WorkResult { + serde_json::from_value(json!({ + "work_item_id": format!("{request_id}.{item_index}"), + "request_id": request_id, + "item_index": item_index, + "success": false, + "error": message, + "error_code": code, + })) + .unwrap() +} + fn refused_result( request_id: &str, item_index: u32, @@ -584,6 +603,13 @@ impl WorkDispatcher for RecordingDispatcher { 0, json!([{"item_id": "0", "score": 0.5, "rank": 0}]), )] + } else if let Some((code, message)) = (endpoint == "extract") + .then(|| *self.extract_failure.lock().unwrap()) + .flatten() + { + (0..items.len() as u32) + .map(|index| failed_result(&request_id, index, code, message)) + .collect() } else if endpoint == "extract" { let data = self .extract_data diff --git a/packages/sie_gateway/src/http_error.rs b/packages/sie_gateway/src/http_error.rs index d60e6d1c6..9ac15c787 100644 --- a/packages/sie_gateway/src/http_error.rs +++ b/packages/sie_gateway/src/http_error.rs @@ -289,13 +289,14 @@ pub fn embeddings_error(sie_code: &str, param: Option<&str>, message: impl Into< json_openai_error(message, err_type, param, err_code) } -const OPENAI_COMPATIBLE_PATHS: [&str; 7] = [ +const OPENAI_COMPATIBLE_PATHS: [&str; 8] = [ "/v1/chat/completions", "/v1/completions", "/v1/responses", "/v1/embeddings", "/v1/models", "/v1/audio/transcriptions", + "/v1/audio/speech", "/v1/moderations", ]; @@ -303,8 +304,8 @@ const MAX_ERROR_BODY: usize = 1024 * 1024; /// Whether a path is one of the gateway's OpenAI-compatible routes or below /// one: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, -/// `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions` and -/// `/v1/moderations`. `/v1/messages` and the SIE-native routes are not. +/// `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions`, +/// `/v1/audio/speech` and `/v1/moderations`. `/v1/messages` and the SIE-native routes are not. pub fn is_openai_path(path: &str) -> bool { OPENAI_COMPATIBLE_PATHS.iter().any(|base| { path.strip_prefix(base) @@ -625,7 +626,7 @@ mod tests { use axum::Router; use tower::ServiceExt; - const OPENAI_PATHS: [&str; 11] = [ + const OPENAI_PATHS: [&str; 12] = [ "/v1/chat/completions", "/v1/completions", "/v1/responses", @@ -634,6 +635,7 @@ mod tests { "/v1/models", "/v1/models/BAAI/bge-m3", "/v1/audio/transcriptions", + "/v1/audio/speech", "/v1/moderations", "/v1/chat/completions/chatcmpl_1", "/v1/completions/", diff --git a/packages/sie_gateway/src/middleware/metrics.rs b/packages/sie_gateway/src/middleware/metrics.rs index 24f2bc705..28ee48aa9 100644 --- a/packages/sie_gateway/src/middleware/metrics.rs +++ b/packages/sie_gateway/src/middleware/metrics.rs @@ -314,8 +314,8 @@ impl HttpBody for ObservedBody { /// otherwise `None`. Every generation surface /// intentionally collapses to `generate`: the route spelling is bounded HTTP /// metadata, while the operational work and service-level objective are shared. -/// The OpenAI audio transcription and System One decision surfaces similarly -/// collapse to their native `extract` primitive. +/// The OpenAI audio transcription and speech and the System One decision +/// surfaces similarly collapse to their native `extract` primitive. /// Non-inference /// paths are intentionally excluded — see module-level docs. /// @@ -342,7 +342,7 @@ fn classify_endpoint(path: &str) -> Option<&'static str> { Some("moderations") } else if matches!( path, - "/v1/audio/transcriptions" | "/v1/systemone" | "/v1/decisions" + "/v1/audio/transcriptions" | "/v1/audio/speech" | "/v1/systemone" | "/v1/decisions" ) { Some("extract") } else { @@ -903,6 +903,8 @@ mod tests { classify_endpoint("/v1/audio/transcriptions"), Some("extract") ); + assert_eq!(classify_endpoint("/v1/audio/speech"), Some("extract")); + assert_eq!(classify_endpoint("/v1/audio/speech/extra"), None); assert_eq!(classify_endpoint("/v1/systemone"), Some("extract")); assert_eq!(classify_endpoint("/v1/systemone/extra"), None); assert_eq!(classify_endpoint("/v1/decisions"), Some("extract")); diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs index 99684044d..b1786b607 100644 --- a/packages/sie_gateway/src/openapi.rs +++ b/packages/sie_gateway/src/openapi.rs @@ -52,6 +52,7 @@ static OPENAPI_JSON: LazyLock = LazyLock::new(|| { crate::handlers::proxy::proxy_encode, crate::handlers::proxy::proxy_openai_embeddings, crate::handlers::audio::proxy_openai_transcription, + crate::handlers::speech::proxy_openai_speech, crate::handlers::proxy::proxy_rerank, crate::handlers::proxy::proxy_rerank_v2, crate::handlers::systemone::proxy_systemone, @@ -127,6 +128,9 @@ static OPENAPI_JSON: LazyLock = LazyLock::new(|| { OpenAIEmbeddingUsage, OpenAIEmbeddingVector, OpenAIEmbeddingsListResponse, + OpenAISpeechAudio, + OpenAISpeechRequest, + OpenAISpeechResponseFormat, OpenAITranscriptionRequest, OpenAITranscriptionResponse, OpenAITranscriptionResponseFormat, @@ -1233,6 +1237,7 @@ fn inject_remote_control_header(paths: &mut serde_json::Map) { "/v1/decisions", "/v1/messages", "/v1/audio/transcriptions", + "/v1/audio/speech", ] { let Some(operation) = paths .get_mut(path) @@ -1294,6 +1299,7 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map) "/v1/extract/{model}", "/v1/generate/{model}", "/v1/audio/transcriptions", + "/v1/audio/speech", ] { let Some(responses) = paths .get_mut(path) @@ -1773,6 +1779,44 @@ pub struct OpenAITranscriptionRequest { pub timestamp_granularities: Option>, } +/// Audio formats of `POST /v1/audio/speech`: a WAV file, or raw 24 kHz +/// 16-bit little-endian mono samples. +#[derive(Debug, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum OpenAISpeechResponseFormat { + Wav, + Pcm, +} + +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct OpenAISpeechRequest { + /// A text-to-speech model, such as `hexgrad/Kokoro-82M`. + pub model: String, + /// The text to speak. The model bounds its length. + #[schema(min_length = 1)] + pub input: String, + /// A voice id of the model, such as `af_heart`; the model's default when omitted. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub voice: Option, + /// Defaults to `wav`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub response_format: Option, + /// Defaults to 1.0. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schema(minimum = 0.5, maximum = 2.0)] + pub speed: Option, + /// Only `audio`: the whole audio in one response body. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schema(pattern = "^audio$")] + pub stream_format: Option, +} + +/// The binary audio body of `POST /v1/audio/speech`. Documentation only. +#[derive(ToSchema)] +#[schema(value_type = String, format = Binary)] +#[allow(dead_code)] +pub struct OpenAISpeechAudio(Vec); + #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct OpenAITranscriptionUsage { #[serde(rename = "type")] @@ -3793,6 +3837,7 @@ mod tests { "/v1/configs/models", "/v1/configs/models/{id}/status", "/v1/audio/transcriptions", + "/v1/audio/speech", "/v1/rerank", "/v2/rerank", "/v1/embeddings", @@ -3827,6 +3872,7 @@ mod tests { ("/v1/configs/bundles/{id}", &["get"][..]), ("/v1/configs/resolve", &["post"][..]), ("/v1/audio/transcriptions", &["post"][..]), + ("/v1/audio/speech", &["post"][..]), ("/v1/embeddings", &["post"][..]), ("/v1/chat/completions", &["post"][..]), ("/v1/completions", &["post"][..]), @@ -3904,6 +3950,7 @@ mod tests { "/v1/score/{model}", "/v1/extract/{model}", "/v1/audio/transcriptions", + "/v1/audio/speech", "/v1/embeddings", ] { let parameters = spec["paths"][path]["post"]["parameters"] @@ -4052,7 +4099,7 @@ mod tests { ); } } - assert_eq!(seen, 8); + assert_eq!(seen, 9); assert_eq!(schema("/v1/models/{model}", "get", "404"), openai); for (path, method) in [ ("/v1/encode/{model}", "post"), @@ -4150,6 +4197,7 @@ mod tests { "/v1/extract/{model}", "/v1/generate/{model}", "/v1/audio/transcriptions", + "/v1/audio/speech", "/v1/embeddings", "/v1/chat/completions", "/v1/completions", diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs index e93ccf650..a99a549df 100644 --- a/packages/sie_gateway/src/server.rs +++ b/packages/sie_gateway/src/server.rs @@ -8,7 +8,8 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::config::Config; use crate::handlers::{ - audio, config_api, decisions, health, messages, models, pools, proxy, responses, systemone, + audio, config_api, decisions, health, messages, models, pools, proxy, responses, speech, + systemone, }; use crate::middleware::audit::AuditLayer; use crate::middleware::auth::AuthLayer; @@ -635,6 +636,11 @@ pub fn create_router_core( post(audio::proxy_openai_transcription) .layer(DefaultBodyLimit::max(audio::MAX_MULTIPART_BYTES)), ) + .route( + "/v1/audio/speech", + post(speech::proxy_openai_speech) + .layer(DefaultBodyLimit::max(speech::MAX_SPEECH_REQUEST_BYTES)), + ) .route("/v1/embeddings", post(proxy::proxy_openai_embeddings)) .route("/v1/rerank", post(proxy::proxy_rerank)) .route("/v2/rerank", post(proxy::proxy_rerank_v2)) diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md index e16558234..d2919cac1 100644 --- a/packages/sie_server/README.md +++ b/packages/sie_server/README.md @@ -770,9 +770,12 @@ with SIEClient("http://localhost:8080") as client: Options are `voice` (default `af_heart`; any voice file of the pinned checkpoint, such as `am_adam` or `bf_emma`), `speed` (0.5 to 2.0, default 1.0) -and `lang`: `a` or `en-us` for American English (the default), `b` or `en-gb` -for British English. Other Kokoro languages are not served. An unknown voice or -option is an `INVALID_INPUT` error; `labels` and `output_schema` are rejected. +and `lang`: `a` or `en-us` for American English, `b` or `en-gb` for British +English. Without `lang`, the voice id's first letter picks it, so `bf_emma` is +read as British English and `af_heart` as American; voices of other languages +are read as American English. Other Kokoro languages are not served. An unknown +voice or option is an `INVALID_INPUT` error; `labels` and `output_schema` are +rejected. One item may hold up to 3,000 characters at speed 1.0, fewer below it, and its audio may last up to four minutes; a longer item fails alone with @@ -780,6 +783,27 @@ audio may last up to four minutes; a longer item fails alone with number of phoneme ids the model read for the items that returned audio; a refused item counts nothing. Items are synthesized one at a time. +The OpenAI-compatible `POST /v1/audio/speech` route, on the server and the +gateway, sends one `input` text to such a model and returns the audio itself +rather than JSON, so OpenAI clients work by changing their base URL: + +```bash +curl http://localhost:8080/v1/audio/speech \ + -H "Content-Type: application/json" \ + -d '{"model": "hexgrad/Kokoro-82M", "input": "Plants turn light into sugar.", "voice": "af_heart", "response_format": "wav"}' \ + --output speech.wav +``` + +`voice` is a voice id of the model (the model's default when omitted) and +`speed` is 0.5 to 2.0. `response_format` is `wav` (the default; OpenAI's is +`mp3`) or `pcm`, the same audio as raw 16-bit little-endian mono samples at +24 kHz. Other formats, `instructions` and `stream_format: "sse"` are refused +with a `400` that names what is supported, as is a voice or text the model +refuses; its `param` is `voice` or `speed` when the model's message names that +option, and `input` for a text over the model's length limit. OpenAI voice +names such as `alloy` are not mapped; use the model's own ids. The route sets +no `lang`, so the model picks the language (for Kokoro, from the voice id). + Text becomes phonemes through misaki's English lexicon. A word outside it, such as a rare name or an invented word, is read by the `cisco-ai/mini-bart-g2p` letter-to-sound model (Apache-2.0, 16 MB), so it is spoken, though less reliably @@ -1183,7 +1207,7 @@ values that carry different tokens, while the gateway reads only the first A refused request gets `401` with `WWW-Authenticate: Bearer` and the code `UNAUTHORIZED`, on the server and the gateway alike. On the OpenAI-compatible routes (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, -`/v1/embeddings`, `/v1/audio/transcriptions`, and on the gateway also +`/v1/embeddings`, `/v1/audio/transcriptions`, `/v1/audio/speech`, and on the gateway also `/v1/models` and `/v1/moderations`) the body is the OpenAI error envelope, `{"error": {"message", "type": "authentication_error", "param": null, "code"}}`, so OpenAI clients read it; `/v1/messages` answers in the Anthropic envelope and diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json index 82a0c79fc..827343454 100644 --- a/packages/sie_server/openapi.json +++ b/packages/sie_server/openapi.json @@ -798,6 +798,132 @@ } } }, + "/v1/audio/speech": { + "post": { + "tags": [ + "openai-compat" + ], + "summary": "Create Speech", + "description": "Synthesize speech for one text through SIE's native extract path.", + "operationId": "create_speech_v1_audio_speech_post", + "parameters": [ + { + "name": "X-SIE-MACHINE-PROFILE", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Sie-Machine-Profile" + } + }, + { + "name": "X-SIE-Remote", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The only accepted value is `forbid`. It keeps the request off remote upstreams: local capacity serves or refuses it, and a model served only by an upstream answers 400. Any other value answers 400.", + "title": "X-Sie-Remote" + }, + "description": "The only accepted value is `forbid`. It keeps the request off remote upstreams: local capacity serves or refuses it, and a model served only by an upstream answers 400. Any other value answers 400." + } + ], + "responses": { + "200": { + "description": "The speech audio: a WAV file, or raw 16-bit little-endian PCM samples", + "content": { + "audio/wav": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "audio/pcm": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "model", + "input" + ], + "properties": { + "model": { + "type": "string", + "description": "A text-to-speech model, such as hexgrad/Kokoro-82M" + }, + "input": { + "type": "string", + "minLength": 1, + "description": "The text to speak" + }, + "voice": { + "type": "string", + "description": "A voice id of the model, such as af_heart; the model's default when omitted" + }, + "response_format": { + "type": "string", + "enum": [ + "wav", + "pcm" + ], + "default": "wav" + }, + "speed": { + "type": "number", + "minimum": 0.5, + "maximum": 2.0, + "default": 1.0 + }, + "stream_format": { + "type": "string", + "enum": [ + "audio" + ], + "default": "audio" + } + }, + "additionalProperties": false + } + } + } + } + } + }, "/v1/embeddings": { "post": { "tags": [ diff --git a/packages/sie_server/src/sie_server/adapters/kokoro/adapter.py b/packages/sie_server/src/sie_server/adapters/kokoro/adapter.py index ff51e2aa2..626c5353e 100644 --- a/packages/sie_server/src/sie_server/adapters/kokoro/adapter.py +++ b/packages/sie_server/src/sie_server/adapters/kokoro/adapter.py @@ -21,9 +21,11 @@ item, therefore run one after another. Runtime options are ``voice`` (default ``af_heart``), ``speed`` (0.5 to 2.0, -default 1.0) and ``lang``: ``a`` (American English, the default) or ``b`` -(British English), also spelled ``en-us`` and ``en-gb``. Other Kokoro languages -need G2P packages that the bundle does not ship. +default 1.0) and ``lang``: ``a`` (American English) or ``b`` (British English), +also spelled ``en-us`` and ``en-gb``. Without ``lang``, the first letter of the +voice id picks it (``bf_emma`` is British, ``af_heart`` American), and voices of +other languages are read as American English. Other Kokoro languages need G2P +packages that the bundle does not ship. An item longer than ``max_chars_per_item`` characters (scaled down for speeds below 1.0), or whose audio would exceed ``max_audio_ms``, fails on its own with @@ -376,7 +378,8 @@ def _parse_options(options: dict[str, Any] | None, voices: dict[str, Path]) -> t ): raise InvalidInputError(f"speed must be a number from {MIN_SPEED} to {MAX_SPEED}") - raw_lang = options.get("lang", DEFAULT_LANG) + # Kokoro voice ids start with their language code: "bf_emma" is British. + raw_lang = options.get("lang", voice[0] if voice[0] in _LANGS else DEFAULT_LANG) lang = _LANGS.get(raw_lang.strip().lower()) if isinstance(raw_lang, str) else None if lang is None: raise InvalidInputError(f"lang must be one of {', '.join(sorted(_LANGS))}; got {raw_lang!r}") diff --git a/packages/sie_server/src/sie_server/api/openai_errors.py b/packages/sie_server/src/sie_server/api/openai_errors.py index c4c2a8960..2c33756af 100644 --- a/packages/sie_server/src/sie_server/api/openai_errors.py +++ b/packages/sie_server/src/sie_server/api/openai_errors.py @@ -4,8 +4,8 @@ such as token authentication's, use the SIE ``{"detail": ...}`` envelope, which OpenAI clients cannot read. :class:`OpenAIErrorEnvelopeMiddleware` re-renders those on ``/v1/chat/completions``, ``/v1/completions``, ``/v1/responses``, -``/v1/embeddings`` and ``/v1/audio/transcriptions`` with the rule the gateway's -``openai_error_envelope`` applies. +``/v1/embeddings``, ``/v1/audio/transcriptions`` and ``/v1/audio/speech`` with +the rule the gateway's ``openai_error_envelope`` applies. """ from __future__ import annotations @@ -22,6 +22,7 @@ "/v1/responses", "/v1/embeddings", "/v1/audio/transcriptions", + "/v1/audio/speech", ) _MAX_ERROR_BODY_BYTES = 1024 * 1024 _MAX_LENGTH_DIGITS = len(str(_MAX_ERROR_BODY_BYTES)) diff --git a/packages/sie_server/src/sie_server/api/openai_speech.py b/packages/sie_server/src/sie_server/api/openai_speech.py new file mode 100644 index 000000000..bd73c4447 --- /dev/null +++ b/packages/sie_server/src/sie_server/api/openai_speech.py @@ -0,0 +1,382 @@ +"""OpenAI-compatible text-to-speech backed by native ``extract``. + +``POST /v1/audio/speech`` turns one ``input`` text into one extract item for a +text-to-speech model such as ``hexgrad/Kokoro-82M``. ``voice`` and ``speed`` +become the item's runtime options, and the WAV the model returns is sent back +as the binary response body: unchanged for ``response_format=wav``, or as its +raw 16-bit little-endian samples for ``response_format=pcm``. Other formats, +``instructions`` and streaming are refused with a 400 that names what is +supported. +""" + +from __future__ import annotations + +import base64 +import binascii +import io +import logging +import math +import re +import wave +from dataclasses import dataclass +from typing import Annotated, Any, cast + +import orjson +from fastapi import APIRouter, Depends, Header, HTTPException, Request, status +from fastapi.responses import JSONResponse, Response +from sie_sdk.queue_types import denormalize_model_id + +from sie_server.adapters.errors import InputTooLongError +from sie_server.api.extract import _extract_via_worker +from sie_server.api.helpers import ( + InferenceErrorHandler, + ModelStateChecker, + ResponseBuilder, + check_sdk_version, + oom_retry_after_from_registry, +) +from sie_server.api.openai_audio import _http_error_response, _openai_error +from sie_server.api.options import resolve_runtime_options +from sie_server.api.routing import error_code, fallback_refusal, remote_routing, route_request +from sie_server.api.validation import validate_machine_profile_header +from sie_server.core.inference_output import ExtractOutput +from sie_server.core.worker import QueueFullError +from sie_server.core.worker.handlers.extract import ExtractHandler +from sie_server.observability.tracing import tracer +from sie_server.observability.worker_telemetry import worker_telemetry, worker_telemetry_enabled +from sie_server.types.inputs import Item +from sie_server.types.responses import ErrorCode + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/v1", tags=["openai-compat"], dependencies=[Depends(remote_routing)]) + +MAX_SPEECH_REQUEST_BYTES = 64 * 1024 +MIN_SPEED = 0.5 +MAX_SPEED = 2.0 +_PCM16_SAMPLE_BYTES = 2 +_MODEL_ID_PATTERN = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._/-]*$") +_RESPONSE_FORMATS = {"wav": "audio/wav", "pcm": "audio/pcm"} +_OPENAI_ONLY_FORMATS = frozenset({"mp3", "opus", "aac", "flac"}) +_ALLOWED_FIELDS = frozenset({"model", "input", "voice", "response_format", "speed", "stream_format"}) +# Runtime options a model may refuse, in the order a refusal is matched to them. +_REFUSABLE_OPTIONS = ("voice", "speed") +_WORD = re.compile(r"[A-Za-z0-9_]+") +_SPEECH_OPENAPI: dict[str, Any] = { + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["model", "input"], + "properties": { + "model": { + "type": "string", + "description": "A text-to-speech model, such as hexgrad/Kokoro-82M", + }, + "input": {"type": "string", "minLength": 1, "description": "The text to speak"}, + "voice": { + "type": "string", + "description": "A voice id of the model, such as af_heart; the model's default when omitted", + }, + "response_format": {"type": "string", "enum": ["wav", "pcm"], "default": "wav"}, + "speed": {"type": "number", "minimum": MIN_SPEED, "maximum": MAX_SPEED, "default": 1.0}, + "stream_format": {"type": "string", "enum": ["audio"], "default": "audio"}, + }, + "additionalProperties": False, + } + } + }, + }, + "responses": { + "200": { + "description": "The speech audio: a WAV file, or raw 16-bit little-endian PCM samples", + "content": { + "audio/wav": {"schema": {"type": "string", "format": "binary"}}, + "audio/pcm": {"schema": {"type": "string", "format": "binary"}}, + }, + } + }, +} + + +@dataclass(slots=True) +class _SpeechRequest: + model: str + input: str + voice: str | None + response_format: str + speed: float | None + + +class _SpeechRequestError(Exception): + def __init__( + self, + message: str, + *, + param: str | None = None, + code: str = "invalid_request", + status_code: int = status.HTTP_400_BAD_REQUEST, + ) -> None: + super().__init__(message) + self.message = message + self.param = param + self.code = code + self.status_code = status_code + + +def _request_error_response(error: _SpeechRequestError) -> JSONResponse: + return _openai_error(error.message, status_code=error.status_code, param=error.param, code=error.code) + + +def _too_large() -> _SpeechRequestError: + return _SpeechRequestError( + f"request body exceeds {MAX_SPEECH_REQUEST_BYTES} bytes", + code="payload_too_large", + status_code=status.HTTP_413_CONTENT_TOO_LARGE, + ) + + +async def _read_body(request: Request) -> bytes: + content_length = request.headers.get("content-length") + if content_length is not None and content_length.isdigit() and int(content_length) > MAX_SPEECH_REQUEST_BYTES: + raise _too_large() + body = bytearray() + async for chunk in request.stream(): + body.extend(chunk) + if len(body) > MAX_SPEECH_REQUEST_BYTES: + raise _too_large() + return bytes(body) + + +def _parse_speech_request(body: bytes) -> _SpeechRequest: + try: + parsed = orjson.loads(body) + except orjson.JSONDecodeError as exc: + raise _SpeechRequestError("request body must be a JSON object") from exc + if not isinstance(parsed, dict): + raise _SpeechRequestError("request body must be a JSON object") + fields = cast("dict[str, Any]", parsed) + + if "instructions" in fields: + raise _SpeechRequestError( + "field 'instructions' is not supported; control the speech with 'voice' and 'speed'", + param="instructions", + code="unsupported_field", + ) + for name in fields: + if name not in _ALLOWED_FIELDS: + raise _SpeechRequestError( + f"unsupported field '{name}'; supported fields are model, input, voice, response_format and speed", + param=name, + code="unsupported_field", + ) + + model = fields.get("model") + if not isinstance(model, str) or not model.strip(): + raise _SpeechRequestError("field 'model' is required", param="model") + model = model.strip() + if ".." in model or "\\" in model or not _MODEL_ID_PATTERN.fullmatch(model): + raise _SpeechRequestError("invalid model id for path", param="model") + + text = fields.get("input") + if not isinstance(text, str) or not text.strip(): + raise _SpeechRequestError("field 'input' must be a non-empty string", param="input") + + voice = fields.get("voice") + if voice is not None and (not isinstance(voice, str) or not voice.strip()): + raise _SpeechRequestError("field 'voice' must be a non-empty string voice id", param="voice") + + response_format = fields.get("response_format", "wav") + if not isinstance(response_format, str) or response_format not in _RESPONSE_FORMATS: + openai_only = isinstance(response_format, str) and response_format in _OPENAI_ONLY_FORMATS + code = "unsupported_field" if openai_only else "invalid_request" + raise _SpeechRequestError( + "response_format must be wav or pcm (24 kHz 16-bit little-endian mono)", + param="response_format", + code=code, + ) + + speed = fields.get("speed") + if speed is not None and ( + isinstance(speed, bool) + or not isinstance(speed, int | float) + or not math.isfinite(speed) + or not MIN_SPEED <= speed <= MAX_SPEED + ): + raise _SpeechRequestError(f"speed must be a number from {MIN_SPEED} to {MAX_SPEED}", param="speed") + + stream_format = fields.get("stream_format", "audio") + if stream_format != "audio": + raise _SpeechRequestError( + "streaming speech is not supported; omit stream_format or set it to 'audio'", + param="stream_format", + code="unsupported_field", + ) + + return _SpeechRequest( + model=model, + input=text, + voice=voice.strip() if isinstance(voice, str) else None, + response_format=response_format, + speed=float(speed) if speed is not None else None, + ) + + +def _refused_option(message: str, options: dict[str, Any]) -> str | None: + """The option of the request that a model's refusal ``message`` names, if any. + + A worker reports a refused request as a code and a message, with no field, + so the option is found by name: ``voice`` or ``speed`` as a whole word of + the message, and only when the request sent that option. The gateway route + applies the same rule. + """ + words = {word.lower() for word in _WORD.findall(message)} + return next((name for name in _REFUSABLE_OPTIONS if name in options and name in words), None) + + +def _pcm16_samples(wav: bytes) -> bytes: + """The sample bytes of a 16-bit PCM WAV file.""" + try: + with wave.open(io.BytesIO(wav), "rb") as reader: + if reader.getsampwidth() != _PCM16_SAMPLE_BYTES or reader.getcomptype() != "NONE": + raise ValueError("extract response audio is not 16-bit PCM") + return reader.readframes(reader.getnframes()) + except (wave.Error, EOFError) as exc: + raise ValueError("extract response audio is not a valid WAV file") from exc + + +def _speech_audio(data: dict[str, Any]) -> bytes: + """The WAV bytes of one native extract result.""" + audio = data.get("audio") + if not isinstance(audio, str) or data.get("format") != "wav": + raise ValueError("extract response is missing WAV audio") + try: + return base64.b64decode(audio, validate=True) + except binascii.Error as exc: + raise ValueError("extract response audio is not valid base64") from exc + + +def _speech_response(wav: bytes, response_format: str, headers: dict[str, str]) -> Response: + pcm = _pcm16_samples(wav) + body = wav if response_format == "wav" else pcm + return Response(content=body, media_type=_RESPONSE_FORMATS[response_format], headers=headers) + + +@router.post("/audio/speech", response_model=None, response_class=Response, openapi_extra=_SPEECH_OPENAPI) +async def create_speech( + http_request: Request, + x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None, +) -> Response: + """Synthesize speech for one text through SIE's native extract path.""" + try: + validate_machine_profile_header(x_machine_profile) + check_sdk_version(http_request) + speech = _parse_speech_request(await _read_body(http_request)) + except _SpeechRequestError as error: + return _request_error_response(error) + except HTTPException as error: + return _http_error_response(error) + + registry_key = denormalize_model_id(speech.model) + registry = http_request.app.state.registry + try: + with tracer.start_as_current_span("openai_audio_speech") as span: + span.set_attribute("model", registry_key) + ModelStateChecker(registry, registry_key, span).check_exists() + config = registry.get_config(registry_key) + if config.tasks.extract is None or not config.inputs.text: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={ + "code": ErrorCode.INVALID_INPUT.value, + "message": f"Model '{speech.model}' does not support text-to-speech", + "param": "model", + }, + ) + + raw_options: dict[str, Any] = {} + if speech.voice is not None: + raw_options["voice"] = speech.voice + if speech.speed is not None: + raw_options["speed"] = speech.speed + options = resolve_runtime_options(config, raw_options, span) + route = await route_request(http_request, registry_key, span, queued_items=1) + error_handler = InferenceErrorHandler( + registry_key, + "extract", + span, + oom_retry_after_s=oom_retry_after_from_registry(registry), + ) + try: + worker_result = await _extract_via_worker( + registry, + route.key, + [Item(text=speech.input)], + options=options, + ) + output = ExtractHandler.format_output(cast("ExtractOutput", worker_result.output)) + except QueueFullError as error: + raise error_handler.handle_queue_full(error) from error + except InputTooLongError as error: + raise error_handler.handle_input_too_long(error) from error + except ValueError as error: + refusal = error_handler.handle_value_error(error) + param = _refused_option(str(error), raw_options) + if param is not None and isinstance(refusal.detail, dict): + refusal.detail["param"] = param + raise refusal from error + except Exception as error: + raise error_handler.handle_inference_error(error, "Speech synthesis") from error + + if len(output) != 1: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={"code": ErrorCode.INFERENCE_ERROR.value, "message": "malformed extract response"}, + ) + item_error = output[0].get("error") + if isinstance(item_error, dict): + # The model refused this text, for example as longer than its limit. + message = str(item_error.get("message") or "the model could not synthesize this input") + code = str(item_error.get("code") or ErrorCode.INVALID_INPUT.value) + param = "input" if code == ErrorCode.INPUT_TOO_LONG.value else _refused_option(message, raw_options) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={"code": code, "message": message, "param": param or "input"}, + ) + data = output[0].get("data") + if not isinstance(data, dict) or "audio" not in data: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={ + "code": ErrorCode.INVALID_INPUT.value, + "message": f"Model '{speech.model}' did not return speech audio", + "param": "model", + }, + ) + headers = ResponseBuilder.build_headers(worker_result.timing) + headers.update(route.headers()) + response = _speech_response(_speech_audio(cast("dict[str, Any]", data)), speech.response_format, headers) + if worker_telemetry_enabled(): + worker_telemetry().item_completed( + operation="extract", + outcome="success", + model=registry_key, + profile="default", + duration_s=worker_result.timing.total_ms / 1_000.0, + item_count=1, + tokenization_s=worker_result.timing.tokenization_ms / 1_000.0, + inference_s=worker_result.timing.inference_ms / 1_000.0, + postprocessing_s=worker_result.timing.postprocessing_ms / 1_000.0, + ) + return response + except HTTPException as error: + return _http_error_response(fallback_refusal(http_request, error.status_code, error_code(error)) or error) + except ValueError: + logger.exception("Failed to format speech response for %s", registry_key) + return _openai_error( + "internal server error", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + code="internal_error", + ) diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.py index 1c80a95b7..ed4c7367c 100644 --- a/packages/sie_server/src/sie_server/app/app_factory.py +++ b/packages/sie_server/src/sie_server/app/app_factory.py @@ -23,6 +23,7 @@ from sie_server.api.openai_errors import OpenAIErrorEnvelopeMiddleware from sie_server.api.openai_local import router as openai_local_router from sie_server.api.openai_responses import router as openai_responses_router +from sie_server.api.openai_speech import router as openai_speech_router from sie_server.api.openapi import setup_custom_openapi_schema from sie_server.api.root import router as root_router from sie_server.api.score import router as score_router @@ -136,6 +137,7 @@ def create_app(cls, config: AppStateConfig) -> FastAPI: app.include_router(score_router) app.include_router(models_router) app.include_router(openai_audio_router) # OpenAI-compatible /v1/audio/transcriptions + app.include_router(openai_speech_router) # OpenAI-compatible /v1/audio/speech app.include_router(openai_router) # OpenAI-compatible /v1/embeddings app.include_router(openai_completions_router) # OpenAI-compatible /v1/completions app.include_router(openai_responses_router) # OpenAI-compatible /v1/responses diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py index cf61950dc..68cef27d6 100644 --- a/packages/sie_server/src/sie_server/cli.py +++ b/packages/sie_server/src/sie_server/cli.py @@ -47,6 +47,7 @@ from sie_server.api.decisions import router as decisions_router from sie_server.api.generate import router as generate_router from sie_server.api.openai_audio import router as openai_audio_router +from sie_server.api.openai_speech import router as openai_speech_router from sie_server.app.app_state_config import ( ENV_DEVICES, ENV_PINNED_MODELS, @@ -472,6 +473,7 @@ def openapi_export( app_.include_router(models_router) app_.include_router(ws_router) app_.include_router(openai_audio_router) + app_.include_router(openai_speech_router) app_.include_router(openai_router) app_.include_router(openai_completions_router) app_.include_router(systemone_router) diff --git a/packages/sie_server/tests/adapters/test_kokoro.py b/packages/sie_server/tests/adapters/test_kokoro.py index ce39fab98..dc9468031 100644 --- a/packages/sie_server/tests/adapters/test_kokoro.py +++ b/packages/sie_server/tests/adapters/test_kokoro.py @@ -320,6 +320,37 @@ def test_options_select_voice_speed_and_language(kokoro_module: ModuleType, chec assert _decode_wav(output.data[0])[1].shape[0] == 5 * SAMPLES_PER_PHONEME // 2 +@pytest.mark.parametrize( + ("options", "lang"), + [ + ({"voice": "bf_emma"}, "b"), + ({"voice": "af_heart"}, "a"), + ({}, "a"), + ({"voice": "bf_emma", "lang": "a"}, "a"), + ({"voice": "af_heart", "lang": "b"}, "b"), + ], +) +def test_language_follows_the_voice_unless_given( + kokoro_module: ModuleType, checkpoint: Path, options: dict[str, Any], lang: str +) -> None: + adapter = _loaded(checkpoint) + + adapter.extract([Item(text="Hello")], options=options) + + voice = options.get("voice", "af_heart") + assert _pipeline(lang).calls == [("Hello", str(checkpoint / "voices" / f"{voice}.pt"), 1.0)] + assert _pipeline("b" if lang == "a" else "a").calls == [] + + +def test_voices_of_other_languages_default_to_american_english(kokoro_module: ModuleType, checkpoint: Path) -> None: + (checkpoint / "voices" / "jf_alpha.pt").write_bytes(b"") + adapter = _loaded(checkpoint) + + adapter.extract([Item(text="Hello")], options={"voice": "jf_alpha"}) + + assert _pipeline("a").calls == [("Hello", str(checkpoint / "voices" / "jf_alpha.pt"), 1.0)] + + @pytest.mark.parametrize( ("options", "message"), [ diff --git a/packages/sie_server/tests/api/test_openai_error_envelope.py b/packages/sie_server/tests/api/test_openai_error_envelope.py index f4d13de50..2eb47c250 100644 --- a/packages/sie_server/tests/api/test_openai_error_envelope.py +++ b/packages/sie_server/tests/api/test_openai_error_envelope.py @@ -25,6 +25,7 @@ "/v1/responses/resp_1", "/v1/embeddings", "/v1/audio/transcriptions", + "/v1/audio/speech", ] OTHER_PATHS = [ "/v1/messages", @@ -234,7 +235,14 @@ def served(monkeypatch: pytest.MonkeyPatch) -> TestClient: @pytest.mark.parametrize( "path", - ["/v1/chat/completions", "/v1/completions", "/v1/responses", "/v1/embeddings", "/v1/audio/transcriptions"], + [ + "/v1/chat/completions", + "/v1/completions", + "/v1/responses", + "/v1/embeddings", + "/v1/audio/transcriptions", + "/v1/audio/speech", + ], ) def test_a_missing_token_on_an_openai_route_gets_the_openai_envelope(served: TestClient, path: str) -> None: response = served.post(path, json={}) diff --git a/packages/sie_server/tests/api/test_openai_speech.py b/packages/sie_server/tests/api/test_openai_speech.py new file mode 100644 index 000000000..38201c4cb --- /dev/null +++ b/packages/sie_server/tests/api/test_openai_speech.py @@ -0,0 +1,383 @@ +"""Contract tests for the OpenAI-compatible speech adapter.""" + +import base64 +import io +import wave +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from sie_server.api import openai_speech +from sie_server.config.model import ExtractTask, InputModalities, ModelConfig, ProfileConfig, Tasks +from sie_server.core.inference_output import ExtractItemError, ExtractOutput +from sie_server.core.registry import ModelRegistry +from sie_server.core.timing import RequestTiming +from sie_server.core.worker import WorkerResult +from sie_server.types.inputs import InvalidInputError + +MODEL = "hexgrad/Kokoro-82M" +SAMPLES = bytes(range(256)) * 48 # 6,144 16-bit samples + + +def _wav(samples: bytes = SAMPLES, *, sample_width: int = 2) -> bytes: + buffer = io.BytesIO() + with wave.open(buffer, "wb") as writer: + writer.setnchannels(1) + writer.setsampwidth(sample_width) + writer.setframerate(24_000) + writer.writeframes(samples) + return buffer.getvalue() + + +WAV = _wav() + + +def _model_config(*, text: bool = True, extract: bool = True) -> ModelConfig: + return ModelConfig( + sie_id=MODEL, + hf_id=MODEL, + inputs=InputModalities(text=text), + tasks=Tasks(extract=ExtractTask() if extract else None), + profiles={ + "default": ProfileConfig( + adapter_path="sie_server.adapters.kokoro.adapter:KokoroAdapter", + max_batch_tokens=6_000, + ) + }, + ) + + +def _output(data: dict[str, Any], error: ExtractItemError | None = None) -> ExtractOutput: + return ExtractOutput( + entities=[[]], + data=[data], + errors=[error] if error is not None else None, + batch_size=1, + ) + + +def _speech_data(audio: bytes = WAV) -> dict[str, Any]: + return { + "audio": base64.b64encode(audio).decode("ascii"), + "format": "wav", + "sample_rate": 24_000, + "duration_ms": 256, + "voice": "af_heart", + } + + +@pytest.fixture +def registry() -> MagicMock: + registry = MagicMock(spec=ModelRegistry) + registry.has_model.return_value = True + registry.is_loaded.return_value = True + registry.is_loading.return_value = False + registry.is_unloading.return_value = False + registry.is_failed.return_value = False + registry.get_failure.return_value = None + registry.get_worker.return_value = None + registry.get_config.return_value = _model_config() + registry.device = "cpu" + registry.engine_config = None + return registry + + +@pytest.fixture +def extract_mock(monkeypatch: pytest.MonkeyPatch) -> AsyncMock: + mock = AsyncMock(return_value=WorkerResult(output=_output(_speech_data()), timing=RequestTiming())) + monkeypatch.setattr(openai_speech, "_extract_via_worker", mock) + return mock + + +@pytest.fixture +def client(registry: MagicMock, extract_mock: AsyncMock) -> TestClient: + del extract_mock + app = FastAPI() + app.include_router(openai_speech.router) + app.state.registry = registry + return TestClient(app, raise_server_exceptions=False) + + +def _post(client: TestClient, **fields: Any) -> Any: + return client.post("/v1/audio/speech", json={"model": MODEL, "input": "Hello there.", **fields}) + + +class TestSpeechSuccess: + def test_wav_is_the_native_extract_audio(self, client: TestClient, extract_mock: AsyncMock) -> None: + response = _post(client, voice="bf_emma", speed=1.25) + + assert response.status_code == 200 + assert response.headers["content-type"] == "audio/wav" + assert response.content == WAV + assert "x-sie-server-version" in response.headers + + args = extract_mock.await_args + assert args.args[1] == MODEL + assert len(args.args[2]) == 1 + assert args.args[2][0].text == "Hello there." + assert args.kwargs["options"] == {"voice": "bf_emma", "speed": 1.25} + + def test_wav_is_the_default_and_omitted_options_are_not_sent( + self, client: TestClient, extract_mock: AsyncMock + ) -> None: + response = _post(client) + + assert response.status_code == 200 + assert response.headers["content-type"] == "audio/wav" + assert extract_mock.await_args.kwargs["options"] == {} + + def test_a_british_voice_leaves_the_language_to_the_model( + self, client: TestClient, extract_mock: AsyncMock + ) -> None: + response = _post(client, voice="bf_emma") + + assert response.status_code == 200 + # No lang: the model derives it from the voice (Kokoro reads "b..." voices as British English). + assert extract_mock.await_args.kwargs["options"] == {"voice": "bf_emma"} + + def test_pcm_is_the_wav_samples_without_the_header(self, client: TestClient) -> None: + response = _post(client, response_format="pcm", voice="af_heart", speed=1) + + assert response.status_code == 200 + assert response.headers["content-type"] == "audio/pcm" + assert response.content == SAMPLES + + def test_explicit_audio_stream_format_is_accepted(self, client: TestClient) -> None: + assert _post(client, stream_format="audio").status_code == 200 + + def test_openai_client_reads_the_audio(self, client: TestClient) -> None: + from openai import OpenAI + + openai_client = OpenAI(base_url="http://testserver/v1", api_key="unused", http_client=client) + response = openai_client.audio.speech.create( + model=MODEL, + input="Hello there.", + voice="af_heart", # type: ignore[arg-type] + response_format="wav", + ) + + assert response.content == WAV + + def test_success_records_worker_telemetry( + self, + client: TestClient, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + telemetry = MagicMock() + monkeypatch.setattr(openai_speech, "worker_telemetry_enabled", lambda: True) + monkeypatch.setattr(openai_speech, "worker_telemetry", lambda: telemetry) + + assert _post(client).status_code == 200 + + telemetry.item_completed.assert_called_once() + assert telemetry.item_completed.call_args.kwargs["operation"] == "extract" + assert telemetry.item_completed.call_args.kwargs["model"] == MODEL + + +class TestSpeechValidation: + @pytest.mark.parametrize( + ("fields", "param", "code"), + [ + ({"response_format": "mp3"}, "response_format", "unsupported_field"), + ({"response_format": "opus"}, "response_format", "unsupported_field"), + ({"response_format": "aac"}, "response_format", "unsupported_field"), + ({"response_format": "flac"}, "response_format", "unsupported_field"), + ({"response_format": "ogg"}, "response_format", "invalid_request"), + ({"response_format": []}, "response_format", "invalid_request"), + ({"response_format": {}}, "response_format", "invalid_request"), + ({"response_format": ["mp3"]}, "response_format", "invalid_request"), + ({"instructions": "Speak slowly."}, "instructions", "unsupported_field"), + ({"stream_format": "sse"}, "stream_format", "unsupported_field"), + ({"stream": True}, "stream", "unsupported_field"), + ({"speed": 0.25}, "speed", "invalid_request"), + ({"speed": 4.0}, "speed", "invalid_request"), + ({"speed": True}, "speed", "invalid_request"), + ({"speed": "1.0"}, "speed", "invalid_request"), + ({"voice": ""}, "voice", "invalid_request"), + ({"voice": 3}, "voice", "invalid_request"), + ({"input": ""}, "input", "invalid_request"), + ({"input": " "}, "input", "invalid_request"), + ({"input": ["a"]}, "input", "invalid_request"), + ({"model": ""}, "model", "invalid_request"), + ({"model": "/leading"}, "model", "invalid_request"), + ({"model": "two..dots"}, "model", "invalid_request"), + ({"model": "back\\slash"}, "model", "invalid_request"), + ({"model": "query?x=1"}, "model", "invalid_request"), + ({"model": "unicode-model-模型"}, "model", "invalid_request"), + ], + ) + def test_strict_field_validation( + self, + client: TestClient, + extract_mock: AsyncMock, + fields: dict[str, Any], + param: str, + code: str, + ) -> None: + response = _post(client, **fields) + + assert response.status_code == 400 + error = response.json()["error"] + assert error["type"] == "invalid_request_error" + assert error["param"] == param + assert error["code"] == code + extract_mock.assert_not_awaited() + + def test_unsupported_format_names_the_supported_ones(self, client: TestClient) -> None: + message = _post(client, response_format="mp3").json()["error"]["message"] + + assert "wav" in message + assert "pcm" in message + + @pytest.mark.parametrize("body", [b"not json", b"[1]", b'"text"']) + def test_rejects_a_body_that_is_not_a_json_object(self, client: TestClient, body: bytes) -> None: + response = client.post("/v1/audio/speech", content=body, headers={"content-type": "application/json"}) + + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + def test_rejects_body_above_declared_limit(self, client: TestClient) -> None: + response = client.post( + "/v1/audio/speech", + headers={ + "content-type": "application/json", + "content-length": str(openai_speech.MAX_SPEECH_REQUEST_BYTES + 1), + }, + content=b"", + ) + + assert response.status_code == 413 + assert response.json()["error"]["code"] == "payload_too_large" + + def test_rejects_streamed_body_above_limit(self, client: TestClient) -> None: + response = _post(client, input="x" * openai_speech.MAX_SPEECH_REQUEST_BYTES) + + assert response.status_code == 413 + assert response.json()["error"]["code"] == "payload_too_large" + + def test_model_not_found_uses_openai_error_envelope(self, client: TestClient, registry: MagicMock) -> None: + registry.has_model.return_value = False + + response = _post(client) + + assert response.status_code == 404 + assert response.json()["error"] == { + "message": f"Model '{MODEL}' not found", + "type": "invalid_request_error", + "param": None, + "code": "model_not_found", + } + + @pytest.mark.parametrize("config", [_model_config(text=False), _model_config(extract=False)]) + def test_rejects_models_without_text_extract( + self, + client: TestClient, + registry: MagicMock, + config: ModelConfig, + ) -> None: + registry.get_config.return_value = config + + response = _post(client) + + assert response.status_code == 400 + assert response.json()["error"]["param"] == "model" + + @pytest.mark.parametrize( + ("message", "fields", "param"), + [ + ("unknown Kokoro voice 'alloy'; available voices: af_heart", {"voice": "alloy"}, "voice"), + ("speed must be a number from 0.8 to 1.2", {"speed": 1.5}, "speed"), + ("Speed must be a number", {"voice": "af_heart", "speed": 1.5}, "speed"), + # Named options the request did not send, or no option at all, stay unnamed. + ("unknown Kokoro voice 'af_heart'", {}, None), + ("available voices: af_heart; speedy", {"voice": "x", "speed": 1.5}, None), + ("Kokoro text-to-speech does not accept labels", {"voice": "af_heart"}, None), + ], + ) + def test_model_refusal_of_an_option_names_it( + self, + client: TestClient, + extract_mock: AsyncMock, + message: str, + fields: dict[str, Any], + param: str | None, + ) -> None: + extract_mock.side_effect = InvalidInputError(message) + + response = _post(client, **fields) + + assert response.status_code == 400 + error = response.json()["error"] + assert error["type"] == "invalid_request_error" + assert error["message"] == message + assert error["param"] == param + + def test_item_refusal_of_an_option_names_it(self, client: TestClient, extract_mock: AsyncMock) -> None: + extract_mock.return_value = WorkerResult( + output=_output({}, ExtractItemError(code="INVALID_INPUT", message="unknown Kokoro voice 'alloy'")), + timing=RequestTiming(), + ) + + response = _post(client, voice="alloy") + + assert response.status_code == 400 + assert response.json()["error"]["param"] == "voice" + + @pytest.mark.parametrize("options", [{}, {"speed": 1.0}, {"voice": "af_heart", "speed": 1.0}]) + def test_item_refusal_is_a_400_on_input( + self, client: TestClient, extract_mock: AsyncMock, options: dict[str, Any] + ) -> None: + # The length refusal names the speed it was measured at; it is still about the input. + extract_mock.return_value = WorkerResult( + output=_output( + {}, + ExtractItemError( + code="INPUT_TOO_LONG", message="text has 3001 characters; the limit at speed 1 is 3000" + ), + ), + timing=RequestTiming(), + ) + + response = _post(client, **options) + + assert response.status_code == 400 + error = response.json()["error"] + assert error["param"] == "input" + assert "3000" in error["message"] + + def test_model_without_audio_output_is_a_400(self, client: TestClient, extract_mock: AsyncMock) -> None: + extract_mock.return_value = WorkerResult(output=_output({"text": "not audio"}), timing=RequestTiming()) + + response = _post(client) + + assert response.status_code == 400 + assert response.json()["error"]["param"] == "model" + + @pytest.mark.parametrize( + "data", + [ + {**_speech_data(), "audio": "not base64!"}, + {**_speech_data(), "format": "mp3"}, + _speech_data(b"RIFF-not-a-wav"), + _speech_data(_wav(bytes(range(256)), sample_width=1)), + ], + ) + def test_malformed_native_audio_is_a_500_and_not_recorded_as_success( + self, + client: TestClient, + extract_mock: AsyncMock, + monkeypatch: pytest.MonkeyPatch, + data: dict[str, Any], + ) -> None: + extract_mock.return_value = WorkerResult(output=_output(data), timing=RequestTiming()) + telemetry = MagicMock() + monkeypatch.setattr(openai_speech, "worker_telemetry_enabled", lambda: True) + monkeypatch.setattr(openai_speech, "worker_telemetry", lambda: telemetry) + + response = _post(client) + + assert response.status_code == 500 + assert response.json()["error"]["type"] == "server_error" + telemetry.item_completed.assert_not_called() diff --git a/packages/sie_server/tests/test_openapi_export.py b/packages/sie_server/tests/test_openapi_export.py index a010bcd79..783d6b4d0 100644 --- a/packages/sie_server/tests/test_openapi_export.py +++ b/packages/sie_server/tests/test_openapi_export.py @@ -173,6 +173,20 @@ def test_openapi_audio_timestamp_contract() -> None: assert granularities["items"]["enum"] == ["word", "segment"] +def test_openapi_speech_contract() -> None: + """Speech compatibility documents its JSON request and binary audio response.""" + result = runner.invoke(app, ["openapi"]) + assert result.exit_code == 0, result.output + spec = json.loads(result.output) + operation = spec["paths"]["/v1/audio/speech"]["post"] + schema = operation["requestBody"]["content"]["application/json"]["schema"] + assert schema["required"] == ["model", "input"] + assert schema["properties"]["response_format"]["enum"] == ["wav", "pcm"] + assert schema["properties"]["speed"]["minimum"] == 0.5 + assert schema["properties"]["speed"]["maximum"] == 2.0 + assert set(operation["responses"]["200"]["content"]) == {"audio/wav", "audio/pcm"} + + def test_openapi_documents_media_bytes_as_base64_strings() -> None: """Every media `data` field advertises the one JSON encoding the API accepts.