Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): reject token ids and apply model profiles on /v1/embeddings (#395)
Krisztian Gajdar078c6e5d3f1b
diff --git a/integrations/sie_chroma/src/sie_chroma/embedding_function.py b/integrations/sie_chroma/src/sie_chroma/embedding_function.pyindex 814f139eb..d7bf0b7ba 100644--- a/integrations/sie_chroma/src/sie_chroma/embedding_function.py+++ b/integrations/sie_chroma/src/sie_chroma/embedding_function.py@@ -81,17 +81,35 @@ class SIEEmbeddingFunction(EmbeddingFunction[Documents]):Returns:List of embedding vectors as numpy arrays (ChromaDB's expected format)."""- if not documents:+ return self._encode(documents, options=None)++ def embed_query(self, input: Documents) -> Embeddings:+ """Generate embeddings for query texts.++ ChromaDB calls this for ``query_texts``. Uses is_query=True for+ asymmetric models.++ Args:+ input: List of query texts to embed.++ Returns:+ List of embedding vectors as numpy arrays (ChromaDB's expected format).+ """+ return self._encode(input, options={"is_query": True})++ def _encode(self, texts: Documents, *, options: dict[str, Any] | None) -> Embeddings:+ if not texts:return []import numpy as np- items = [Item(text=text) for text in documents]+ items = [Item(text=text) for text in texts]results = self.client.encode(self._model,items,output_types=["dense"],+ options=options,)embeddings: Embeddings = []@@ -179,15 +197,34 @@ class SIESparseEmbeddingFunction:List of sparse embeddings. Each sparse embedding is a dictmapping token indices (int) to weights (float)."""- if not documents:+ return self._encode(documents, options=None)++ def embed_query(self, input: Documents) -> SparseEmbeddings:+ """Generate sparse embeddings for query texts.++ ChromaDB calls this for string queries. Uses is_query=True for+ asymmetric models.++ Args:+ input: List of query texts to embed.++ Returns:+ List of sparse embeddings. Each sparse embedding is a dict+ mapping token indices (int) to weights (float).+ """+ return self._encode(input, options={"is_query": True})++ def _encode(self, texts: Documents, *, options: dict[str, Any] | None) -> SparseEmbeddings:+ if not texts:return []- items = [Item(text=text) for text in documents]+ items = [Item(text=text) for text in texts]results = self.client.encode(self._model,items,output_types=["sparse"],+ options=options,)return [sparse_embedding_dict(result) for result in results]diff --git a/integrations/sie_chroma/tests/test_embedding_function.py b/integrations/sie_chroma/tests/test_embedding_function.pyindex 2ffbf0458..72ea5f407 100644--- a/integrations/sie_chroma/tests/test_embedding_function.py+++ b/integrations/sie_chroma/tests/test_embedding_function.py@@ -3,7 +3,9 @@from __future__ import annotationsimport contextlib+import uuid+import chromadbimport numpy as npfrom sie_chroma import SIEEmbeddingFunction, SIESparseEmbeddingFunction@@ -251,3 +253,61 @@ class TestSIESparseEmbeddingFunction:for k, v in embedding.items():assert isinstance(k, int)assert isinstance(v, float)+++class TestQueryMode:+ """ChromaDB embeds ``query_texts`` through ``embed_query``, so asymmetric+ models must see ``is_query=True`` there and only there.+ """++ def test_collection_query_texts_encode_as_queries(+ self, mock_sie_client: object, sample_documents: list[str]+ ) -> None:+ embedding_function = SIEEmbeddingFunction(model="test-model")+ embedding_function._client = mock_sie_client+ collection = chromadb.EphemeralClient().create_collection(+ name=f"sie-query-mode-{uuid.uuid4().hex}",+ embedding_function=embedding_function,+ )++ collection.add(ids=[str(i) for i in range(len(sample_documents))], documents=sample_documents)+ assert mock_sie_client.encode.call_args.kwargs["options"] is None++ result = collection.query(query_texts=["How do neural networks learn?"], n_results=2)+ assert mock_sie_client.encode.call_args.kwargs["options"] == {"is_query": True}+ assert len(result["ids"][0]) == 2++ def test_embed_query_returns_dense_vectors(self, mock_sie_client: object) -> None:+ embedding_function = SIEEmbeddingFunction(model="test-model")+ embedding_function._client = mock_sie_client++ embeddings = embedding_function.embed_query(["What is machine learning?"])++ assert len(embeddings) == 1+ assert isinstance(embeddings[0], np.ndarray)+ assert len(embeddings[0]) == 384+ call_kwargs = mock_sie_client.encode.call_args.kwargs+ assert call_kwargs["output_types"] == ["dense"]+ assert call_kwargs["options"] == {"is_query": True}++ def test_sparse_embed_query_encodes_as_query(self, mock_sie_client: object) -> None:+ embedding_function = SIESparseEmbeddingFunction(model="test-model")+ embedding_function._client = mock_sie_client++ embeddings = embedding_function.embed_query(["What is machine learning?"])++ assert len(embeddings) == 1+ assert isinstance(embeddings[0], dict)+ call_kwargs = mock_sie_client.encode.call_args.kwargs+ assert call_kwargs["output_types"] == ["sparse"]+ assert call_kwargs["options"] == {"is_query": True}++ def test_sparse_documents_do_not_encode_as_queries(+ self, mock_sie_client: object, sample_documents: list[str]+ ) -> None:+ embedding_function = SIESparseEmbeddingFunction(model="test-model")+ embedding_function._client = mock_sie_client++ embedding_function(sample_documents)++ assert mock_sie_client.encode.call_args.kwargs["options"] is Nonediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 3720d3ee5..7d6958e51 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -44,7 +44,7 @@ Key terms used throughout this document:- `POST /v1/encode/{*model}`- `POST /v1/score/{*model}`- `POST /v1/extract/{*model}`- - `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.+ - `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**. `dimensions` is accepted only when it equals the model's native dense width and otherwise rejected with **`400 unsupported_field`**, the same rule as the single-node server. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.2. Gateway resolves the request to a model, a bundle, a machine profile, a logical API pool, and the backing queue pool using its in-memory registry.3. Gateway ordinarily publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item. A capped logical batch pool instead targets one assigned worker on `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.4. A matching worker consumes the work item, verifies its logical pool assignment when `admission_pool` differs from its physical queue pool, and executes inference.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex f75f52c53..70c66ac11 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -2591,7 +2591,7 @@"description": "OpenAI-compatible ``POST /v1/embeddings`` request (subset supported on gateway).","properties": {"dimensions": {- "description": "Accepted but ignored; the gateway returns the model's native dimension.",+ "description": "Requested embedding width. SIE always returns the model's native dense\nwidth, so this is accepted only when it equals that width; any other\nvalue is rejected with 400 `unsupported_field` rather than ignored.","format": "int32","minimum": 0,"type": [diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 82698f25a..d44929605 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -12542,6 +12542,70 @@ pub fn openai_embeddings_encode_body(input: &Value) -> Result<(Value, u64), Stri))}+/// The single-node server's `dimensions` rule: SIE never truncates, so only+/// the model's native dense width is accepted. Applied only to a model this+/// caller can see and the registry describes; the encode dispatch answers+/// every other case, so a hidden model stays indistinguishable from an absent+/// one.+fn openai_embeddings_dimensions_error(+ state: &AppState,+ parsed: &Value,+ model_spec: &str,+ ext: &axum::http::Extensions,+) -> Option<Response> {+ let requested = match parsed.get("dimensions") {+ None | Some(Value::Null) => return None,+ Some(value) => value,+ };+ let Some(requested) = requested.as_i64() else {+ return Some(+ (+ StatusCode::BAD_REQUEST,+ Json(embeddings_error(+ err_code::INVALID_REQUEST,+ Some("dimensions"),+ "dimensions must be an integer",+ )),+ )+ .into_response(),+ );+ };+ let (model_name, _) = resolve_model_and_bundle(state, model_spec, ext).ok()?;+ let native = state+ .model_registry+ .get_model_info(&model_name)?+ .info_extras+ .dims+ .get("dense")+ .copied();+ if native == Some(requested) {+ return None;+ }+ let message = match native {+ Some(native) => format!(+ "'dimensions' is not supported by this endpoint: model '{model_spec}' returns \+ {native}-dimensional embeddings and SIE does not truncate them. Omit \+ 'dimensions', or set it to {native}."+ ),+ None => format!(+ "'dimensions' is not supported by this endpoint: model '{model_spec}' declares \+ no dense embedding width."+ ),+ };+ Some(+ (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ message,+ oai_type::INVALID_REQUEST,+ Some("dimensions"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response(),+ )+}+fn openai_embedding_input_to_texts(input: &Value) -> Result<OpenAiEmbeddingInput, String> {match input {Value::String(s) => {@@ -12728,6 +12792,11 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re).into_response();}+ if let Some(response) =+ openai_embeddings_dimensions_error(&state, &parsed, &model_str, &parts.extensions)+ {+ return response;+ }let input = parsed.get("input").cloned().unwrap_or(Value::Null);let (encode_body, token_count) = match openai_embeddings_encode_body(&input) {Ok(normalized) => normalized,@@ -18864,6 +18933,162 @@ mod tests {assert!(err.contains("token-array embeddings input is not supported"));}+ /// A state whose populated registry routes `known/embedder` (384-wide+ /// dense) and `known/sparse` (no dense output). The dirs must outlive the+ /// state.+ fn embeddings_dimensions_state() -> (AppState, tempfile::TempDir, tempfile::TempDir) {+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ std::fs::write(+ bundles_dir.path().join("default.yaml"),+ "name: default\nadapters:\n - sie_server.adapters.sentence_transformer\ndefault: true\n",+ )+ .unwrap();+ for (file, sie_id, encode) in [+ ("embedder.yaml", "known/embedder", "dense:\n dim: 384"),+ ("sparse.yaml", "known/sparse", "sparse:\n dim: 30522"),+ ] {+ std::fs::write(+ models_dir.path().join(file),+ format!(+ "sie_id: {sie_id}\ntasks:\n encode:\n {encode}\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:Adapter\n"+ ),+ )+ .unwrap();+ }+ let mut state = admission_test_state(Arc::new(PoolManager::new(vec!["l4".to_string()])));+ state.model_registry = Arc::new(ModelRegistry::new(+ bundles_dir.path(),+ models_dir.path(),+ true,+ ));+ (state, bundles_dir, models_dir)+ }++ async fn post_embeddings(state: AppState, body: Value) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(Method::POST)+ .uri("/v1/embeddings")+ .header(axum::http::header::CONTENT_TYPE, "application/json")+ .body(Body::from(body.to_string()))+ .unwrap();+ let response = proxy_openai_embeddings(State(Arc::new(state)), req).await;+ let status = response.status();+ let bytes = to_bytes(response.into_body(), 64 * 1024).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap())+ }++ #[tokio::test]+ async fn test_openai_embeddings_rejects_dimensions_the_model_does_not_produce() {+ let (state, _bundles, _models) = embeddings_dimensions_state();++ let (status, body) = post_embeddings(+ state,+ json!({"model": "known/embedder", "input": "hello", "dimensions": 256}),+ )+ .await;++ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert_eq!(+ body["error"],+ json!({+ "message": "'dimensions' is not supported by this endpoint: model 'known/embedder' returns 384-dimensional embeddings and SIE does not truncate them. Omit 'dimensions', or set it to 384.",+ "type": "invalid_request_error",+ "param": "dimensions",+ "code": "unsupported_field",+ })+ );+ }++ #[test]+ fn test_openai_embeddings_dimensions_matching_or_omitted_pass_through() {+ let (state, _bundles, _models) = embeddings_dimensions_state();+ let ext = axum::http::Extensions::new();+ assert!(+ openai_embeddings_dimensions_error(+ &state,+ &json!({"dimensions": 256}),+ "known/embedder",+ &ext+ )+ .is_some(),+ "the fixture must resolve the model, or the pass-through below proves nothing"+ );++ for body in [+ json!({"dimensions": 384}),+ json!({"dimensions": null}),+ json!({}),+ ] {+ assert!(+ openai_embeddings_dimensions_error(&state, &body, "known/embedder", &ext).is_none(),+ "{body}"+ );+ }+ }++ #[tokio::test]+ async fn test_openai_embeddings_dimensions_for_a_model_without_dense_output() {+ let (state, _bundles, _models) = embeddings_dimensions_state();++ let (status, body) = post_embeddings(+ state,+ json!({"model": "known/sparse", "input": "hello", "dimensions": 256}),+ )+ .await;++ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert_eq!(body["error"]["code"], "unsupported_field");+ assert_eq!(+ body["error"]["message"],+ "'dimensions' is not supported by this endpoint: model 'known/sparse' declares no dense embedding width."+ );+ }++ #[tokio::test]+ async fn test_openai_embeddings_rejects_non_integer_dimensions() {+ let (state, _bundles, _models) = embeddings_dimensions_state();++ let (status, body) = post_embeddings(+ state,+ json!({"model": "known/embedder", "input": "hello", "dimensions": "384"}),+ )+ .await;++ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert_eq!(body["error"]["code"], "invalid_request");+ assert_eq!(body["error"]["param"], "dimensions");+ }++ #[tokio::test]+ async fn test_openai_embeddings_dimensions_leave_unknown_and_hidden_models_to_dispatch() {+ let (state, _bundles, _models) = embeddings_dimensions_state();+ let ext = axum::http::Extensions::new();+ assert!(openai_embeddings_dimensions_error(+ &state,+ &json!({"dimensions": 256}),+ "unknown/model",+ &ext+ )+ .is_none());++ let mut responses = Vec::new();+ for body in [+ json!({"model": "known/embedder", "input": "hello", "dimensions": 256}),+ json!({"model": "known/embedder", "input": "hello"}),+ ] {+ let (mut state, _bundles, _models) = embeddings_dimensions_state();+ state.model_access_policy =+ Some(hiding_policy() as Arc<dyn crate::server::ModelAccessPolicy>);+ responses.push(post_embeddings(state, body).await);+ }+ assert_eq!(responses[0].0, StatusCode::NOT_FOUND);+ assert_eq!(+ responses[0], responses[1],+ "a hidden model must answer a bad 'dimensions' exactly like an absent model"+ );+ }+#[test]fn test_openai_embeddings_item_cap_accepts_256_and_rejects_257() {let accepted = json!(vec!["text"; MAX_EMBEDDING_INPUTS]);diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 4b19292de..a89e84d4c 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -1782,7 +1782,9 @@ pub struct OpenAIEmbeddingRequest {pub input: OpenAIEmbeddingInput,#[serde(default, skip_serializing_if = "Option::is_none")]pub encoding_format: Option<OpenAIEmbeddingEncodingFormat>,- /// Accepted but ignored; the gateway returns the model's native dimension.+ /// Requested embedding width. SIE always returns the model's native dense+ /// width, so this is accepted only when it equals that width; any other+ /// value is rejected with 400 `unsupported_field` rather than ignored.#[serde(default, skip_serializing_if = "Option::is_none")]pub dimensions: Option<u32>,/// Accepted but ignored; kept for OpenAI SDK compatibility.diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 4f14268cf..708dcec7c 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -1829,25 +1829,10 @@"type": "string"},"type": "array"- },- {- "items": {- "type": "integer"- },- "type": "array"- },- {- "items": {- "items": {- "type": "integer"- },- "type": "array"- },- "type": "array"}],"title": "Input",- "description": "Input text(s) or token array(s) to embed."+ "description": "Input text or list of texts to embed. Token-id arrays are rejected with 400."},"encoding_format": {"anyOf": [diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.pyindex 186c8b495..5a1a5597f 100644--- a/packages/sie_server/src/sie_server/api/encode.py+++ b/packages/sie_server/src/sie_server/api/encode.py@@ -298,40 +298,7 @@ async def encode(# Check if LoRA is specified and ensure it's loadedlora = options.get("lora_id")if lora is not None:- try:- is_ready, is_loading = await registry.ensure_lora_loaded_async(model, lora)- if is_loading:- # LoRA is loading - return 503 with retry hint- span.set_attribute("error", "lora_loading")- raise HTTPException(- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,- detail={- "code": ErrorCode.LORA_LOADING.value,- "message": f"LoRA '{lora}' is loading for model '{model}', please retry",- },- headers={"Retry-After": "1"},- )- if not is_ready:- # LoRA load failed- span.set_attribute("error", "lora_load_failed")- raise HTTPException(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail={- "code": ErrorCode.INFERENCE_ERROR.value,- "message": f"Failed to load LoRA '{lora}' for model '{model}'",- },- )- except ValueError as e:- # Model doesn't support LoRA- span.set_attribute("error", "lora_not_supported")- raise HTTPException(- status_code=status.HTTP_400_BAD_REQUEST,- detail={- "code": ErrorCode.INVALID_INPUT.value,- "message": str(e),- },- ) from e-+ await model_checker.ensure_lora_loaded(lora)# Worker batcher routes on options["lora"]; profile uses "lora_id".options["lora"] = loradiff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.pyindex 4c781fe7e..405fb9778 100644--- a/packages/sie_server/src/sie_server/api/helpers.py+++ b/packages/sie_server/src/sie_server/api/helpers.py@@ -450,6 +450,48 @@ class ModelStateChecker:headers={"Retry-After": "5"},)+ async def ensure_lora_loaded(self, lora: str) -> None:+ """Start loading a LoRA adapter if needed, raise 503 to retry.++ Args:+ lora: LoRA id selected by the resolved profile or request options.++ Raises:+ HTTPException: 503 ``LORA_LOADING`` with ``Retry-After`` while the+ adapter loads, 500 if it failed to load, 400 if the model does+ not support LoRA.+ """+ try:+ is_ready, is_loading = await self.registry.ensure_lora_loaded_async(self.model, lora)+ if is_loading:+ self.span.set_attribute("error", "lora_loading")+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "code": ErrorCode.LORA_LOADING.value,+ "message": f"LoRA '{lora}' is loading for model '{self.model}', please retry",+ },+ headers={"Retry-After": "1"},+ )+ if not is_ready:+ self.span.set_attribute("error", "lora_load_failed")+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail={+ "code": ErrorCode.INFERENCE_ERROR.value,+ "message": f"Failed to load LoRA '{lora}' for model '{self.model}'",+ },+ )+ except ValueError as e:+ self.span.set_attribute("error", "lora_not_supported")+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "code": ErrorCode.INVALID_INPUT.value,+ "message": str(e),+ },+ ) from e+async def validate_ready(self, device: str) -> None:"""Run all state checks to ensure model is ready for inference.diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.pyindex 027fe82eb..dbbbef28b 100644--- a/packages/sie_server/src/sie_server/api/openai_compat.py+++ b/packages/sie_server/src/sie_server/api/openai_compat.py@@ -3,10 +3,14 @@POST /v1/embeddings - Generate embeddings using OpenAI's API format.This enables zero-friction migration from OpenAI, Azure OpenAI, or any-OpenAI-compatible embedding service. Works with LangChain's OpenAIEmbeddings-class out of the box:+OpenAI-compatible embedding service. Input must be text; token-id arrays are+rejected with 400, so LangChain's OpenAIEmbeddings needs its client-side+tiktoken chunking turned off:- embeddings = OpenAIEmbeddings(base_url="http://localhost:8080/v1")+ embeddings = OpenAIEmbeddings(+ base_url="http://localhost:8080/v1",+ check_embedding_ctx_length=False,+ )This module implements the OpenAI-compatible embeddings API surface."""@@ -22,6 +26,7 @@ import numpy as npfrom fastapi import APIRouter, Header, HTTPException, Request, statusfrom fastapi.responses import JSONResponsefrom pydantic import BaseModel, ConfigDict, Field+from pydantic.json_schema import SkipJsonSchemafrom sie_server.api.helpers import (WORKER_DRAINED_RETRY_AFTER_S,@@ -30,8 +35,9 @@ from sie_server.api.helpers import (oom_retry_after_from_registry,openai_error_response,)+from sie_server.api.options import resolve_runtime_options_with_profilefrom sie_server.api.validation import validate_machine_profile_header-from sie_server.core.encode_pipeline import EncodePipeline+from sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_typesfrom sie_server.core.model_suggestions import suggestion_suffixfrom sie_server.core.oom import is_oom_errorfrom sie_server.core.worker import QueueFullError@@ -56,9 +62,10 @@ router = APIRouter(prefix="/v1", tags=["openai-compat"])# OpenAI-compatible request/response types-# Type alias for OpenAI input formats-# OpenAI accepts: string, array of strings, array of tokens, or array of token arrays-OpenAIInput = str | list[str] | list[int] | list[list[int]]+OpenAIInput = str | list[str]+# Parsed but never published, so the route can reject OpenAI token-id input+# with the same 400 envelope as the gateway instead of a 422.+TokenArrayInput = list[int] | list[list[int]]class OpenAIEmbeddingRequest(BaseModel):@@ -71,8 +78,8 @@ class OpenAIEmbeddingRequest(BaseModel):model: Annotated[str, Field(description="Model ID to use for embedding")]input: Annotated[- OpenAIInput,- Field(description="Input text(s) or token array(s) to embed."),+ OpenAIInput | SkipJsonSchema[TokenArrayInput],+ Field(description="Input text or list of texts to embed. Token-id arrays are rejected with 400."),]encoding_format: Annotated[Literal["float", "base64"] | None,@@ -146,85 +153,29 @@ def _estimate_tokens(texts: list[str]) -> int:return max(1, total_chars // 4)-def _normalize_input(input_data: OpenAIInput, registry: object, model: str) -> tuple[list[str], int]:- """Normalize OpenAI input format to list of strings.-- OpenAI accepts:- - str: single text- - list[str]: multiple texts- - list[int]: single token array- - list[list[int]]: multiple token arrays-- Args:- input_data: Raw input from request- registry: Model registry (for tokenizer access)- model: Model name+def _normalize_input(input_data: OpenAIInput | TokenArrayInput) -> list[str]:+ """Return the request's input as a list of texts.- Returns:- Tuple of (list of texts, token count)+ Raises:+ HTTPException: 400 ``invalid_request`` for token-id input, which SIE+ cannot map back to the text the caller tokenized."""- # Single stringif isinstance(input_data, str):- return [input_data], _estimate_tokens([input_data])-- # Empty list- if not input_data:- return [], 0-- # Check if it's a token array (list[int]) or list of token arrays (list[list[int]])- first = input_data[0]-- if isinstance(first, str):- # list[str] - multiple texts- return list(input_data), _estimate_tokens(input_data) # type: ignore-- if isinstance(first, int):- # list[int] - single token array, decode it- token_count = len(input_data)- text = _decode_tokens(input_data, registry, model) # type: ignore- return [text], token_count-- if isinstance(first, list):- # list[list[int]] - multiple token arrays- texts = []- token_count = 0- for tokens in input_data:- if isinstance(tokens, list) and all(isinstance(t, int) for t in tokens):- texts.append(_decode_tokens(tokens, registry, model))- token_count += len(tokens)- else:- # Unexpected format- texts.append(str(tokens))- return texts, token_count-- # Fallback: convert to string- return [str(input_data)], 1---def _decode_tokens(tokens: list[int], registry: object, model: str) -> str:- """Decode token IDs back to text using the model's tokenizer.-- Args:- tokens: List of token IDs- registry: Model registry- model: Model name-- Returns:- Decoded text string- """- try:- preprocessor_registry = registry.preprocessor_registry # type: ignore- if preprocessor_registry.has_preprocessor(model, "text"):- tokenizer = preprocessor_registry.get_tokenizer(model)- if tokenizer is not None:- return tokenizer.decode(tokens, skip_special_tokens=True)- except (AttributeError, TypeError, ValueError) as e:- logger.debug("Token decoding failed for model %s: %s", model, e)-- # Fallback: can't decode, return placeholder- # This happens if the model doesn't have a registered tokenizer- logger.warning("Cannot decode tokens for model %s, using placeholder", model)- return f"[{len(tokens)} tokens]"+ return [input_data]+ texts = [value for value in input_data if isinstance(value, str)]+ if len(texts) == len(input_data):+ return texts+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "error": {+ "code": "invalid_request",+ "message": "token-array embeddings input is not supported; use text input",+ "type": "invalid_request_error",+ "param": "input",+ }+ },+ )def _openai_state_error(error: HTTPException) -> HTTPException:@@ -299,7 +250,6 @@ def _build_embeddings_response(texts: list[str],model: str,encoding_format: str,- token_count: int | None = None,) -> OpenAIEmbeddingResponse:"""Build OpenAI-format response from encoding results.@@ -308,7 +258,6 @@ def _build_embeddings_response(texts: Input textsmodel: Model nameencoding_format: "float" or "base64"- token_count: Known token count (from token input), or None to estimate"""embeddings_data: list[OpenAIEmbeddingData] = []@@ -345,9 +294,7 @@ def _build_embeddings_response())- # Use provided token count or estimate- if token_count is None or token_count == 0:- token_count = _estimate_tokens(texts)+ token_count = _estimate_tokens(texts)return OpenAIEmbeddingResponse(object="list",@@ -443,7 +390,7 @@ async def _create_embeddings(registry = http_request.app.state.registry- # Check if model exists first (needed for token decoding)+ # Check if model exists firstif not registry.has_model(model):span.set_attribute("error", "model_not_found")raise HTTPException(@@ -475,8 +422,7 @@ async def _create_embeddings(},)- # Normalize input (handles strings, token arrays, etc.)- texts, token_count = _normalize_input(request.input, registry, model)+ texts = _normalize_input(request.input)if not texts:raise HTTPException(@@ -526,6 +472,33 @@ async def _create_embeddings(config = registry.get_config(model)+ # Same profile resolution as native /v1/encode with no request params,+ # which is the body the gateway rewrites this route into.+ options, selected_profile = resolve_runtime_options_with_profile(config, None, span)+ # The OpenAI response format carries float vectors only.+ options["output_dtype"] = "float32"+ try:+ adapter_output_types, response_output_types = resolve_encode_output_types(+ config, ["dense"], selected_profile, options+ )+ except ValueError as e:+ span.set_attribute("error", "unsupported_output_types")+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "error": {+ "code": "invalid_request",+ "message": str(e),+ "type": "invalid_request_error",+ "param": "model",+ }+ },+ ) from e+ lora = options.get("lora_id")+ if lora is not None:+ await checker.ensure_lora_loaded(lora)+ options["lora"] = lora+# Run encodingtelemetry_enabled = worker_telemetry_enabled()inference_started = time.perf_counter() if telemetry_enabled else None@@ -534,11 +507,12 @@ async def _create_embeddings(registry=registry,model=model,items=items,- output_types=["dense"],- instruction=None,+ output_types=adapter_output_types,+ instruction=options.get("instruction"),config=config,- is_query=False,- options={},+ is_query=bool(options.get("is_query", False)),+ options=options,+ response_output_types=response_output_types,)except QueueFullError as e:span.set_attribute("error", "queue_full")@@ -659,4 +633,4 @@ async def _create_embeddings(postprocessing_s=timing.postprocessing_ms / 1000.0,units=units,)- return _build_embeddings_response(results, texts, model, encoding_format, token_count)+ return _build_embeddings_response(results, texts, model, encoding_format)diff --git a/packages/sie_server/tests/api/test_openai_compat.py b/packages/sie_server/tests/api/test_openai_compat.pyindex eab660bef..d8c518874 100644--- a/packages/sie_server/tests/api/test_openai_compat.py+++ b/packages/sie_server/tests/api/test_openai_compat.py@@ -1,6 +1,8 @@"""Tests for OpenAI-compatible embeddings endpoint."""import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Pathfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch@@ -8,13 +10,47 @@ import numpy as npimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from sie_server.api.encode import router as encode_routerfrom sie_server.api.openai_compat import router as openai_router-from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.config.model import AdapterOptions, EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.load_errors import LoadErrorClass, LoadFailurefrom sie_server.core.oom import ResourceExhausted, ResourceExhaustedError+from sie_server.core.postprocessor_registry import PostprocessorRegistry+from sie_server.core.preprocessor_registry import PreprocessorRegistryfrom sie_server.core.registry import ModelRegistryfrom sie_server.types.inputs import MAX_ITEM_TEXT_BYTES+# A fake embedder whose vector depends on the runtime options it receives, so a+# route that drops profile options produces a different vector.+_OPTION_AWARE_ADAPTER_SOURCE = """+import hashlib++import numpy as np++from sie_server.adapters._utils import extract_texts, resolve_embedding_options+from sie_server.adapters.fake.adapter import FakeAdapter+from sie_server.core.inference_output import EncodeOutput+++class OptionAwareFakeAdapter(FakeAdapter):+ def encode(self, items, output_types, *, instruction=None, is_query=False, prepared_items=None, options=None):+ _, pooling, query_template, doc_template = resolve_embedding_options(+ options,+ default_normalize=True,+ default_pooling="mean",+ default_query_template=None,+ default_doc_template=None,+ )+ texts = extract_texts(+ items, instruction, is_query=is_query, query_template=query_template, doc_template=doc_template+ )+ digests = [hashlib.sha256(f"{pooling}|{text}".encode()).digest()[:8] for text in texts]+ dense = np.stack([np.frombuffer(digest, dtype=np.uint8) for digest in digests]).astype(np.float32)+ return EncodeOutput(dense=dense, is_query=is_query, dense_dim=8)+"""++_PROFILED_MODEL = "test/profiled-embedder"+def _mock_encode_impl(items: list[Any], output_types: list[str], **kwargs: Any) -> Any:"""Implementation for mock encode - returns EncodeOutput."""@@ -61,13 +97,12 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:profiles={"default": ProfileConfig(adapter_path="test:TestAdapter", max_batch_tokens=8192)},)registry.model_names = ["text-embedding-3-small"]- # Mock preprocessor_registry to NOT have a tokenizer (use direct adapter path)- preprocessor_registry = MagicMock()- preprocessor_registry.has_tokenizer.return_value = False+ # No registered text preprocessor, so encode takes the direct adapter path.+ preprocessor_registry = MagicMock(spec=PreprocessorRegistry)preprocessor_registry.has_preprocessor.return_value = Falseregistry.preprocessor_registry = preprocessor_registry- postprocessor_registry = MagicMock()+ postprocessor_registry = MagicMock(spec=PostprocessorRegistry)postprocessor_registry.transform_sync.return_value = 0registry.postprocessor_registry = postprocessor_registry@@ -246,6 +281,31 @@ class TestOpenAIEmbeddings:}mock_adapter.encode.assert_not_called()+ @pytest.mark.parametrize(+ "token_input",+ [[9906, 1917], [[9906, 1917], [3923, 374]], [[]]],+ ids=["token-array", "token-arrays", "empty-token-array"],+ )+ def test_token_id_input_rejected_like_the_gateway(+ self, client: TestClient, mock_adapter: MagicMock, token_input: list[Any]+ ) -> None:+ """Token ids cannot be mapped back to text, so they must fail instead of embedding a placeholder."""+ response = client.post(+ "/v1/embeddings",+ json={"model": "text-embedding-3-small", "input": token_input},+ )++ assert response.status_code == 400+ assert response.json() == {+ "error": {+ "message": "token-array embeddings input is not supported; use text input",+ "type": "invalid_request_error",+ "param": "input",+ "code": "invalid_request",+ }+ }+ mock_adapter.encode.assert_not_called()+def test_unhonourable_dimensions_rejected(self, client: TestClient) -> None:"""A width SIE cannot produce must fail, not be silently ignored.@@ -537,3 +597,214 @@ class TestOpenAIEmbeddingsOom:error = data["error"]assert error["code"] == "RESOURCE_EXHAUSTED"assert error["type"] == "server_error"+++def _profiled_embedder_config() -> ModelConfig:+ return ModelConfig.model_validate(+ {+ "sie_id": _PROFILED_MODEL,+ "package_backed": True,+ "inputs": {"text": True},+ "tasks": {"encode": {"dense": {"dim": 8}}},+ "max_sequence_length": 512,+ "profiles": {+ "default": {+ "max_batch_tokens": 8192,+ "adapter_path": "option_aware_adapter.py:OptionAwareFakeAdapter",+ "adapter_options": {+ "loadtime": {"dense_dim": 8},+ "runtime": {+ "pooling": "last",+ "query_template": "query: {text}",+ "doc_template": "passage: {text}",+ },+ },+ },+ "cls": {+ "extends": "default",+ "adapter_options": {+ "runtime": {"pooling": "cls", "doc_template": "search_document: {text}"},+ },+ },+ },+ }+ )+++class TestOpenAIEmbeddingsProfileParity:+ """/v1/embeddings must embed exactly what native /v1/encode embeds.++ Runs the real registry, worker, and encode pipeline. Only the adapter is a+ weightless fake, and its vector depends on the profile's pooling and+ document template, like a real embedder's does.+ """++ @pytest.fixture+ def app(self, tmp_path: Path) -> FastAPI:+ (tmp_path / "option_aware_adapter.py").write_text(_OPTION_AWARE_ADAPTER_SOURCE)+ registry = ModelRegistry()+ registry.add_config(_profiled_embedder_config(), model_dir=tmp_path)+ app = FastAPI()+ app.include_router(encode_router)+ app.include_router(openai_router)+ app.state.registry = registry+ return app++ def test_profile_runtime_options_match_native_encode(self, app: FastAPI) -> None:+ registry: ModelRegistry = app.state.registry+ texts = ["hello world", "second text"]+ vectors: dict[str, list[list[float]]] = {}+ with TestClient(app) as client:+ portal = client.portal+ assert portal is not None+ try:+ for model in (_PROFILED_MODEL, f"{_PROFILED_MODEL}:cls"):+ portal.call(registry.load_async, model, "cpu")+ native = client.post(+ f"/v1/encode/{model}",+ json={"items": [{"text": text} for text in texts]},+ headers={"Accept": "application/json"},+ )+ openai = client.post("/v1/embeddings", json={"model": model, "input": texts})++ assert native.status_code == 200, native.text+ assert openai.status_code == 200, openai.text+ native_vectors = [item["dense"]["values"] for item in native.json()["items"]]+ vectors[model] = [item["embedding"] for item in openai.json()["data"]]+ assert vectors[model] == native_vectors, model+ finally:+ portal.call(registry.unload_all_async)++ assert vectors[_PROFILED_MODEL] != vectors[f"{_PROFILED_MODEL}:cls"]+++class TestOpenAIEmbeddingsProfileResolution:+ """Profile-level encode settings that are not vector-shaping options."""++ def test_profile_lora_is_loaded_and_routed(+ self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock+ ) -> None:+ mock_registry.get_config.return_value = ModelConfig(+ sie_id="text-embedding-3-small",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:TestAdapter",+ max_batch_tokens=8192,+ adapter_options=AdapterOptions(+ runtime={"lora_id": "org/test-lora", "instruction": "Classify banking intent"}+ ),+ )+ },+ )+ mock_registry.ensure_lora_loaded_async = AsyncMock(return_value=(True, False))++ response = client.post("/v1/embeddings", json={"model": "text-embedding-3-small", "input": "hello"})++ assert response.status_code == 200, response.text+ mock_registry.ensure_lora_loaded_async.assert_awaited_once_with("text-embedding-3-small", "org/test-lora")+ call = mock_adapter.encode.call_args+ assert call.kwargs["options"]["lora"] == "org/test-lora"+ assert call.kwargs["instruction"] == "Classify banking intent"+ assert call.kwargs["is_query"] is False++ def test_profile_lora_still_loading_is_retryable(+ self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock+ ) -> None:+ mock_registry.get_config.return_value = ModelConfig(+ sie_id="text-embedding-3-small",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:TestAdapter",+ max_batch_tokens=8192,+ adapter_options=AdapterOptions(runtime={"lora_id": "org/test-lora"}),+ )+ },+ )+ mock_registry.ensure_lora_loaded_async = AsyncMock(return_value=(False, True))++ response = client.post("/v1/embeddings", json={"model": "text-embedding-3-small", "input": "hello"})++ assert response.status_code == 503, response.text+ assert response.headers.get("Retry-After") == "1"+ error = response.json()["error"]+ assert error["code"] == "LORA_LOADING"+ assert error["type"] == "server_error"+ mock_adapter.encode.assert_not_called()++ def test_profile_lora_unsupported_is_an_openai_client_error(+ self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock+ ) -> None:+ mock_registry.get_config.return_value = ModelConfig(+ sie_id="text-embedding-3-small",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:TestAdapter",+ max_batch_tokens=8192,+ adapter_options=AdapterOptions(runtime={"lora_id": "org/test-lora"}),+ )+ },+ )+ mock_registry.ensure_lora_loaded_async = AsyncMock(side_effect=ValueError("Model does not support LoRA"))++ response = client.post("/v1/embeddings", json={"model": "text-embedding-3-small", "input": "hello"})++ assert response.status_code == 400, response.text+ assert response.json() == {+ "error": {+ "message": "Model does not support LoRA",+ "type": "invalid_request_error",+ "param": None,+ "code": "INVALID_INPUT",+ }+ }+ mock_adapter.encode.assert_not_called()++ def test_profile_output_dtype_cannot_quantize_openai_vectors(+ self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock+ ) -> None:+ mock_registry.get_config.return_value = ModelConfig(+ sie_id="text-embedding-3-small",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:TestAdapter",+ max_batch_tokens=8192,+ adapter_options=AdapterOptions(runtime={"output_dtype": "int8"}),+ )+ },+ )+ with ThreadPoolExecutor(max_workers=1) as cpu_pool:+ mock_registry.postprocessor_registry = PostprocessorRegistry(cpu_pool)++ response = client.post("/v1/embeddings", json={"model": "text-embedding-3-small", "input": "hello"})++ assert response.status_code == 200, response.text+ assert mock_adapter.encode.call_args.kwargs["options"]["output_dtype"] == "float32"+ assert response.json()["data"][0]["embedding"] == pytest.approx([0.1, 0.2, 0.3])++ def test_model_without_dense_output_rejected(+ self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock+ ) -> None:+ mock_registry.get_config.return_value = ModelConfig(+ sie_id="text-embedding-3-small",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(sparse=EmbeddingDim(dim=30522))),+ profiles={"default": ProfileConfig(adapter_path="test:TestAdapter", max_batch_tokens=8192)},+ )++ response = client.post("/v1/embeddings", json={"model": "text-embedding-3-small", "input": "hello"})++ assert response.status_code == 400, response.text+ error = response.json()["error"]+ assert error["code"] == "invalid_request"+ assert error["type"] == "invalid_request_error"+ assert error["param"] == "model"+ assert "does not support output types" in error["message"]+ mock_adapter.encode.assert_not_called()