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(gateway): accept and ignore metadata, store and service_tier on chat completions (#973)
Shai Shmuele58777abb5eb
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex e86cf1ba3..f0b1390ee 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -395,7 +395,7 @@"type": "object"},"ChatCompletionRequest": {- "description": "OpenAI-compatible ``POST /v1/chat/completions`` request.\n\n**Strict allow-list:** unknown top-level fields reject with 400\n``unsupported_field``. Type-invalid values for accepted fields reject\nwith 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead.\n- ``modalities``, ``audio``, ``metadata``, ``store``, ``service_tier``,\n ``prediction``, ``verbosity`` — out of scope.\n\n**Streaming:** ``stream: true`` is supported (SSE ``chat.completion.chunk``).\n``n > 1`` streaming fans candidates out as per-``choice_index``-tagged delta\nchunks with a per-choice closure carrying ``finish_reason`` (and a per-choice\n``delta.role:\"assistant\"`` once per choice) before the single global ``[DONE]``.",+ "description": "OpenAI-compatible ``POST /v1/chat/completions`` request.\n\n**Strict allow-list:** unknown top-level fields reject with 400\n``unsupported_field``. Type-invalid values for accepted fields reject\nwith 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead.\n- ``modalities``, ``audio``, ``prediction``, ``verbosity`` — out of scope.\n\n**Accepted and ignored**: ``metadata``, ``store`` and ``service_tier`` are\ntype-checked, never forwarded, and have no effect on the request.\n\n**Streaming:** ``stream: true`` is supported (SSE ``chat.completion.chunk``).\n``n > 1`` streaming fans candidates out as per-``choice_index``-tagged delta\nchunks with a per-choice closure carrying ``finish_reason`` (and a per-choice\n``delta.role:\"assistant\"`` once per choice) before the single global ``[DONE]``.","properties": {"best_of": {"description": "Generate this many candidates and return the top `n` by cumulative logprob. Integer in [1, 128]. Cross-field rule: `best_of >= n` (otherwise 400 invalid_request). Rejected with 400 unsupported_field when `stream: true` (mirrors OpenAI).",@@ -486,6 +486,13 @@},"type": "array"},+ "metadata": {+ "description": "OpenAI ``metadata`` — accepted and ignored (never forwarded).",+ "type": [+ "object",+ "null"+ ]+ },"min_tokens": {"description": "SGLang ``sampling_params.min_new_tokens``: integer ``>= 0`` capping\nhow many tokens the model must emit before any stop condition can\nfire. Use to work around models that occasionally emit the stop\ntoken as the very first decoded token (e.g. Qwen3.6 thinking-off\nunder greedy decode). Absent → sampler default (no minimum).","format": "int32",@@ -597,6 +604,13 @@"null"]},+ "service_tier": {+ "description": "OpenAI ``service_tier`` — accepted and ignored (never forwarded).",+ "type": [+ "string",+ "null"+ ]+ },"stop": {"description": "Either a string or an array of strings, mirroring OpenAI.","oneOf": [@@ -611,6 +625,13 @@}]},+ "store": {+ "description": "OpenAI ``store`` — accepted and ignored (never forwarded).",+ "type": [+ "boolean",+ "null"+ ]+ },"stream": {"description": "SSE streaming. When true, the response is a stream of `chat.completion.chunk` events terminated by `data: [DONE]`. For n > 1: per-`choice_index` delta chunks include a per-choice `delta.role:\"assistant\"` once per choice; per-choice closure chunks carry the `finish_reason` for that choice before the global `[DONE]`. Non-boolean values reject with 400 invalid_request.","type": [diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 00e0a17bd..f5b2f329a 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -6770,6 +6770,9 @@ fn decode_video_data_uri(value: &serde_json::Value) -> Result<(String, String),/// ``stream`` / ``stream_options``./// * ``user`` (debug-log only), ``safety_identifier`` (silent),/// ``prompt_cache_key`` (plumbed), ``routing_key`` (plumbed)+/// * ``metadata`` (object), ``store`` (boolean), ``service_tier`` (string) —+/// accepted for OpenAI SDK compatibility and ignored: type-checked, never+/// forwarded, no effect on the request.////// Any field outside this set surfaces as 400 with/// ``code: "unsupported_field"`` and ``param`` set to the offending field@@ -7600,6 +7603,29 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {// (decision 0.2 in plan §0). We just acknowledge its presence by// not rejecting it.let _ = obj.get("safety_identifier");+ // ``metadata`` / ``store`` / ``service_tier`` — standard OpenAI SDK+ // clients send these and SIE has no use for them. They are+ // type-checked, then dropped: never forwarded to the worker.+ for (fname, well_typed, expected) in [+ (+ "metadata",+ serde_json::Value::is_object as fn(&serde_json::Value) -> bool,+ "an object",+ ),+ ("store", serde_json::Value::is_boolean, "a boolean"),+ ("service_tier", serde_json::Value::is_string, "a string"),+ ] {+ if obj+ .get(fname)+ .is_some_and(|v| !v.is_null() && !well_typed(v))+ {+ return bad(+ &format!("'{fname}' must be {expected}"),+ Some(fname),+ oai_code::INVALID_REQUEST,+ );+ }+ }// ``seed`` — validate once across every generation route and preserve the// signed value on the worker wire. ``null`` and absent are both no-ops.let seed = match parse_seed_field(obj.get("seed")) {@@ -7774,9 +7800,6 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {"function_call","modalities","audio",- "metadata",- "store",- "service_tier","prediction","verbosity",] {@@ -7935,6 +7958,9 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {"lora_adapter","user","safety_identifier",+ "metadata",+ "store",+ "service_tier","seed","logprobs","top_logprobs",@@ -27525,6 +27551,52 @@ mod tests {assert_eq!(p.messages[2].tool_call_id.as_deref(), Some("call_1"));}+ #[tokio::test]+ async fn test_chat_params_from_json_ignores_metadata_store_service_tier() {+ let baseline = format!("{:?}", _expect_chat_ok(_chat_body_min("m")));+ let mut body = _chat_body_min("m");+ body["metadata"] = serde_json::json!({"run": "eval-7"});+ body["store"] = serde_json::json!(true);+ body["service_tier"] = serde_json::json!("auto");+ assert_eq!(format!("{:?}", _expect_chat_ok(body)), baseline);+ // ``null`` is the SDK's "unset" and is accepted too.+ for fname in ["metadata", "store", "service_tier"] {+ let mut body = _chat_body_min("m");+ body[fname] = serde_json::Value::Null;+ assert_eq!(format!("{:?}", _expect_chat_ok(body)), baseline);+ }++ for (fname, wrong) in [+ ("metadata", serde_json::json!("run")),+ ("store", serde_json::json!("yes")),+ ("service_tier", serde_json::json!(1)),+ ] {+ let mut body = _chat_body_min("m");+ body[fname] = wrong;+ let v = _expect_chat_err(body).await;+ assert_eq!(v["error"]["code"], "invalid_request");+ assert_eq!(v["error"]["param"], fname);+ }+ }++ #[tokio::test]+ async fn test_chat_params_from_json_still_rejects_out_of_scope_openai_fields() {+ for fname in [+ "functions",+ "function_call",+ "modalities",+ "audio",+ "prediction",+ "verbosity",+ ] {+ let mut body = _chat_body_min("m");+ body[fname] = serde_json::json!({});+ let v = _expect_chat_err(body).await;+ assert_eq!(v["error"]["code"], "unsupported_field");+ assert_eq!(v["error"]["param"], fname);+ }+ }+#[tokio::test]async fn test_chat_params_from_json_rejects_unknown_field() {let mut body = _chat_body_min("m");diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex b31ef0e7e..15f5f5289 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -2292,8 +2292,10 @@ pub struct ChatTemplateKwargs {////// **Known-rejected fields**:/// - ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead.-/// - ``modalities``, ``audio``, ``metadata``, ``store``, ``service_tier``,-/// ``prediction``, ``verbosity`` — out of scope.+/// - ``modalities``, ``audio``, ``prediction``, ``verbosity`` — out of scope.+///+/// **Accepted and ignored**: ``metadata``, ``store`` and ``service_tier`` are+/// type-checked, never forwarded, and have no effect on the request.////// **Streaming:** ``stream: true`` is supported (SSE ``chat.completion.chunk``)./// ``n > 1`` streaming fans candidates out as per-``choice_index``-tagged delta@@ -2380,6 +2382,16 @@ pub struct ChatCompletionRequest {/// Accepted and silently ignored (never logged, never forwarded).#[serde(default, skip_serializing_if = "Option::is_none")]pub safety_identifier: Option<String>,+ /// OpenAI ``metadata`` — accepted and ignored (never forwarded).+ #[schema(value_type = Option<Object>)]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub metadata: Option<Value>,+ /// OpenAI ``store`` — accepted and ignored (never forwarded).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub store: Option<bool>,+ /// OpenAI ``service_tier`` — accepted and ignored (never forwarded).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub service_tier: Option<String>,/// Prompt-cache hint; plumbed onto the work envelope and/// ignored by the worker on the chat-completions surface.#[serde(default, skip_serializing_if = "Option::is_none")]diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 12733c69b..dbad2217a 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -161,6 +161,14 @@ _ANSWER_FINISH_REASONS = frozenset({"stop", "tool_calls"})# Compatibility requests project onto the same native score bound._MAX_RERANK_DOCS = MAX_SCORE_ITEMS+# OpenAI request fields that standard SDK clients send and SIE has no use for.+# They are type-checked, then dropped before the request reaches an engine.+_IGNORED_CHAT_FIELDS: dict[str, tuple[type, str]] = {+ "metadata": (dict, "an object"),+ "store": (bool, "a boolean"),+ "service_tier": (str, "a string"),+}+# Mirror the gateway's public chat field boundary, minus controls that require# gateway-owned admission/routing translation (best_of, cache# keys). Most importantly this excludes SGLang's backend/DP/custom-processor@@ -198,6 +206,7 @@ _CUDA_CHAT_FIELDS = frozenset("parallel_tool_calls","stream_options","lora_adapter",+ *_IGNORED_CHAT_FIELDS,})@@ -231,6 +240,7 @@ _MLX_CHAT_FIELDS = frozenset("tool_choice","parallel_tool_calls","role_mapping",+ *_IGNORED_CHAT_FIELDS,})@@ -562,6 +572,9 @@ def _validate_cuda_chat_body(body: dict[str, Any]) -> None:def _validate_common_chat_body(body: dict[str, Any]) -> None:+ for field, (expected, description) in _IGNORED_CHAT_FIELDS.items():+ if body.get(field) is not None and not isinstance(body[field], expected):+ raise _bad_request(f"'{field}' must be {description}", param=field)response_format = body.get("response_format")if response_format is not None and not isinstance(response_format, dict):raise _bad_request("'response_format' must be an object", param="response_format")@@ -861,6 +874,8 @@ def _prepare_chat_body(# SIE owns these edge-only identifiers; do not send unknown metadata into# the engine process.proxied.pop("safety_identifier", None)+ for field in _IGNORED_CHAT_FIELDS:+ proxied.pop(field, None)proxied.pop("schema_in_prompt", None)proxied.pop("include_reasoning", None)proxied.pop("reasoning_effort", None)@@ -1015,6 +1030,8 @@ def _prepare_mlx_body(proxied = dict(body)proxied.pop("include_reasoning", None)proxied.pop("reasoning_effort", None)+ for field in _IGNORED_CHAT_FIELDS:+ proxied.pop(field, None)proxied["model"] = adapter.mlx_reporequested_cap = max_completion_tokens if max_completion_tokens is not None else max_tokensif requested_cap is not None and requested_cap > cap:diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex 4d325eee5..60857bb24 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -3103,3 +3103,93 @@ def test_mlx_messages_refuse_a_prompt_over_the_window_with_the_compaction_wordin"type": "invalid_request_error","message": f"prompt is too long: {42 + 32} tokens > {_WINDOW} maximum",}+++_IGNORED_OPENAI_FIELDS = {"metadata": {"run": "eval-7"}, "store": True, "service_tier": "auto"}+++def _chat_client_for(+ engine: str, monkeypatch: pytest.MonkeyPatch, handler: Callable[[httpx.Request], httpx.Response]+) -> TestClient:+ if engine == "cuda":+ return _cuda_chat_client(monkeypatch, handler)[0]+ return _mlx_chat_client(monkeypatch, handler, chat_template_kwargs={"enable_thinking": False})[0]++[email protected]("engine", ["cuda", "mlx"])[email protected]("extra", [_IGNORED_OPENAI_FIELDS, dict.fromkeys(_IGNORED_OPENAI_FIELDS)])+def test_chat_accepts_and_drops_metadata_store_service_tier(+ monkeypatch: pytest.MonkeyPatch, engine: str, extra: dict[str, Any]+) -> None:+ forwarded: list[dict[str, Any]] = []++ def _handler(request: httpx.Request) -> httpx.Response:+ forwarded.append(json.loads(request.content))+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-test",+ "object": "chat.completion",+ "created": 1,+ "model": "served",+ "choices": [+ {"index": 0, "message": {"role": "assistant", "content": "Hello"}, "finish_reason": "stop"}+ ],+ "usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4},+ },+ )++ client = _chat_client_for(engine, monkeypatch, _handler)+ body = {"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 8}++ plain = client.post("/v1/chat/completions", json=body)+ with_fields = client.post("/v1/chat/completions", json={**body, **extra})++ assert plain.status_code == 200+ assert with_fields.status_code == 200+ # The engine sees the same request either way: the fields are not forwarded.+ assert forwarded[1] == forwarded[0]+ assert not forwarded[1].keys() & _IGNORED_OPENAI_FIELDS.keys()+ assert with_fields.json()["choices"] == plain.json()["choices"]++[email protected]("engine", ["cuda", "mlx"])+ ("field", "value", "expected"),+ [("metadata", "run", "an object"), ("store", "yes", "a boolean"), ("service_tier", 1, "a string")],+)+def test_chat_rejects_wrongly_typed_metadata_store_service_tier(+ monkeypatch: pytest.MonkeyPatch, engine: str, field: str, value: Any, expected: str+) -> None:+ client = _chat_client_for(+ engine, monkeypatch, lambda _request: pytest.fail("rejected request must not reach the engine")+ )++ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], field: value},+ )++ assert response.status_code == 400+ assert response.json()["error"]["param"] == field+ assert response.json()["error"]["message"] == f"'{field}' must be {expected}"+ assert response.json()["error"]["code"] != "unsupported_field"++[email protected]("engine", ["cuda", "mlx"])[email protected]("field", ["functions", "function_call", "modalities", "audio", "prediction", "verbosity"])+def test_chat_still_rejects_out_of_scope_openai_fields(+ monkeypatch: pytest.MonkeyPatch, engine: str, field: str+) -> None:+ client = _chat_client_for(+ engine, monkeypatch, lambda _request: pytest.fail("rejected request must not reach the engine")+ )++ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], field: {}},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == field