Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat: accept reasoning_effort on chat completions (#955)
Krisztian Gajdarc570c1b6889c
diff --git a/conformance/anthropic_messages/claude_code_requests.json b/conformance/anthropic_messages/claude_code_requests.jsonindex 275a1c4f5..7b7807c53 100644--- a/conformance/anthropic_messages/claude_code_requests.json+++ b/conformance/anthropic_messages/claude_code_requests.json@@ -665,7 +665,7 @@"stream": true},"expect": {- "error": "output_config.effort: Extra inputs are not permitted"+ "error": "messages.1.role: role \"system\" is not supported in messages; use the top-level system parameter"}},{@@ -5516,7 +5516,7 @@"stream": true},"expect": {- "error": "output_config.effort: Extra inputs are not permitted"+ "error": "messages.1.role: role \"system\" is not supported in messages; use the top-level system parameter"}},{@@ -5674,7 +5674,17 @@"stream": true},"expect": {- "error": "output_config.effort: Extra inputs are not permitted"+ "chat": {+ "roles": [+ "system",+ "user"+ ],+ "stream": true,+ "max_tokens": 32768,+ "tool_count": 3,+ "include_reasoning": true,+ "reasoning_effort": "high"+ }}},{diff --git a/conformance/anthropic_messages/error_vectors.json b/conformance/anthropic_messages/error_vectors.jsonindex 7374dda20..0d4292ec5 100644--- a/conformance/anthropic_messages/error_vectors.json+++ b/conformance/anthropic_messages/error_vectors.json@@ -133,6 +133,12 @@"headers": {"retry-after": "5"},"body": {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}, "request_id": null},"expect": {"status": 529, "type": "overloaded_error", "message": "Overloaded", "headers": {"retry-after": "5", "x-should-retry": "true"}}+ },+ {+ "name": "model without a reasoning_effort declaration",+ "status": 400,+ "body": {"error": {"message": "Model 'm' does not support reasoning_effort", "type": "invalid_request_error", "param": "reasoning_effort", "code": "unsupported_field"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "output_config.effort: Extra inputs are not permitted", "headers": {"x-sie-error-code": "unsupported_field"}}}]}diff --git a/conformance/anthropic_messages/request_vectors.json b/conformance/anthropic_messages/request_vectors.jsonindex b55d05a3c..6e64d3f83 100644--- a/conformance/anthropic_messages/request_vectors.json+++ b/conformance/anthropic_messages/request_vectors.json@@ -409,6 +409,16 @@"name": "empty output_config is accepted","body": {"model": "m", "max_tokens": 16, "output_config": {}, "messages": [{"role": "user", "content": "x"}]},"chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": false}+ },+ {+ "name": "output_config effort becomes reasoning_effort",+ "body": {"model": "m", "max_tokens": 16, "output_config": {"effort": "high"}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": false, "reasoning_effort": "high"}+ },+ {+ "name": "null output_config effort is accepted",+ "body": {"model": "m", "max_tokens": 16, "output_config": {"effort": null}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": false}}],"rejected": [@@ -419,7 +429,8 @@{"name": "missing messages", "body": {"model": "m", "max_tokens": 1}, "message": "messages: Field required"},{"name": "empty messages", "body": {"model": "m", "max_tokens": 1, "messages": []}, "message": "messages: List should have at least 1 item"},{"name": "unknown top-level field", "body": {"model": "m", "max_tokens": 1, "service_tier": "auto", "messages": [{"role": "user", "content": "x"}]}, "message": "service_tier: Extra inputs are not permitted"},- {"name": "effort", "body": {"model": "m", "max_tokens": 1, "output_config": {"effort": "high"}, "messages": [{"role": "user", "content": "x"}]}, "message": "output_config.effort: Extra inputs are not permitted"},+ {"name": "effort outside Anthropic's values", "body": {"model": "m", "max_tokens": 1, "output_config": {"effort": "none"}, "messages": [{"role": "user", "content": "x"}]}, "message": "output_config.effort: Input should be 'low', 'medium', 'high', 'xhigh' or 'max'"},+ {"name": "effort beside another output_config key", "body": {"model": "m", "max_tokens": 1, "output_config": {"effort": "low", "format": {"type": "json_schema"}}, "messages": [{"role": "user", "content": "x"}]}, "message": "output_config.format: Extra inputs are not permitted"},{"name": "structured output format", "body": {"model": "m", "max_tokens": 1, "output_config": {"format": {"type": "json_schema"}}, "messages": [{"role": "user", "content": "x"}]}, "message": "output_config.format: Extra inputs are not permitted"},{"name": "context management", "body": {"model": "m", "max_tokens": 1, "context_management": {"edits": []}, "messages": [{"role": "user", "content": "x"}]}, "message": "context_management: Extra inputs are not permitted (Claude Code: set CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)"},{"name": "unsupported anthropic-version", "anthropic_version": "2024-01-01", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}]}, "message": "anthropic-version: only 2023-06-01 is supported"},diff --git a/conformance/openai_generation/reasoning_effort_vectors.json b/conformance/openai_generation/reasoning_effort_vectors.jsonnew file mode 100644index 000000000..e903575aa--- /dev/null+++ b/conformance/openai_generation/reasoning_effort_vectors.json@@ -0,0 +1,117 @@+{+ "description": [+ "Chat completions reasoning_effort, read by the gateway and the single-instance server suites.",+ "Each model is a model config. A case names a model and the request's value. An accepted case",+ "gives what the worker applies (null when nothing changes). A refused case gives the message,",+ "sent as 400 unsupported_field with param reasoning_effort. `capability` is the",+ "capabilities.reasoning object /v1/models reports for the model."+ ],+ "malformed_message": "'reasoning_effort' must be one of: none, minimal, low, medium, high, xhigh, max",+ "malformed": ["extreme", "", "LOW", 3, true, ["low"], {"value": "low"}],+ "models": {+ "acme/declared": {+ "config": {+ "sie_id": "acme/declared",+ "package_backed": true,+ "tasks": {+ "generate": {+ "context_length": 4096,+ "max_output_tokens": 256,+ "chat_template_kwargs": {"enable_thinking": true},+ "reasoning_effort": {+ "default": "max",+ "values": {+ "max": {},+ "high": {"chat_template_kwargs": {"reasoning_effort": "high"}},+ "low": {"chat_template_kwargs": {"reasoning_effort": "low"}}+ }+ }+ }+ },+ "profiles": {+ "default": {"adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter", "max_batch_tokens": 8192, "kv_budget_tokens": 8192}+ }+ },+ "capability": {"effort": ["low", "high", "max"], "default_effort": "max", "budget_tokens": {}}+ },+ "acme/silent": {+ "config": {+ "sie_id": "acme/silent",+ "package_backed": true,+ "tasks": {"generate": {"context_length": 4096, "max_output_tokens": 256}},+ "profiles": {+ "default": {"adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter", "max_batch_tokens": 8192, "kv_budget_tokens": 8192}+ }+ },+ "capability": null+ },+ "acme/thinking": {+ "config": {+ "sie_id": "acme/thinking",+ "package_backed": true,+ "tasks": {"generate": {"context_length": 4096, "max_output_tokens": 256, "chat_template_kwargs": {"enable_thinking": true}}},+ "profiles": {+ "default": {"adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter", "max_batch_tokens": 8192, "kv_budget_tokens": 8192}+ }+ },+ "capability": {"effort": [], "default_effort": null, "budget_tokens": {}}+ },+ "acme/remote": {+ "config": {+ "sie_id": "acme/remote",+ "remote_backed": true,+ "tasks": {+ "generate": {+ "context_length": 1000000,+ "max_output_tokens": 32768,+ "reasoning_effort": {+ "default": "high",+ "values": {+ "none": {"upstream": "none"},+ "low": {"upstream": "low"},+ "high": {"upstream": "high"}+ }+ }+ }+ },+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.remote.openai:OpenAIUpstreamAdapter",+ "max_batch_tokens": 16384,+ "adapter_options": {"loadtime": {"upstream": "acme-openai", "upstream_model": "acme/upstream-model"}}+ }+ }+ },+ "capability": {"effort": ["none", "low", "high"], "default_effort": "high", "budget_tokens": {}}+ },+ "acme/profile-declared": {+ "config": {+ "sie_id": "acme/profile-declared",+ "package_backed": true,+ "tasks": {"generate": {"context_length": 4096, "max_output_tokens": 256}},+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter",+ "max_batch_tokens": 8192,+ "kv_budget_tokens": 8192,+ "reasoning_effort": {"values": {"low": {"chat_template_kwargs": {"reasoning_strength": "low"}}}}+ }+ }+ },+ "capability": {"effort": ["low"], "default_effort": null, "budget_tokens": {}}+ }+ },+ "cases": [+ {"name": "a declared template value", "model": "acme/declared", "value": "low", "applied": {"chat_template_kwargs": {"reasoning_effort": "low"}, "upstream": null}},+ {"name": "a declared value that changes nothing", "model": "acme/declared", "value": "max", "applied": {"chat_template_kwargs": {}, "upstream": null}},+ {"name": "an undeclared value", "model": "acme/declared", "value": "minimal", "message": "Model 'acme/declared' does not support reasoning_effort 'minimal'. Supported values: low, high, max"},+ {"name": "none where it is not declared", "model": "acme/declared", "value": "none", "message": "Model 'acme/declared' does not support reasoning_effort 'none'. Supported values: low, high, max"},+ {"name": "none on a model that cannot reason", "model": "acme/silent", "value": "none", "applied": null},+ {"name": "another value on a model that cannot reason", "model": "acme/silent", "value": "low", "message": "Model 'acme/silent' does not support reasoning_effort"},+ {"name": "a reasoning model without a declaration", "model": "acme/thinking", "value": "none", "message": "Model 'acme/thinking' does not support reasoning_effort"},+ {"name": "a remote value", "model": "acme/remote", "value": "none", "applied": {"chat_template_kwargs": {}, "upstream": "none"}},+ {"name": "an undeclared remote value", "model": "acme/remote", "value": "medium", "message": "Model 'acme/remote' does not support reasoning_effort 'medium'. Supported values: none, low, high"},+ {"name": "a profile's own declaration", "model": "acme/profile-declared", "value": "low", "applied": {"chat_template_kwargs": {"reasoning_strength": "low"}, "upstream": null}},+ {"name": "a value outside a profile's own declaration", "model": "acme/profile-declared", "value": "high", "message": "Model 'acme/profile-declared' does not support reasoning_effort 'high'. Supported values: low"}+ ]+}diff --git a/packages/sie_config/src/sie_config/model_config.schema.json b/packages/sie_config/src/sie_config/model_config.schema.jsonindex 403d3cb91..e8fbd8131 100644--- a/packages/sie_config/src/sie_config/model_config.schema.json+++ b/packages/sie_config/src/sie_config/model_config.schema.json@@ -125,7 +125,7 @@},"GenerateTask": {"additionalProperties": false,- "description": "Generation task declaration.\n\n``context_length`` is the maximum shared prompt-plus-completion envelope by\ndefault. Encoder-decoder adapters may instead declare independent axes, in\nwhich case it bounds encoder input and ``max_output_tokens`` independently\ncaps decoder output. The gateway uses ``max_output_tokens`` for\npre-admission, and the worker authoritatively enforces it as the per-request\nhard cap on ``max_new_tokens`` before adapter dispatch.\n\n``chat_template_kwargs`` are a bounded operator-owned mapping forwarded\nto the tokenizer's ``apply_chat_template(**kwargs)`` call when the worker\nrenders an OpenAI-shaped ``messages`` request. The accepted schema covers\n``enable_thinking`` and Granite Guardian's bounded ``guardian_config``;\nunknown keys and invalid nested shapes fail at config load. Empty dict by\ndefault \u2014 non-chat / prompt-shape requests ignore the field.\n\n``prewarm_grammars`` is an optional list of grammars to compile at\nmodel-load time so the cold-start TTFT for these schemas excludes\nOutlines compile cost. See :class:`PrewarmGrammar` for the entry\nshape; the worker iterates the list once on boot and silently\ncontinues past individual compile failures (which are surfaced via\n``sie.worker.generation.grammar.compile.duration`` with\n``phase=\"prewarm\", outcome=\"error\"``).\n\n``kv_budget_tokens`` for admission control lives on\n:class:`ProfileConfig` rather than here, because the\nbudget is a per-worker/per-profile shape rather than a per-task\nsemantic.\n\n``grammar_profile`` optionally names a profile that grammar-constrained\nrequests (OpenAI ``response_format`` / SIE-native ``grammar``) must run on.\nWhen set, the gateway rewrites such a request's model id to the\n``{sie_id}:{grammar_profile}`` variant so it is served by that profile,\nwhile unconstrained requests keep the request's resolved profile. A\nprofile may override this with its own grammar-safe sibling so context,\nhardware launch shape, and thinking mode remain unchanged. A directly\ninheriting explicit variant may remain selected when its resolved launch\nsettings are already grammar-safe. This exists\nbecause some throughput optimisations are incompatible with\ndecode-time grammar enforcement \u2014 notably NEXTN/MTP speculative decoding\nbypasses SGLang's Outlines FSM (leaks out-of-schema keys, truncates\nmid-JSON), so a model whose default profile is speculative points\n``grammar_profile`` at a non-speculative profile (e.g. ``no-spec``). ``None``\n(default) means no rewrite \u2014 grammar runs on the request's resolved profile.",+ "description": "Generation task declaration.\n\n``context_length`` is the maximum shared prompt-plus-completion envelope by\ndefault. Encoder-decoder adapters may instead declare independent axes, in\nwhich case it bounds encoder input and ``max_output_tokens`` independently\ncaps decoder output. The gateway uses ``max_output_tokens`` for\npre-admission, and the worker authoritatively enforces it as the per-request\nhard cap on ``max_new_tokens`` before adapter dispatch.\n\n``chat_template_kwargs`` are a bounded operator-owned mapping forwarded\nto the tokenizer's ``apply_chat_template(**kwargs)`` call when the worker\nrenders an OpenAI-shaped ``messages`` request. The accepted schema covers\n``enable_thinking`` and Granite Guardian's bounded ``guardian_config``;\nunknown keys and invalid nested shapes fail at config load. Empty dict by\ndefault \u2014 non-chat / prompt-shape requests ignore the field.\n\n``prewarm_grammars`` is an optional list of grammars to compile at\nmodel-load time so the cold-start TTFT for these schemas excludes\nOutlines compile cost. See :class:`PrewarmGrammar` for the entry\nshape; the worker iterates the list once on boot and silently\ncontinues past individual compile failures (which are surfaced via\n``sie.worker.generation.grammar.compile.duration`` with\n``phase=\"prewarm\", outcome=\"error\"``).\n\n``kv_budget_tokens`` for admission control lives on\n:class:`ProfileConfig` rather than here, because the\nbudget is a per-worker/per-profile shape rather than a per-task\nsemantic.\n\n``reasoning_effort`` declares the OpenAI ``reasoning_effort`` values the\nmodel's profiles accept and what each does. A profile may replace it with\nits own declaration. ``None`` refuses the request field.\n\n``grammar_profile`` optionally names a profile that grammar-constrained\nrequests (OpenAI ``response_format`` / SIE-native ``grammar``) must run on.\nWhen set, the gateway rewrites such a request's model id to the\n``{sie_id}:{grammar_profile}`` variant so it is served by that profile,\nwhile unconstrained requests keep the request's resolved profile. A\nprofile may override this with its own grammar-safe sibling so context,\nhardware launch shape, and thinking mode remain unchanged. A directly\ninheriting explicit variant may remain selected when its resolved launch\nsettings are already grammar-safe. This exists\nbecause some throughput optimisations are incompatible with\ndecode-time grammar enforcement \u2014 notably NEXTN/MTP speculative decoding\nbypasses SGLang's Outlines FSM (leaks out-of-schema keys, truncates\nmid-JSON), so a model whose default profile is speculative points\n``grammar_profile`` at a non-speculative profile (e.g. ``no-spec``). ``None``\n(default) means no rewrite \u2014 grammar runs on the request's resolved profile.","properties": {"context_length": {"title": "Context Length",@@ -169,6 +169,17 @@],"default": null,"title": "Grammar Profile"+ },+ "reasoning_effort": {+ "anyOf": [+ {+ "$ref": "#/$defs/ReasoningEffortDeclaration"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"required": [@@ -366,7 +377,7 @@},"ProfileConfig": {"additionalProperties": false,- "description": "Per-profile configuration.\n\n``kv_budget_tokens`` is the per-worker KV-cache budget\nused by the streaming admission controller to reject requests whose\n``input_tokens_estimate + max_new_tokens`` would push the worker\nover capacity. **Required** (positive int) for profiles whose\n``adapter_path`` resolves to a ``GenerationAdapter`` subclass \u2014\ni.e. for any profile attached to a model with ``tasks.generate``\nset. Calibration of the actual value lives in the calibration\nfollow-up; until then the model YAML may carry a sentinel\nplaceholder, but a missing / zero / negative value at config-load\ntime is a hard error pointing operators at the calibration\ndeliverable.\n\n``admission_enabled`` gates admission control per\nprofile. ``None`` defers to the ``SIE_GENERATION_ADMISSION`` env\nvar (default-off until the calibration ablation flips it); explicit\n``True`` / ``False`` wins unless the env var is set to ``on`` or\n``off`` (which override the profile in both directions).\n\n``max_output_tokens`` optionally overrides the model-level generation cap\nfor the materialized ``model:profile`` variant. This lets a long-context\nreasoning profile expose the checkpoint's supported decode budget without\nweakening the conservative cap on the bare model or shorter profiles.\n\n``chat_template_kwargs`` optionally overrides the same bounded model-level\n:class:`GenerateTask` defaults for the materialized ``model:profile``\nvariant. This keeps tokenizer render presets such as explicit thinking\nmode on the profile identity while preserving the bare model's safer\nnon-thinking default. The profile mapping is merged over the task mapping;\nrequest-time kwargs are still applied later by the generation processor.\n\n``grammar_profile`` optionally overrides the model-level grammar fallback\nfor this concrete profile. It must name a non-default sibling profile. The\ngateway uses it only for constrained requests, allowing a long-context or\nthinking profile to route to a non-speculative twin without losing its\ncontext window, hardware launch shape, or tokenizer mode.",+ "description": "Per-profile configuration.\n\n``kv_budget_tokens`` is the per-worker KV-cache budget\nused by the streaming admission controller to reject requests whose\n``input_tokens_estimate + max_new_tokens`` would push the worker\nover capacity. **Required** (positive int) for profiles whose\n``adapter_path`` resolves to a ``GenerationAdapter`` subclass \u2014\ni.e. for any profile attached to a model with ``tasks.generate``\nset. Calibration of the actual value lives in the calibration\nfollow-up; until then the model YAML may carry a sentinel\nplaceholder, but a missing / zero / negative value at config-load\ntime is a hard error pointing operators at the calibration\ndeliverable.\n\n``admission_enabled`` gates admission control per\nprofile. ``None`` defers to the ``SIE_GENERATION_ADMISSION`` env\nvar (default-off until the calibration ablation flips it); explicit\n``True`` / ``False`` wins unless the env var is set to ``on`` or\n``off`` (which override the profile in both directions).\n\n``max_output_tokens`` optionally overrides the model-level generation cap\nfor the materialized ``model:profile`` variant. This lets a long-context\nreasoning profile expose the checkpoint's supported decode budget without\nweakening the conservative cap on the bare model or shorter profiles.\n\n``chat_template_kwargs`` optionally overrides the same bounded model-level\n:class:`GenerateTask` defaults for the materialized ``model:profile``\nvariant. This keeps tokenizer render presets such as explicit thinking\nmode on the profile identity while preserving the bare model's safer\nnon-thinking default. The profile mapping is merged over the task mapping;\nrequest-time kwargs are still applied later by the generation processor.\n\n``grammar_profile`` optionally overrides the model-level grammar fallback\nfor this concrete profile. It must name a non-default sibling profile. The\ngateway uses it only for constrained requests, allowing a long-context or\nthinking profile to route to a non-speculative twin without losing its\ncontext window, hardware launch shape, or tokenizer mode.\n\n``reasoning_effort`` replaces the generation task's declaration for this\nprofile and the profiles that extend it.","properties": {"extends": {"anyOf": [@@ -512,11 +523,107 @@],"default": null,"title": "Grammar Profile"+ },+ "reasoning_effort": {+ "anyOf": [+ {+ "$ref": "#/$defs/ReasoningEffortDeclaration"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"title": "ProfileConfig","type": "object"},+ "ReasoningEffortDeclaration": {+ "additionalProperties": false,+ "description": "The ``reasoning_effort`` values a generation profile accepts, and what each does.\n\n``default`` names the value the profile already runs at when a request\nnames none, or is ``None`` when that is not one of the declared values. It\nis reported on ``/v1/models`` and never applied, so a request without the\nfield renders and calls its upstream exactly as before.",+ "properties": {+ "default": {+ "anyOf": [+ {+ "enum": [+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Default"+ },+ "values": {+ "additionalProperties": {+ "$ref": "#/$defs/ReasoningEffortLevel"+ },+ "propertyNames": {+ "enum": [+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "title": "Values",+ "type": "object"+ }+ },+ "required": [+ "values"+ ],+ "title": "ReasoningEffortDeclaration",+ "type": "object"+ },+ "ReasoningEffortLevel": {+ "additionalProperties": false,+ "description": "What one accepted ``reasoning_effort`` value does on a generation profile.\n\n``chat_template_kwargs`` set the model's own effort switch where SIE renders\nthe prompt. ``upstream`` is the top-level ``reasoning_effort`` a remote\nprofile sends to its upstream chat. A level that sets neither accepts the\nvalue and changes nothing, for the value the model already runs at.",+ "properties": {+ "chat_template_kwargs": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Chat Template Kwargs"+ },+ "upstream": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Upstream"+ }+ },+ "title": "ReasoningEffortLevel",+ "type": "object"+ },"RoutingConfig": {"additionalProperties": false,"description": "How a request for the bare model name chooses between the local and the remote profile.\n\n``remote_only`` is the policy of a ``remote_backed`` model: every request is\nserved by its remote profile. Under ``fallback`` the local profile serves,\nand ``fallback_profile`` serves when local capacity refuses for one of\n``triggers`` before it accepts the work. Under ``threshold`` the remote\nprofile serves until demand stays above ``wake_above`` for ``window_s``,\nand serves again once demand stays below ``sleep_below`` for\n``cooldown_s``. A request that names a profile is never routed.",diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 556cd5568..39f214b98 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -46,7 +46,7 @@ Key terms used throughout this document:- `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`**. `dimensions` is accepted only when it equals the model's native dense width and otherwise rejected with **`400 unsupported_field`**, the same rule as the single-node server. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.- - `POST /v1/messages` — Anthropic Messages compatibility surface (`handlers::messages`). The handler validates the body in Anthropic terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Message, chat SSE chunks into Messages events, and every error into the Anthropic envelope `{"type":"error","error":{"type","message"},"request_id"}` with the status the chat route chose. Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. Unknown fields fail with `400 <field>: Extra inputs are not permitted`; `metadata`, every `cache_control`, `thinking.display: "summarized"`, tool `eager_input_streaming` and the `anthropic-beta` header are accepted and have no effect, and `metadata` is never logged or forwarded. `thinking` `enabled` or `adaptive` sets the chat request's `include_reasoning`, and reasoning comes back as `thinking` blocks with an opaque signature. Usage reports `prompt_tokens - cached_tokens` as `input_tokens` and the cached part as `cache_read_input_tokens`, so the two add up to the chat route's prompt tokens. A stream sends `message_start` with zero usage when the chat stream opens, the authoritative usage on `message_delta`, a `ping` whenever nothing was sent for 10 seconds, and a mid-stream failure as an `error` event without `message_stop`. Dropping the response body drops the chat body, so a client disconnect cancels the generation as on chat. The Anthropic error envelope is also an outer middleware, `anthropic_error_envelope`, applied to `/v1/messages` and every path below it, so auth refusals, unknown sub-paths such as `/v1/messages/count_tokens` (not served) and the method check take the same shape; a composition that adds admission layers applies it outermost. `messages_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/anthropic_messages/` pin the request translation, the buffered answer, the event sequence, the error mapping, and the tool-calling and image-input refusals both chat routes give before any engine runs.+ - `POST /v1/messages` — Anthropic Messages compatibility surface (`handlers::messages`). The handler validates the body in Anthropic terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Message, chat SSE chunks into Messages events, and every error into the Anthropic envelope `{"type":"error","error":{"type","message"},"request_id"}` with the status the chat route chose. Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. Unknown fields fail with `400 <field>: Extra inputs are not permitted`; `metadata`, every `cache_control`, `thinking.display: "summarized"`, tool `eager_input_streaming` and the `anthropic-beta` header are accepted and have no effect, and `metadata` is never logged or forwarded. `thinking` `enabled` or `adaptive` sets the chat request's `include_reasoning`, and reasoning comes back as `thinking` blocks with an opaque signature. `output_config.effort` sets the chat request's `reasoning_effort`, and a model that does not accept the value answers `400 output_config.effort: Extra inputs are not permitted`, the wording clients that drop the field recover from. Usage reports `prompt_tokens - cached_tokens` as `input_tokens` and the cached part as `cache_read_input_tokens`, so the two add up to the chat route's prompt tokens. A stream sends `message_start` with zero usage when the chat stream opens, the authoritative usage on `message_delta`, a `ping` whenever nothing was sent for 10 seconds, and a mid-stream failure as an `error` event without `message_stop`. Dropping the response body drops the chat body, so a client disconnect cancels the generation as on chat. The Anthropic error envelope is also an outer middleware, `anthropic_error_envelope`, applied to `/v1/messages` and every path below it, so auth refusals, unknown sub-paths such as `/v1/messages/count_tokens` (not served) and the method check take the same shape; a composition that adds admission layers applies it outermost. `messages_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/anthropic_messages/` pin the request translation, the buffered answer, the event sequence, the error mapping, and the tool-calling and image-input refusals both chat routes give before any engine runs.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.@@ -567,7 +567,7 @@ Config (read-side only):Pools and operator:- `GET /v1/pools`, `POST /v1/pools`, `GET /v1/pools/{name}`, `POST /v1/pools/{name}/renew`, `DELETE /v1/pools/{name}`-- `GET /v1/models`, `GET /v1/models/{*model}` — model catalogue. JSON objects mirror `sie_server` **`ModelInfo`** shape (including `inputs`, `outputs`, `dims`, `profiles`, worker-derived `loaded` / `state`, optional `last_error`, …). An unknown `model` id returns **`404`** with **`{"detail":{"code":"MODEL_NOT_FOUND",...}}`** (same envelope style as FastAPI validation errors on `sie_server`).+- `GET /v1/models`, `GET /v1/models/{*model}` — model catalogue. JSON objects mirror `sie_server` **`ModelInfo`** shape (including `inputs`, `outputs`, `dims`, `profiles`, worker-derived `loaded` / `state`, optional `last_error`, …). `context_length` and `max_output_tokens` are the limits the route admits, and `capabilities.reasoning` lists the `reasoning_effort` values it accepts, read from the same model config the chat gate checks. An unknown `model` id returns **`404`** with **`{"detail":{"code":"MODEL_NOT_FOUND",...}}`** (same envelope style as FastAPI validation errors on `sie_server`).- `GET /healthz`, `GET /readyz`, `GET /health`- `GET /ws/cluster-status`- `GET /` — HTML status page (operator-facing, not a programmatic API).diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 03d8c44ba..e86cf1ba3 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``, ``reasoning_effort``, ``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``, ``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]``.","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).",@@ -528,6 +528,14 @@"null"]},+ "reasoning_effort": {+ "description": "OpenAI reasoning effort: ``none``, ``minimal``, ``low``, ``medium``,\n``high``, ``xhigh`` or ``max``. Each model accepts the values listed in\n``capabilities.reasoning.effort`` on ``GET /v1/models``, and any other\nvalue is refused with 400 ``unsupported_field``. A value only listed\nthere instructs the model to reason less or more. A value with an entry\nin ``capabilities.reasoning.budget_tokens`` also caps its reasoning\ntokens. ``max_tokens`` still bounds reasoning and answer together.\n``none`` is accepted on a model that cannot reason. Absent keeps the\nmodel's own default.",+ "example": "low",+ "type": [+ "string",+ "null"+ ]+ },"repetition_penalty": {"description": "Non-OpenAI `repetition_penalty`: float in (0.0, 2.0] (1.0 = no penalty). Absent → sampler default.","exclusiveMinimum": 0.0,@@ -2612,6 +2620,17 @@"null"]},+ "reasoning": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ModelReasoningWire",+ "description": "How ``reasoning_effort`` steers the model's reasoning. ``null`` for a\nmodel without a generate task or one that cannot reason."+ }+ ]+ },"sql": {"description": "Whether the model targets the SQL path — backs the ``model=\"sql\"``\nalias. Informational only; never request-gated. Precision-sensitive:\nSQL quality can regress sharply under FP8, so this model-level flag is a\nsupport signal, not a per-profile quality guarantee.","type": "boolean"@@ -2730,6 +2749,15 @@}]},+ "context_length": {+ "description": "Prompt plus completion tokens this id admits; ``null`` for a model\nwithout a generate task.",+ "format": "int32",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },"description": {"description": "One line about the model; `\"\"` when the catalog sets none. Reported for\nSystem One model-list clients (the TypeSafe SDKs).","type": "string"@@ -2754,6 +2782,15 @@"loaded": {"type": "boolean"},+ "max_output_tokens": {+ "description": "The largest ``max_tokens`` this id admits; ``null`` for a model without\na generate task.",+ "format": "int32",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },"max_sequence_length": {"format": "int64","minimum": 0,@@ -2849,6 +2886,42 @@],"type": "object"},+ "ModelReasoningWire": {+ "description": "``capabilities.reasoning`` on a ``GET /v1/models`` entry.",+ "properties": {+ "budget_tokens": {+ "additionalProperties": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "description": "The hard reasoning-token ceiling of each value that has one. Other\nvalues only instruct the model.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "default_effort": {+ "description": "The value the model runs at when a request names none; ``null`` when\nthat is not one of the accepted values.",+ "type": [+ "string",+ "null"+ ]+ },+ "effort": {+ "description": "Accepted ``reasoning_effort`` values in OpenAI's order. Empty when the\nmodel refuses the field.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": [+ "effort",+ "budget_tokens"+ ],+ "type": "object"+ },"ModelRoutingWire": {"description": "Routing summary on a ``GET /v1/models`` entry.","properties": {diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 9dd760e01..98263a1b8 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -814,6 +814,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -1112,6 +1113,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("nonexistent.module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,diff --git a/packages/sie_gateway/src/handlers/messages/error.rs b/packages/sie_gateway/src/handlers/messages/error.rsindex bba04e4c5..86b076ec1 100644--- a/packages/sie_gateway/src/handlers/messages/error.rs+++ b/packages/sie_gateway/src/handlers/messages/error.rs@@ -157,6 +157,15 @@ pub(crate) fn translate_error_body(if status != StatusCode::BAD_REQUEST {return (error_type, message, code);}+ // A route that does not accept the effort answers in the wording clients+ // that drop the field recover from.+ if param == Some("reasoning_effort") && code.as_deref() == Some("unsupported_field") {+ return (+ error_type,+ "output_config.effort: Extra inputs are not permitted".to_string(),+ code,+ );+ }if let Some((requested, cap)) = output_cap(&message) {return (error_type,@@ -201,6 +210,9 @@ fn anthropic_param(param: &str) -> String {if param == "stop" {return "stop_sequences".to_string();}+ if param == "reasoning_effort" {+ return "output_config.effort".to_string();+ }if let Some(rest) = param.strip_prefix("tools[") {if let Some((index, field)) = rest.split_once("].function.") {let field = if field == "parameters" {diff --git a/packages/sie_gateway/src/handlers/messages/request.rs b/packages/sie_gateway/src/handlers/messages/request.rsindex 07d179ab7..1aa39a8a2 100644--- a/packages/sie_gateway/src/handlers/messages/request.rs+++ b/packages/sie_gateway/src/handlers/messages/request.rs@@ -167,12 +167,13 @@ pub(crate) fn messages_to_chat(let Some(body) = body.as_object() else {return Err(invalid("body: Input should be a valid dictionary"));};+ let mut effort = None;for key in body.keys() {match key.as_str() {"model" | "max_tokens" | "messages" | "system" | "stop_sequences" | "temperature"| "top_p" | "top_k" | "stream" | "tools" | "tool_choice" | "thinking" | "metadata"| "cache_control" => {}- "output_config" => output_config(body.get(key).unwrap_or(&Value::Null))?,+ "output_config" => effort = output_config(body.get(key).unwrap_or(&Value::Null))?,"context_management" => return Err(invalid(CONTEXT_MANAGEMENT_REFUSAL)),other => return Err(extra(other)),}@@ -289,6 +290,9 @@ pub(crate) fn messages_to_chat(chat.insert("parallel_tool_calls".into(), json!(parallel));}chat.insert("include_reasoning".into(), json!(include_reasoning));+ if let Some(effort) = effort {+ chat.insert("reasoning_effort".into(), Value::String(effort));+ }Ok(ChatTranslation {chat: Value::Object(chat),model,@@ -297,13 +301,28 @@ pub(crate) fn messages_to_chat(})}-fn output_config(value: &Value) -> Result<(), MessagesError> {+/// Anthropic's ``output_config.effort`` values. Each is also an OpenAI+/// ``reasoning_effort`` value, which the chat route checks against the model.+const ANTHROPIC_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];++/// The chat route's ``reasoning_effort`` from ``output_config``, whose only+/// accepted key is ``effort``.+fn output_config(value: &Value) -> Result<Option<String>, MessagesError> {if value.is_null() {- return Ok(());+ return Ok(None);}- match object(value, "output_config")?.keys().next() {- Some(key) => Err(extra(&format!("output_config.{key}"))),- None => Ok(()),+ let config = object(value, "output_config")?;+ if let Some(key) = config.keys().find(|key| key.as_str() != "effort") {+ return Err(extra(&format!("output_config.{key}")));+ }+ match config.get("effort") {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(effort)) if ANTHROPIC_EFFORTS.contains(&effort.as_str()) => {+ Ok(Some(effort.clone()))+ }+ Some(_) => Err(invalid(+ "output_config.effort: Input should be 'low', 'medium', 'high', 'xhigh' or 'max'",+ )),}}diff --git a/packages/sie_gateway/src/handlers/messages/tests.rs b/packages/sie_gateway/src/handlers/messages/tests.rsindex 665073b8f..470c0e25a 100644--- a/packages/sie_gateway/src/handlers/messages/tests.rs+++ b/packages/sie_gateway/src/handlers/messages/tests.rs@@ -162,6 +162,15 @@ fn every_captured_claude_code_request_translates_or_fails_with_the_recovery_wordchat.get("stop").cloned().unwrap_or(Value::Null),"{name}");+ assert_eq!(+ translation+ .chat+ .get("reasoning_effort")+ .cloned()+ .unwrap_or(Value::Null),+ chat.get("reasoning_effort").cloned().unwrap_or(Value::Null),+ "{name}"+ );assert!(chat_completions_dispatch_inputs(&translation.chat).is_ok(),"{name}: the chat route accepts the translation"@@ -868,7 +877,7 @@ async fn a_translation_refusal_publishes_nothing() {messages_request(json!({"model": "acme/chat","max_tokens": 16,- "output_config": {"effort": "high"},+ "output_config": {"format": {"type": "json_schema"}},"messages": [{"role": "user", "content": "hi"}],})),)@@ -880,7 +889,7 @@ async fn a_translation_refusal_publishes_nothing() {body,json!({"type": "error",- "error": {"type": "invalid_request_error", "message": "output_config.effort: Extra inputs are not permitted"},+ "error": {"type": "invalid_request_error", "message": "output_config.format: Extra inputs are not permitted"},"request_id": null,}));diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 2ca0250c1..af91aee2e 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -356,6 +356,11 @@ fn worker_only_model_info(name: &str, loaded: bool) -> Value {routing: None,max_output_tokens: None,profile_max_output_tokens: HashMap::new(),+ context_length: None,+ profile_context_length: HashMap::new(),+ reasoning_effort: None,+ profile_reasoning_effort: HashMap::new(),+ declares_no_reasoning: false,grammar_capabilities: None,streaming_supported: None,grammar_profile: None,@@ -505,6 +510,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -540,6 +546,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -554,6 +561,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),),@@ -591,6 +599,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),),@@ -701,6 +710,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -722,6 +732,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(8192),compute_precision: None,@@ -1347,6 +1358,7 @@ mod route_tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.remote.sie:SieUpstreamAdapter".to_string()),max_batch_tokens: Some(8192),compute_precision: None,diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex 52a46ec24..383d27137 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -338,6 +338,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -358,6 +359,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 265feb99b..00e0a17bd 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -38,7 +38,9 @@ use crate::state::demand_tracker::PhysicalLane;use crate::state::model_registry::{ModelRegistry, ResolveError};use crate::state::pool_manager::{normalize_pool_name, PoolManager, DEFAULT_POOL_NAME};use crate::state::worker_registry::{QueueRoute, WorkerRegistry};-use crate::types::model::FallbackTrigger;+use crate::types::model::{+ reasoning_effort_malformed_message, FallbackTrigger, REASONING_EFFORT_VALUES,+};use crate::types::AuditEntry;use crate::middleware::auth::request_token_id;@@ -6488,6 +6490,9 @@ struct ChatRequestParams {/// publish the model's reasoning as ``reasoning_content`` on the/// message and on stream deltas. Absent or ``false`` keeps it private.include_reasoning: Option<bool>,+ /// OpenAI ``reasoning_effort``: one of OpenAI's values, checked against the+ /// route's declaration before publication and resolved by the worker.+ reasoning_effort: Option<String>,/// OpenAI ``stream`` flag. ``true`` switches the handler to the/// SSE response branch; ``false`` (default) uses the existing/// aggregating path. Parsed by :func:`chat_params_from_json`;@@ -6572,6 +6577,7 @@ impl ChatRequestParams {grammar: self.grammar,schema_in_prompt: self.schema_in_prompt,include_reasoning: self.include_reasoning,+ reasoning_effort: self.reasoning_effort,routing_key: self.routing_key.clone(),prompt_cache_key: self.prompt_cache_key.clone(),tools: self.tools,@@ -7772,7 +7778,6 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {"store","service_tier","prediction",- "reasoning_effort","verbosity",] {if obj.contains_key(fname) {@@ -7849,6 +7854,21 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {);}};+ let reasoning_effort = match obj.get("reasoning_effort") {+ None | Some(serde_json::Value::Null) => None,+ Some(serde_json::Value::String(value))+ if REASONING_EFFORT_VALUES.contains(&value.as_str()) =>+ {+ Some(value.clone())+ }+ Some(_) => {+ return bad(+ &reasoning_effort_malformed_message(),+ Some("reasoning_effort"),+ oai_code::INVALID_REQUEST,+ );+ }+ };// ``tool_choice`` without ``tools`` is meaningless; OpenAI itself// returns a 400 in that case. We mirror the behaviour so SDKs that// accidentally send ``tool_choice: "auto"`` on a plain chat call@@ -7924,6 +7944,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {"response_format","schema_in_prompt","include_reasoning",+ "reasoning_effort","stream","tools","tool_choice",@@ -7976,6 +7997,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {grammar,schema_in_prompt,include_reasoning,+ reasoning_effort,stream,stream_include_usage,tools,@@ -9628,6 +9650,20 @@ async fn proxy_chat_inner(.into_response();}}+ if let Some(value) = params.reasoning_effort.as_deref() {+ if let Some(message) = info.reasoning_effort_refusal(value, &model_name) {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ message,+ oai_type::INVALID_REQUEST,+ Some("reasoning_effort"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response();+ }+ }// Vision capability gate. ``image_url`` content parts were decoded// into ``ChatMessage.images`` capability-agnostically (the model// wasn't resolved yet); reject here unless the model YAML declares@@ -9697,6 +9733,17 @@ async fn proxy_chat_inner()),).into_response();+ } else if params.reasoning_effort.is_some() {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!("Model '{model_name}' does not support reasoning_effort"),+ oai_type::INVALID_REQUEST,+ Some("reasoning_effort"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response();} else if params.messages.iter()@@ -14287,6 +14334,7 @@ fn generate_params_from_json(stream,lora_adapter,include_reasoning: None,+ reasoning_effort: None,native_prompt: Some(true),}))}@@ -14720,6 +14768,7 @@ fn generate_params_from_rmpv(stream,lora_adapter,include_reasoning: None,+ reasoning_effort: None,native_prompt: Some(true),}))}@@ -17957,6 +18006,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -18707,6 +18757,115 @@ mod tests {}}+ #[tokio::test]+ async fn chat_reasoning_effort_is_refused_before_publication_or_reaches_the_worker() {+ use crate::types::model::{ModelConfig, ProfileConfig};++ let (state, probe) = mixed_governed_generation_state(false).await;+ let body = |value: &str| {+ json!({+ "model": "org/g",+ "messages": [{"role": "user", "content": "hello"}],+ "max_tokens": 4,+ "reasoning_effort": value,+ })+ };+ let refused = proxy_chat(+ State(Arc::clone(&state)),+ json_request("/v1/chat/completions", body("low")),+ )+ .await;+ assert_eq!(refused.status(), StatusCode::BAD_REQUEST);+ let error: serde_json::Value = serde_json::from_slice(+ &axum::body::to_bytes(refused.into_body(), 1 << 16)+ .await+ .unwrap(),+ )+ .unwrap();+ assert_eq!(error["error"]["param"], "reasoning_effort");+ assert_eq!(error["error"]["code"], "unsupported_field");+ assert_eq!(+ error["error"]["message"],+ "Model 'org/g' does not support reasoning_effort"+ );++ let profile = ProfileConfig {+ kv_budget_tokens: None,+ max_output_tokens: None,+ grammar_profile: None,+ chat_template_kwargs: None,+ reasoning_effort: None,+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ };+ let mut no_spec = profile.clone();+ no_spec.adapter_options = Some(json!({"loadtime": {"speculative": {"enabled": false}}}));+ let tasks: serde_json::Value = serde_saphyr::from_str(+ "generate:\n grammar_profile: no-spec\n capabilities:\n grammar: [json_schema]\n reasoning_effort:\n values:\n low:\n chat_template_kwargs:\n reasoning_effort: low\n",+ )+ .unwrap();+ state+ .model_registry+ .add_model_config_authoritative(ModelConfig {+ name: "org/g".to_string(),+ hf_revision: None,+ description: None,+ release_date: None,+ routing: None,+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles: [+ ("default".to_string(), profile),+ ("no-spec".to_string(), no_spec),+ ]+ .into_iter()+ .collect(),+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .expect("declared model");++ let undeclared = proxy_chat(+ State(Arc::clone(&state)),+ json_request("/v1/chat/completions", body("high")),+ )+ .await;+ assert_eq!(undeclared.status(), StatusCode::BAD_REQUEST);++ *probe.worker_chunks.lock().unwrap() = vec![+ reasoning_worker_chunk(0, json!({"text_delta": "Hi", "is_first": true})),+ reasoning_worker_terminal(1, json!({})),+ ];+ let accepted = proxy_chat(+ State(Arc::clone(&state)),+ json_request("/v1/chat/completions", body("low")),+ )+ .await;+ let status = accepted.status();+ let text = String::from_utf8(+ axum::body::to_bytes(accepted.into_body(), 1 << 16)+ .await+ .unwrap()+ .to_vec(),+ )+ .unwrap();+ assert_eq!(status, StatusCode::OK, "{text}");+ assert_eq!(+ probe+ .take_params()+ .generate+ .expect("generate")+ .reasoning_effort+ .as_deref(),+ Some("low")+ );+ }+#[tokio::test]async fn chat_include_reasoning_keeps_each_candidate_reasoning_on_its_choice() {let (state, probe) = mixed_governed_generation_state(false).await;@@ -22702,6 +22861,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: None,compute_precision: None,@@ -26057,6 +26217,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -26112,6 +26273,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -26211,6 +26373,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -26258,6 +26421,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -26271,6 +26435,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -26341,6 +26506,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -26574,6 +26740,57 @@ mod tests {assert_eq!(wire["include_reasoning"], serde_json::json!(true));}+ #[test]+ fn test_chat_reasoning_effort_is_forwarded_and_absent_by_default() {+ let mut body = _chat_body_min("m");+ let generate = _expect_chat_ok(body.clone())+ .into_work_params()+ .generate+ .expect("generate params");+ assert_eq!(generate.reasoning_effort, None);+ assert!(serde_json::to_value(&generate)+ .unwrap()+ .get("reasoning_effort")+ .is_none());++ body["reasoning_effort"] = serde_json::Value::Null;+ let generate = _expect_chat_ok(body.clone())+ .into_work_params()+ .generate+ .unwrap();+ assert_eq!(generate.reasoning_effort, None);++ for value in REASONING_EFFORT_VALUES {+ body["reasoning_effort"] = serde_json::json!(value);+ let generate = _expect_chat_ok(body.clone())+ .into_work_params()+ .generate+ .unwrap();+ assert_eq!(generate.reasoning_effort.as_deref(), Some(*value));+ let wire = serde_json::to_value(&generate).unwrap();+ assert_eq!(wire["reasoning_effort"], serde_json::json!(value));+ }+ }++ #[tokio::test]+ async fn test_chat_reasoning_effort_outside_openais_values_is_malformed() {+ let vectors: serde_json::Value = serde_json::from_str(include_str!(+ "../../../../conformance/openai_generation/reasoning_effort_vectors.json"+ ))+ .unwrap();+ for value in vectors["malformed"].as_array().unwrap() {+ let mut body = _chat_body_min("m");+ body["reasoning_effort"] = value.clone();+ let err = _expect_chat_err(body).await;+ assert_eq!(err["error"]["param"], "reasoning_effort", "{value}");+ assert_eq!(err["error"]["code"], "invalid_request", "{value}");+ assert_eq!(+ err["error"]["message"], vectors["malformed_message"],+ "{value}"+ );+ }+ }+#[tokio::test]async fn test_chat_include_reasoning_must_be_a_boolean() {let mut body = _chat_body_min("m");@@ -30372,6 +30589,11 @@ profiles:routing: None,max_output_tokens: None,profile_max_output_tokens: std::collections::HashMap::new(),+ context_length: None,+ profile_context_length: std::collections::HashMap::new(),+ reasoning_effort: None,+ profile_reasoning_effort: std::collections::HashMap::new(),+ declares_no_reasoning: false,grammar_capabilities: None,streaming_supported: None,grammar_profile: None,diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex 1d228341d..d5c6d92f3 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -801,6 +801,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string(),),diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 4a786c25b..b31ef0e7e 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -110,6 +110,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {MessageResponse,ModelAckBundleStatus,ModelCapabilitiesWire,+ ModelReasoningWire,ModelConfigStatusResponse,ModelInfoWire,ModelRoutingWire,@@ -2292,7 +2293,7 @@ pub struct ChatTemplateKwargs {/// **Known-rejected fields**:/// - ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead./// - ``modalities``, ``audio``, ``metadata``, ``store``, ``service_tier``,-/// ``prediction``, ``reasoning_effort``, ``verbosity`` — out of scope.+/// ``prediction``, ``verbosity`` — out of scope.////// **Streaming:** ``stream: true`` is supported (SSE ``chat.completion.chunk``)./// ``n > 1`` streaming fans candidates out as per-``choice_index``-tagged delta@@ -2428,6 +2429,18 @@ pub struct ChatCompletionRequest {/// ``usage`` is unchanged either way.#[serde(default, skip_serializing_if = "Option::is_none")]pub include_reasoning: Option<bool>,+ /// OpenAI reasoning effort: ``none``, ``minimal``, ``low``, ``medium``,+ /// ``high``, ``xhigh`` or ``max``. Each model accepts the values listed in+ /// ``capabilities.reasoning.effort`` on ``GET /v1/models``, and any other+ /// value is refused with 400 ``unsupported_field``. A value only listed+ /// there instructs the model to reason less or more. A value with an entry+ /// in ``capabilities.reasoning.budget_tokens`` also caps its reasoning+ /// tokens. ``max_tokens`` still bounds reasoning and answer together.+ /// ``none`` is accepted on a model that cannot reason. Absent keeps the+ /// model's own default.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<String>, example = "low")]+ pub reasoning_effort: Option<String>,/// 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@@ -2767,6 +2780,12 @@ pub struct ModelInfoWire {#[serde(skip_serializing_if = "Option::is_none")]pub last_error: Option<serde_json::Value>,pub max_sequence_length: Option<u64>,+ /// Prompt plus completion tokens this id admits; ``null`` for a model+ /// without a generate task.+ pub context_length: Option<u32>,+ /// The largest ``max_tokens`` this id admits; ``null`` for a model without+ /// a generate task.+ pub max_output_tokens: Option<u32>,/// Immutable model weights revision, when the catalog pins one.pub revision: Option<String>,/// One line about the model; `""` when the catalog sets none. Reported for@@ -2874,6 +2893,23 @@ pub struct ModelCapabilitiesWire {/// backs the ``model="guard"`` alias. Informational only; never/// request-gated.pub guard: bool,+ /// How ``reasoning_effort`` steers the model's reasoning. ``null`` for a+ /// model without a generate task or one that cannot reason.+ pub reasoning: Option<ModelReasoningWire>,+}++/// ``capabilities.reasoning`` on a ``GET /v1/models`` entry.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelReasoningWire {+ /// Accepted ``reasoning_effort`` values in OpenAI's order. Empty when the+ /// model refuses the field.+ pub effort: Vec<String>,+ /// The value the model runs at when a request names none; ``null`` when+ /// that is not one of the accepted values.+ pub default_effort: Option<String>,+ /// The hard reasoning-token ceiling of each value that has one. Other+ /// values only instruct the model.+ pub budget_tokens: std::collections::HashMap<String, u32>,}/// One OpenAI-shaped model object in the `data` array ofdiff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex d9db414ff..82a07d720 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -446,6 +446,11 @@ pub struct GenerateParams {/// private.#[serde(default, skip_serializing_if = "Option::is_none")]pub include_reasoning: Option<bool>,+ /// Chat ``reasoning_effort``: one of OpenAI's values, already checked+ /// against the route's declaration. The worker resolves it against the+ /// profile it serves. Absent leaves the profile's own default.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reasoning_effort: Option<String>,/// ``Some(true)`` only from the native ``/v1/generate`` route. A/// remote-backed model whose upstream serves chat only then receives/// the prompt as one user message. Every other route's prompt is a rawdiff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 436e2bd3e..bf075a126 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -916,6 +916,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string(),),diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex d363fc991..d8d5c1c7e 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -989,6 +989,7 @@ impl ModelRegistry {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: None,max_batch_tokens: None,compute_precision: None,@@ -1065,6 +1066,7 @@ impl ModelRegistry {fn merge_profiles_for_resolution(existing: &HashMap<String, CanonicalProfile>,existing_output_caps: &HashMap<String, u32>,+ existing_reasoning_effort: &HashMap<String, crate::types::model::ReasoningEffortDecl>,incoming: &HashMap<String, crate::types::model::ProfileConfig>,) -> HashMap<String, crate::types::model::ProfileConfig> {let mut merged: HashMap<String, crate::types::model::ProfileConfig> = existing@@ -1077,6 +1079,9 @@ impl ModelRegistry {max_output_tokens: existing_output_caps.get(name).copied(),grammar_profile: canon.grammar_profile.clone(),chat_template_kwargs: canon.chat_template_kwargs.clone(),+ reasoning_effort: existing_reasoning_effort+ .get(name)+ .map(crate::types::model::ReasoningEffortDecl::to_yaml_value),adapter_path: canon.adapter_path.clone(),max_batch_tokens: canon.max_batch_tokens,compute_precision: canon.compute_precision.clone(),@@ -2846,6 +2851,7 @@ impl ModelRegistry {let merged_profiles = Self::merge_profiles_for_resolution(&existing.profile_configs,&existing.info_extras.profile_max_output_tokens,+ &existing.info_extras.profile_reasoning_effort,&config.profiles,);@@ -3051,6 +3057,8 @@ impl ModelRegistry {// reload (otherwise grammar_route_variant keeps routing to the// stale profile).existing.grammar_profile = refreshed.grammar_profile;+ existing.context_length = refreshed.context_length;+ existing.reasoning_effort = refreshed.reasoning_effort.clone();}if config.max_sequence_length.is_some() {existing.max_sequence_length = refreshed.max_sequence_length;@@ -3076,6 +3084,35 @@ impl ModelRegistry {existing.lora_adapters = lora_refreshed.lora_adapters;existing.profile_lora_adapters = lora_refreshed.profile_lora_adapters;existing.profile_max_output_tokens = lora_refreshed.profile_max_output_tokens;+ existing.profile_context_length = lora_refreshed.profile_context_length;+ existing.profile_reasoning_effort = lora_refreshed.profile_reasoning_effort;+ }+ // Whether the model can reason at all depends on its generate task and+ // every profile. A delta without ``tasks`` keeps the known answer and+ // can only take it away: a ``true`` here accepts ``none`` as a no-op.+ if config.tasks.is_some() {+ let mut merged_config = config.clone();+ merged_config.profiles = merged_profiles.clone();+ existing.declares_no_reasoning =+ ModelInfoExtras::from_model_config(&merged_config).declares_no_reasoning;+ } else if touches_profiles {+ existing.declares_no_reasoning &= config.profiles.values().all(|profile| {+ profile.reasoning_effort.is_none()+ && profile+ .chat_template_kwargs+ .as_ref()+ .and_then(|kwargs| kwargs.get("enable_thinking"))+ .is_none()+ && !profile.adapter_path.as_deref().is_some_and(|path| {+ path.starts_with(crate::types::model::REMOTE_ADAPTER_MODULE_PREFIX)+ })+ && profile+ .adapter_options+ .as_ref()+ .and_then(|options| options.get("loadtime"))+ .and_then(|loadtime| loadtime.get("reasoning_parser"))+ .is_none_or(serde_json::Value::is_null)+ });}}}@@ -3109,6 +3146,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: adapter_path.map(str::to_string),max_batch_tokens,compute_precision: None,@@ -3585,6 +3623,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -3629,6 +3668,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -4405,6 +4445,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -4449,6 +4490,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -4691,6 +4733,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -4749,6 +4792,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -4765,6 +4809,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -4933,6 +4978,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),),@@ -5422,6 +5468,7 @@ profiles:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string(),),@@ -5704,6 +5751,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -5755,6 +5803,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -5801,6 +5850,7 @@ encode:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -5815,6 +5865,7 @@ encode:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(2048),compute_precision: None,@@ -5972,6 +6023,7 @@ encode:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -6082,6 +6134,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -6123,6 +6176,7 @@ encode:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -6137,6 +6191,7 @@ encode:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(2048),compute_precision: None,@@ -6191,6 +6246,7 @@ encode:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some(adapter_path.to_string()),max_batch_tokens: Some(max_batch_tokens),compute_precision: None,@@ -6422,6 +6478,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,compute_precision: None,adapter_options: None,extends: None,@@ -6753,6 +6810,79 @@ profiles:);}+ #[test]+ fn test_profile_delta_keeps_stored_reasoning_effort_declarations() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let seed: ModelConfig = serde_saphyr::from_str(+ r#"+sie_id: test/model+tasks: {generate: {context_length: 4096, max_output_tokens: 1024}}+profiles:+ default:+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"+ max_batch_tokens: 4096+ reasoning_effort: {default: high, values: {low: {}, high: {}}}+ parent:+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"+ max_batch_tokens: 4096+ reasoning_effort: {values: {low: {}}}+"#,+ )+ .unwrap();+ registry.add_model_config(seed).expect("seed");++ let delta: ModelConfig = serde_saphyr::from_str(+ r#"+sie_id: test/model+profiles:+ child:+ extends: parent+ max_batch_tokens: 8192+"#,+ )+ .unwrap();+ registry+ .add_model_config(delta)+ .expect("profile-only delta");++ let accepts = |model: &str, value: &str| {+ registry+ .get_model_info(model)+ .expect(model)+ .reasoning_effort_refusal(value, model)+ .is_none()+ };+ assert!(+ accepts("test/model", "high"),+ "default keeps its declaration"+ );+ assert!(!accepts("test/model", "max"));+ assert_eq!(+ registry+ .get_model_info("test/model")+ .unwrap()+ .effective_reasoning_effort()+ .and_then(|declaration| declaration.default.clone())+ .as_deref(),+ Some("high"),+ );+ assert!(+ accepts("test/model:parent", "low"),+ "parent keeps its declaration"+ );+ assert!(+ accepts("test/model:child", "low"),+ "child inherits the stored parent's"+ );+ assert!(!accepts("test/model:child", "high"));+ }+/// M10 follow-up: a delta-update that adds a profile with new/// ``adapter_options.loadtime.lora_paths`` must refresh both the/// union (`info_extras.lora_adapters`) and the per-profile map@@ -6795,6 +6925,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -6860,6 +6991,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -7668,6 +7800,7 @@ adapters:max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("sie_server.adapters.sentence_transformer:A".to_string(),),diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 1791f794d..a2b23f805 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -2,6 +2,64 @@ use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};use std::collections::{HashMap, HashSet};+/// OpenAI's ``reasoning_effort`` values in rising order, the only ones a+/// request or a model declaration may name.+pub const REASONING_EFFORT_VALUES: &[&str] =+ &["none", "minimal", "low", "medium", "high", "xhigh", "max"];++/// Refusal text for a ``reasoning_effort`` that is not one of OpenAI's values.+pub fn reasoning_effort_malformed_message() -> String {+ format!(+ "'reasoning_effort' must be one of: {}",+ REASONING_EFFORT_VALUES.join(", ")+ )+}++/// The ``reasoning_effort`` values a route accepts, read from the model YAML+/// (``tasks.generate.reasoning_effort`` or ``profiles.<p>.reasoning_effort``).+/// The worker resolves what each value does; the gateway only checks that the+/// route accepts it and reports the set on ``/v1/models``.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ReasoningEffortDecl {+ /// Accepted values in OpenAI's order.+ pub accepted: Vec<String>,+ /// The value the route runs at when a request names none.+ pub default: Option<String>,+}++impl ReasoningEffortDecl {+ fn from_yaml(value: &Value) -> Option<Self> {+ let declaration = value.as_object()?;+ let values = declaration.get("values")?.as_object()?;+ let accepted: Vec<String> = REASONING_EFFORT_VALUES+ .iter()+ .filter(|candidate| values.contains_key(**candidate))+ .map(|candidate| (*candidate).to_string())+ .collect();+ if accepted.is_empty() {+ return None;+ }+ let default = declaration+ .get("default")+ .and_then(Value::as_str)+ .filter(|default| accepted.iter().any(|value| value == default))+ .map(str::to_owned);+ Some(Self { accepted, default })+ }++ /// The YAML shape that parses back to this declaration. The gateway keeps+ /// only the accepted values and the default, so each value's own settings+ /// are left empty.+ pub fn to_yaml_value(&self) -> Value {+ let values: Map<String, Value> = self+ .accepted+ .iter()+ .map(|value| (value.clone(), json!({})))+ .collect();+ json!({"default": self.default, "values": values})+ }+}+/// Fields mirrored from model YAML for ``/v1/models`` wire parity with/// ``sie_server`` ``ModelInfo`` (inputs, outputs, dims, profiles, …).#[derive(Debug, Clone, Default)]@@ -32,6 +90,23 @@ pub struct ModelInfoExtras {/// admission can use the concrete route's cap without widening the bare/// model or sibling variants.pub profile_max_output_tokens: HashMap<String, u32>,+ /// ``tasks.generate.context_length`` from the model YAML: the prompt plus+ /// completion envelope of the bare route.+ pub context_length: Option<u32>,+ /// Per-profile context windows. A materialized ``model:profile`` variant+ /// admits its resolved ``adapter_options.loadtime.max_seq_length`` as its+ /// context, as the worker's profile expansion does.+ pub profile_context_length: HashMap<String, u32>,+ /// ``tasks.generate.reasoning_effort`` from the model YAML.+ pub reasoning_effort: Option<ReasoningEffortDecl>,+ /// Per-profile ``reasoning_effort`` declarations: a profile's own, else+ /// its parent's. A profile without either uses the model-level one.+ pub profile_reasoning_effort: HashMap<String, ReasoningEffortDecl>,+ /// Nothing in the YAML lets the model reason: a generate task with no+ /// ``enable_thinking`` switch, reasoning parser, ``reasoning_effort``+ /// declaration or remote profile. Mirrors+ /// ``sie_server.config.model.ModelConfig.declares_no_reasoning``.+ pub declares_no_reasoning: bool,/// ``tasks.generate.capabilities.grammar`` from the/// model YAML — the list of grammar ``kind`` strings the model/// supports (e.g. ``["json_schema", "regex"]``). Gateway rejects@@ -103,6 +178,57 @@ pub struct ModelInfoExtras {pub profile_lora_adapters: Option<HashMap<String, Vec<String>>>,}+/// Whether nothing in a raw model YAML lets the model reason. A remote+/// profile counts as able to reason, because SIE cannot know whether its+/// upstream does.+fn declares_no_reasoning(raw: &Value) -> bool {+ let Some(generate) = raw+ .get("tasks")+ .and_then(|tasks| tasks.get("generate"))+ .and_then(Value::as_object)+ else {+ return false;+ };+ if raw.get("remote_backed").and_then(Value::as_bool) == Some(true)+ || generate+ .get("reasoning_effort")+ .is_some_and(|value| !value.is_null())+ || generate+ .get("chat_template_kwargs")+ .and_then(|kwargs| kwargs.get("enable_thinking"))+ .is_some()+ {+ return false;+ }+ let Some(profiles) = raw.get("profiles").and_then(Value::as_object) else {+ return true;+ };+ profiles.values().all(|profile| {+ let adapter_path = profile+ .get("adapter_path")+ .and_then(Value::as_str)+ .or_else(|| {+ profile+ .get("extends")+ .and_then(Value::as_str)+ .and_then(|parent| profiles.get(parent))+ .and_then(|parent| parent.get("adapter_path"))+ .and_then(Value::as_str)+ });+ !adapter_path.is_some_and(|path| path.starts_with(REMOTE_ADAPTER_MODULE_PREFIX))+ && profile.get("reasoning_effort").is_none_or(Value::is_null)+ && profile+ .get("chat_template_kwargs")+ .and_then(|kwargs| kwargs.get("enable_thinking"))+ .is_none()+ && profile+ .get("adapter_options")+ .and_then(|options| options.get("loadtime"))+ .and_then(|loadtime| loadtime.get("reasoning_parser"))+ .is_none_or(Value::is_null)+ })+}+impl ModelInfoExtras {/// Best-effort extraction from a raw model YAML document (same files as/// ``sie_server`` / ``sie-config``). Missing sections fall back to@@ -193,6 +319,13 @@ impl ModelInfoExtras {{extras.max_output_tokens = Some(cap);}+ extras.context_length = gen+ .get("context_length")+ .and_then(Value::as_u64)+ .and_then(|n| u32::try_from(n).ok());+ extras.reasoning_effort = gen+ .get("reasoning_effort")+ .and_then(ReasoningEffortDecl::from_yaml);// Read the per-model grammar capability list.// The YAML shape is// ``tasks.generate.capabilities.grammar: [kind, ...]``;@@ -301,7 +434,46 @@ impl ModelInfoExtras {.insert(profile_name.to_string(), cap);}}++ let parent_of = |profile: &Value| -> Option<&Value> {+ profiles.get(profile.get("extends").and_then(Value::as_str)?)+ };+ for (profile_name, profile) in profiles {+ if let Some(declaration) = profile+ .get("reasoning_effort")+ .or_else(|| {+ parent_of(profile).and_then(|parent| parent.get("reasoning_effort"))+ })+ .and_then(ReasoningEffortDecl::from_yaml)+ {+ extras+ .profile_reasoning_effort+ .insert(profile_name.to_string(), declaration);+ }+ let own_loadtime = profile+ .get("adapter_options")+ .and_then(|options| options.get("loadtime"))+ .and_then(Value::as_object)+ .filter(|loadtime| !loadtime.is_empty());+ let loadtime = own_loadtime.or_else(|| {+ parent_of(profile)+ .and_then(|parent| parent.get("adapter_options"))+ .and_then(|options| options.get("loadtime"))+ .and_then(Value::as_object)+ });+ if let Some(window) = loadtime+ .and_then(|loadtime| loadtime.get("max_seq_length"))+ .and_then(Value::as_u64)+ .filter(|value| *value > 0)+ .and_then(|value| u32::try_from(value).ok())+ {+ extras+ .profile_context_length+ .insert(profile_name.to_string(), window);+ }+ }}+ extras.declares_no_reasoning = declares_no_reasoning(raw);// Multi-LoRA: collect the served-names declared per profile and// also flatten/dedup them into the model-level union. The@@ -367,6 +539,11 @@ impl ModelInfoExtras {routing: None,max_output_tokens: None,profile_max_output_tokens: HashMap::new(),+ context_length: None,+ profile_context_length: HashMap::new(),+ reasoning_effort: None,+ profile_reasoning_effort: HashMap::new(),+ declares_no_reasoning: false,grammar_capabilities: None,streaming_supported: None,grammar_profile: None,@@ -617,6 +794,10 @@ pub struct ProfileConfig {/// preserve these exactly so routing cannot switch thinking mode.#[serde(default)]pub chat_template_kwargs: Option<serde_json::Value>,+ /// Per-profile ``reasoning_effort`` declaration; see+ /// :struct:`ReasoningEffortDecl`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reasoning_effort: Option<serde_json::Value>,#[serde(default)]pub adapter_options: Option<serde_json::Value>,#[serde(default)]@@ -680,6 +861,63 @@ impl ModelEntry {.or(self.info_extras.max_output_tokens)}+ /// Prompt plus completion tokens this concrete route admits. An explicit+ /// profile variant admits its profile's window, the bare route the+ /// model-level context, as the worker's profile expansion materializes them.+ pub fn effective_context_length(&self) -> Option<u32> {+ if self.canonical_profile != "default" {+ if let Some(window) = self+ .info_extras+ .profile_context_length+ .get(&self.canonical_profile)+ {+ return Some(*window);+ }+ }+ self.info_extras.context_length+ }++ /// The ``reasoning_effort`` declaration that governs this concrete route.+ pub fn effective_reasoning_effort(&self) -> Option<&ReasoningEffortDecl> {+ self.info_extras+ .profile_reasoning_effort+ .get(&self.canonical_profile)+ .or(self.info_extras.reasoning_effort.as_ref())+ }++ /// The refusal text for ``value`` on this route, ``None`` when the route+ /// accepts it. ``none`` is accepted on a model that cannot reason at all.+ pub fn reasoning_effort_refusal(&self, value: &str, model_name: &str) -> Option<String> {+ match self.effective_reasoning_effort() {+ Some(declaration) if declaration.accepted.iter().any(|accepted| accepted == value) => {+ None+ }+ Some(declaration) => Some(format!(+ "Model '{model_name}' does not support reasoning_effort '{value}'. Supported values: {}",+ declaration.accepted.join(", ")+ )),+ None if value == "none" && self.info_extras.declares_no_reasoning => None,+ None => Some(format!(+ "Model '{model_name}' does not support reasoning_effort"+ )),+ }+ }++ /// ``capabilities.reasoning`` on ``/v1/models``: null for a model without a+ /// generate task or one that cannot reason.+ fn reasoning_capability_value(&self) -> Value {+ if self.info_extras.streaming_supported.is_none() || self.info_extras.declares_no_reasoning+ {+ return Value::Null;+ }+ let declaration = self.effective_reasoning_effort();+ json!({+ "effort": declaration.map(|declaration| declaration.accepted.clone()).unwrap_or_default(),+ "default_effort": declaration.and_then(|declaration| declaration.default.clone()),+ "budget_tokens": {},+ })+ }+/// JSON shaped like ``sie_server.api.models.ModelInfo`` for HTTP clients.pub fn to_model_info_value(&self, loaded: bool) -> Value {let state = if loaded { "loaded" } else { "available" };@@ -696,6 +934,8 @@ impl ModelEntry {"state": state,"last_error": Value::Null,"max_sequence_length": self.info_extras.max_sequence_length,+ "context_length": self.effective_context_length(),+ "max_output_tokens": self.effective_max_output_tokens(),"revision": self.info_extras.revision,"description": self.info_extras.description.as_deref().unwrap_or(""),"release_date": self.info_extras.release_date.as_deref().unwrap_or(""),@@ -717,6 +957,7 @@ impl ModelEntry {"code": self.info_extras.code,"sql": self.info_extras.sql,"guard": self.info_extras.guard,+ "reasoning": self.reasoning_capability_value(),},"routing": self.routing_value(),})@@ -899,6 +1140,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: Some(serde_json::json!({"enable_thinking": true})),+ reasoning_effort: None,adapter_path: Some("module:Adapter".into()),max_batch_tokens: Some(4096),compute_precision: Some("float16".into()),@@ -923,6 +1165,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -940,6 +1183,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -958,6 +1202,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -975,6 +1220,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -1014,6 +1260,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -1076,6 +1323,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -1093,6 +1341,7 @@ mod tests {max_output_tokens: None,grammar_profile: None,chat_template_kwargs: None,+ reasoning_effort: None,adapter_path: Some("mod:A".into()),max_batch_tokens: Some(4096),compute_precision: None,@@ -1257,6 +1506,115 @@ profiles:assert!(!extras.profile_max_output_tokens.contains_key("sibling"));}+ fn vector_entry(config: &Value, name: &str, profile: &str) -> ModelEntry {+ ModelEntry {+ name: name.to_string(),+ canonical_base_model: name.to_string(),+ canonical_profile: profile.to_string(),+ pool: None,+ bundles: Vec::new(),+ adapter_modules: HashSet::new(),+ profile_names: HashSet::new(),+ profile_configs: HashMap::new(),+ info_extras: ModelInfoExtras::from_yaml_raw(config),+ }+ }++ #[test]+ fn test_reasoning_effort_shared_vectors() {+ let vectors: Value = serde_json::from_str(include_str!(+ "../../../../conformance/openai_generation/reasoning_effort_vectors.json"+ ))+ .unwrap();+ assert_eq!(+ reasoning_effort_malformed_message(),+ vectors["malformed_message"]+ );+ for case in vectors["cases"].as_array().unwrap() {+ let model = case["model"].as_str().unwrap();+ let entry = vector_entry(&vectors["models"][model]["config"], model, "default");+ let refusal = entry.reasoning_effort_refusal(case["value"].as_str().unwrap(), model);+ assert_eq!(+ refusal.as_deref(),+ case.get("message").and_then(Value::as_str),+ "{}",+ case["name"]+ );+ }+ for (name, model) in vectors["models"].as_object().unwrap() {+ let config = &model["config"];+ let info = vector_entry(config, name, "default").to_model_info_value(false);+ assert_eq!(+ info["capabilities"]["reasoning"], model["capability"],+ "{name}"+ );+ let generate = &config["tasks"]["generate"];+ assert_eq!(info["context_length"], generate["context_length"], "{name}");+ assert_eq!(+ info["max_output_tokens"], generate["max_output_tokens"],+ "{name}"+ );+ }+ }++ #[test]+ fn test_a_profile_variant_reports_its_own_reasoning_and_limits() {+ let config = json!({+ "sie_id": "acme/hybrid",+ "tasks": {"generate": {"context_length": 16384, "max_output_tokens": 4096}},+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter",+ "reasoning_effort": {"default": "max", "values": {"low": {}, "max": {}}}+ },+ "relay": {+ "adapter_path": "sie_server.adapters.remote.openai:OpenAIUpstreamAdapter",+ "max_output_tokens": 32768,+ "adapter_options": {"loadtime": {"max_seq_length": 131072}},+ "reasoning_effort": {"values": {"low": {"upstream": "low"}, "max": {"upstream": "max"}}}+ },+ "relay-alias": {"extends": "relay"}+ },+ "routing": {"policy": "fallback", "fallback_profile": "relay"}+ });+ let bare = vector_entry(&config, "acme/hybrid", "default").to_model_info_value(false);+ assert_eq!(bare["context_length"], 16384);+ assert_eq!(bare["max_output_tokens"], 4096);+ assert_eq!(bare["capabilities"]["reasoning"]["default_effort"], "max");+ for profile in ["relay", "relay-alias"] {+ let variant = vector_entry(&config, &format!("acme/hybrid:{profile}"), profile);+ let info = variant.to_model_info_value(false);+ assert_eq!(info["context_length"], 131072, "{profile}");+ assert_eq!(info["max_output_tokens"], 32768, "{profile}");+ assert_eq!(+ info["capabilities"]["reasoning"]["effort"],+ json!(["low", "max"])+ );+ assert_eq!(+ info["capabilities"]["reasoning"]["default_effort"],+ Value::Null+ );+ assert_eq!(variant.reasoning_effort_refusal("low", "acme/hybrid"), None);+ }+ }++ #[test]+ fn test_a_model_without_a_generate_task_reports_no_reasoning_or_limits() {+ let config = json!({+ "sie_id": "acme/embedder",+ "tasks": {"encode": {"dense": {"dim": 8}}},+ "profiles": {"default": {"adapter_path": "module:Adapter"}}+ });+ let entry = vector_entry(&config, "acme/embedder", "default");+ let info = entry.to_model_info_value(false);+ assert_eq!(info["capabilities"]["reasoning"], Value::Null);+ assert_eq!(info["context_length"], Value::Null);+ assert_eq!(info["max_output_tokens"], Value::Null);+ assert!(entry+ .reasoning_effort_refusal("none", "acme/embedder")+ .is_some());+ }+#[test]fn test_model_entry_effective_output_cap_does_not_widen_siblings() {let mut profile_caps = HashMap::new();diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex ac0c91c74..bf1ce4a0e 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -325,6 +325,19 @@ class ModelDims(TypedDict, total=False):multivector: int+class ModelReasoning(TypedDict, total=False):+ """How a model's reasoning can be steered with the chat ``reasoning_effort`` field."""++ effort: list[str]+ """Accepted ``reasoning_effort`` values in OpenAI's order. Empty means the field is refused."""++ default_effort: str | None+ """The value the model runs at when a request names none, ``None`` when it is not a declared value."""++ budget_tokens: dict[str, int]+ """The hard reasoning-token ceiling of each value that has one. Other values only instruct the model."""++class ModelCapabilities(TypedDict, total=False):"""Advertised model capabilities.@@ -348,6 +361,8 @@ class ModelCapabilities(TypedDict, total=False):tools: boollora_adapters: list[str]profile_lora_adapters: dict[str, list[str]]+ reasoning: ModelReasoning | None+ """``None`` when nothing in the model's config lets it reason."""code: boolsql: boolguard: bool@@ -453,6 +468,10 @@ class ModelInfo(TypedDict, total=False):outputs: list[str] # ["dense"], ["dense", "sparse"], etc.dims: ModelDimsmax_sequence_length: int | None+ context_length: int | None+ """Prompt plus completion tokens the route admits, ``None`` without a generate task."""+ max_output_tokens: int | None+ """The largest output-token request the route admits, ``None`` without a generate task."""revision: str | Nonedescription: str"""One line about the model; ``""`` when the catalog sets none."""diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 0302ea6c1..14b93fddf 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -2099,6 +2099,16 @@"type": "boolean","title": "Guard","default": false+ },+ "reasoning": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelReasoning"+ },+ {+ "type": "null"+ }+ ]}},"type": "object",@@ -2169,6 +2179,28 @@],"title": "Max Sequence Length"},+ "context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Context Length"+ },+ "max_output_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Max Output Tokens"+ },"profiles": {"additionalProperties": {"$ref": "#/components/schemas/ProfileInfo"@@ -2259,6 +2291,40 @@"title": "ModelLoadError","description": "Diagnostic detail for a recorded load failure.\n\nSurfaced in :class:`ModelInfo` when the registry has a sticky\nfailure for the model. Attributes mirror the server-side\n:class:`sie_server.core.load_errors.LoadFailure`."},+ "ModelReasoning": {+ "properties": {+ "effort": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Effort",+ "default": []+ },+ "default_effort": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Default Effort"+ },+ "budget_tokens": {+ "additionalProperties": {+ "type": "integer"+ },+ "type": "object",+ "title": "Budget Tokens",+ "default": {}+ }+ },+ "type": "object",+ "title": "ModelReasoning",+ "description": "How a model's reasoning can be steered with the chat ``reasoning_effort`` field."+ },"ModelRouting": {"properties": {"policy": {diff --git a/packages/sie_server/src/sie_server/api/anthropic_translation.py b/packages/sie_server/src/sie_server/api/anthropic_translation.pyindex 7a41e5997..f68069612 100644--- a/packages/sie_server/src/sie_server/api/anthropic_translation.py+++ b/packages/sie_server/src/sie_server/api/anthropic_translation.py@@ -305,11 +305,12 @@ def messages_to_chat(body: Any, anthropic_version: str | None) -> ChatTranslatioraise _invalid(f"anthropic-version: only {SUPPORTED_ANTHROPIC_VERSION} is supported")if not isinstance(body, dict):raise _invalid("body: Input should be a valid dictionary")+ effort: str | None = Nonefor key in body:if key in _TOP_LEVEL_FIELDS:continueif key == "output_config":- _output_config(body[key])+ effort = _output_config(body[key])elif key == "context_management":raise _invalid(CONTEXT_MANAGEMENT_REFUSAL)else:@@ -379,14 +380,30 @@ def messages_to_chat(body: Any, anthropic_version: str | None) -> ChatTranslatioif parallel_tool_calls is not None:chat["parallel_tool_calls"] = parallel_tool_callschat["include_reasoning"] = include_reasoning+ if effort is not None:+ chat["reasoning_effort"] = effortreturn ChatTranslation(chat=chat, model=model, stream=stream, first_image=first_image[0] if first_image else None)-def _output_config(value: Any) -> None:+_ANTHROPIC_EFFORTS = ("low", "medium", "high", "xhigh", "max")+EFFORT_REFUSAL = "output_config.effort: Extra inputs are not permitted"+"""A route that does not accept the effort answers in the wording clients that drop the field recover from."""+++def _output_config(value: Any) -> str | None:+ """The chat route's ``reasoning_effort`` from ``output_config``, whose only accepted key is ``effort``."""if value is None:- return- for key in _object(value, "output_config"):- raise _extra(f"output_config.{key}")+ return None+ config = _object(value, "output_config")+ for key in config:+ if key != "effort":+ raise _extra(f"output_config.{key}")+ effort = config.get("effort")+ if effort is None:+ return None+ if not isinstance(effort, str) or effort not in _ANTHROPIC_EFFORTS:+ raise _invalid("output_config.effort: Input should be 'low', 'medium', 'high', 'xhigh' or 'max'")+ return effortdef _max_tokens(value: Any) -> int:@@ -1294,6 +1311,8 @@ def translate_error_body(status: int, body: Any, context: ErrorContext) -> tuplemessage = _default_message(status)if status != HTTPStatus.BAD_REQUEST:return error_type, message, code+ if param == "reasoning_effort" and code == "unsupported_field":+ return error_type, EFFORT_REFUSAL, codecap = _output_cap(message)if cap is not None:requested, limit = cap@@ -1324,6 +1343,8 @@ def _anthropic_param(param: str) -> str:return "max_tokens"if param == "stop":return "stop_sequences"+ if param == "reasoning_effort":+ return "output_config.effort"if param.startswith("tools["):index, separator, field = param[len("tools[") :].partition("].function.")if separator:diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.pyindex 1e51aa4aa..389cd75c0 100644--- a/packages/sie_server/src/sie_server/api/models.py+++ b/packages/sie_server/src/sie_server/api/models.py@@ -56,6 +56,19 @@ class ModelLoadError(BaseModel):"""True when the failure will not auto-retry; operator must intervene."""+class ModelReasoning(BaseModel):+ """How a model's reasoning can be steered with the chat ``reasoning_effort`` field."""++ effort: list[str] = []+ """Accepted ``reasoning_effort`` values in OpenAI's order. Empty means the field is refused."""++ default_effort: str | None = None+ """The value the model runs at when a request names none, ``None`` when it is not a declared value."""++ budget_tokens: dict[str, int] = {}+ """The hard reasoning-token ceiling of each value that has one. Other values only instruct the model."""++class ModelCapabilities(BaseModel):"""Advertised generation capabilities for a model.@@ -80,6 +93,8 @@ class ModelCapabilities(BaseModel):code: bool = Falsesql: bool = Falseguard: bool = False+ reasoning: ModelReasoning | None = None+ """``None`` when nothing in the model's config lets it reason."""class ModelRouting(BaseModel):@@ -109,6 +124,12 @@ class ModelInfo(BaseModel):"""Recorded load failure (when ``state == 'failed'``), else ``None``."""max_sequence_length: int | None = None+ context_length: int | None = None+ """Prompt plus completion tokens the route admits, ``None`` for a model without a generate task."""++ max_output_tokens: int | None = None+ """The largest output-token request the route admits, ``None`` for a model without a generate task."""+profiles: dict[str, ProfileInfo] = {}lora_adapters: list[str] = Field(default_factory=list)"""LoRA served names currently ready on this worker, excluding loading/evicting adapters."""@@ -141,6 +162,12 @@ def _config_text(config: Any, field: str) -> str:return value if isinstance(value, str) else ""+def _generate_limit(config: ModelConfig, field: str) -> int | None:+ """A generation limit of the route ``config`` describes, as admission reads it."""+ generate = config.tasks.generate+ return getattr(generate, field) if generate is not None else None++def _resolve_routing(config: ModelConfig) -> ModelRouting:default = config.resolve_profile("default")policy: RoutingPolicy@@ -215,9 +242,19 @@ def _resolve_capabilities(config: Any) -> ModelCapabilities | None:code=caps.code,sql=caps.sql,guard=caps.guard,+ reasoning=_resolve_reasoning(config),)+def _resolve_reasoning(config: ModelConfig) -> ModelReasoning | None:+ if config.declares_no_reasoning:+ return None+ declaration = config.reasoning_effort_for("default")+ if declaration is None:+ return ModelReasoning()+ return ModelReasoning(effort=list(declaration.accepted), default_effort=declaration.default)++def _profile_info(registry: "ModelRegistry | Any", name: str, config: ModelConfig, profile: str) -> ProfileInfo:remote = is_remote_adapter_path(config.resolve_profile(profile).adapter_path)return ProfileInfo(@@ -268,6 +305,8 @@ async def list_models(http_request: Request) -> ModelsListResponse:state=state,last_error=last_error,max_sequence_length=config.max_sequence_length,+ context_length=_generate_limit(config, "context_length"),+ max_output_tokens=_generate_limit(config, "max_output_tokens"),profiles=profiles,revision=getattr(config, "hf_revision", None),description=_config_text(config, "description"),@@ -321,6 +360,8 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:state=state,last_error=last_error,max_sequence_length=config.max_sequence_length,+ context_length=_generate_limit(config, "context_length"),+ max_output_tokens=_generate_limit(config, "max_output_tokens"),profiles=profiles,revision=getattr(config, "hf_revision", None),description=_config_text(config, "description"),diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex bed0e9b2c..12733c69b 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -50,6 +50,7 @@ from sie_server.adapters._generation_base import (GenerationAdapter,GenerationError,GenerationInputTooLongError,+ GenerationInvalidRequestError,GenerationUnsupportedFieldError,GenerationUpstreamError,ReasoningFormat,@@ -92,6 +93,7 @@ from sie_server.config.upstreams import RemoteServingDisabledErrorfrom sie_server.core.grammar_routing import resolve_grammar_serving_modelfrom sie_server.core.inference_output import ScoreOutputfrom sie_server.core.loader import serves_remotely+from sie_server.core.reasoning_effort import AppliedReasoningEffort, apply_reasoning_effort, parse_reasoning_effortfrom sie_server.core.runtime_options import (GenerationTimeoutError,grammar_default_sampling,@@ -189,6 +191,7 @@ _CUDA_CHAT_FIELDS = frozenset("response_format","schema_in_prompt","include_reasoning",+ "reasoning_effort","stream","tools","tool_choice",@@ -223,6 +226,7 @@ _MLX_CHAT_FIELDS = frozenset("stream","stream_options","include_reasoning",+ "reasoning_effort","tools","tool_choice","parallel_tool_calls",@@ -830,6 +834,13 @@ def _merge_stops(request_stop: Any, configured: Any) -> Any:return merged+def _apply_effort_template_kwargs(proxied: dict[str, Any], effort: AppliedReasoningEffort | None) -> None:+ """Layer the declared template kwargs of the request's ``reasoning_effort`` over the merged kwargs."""+ if effort is None or not effort.chat_template_kwargs:+ return+ proxied["chat_template_kwargs"] = {**(proxied.get("chat_template_kwargs") or {}), **effort.chat_template_kwargs}++def _prepare_chat_body(body: dict[str, Any],*,@@ -852,6 +863,7 @@ def _prepare_chat_body(proxied.pop("safety_identifier", None)proxied.pop("schema_in_prompt", None)proxied.pop("include_reasoning", None)+ proxied.pop("reasoning_effort", None)proxied.pop("lora_adapter", None)if proxied.get("parallel_tool_calls") is None:proxied.pop("parallel_tool_calls", None)@@ -1002,6 +1014,7 @@ def _prepare_mlx_body() -> dict[str, Any]:proxied = dict(body)proxied.pop("include_reasoning", None)+ proxied.pop("reasoning_effort", 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:@@ -1739,6 +1752,12 @@ async def _chat_completions(raise _bad_request(f"Model '{model}' does not support tool calling", param="tools", code="unsupported_field")+ try:+ reasoning_effort = parse_reasoning_effort(body.get("reasoning_effort"))+ apply_reasoning_effort(config, reasoning_effort, model=model)+ except (GenerationInvalidRequestError, GenerationUnsupportedFieldError) as exc:+ code = "unsupported_field" if isinstance(exc, GenerationUnsupportedFieldError) else None+ raise _bad_request(str(exc), param=exc.param, code=code) from excadapter_chat = _adapter_answers_chat(config)if _has_image_parts(messages) and not ((config.inputs.image and str(device).startswith("cuda") and not adapter_chat)@@ -1785,11 +1804,18 @@ async def _chat_completions(registry.touch_lru(route.key)await ensure_generation_lora(registry, route.key, lora, n=body.get("n"))route_config = registry.get_config(route.key)+ try:+ effort = apply_reasoning_effort(route_config, reasoning_effort, model=model)+ except GenerationUnsupportedFieldError as exc:+ raise _bad_request(str(exc), param=exc.param, code="unsupported_field") from excif _adapter_answers_chat(route_config) and isinstance(adapter, GenerationAdapter):_validate_remote_chat_media(messages, images=_remote_chat_accepts_images(route_config))+ upstream_effort = (+ {"reasoning_effort": effort.upstream} if effort is not None and effort.upstream is not None else {}+ )return await _remote_chat_response(adapter,- {**prepared_chat, "messages": _remote_chat_messages(prepared_chat["messages"])},+ {**prepared_chat, "messages": _remote_chat_messages(prepared_chat["messages"]), **upstream_effort},requested_model=model,config=config,stream=bool(stream_opt),@@ -1813,6 +1839,7 @@ async def _chat_completions(max_tokens=max_tokens,seed=seed,)+ _apply_effort_template_kwargs(proxied, effort)try:await adapter.check_chat_window(proxied, requested_model=model)except GenerationInputTooLongError as exc:@@ -1830,6 +1857,7 @@ async def _chat_completions(max_tokens=max_tokens,seed=seed,)+ _apply_effort_template_kwargs(proxied, effort)proxied["messages"] = await _messages_showing_response_format(body, config, proxied["messages"])else:raise _unsupported_chat(model, device)diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex f945ec91d..4ce8a7b91 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -89,6 +89,77 @@ def validate_chat_template_kwargs(value: dict[str, Any] | None) -> dict[str, Anyreturn value+REASONING_EFFORT_VALUES: tuple[str, ...] = ("none", "minimal", "low", "medium", "high", "xhigh", "max")+"""OpenAI's ``reasoning_effort`` values in rising order, the only ones a request or a declaration may name."""+ReasoningEffortValue = Literal["none", "minimal", "low", "medium", "high", "xhigh", "max"]+_REASONING_LEVEL_TEMPLATE_KWARGS = frozenset({"reasoning_effort", "reasoning_strength"})+_REASONING_LEVEL_TEXT = re.compile(r"^[A-Za-z0-9_-]{1,32}$")+++class ReasoningEffortLevel(BaseModel):+ """What one accepted ``reasoning_effort`` value does on a generation profile.++ ``chat_template_kwargs`` set the model's own effort switch where SIE renders+ the prompt. ``upstream`` is the top-level ``reasoning_effort`` a remote+ profile sends to its upstream chat. A level that sets neither accepts the+ value and changes nothing, for the value the model already runs at.+ """++ model_config = ConfigDict(extra="forbid", frozen=True)++ chat_template_kwargs: dict[str, str] | None = None+ upstream: str | None = None++ @field_validator("chat_template_kwargs")+ @classmethod+ def validate_level_template_kwargs(cls, value: dict[str, str] | None) -> dict[str, str] | None:+ if value is None:+ return None+ unsupported = set(value) - _REASONING_LEVEL_TEMPLATE_KWARGS+ if unsupported:+ names = ", ".join(sorted(unsupported))+ raise ValueError(f"unsupported reasoning_effort chat_template_kwargs key(s): {names}")+ for key, text in value.items():+ if not _REASONING_LEVEL_TEXT.fullmatch(text):+ raise ValueError(f"reasoning_effort chat_template_kwargs.{key} must be 1 to 32 letters, digits, - or _")+ return value++ @field_validator("upstream")+ @classmethod+ def validate_upstream_value(cls, value: str | None) -> str | None:+ if value is not None and not _REASONING_LEVEL_TEXT.fullmatch(value):+ raise ValueError("reasoning_effort upstream must be 1 to 32 letters, digits, - or _")+ return value+++class ReasoningEffortDeclaration(BaseModel):+ """The ``reasoning_effort`` values a generation profile accepts, and what each does.++ ``default`` names the value the profile already runs at when a request+ names none, or is ``None`` when that is not one of the declared values. It+ is reported on ``/v1/models`` and never applied, so a request without the+ field renders and calls its upstream exactly as before.+ """++ model_config = ConfigDict(extra="forbid", frozen=True)++ default: ReasoningEffortValue | None = None+ values: dict[ReasoningEffortValue, ReasoningEffortLevel]++ @model_validator(mode="after")+ def validate_values(self) -> "ReasoningEffortDeclaration":+ if not self.values:+ raise ValueError("reasoning_effort.values must name at least one value")+ if self.default is not None and self.default not in self.values:+ raise ValueError(f"reasoning_effort.default '{self.default}' is not one of its values")+ return self++ @property+ def accepted(self) -> tuple[str, ...]:+ """The accepted values in OpenAI's order."""+ return tuple(value for value in REASONING_EFFORT_VALUES if value in self.values)++# Served-model version identity. An *immutable* HF revision is a full 40-char git# commit SHA (SHA-1, lowercase hex). Branch/tag names ("main", "v1.0") resolve to# *moving* targets on the Hub, so they are NOT acceptable pins for a promoted/served@@ -261,6 +332,10 @@ class GenerateTask(BaseModel):budget is a per-worker/per-profile shape rather than a per-tasksemantic.+ ``reasoning_effort`` declares the OpenAI ``reasoning_effort`` values the+ model's profiles accept and what each does. A profile may replace it with+ its own declaration. ``None`` refuses the request field.+``grammar_profile`` optionally names a profile that grammar-constrainedrequests (OpenAI ``response_format`` / SIE-native ``grammar``) must run on.When set, the gateway rewrites such a request's model id to the@@ -286,6 +361,14 @@ class GenerateTask(BaseModel):chat_template_kwargs: dict[str, Any] = Field(default_factory=dict)prewarm_grammars: list[PrewarmGrammar] = Field(default_factory=list)grammar_profile: str | None = None+ reasoning_effort: ReasoningEffortDeclaration | None = None++ @model_serializer(mode="wrap")+ def _serialize_generate_task(self, handler: SerializerFunctionWrapHandler): # noqa: ANN202 -- retain field-level serialization schema+ data = handler(self)+ if data.get("reasoning_effort") is None:+ data.pop("reasoning_effort", None)+ return data@field_validator("chat_template_kwargs")@classmethod@@ -566,6 +649,9 @@ class ProfileConfig(BaseModel):gateway uses it only for constrained requests, allowing a long-context orthinking profile to route to a non-speculative twin without losing itscontext window, hardware launch shape, or tokenizer mode.++ ``reasoning_effort`` replaces the generation task's declaration for this+ profile and the profiles that extend it."""model_config = ConfigDict(extra="forbid")@@ -583,6 +669,7 @@ class ProfileConfig(BaseModel):max_output_tokens: int | None = Field(default=None, gt=0)chat_template_kwargs: dict[str, Any] | None = Nonegrammar_profile: str | None = None+ reasoning_effort: ReasoningEffortDeclaration | None = None@model_serializer(mode="wrap")def _serialize_profile(self, handler: SerializerFunctionWrapHandler): # noqa: ANN202 -- retain field-level serialization schema@@ -591,6 +678,8 @@ class ProfileConfig(BaseModel):# new option is omitted. Explicit False must survive parent overrides.if data.get("bounded_batch_progress") is None:data.pop("bounded_batch_progress", None)+ if data.get("reasoning_effort") is None:+ data.pop("reasoning_effort", None)return data@field_validator("chat_template_kwargs")@@ -1067,6 +1156,92 @@ class ModelConfig(BaseModel):parent = self.profiles.get(profile.extends)return parent.adapter_path if parent is not None else None+ @model_validator(mode="after")+ def validate_reasoning_effort(self) -> "ModelConfig":+ """A declaration fits the side that serves it, and a routed model's two profiles accept the same values."""+ declared_on_profiles = [name for name, profile in self.profiles.items() if profile.reasoning_effort is not None]+ if self.tasks.generate is None:+ if declared_on_profiles:+ msg = (+ f"Profile '{declared_on_profiles[0]}' declares reasoning_effort, but the model has no generate task"+ )+ raise ValueError(msg)+ return self+ for name in self.profiles:+ declaration = self.reasoning_effort_for(name)+ if declaration is None:+ continue+ remote = is_remote_adapter_path(self._declared_adapter_path(name))+ for value, level in declaration.values.items():+ if remote and level.chat_template_kwargs is not None:+ msg = (+ f"Profile '{name}' is remote, so its reasoning_effort value '{value}' can only name "+ "the upstream's own value, not chat_template_kwargs"+ )+ raise ValueError(msg)+ if not remote and level.upstream is not None:+ msg = f"Profile '{name}' is local, so its reasoning_effort value '{value}' cannot name an upstream value"+ raise ValueError(msg)+ routing = self.routing+ if routing is not None and routing.fallback_profile is not None and "default" in self.profiles:+ local = self.reasoning_effort_for("default")+ remote = self.reasoning_effort_for(routing.fallback_profile)+ local_values = local.accepted if local is not None else ()+ remote_values = remote.accepted if remote is not None else ()+ if local_values != remote_values:+ msg = (+ f"Profiles 'default' and '{routing.fallback_profile}' serve one route, so they must accept "+ f"the same reasoning_effort values, got {list(local_values)} and {list(remote_values)}"+ )+ raise ValueError(msg)+ local_default = local.default if local is not None else None+ remote_default = remote.default if remote is not None else None+ if local_default != remote_default:+ msg = (+ f"Profiles 'default' and '{routing.fallback_profile}' serve one route, so they must declare "+ f"the same reasoning_effort default, got {local_default!r} and {remote_default!r}"+ )+ raise ValueError(msg)+ return self++ def reasoning_effort_for(self, profile_name: str = "default") -> ReasoningEffortDeclaration | None:+ """The ``reasoning_effort`` declaration that governs ``profile_name``.++ The profile's own declaration wins, then its parent's, then the+ generation task's.+ """+ profile = self.profiles.get(profile_name)+ if profile is not None:+ if profile.reasoning_effort is not None:+ return profile.reasoning_effort+ parent = self.profiles.get(profile.extends) if profile.extends is not None else None+ if parent is not None and parent.reasoning_effort is not None:+ return parent.reasoning_effort+ generate = self.tasks.generate+ return generate.reasoning_effort if generate is not None else None++ @property+ def declares_no_reasoning(self) -> bool:+ """Whether nothing in this config lets the model reason.++ That needs a generate task with no ``enable_thinking`` switch, no+ reasoning parser, no ``reasoning_effort`` declaration and no remote+ profile, because SIE cannot know whether an upstream reasons.+ """+ generate = self.tasks.generate+ if generate is None or self.remote_backed:+ return False+ if "enable_thinking" in generate.chat_template_kwargs or generate.reasoning_effort is not None:+ return False+ for name, profile in self.profiles.items():+ if profile.reasoning_effort is not None or is_remote_adapter_path(self._declared_adapter_path(name)):+ return False+ if profile.chat_template_kwargs is not None and "enable_thinking" in profile.chat_template_kwargs:+ return False+ if profile.adapter_options.loadtime.get("reasoning_parser") is not None:+ return False+ return True+def lora_revisions(self) -> dict[str, str | None]:"""Every LoRA id any profile declares -> its pinned revision (``None`` = unpinned).diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 16b146d6e..f23aff222 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -294,6 +294,10 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:)if profile_max_output_tokens is not None and config.tasks.generate is not None:generate_updates["max_output_tokens"] = profile_max_output_tokens+ if config.tasks.generate is not None:+ profile_reasoning_effort = config.reasoning_effort_for(profile_name)+ if profile_reasoning_effort != config.tasks.generate.reasoning_effort:+ generate_updates["reasoning_effort"] = profile_reasoning_effortif generate_updates and config.tasks.generate is not None:variant_updates["tasks"] = config.tasks.model_copy(update={diff --git a/packages/sie_server/src/sie_server/core/reasoning_effort.py b/packages/sie_server/src/sie_server/core/reasoning_effort.pynew file mode 100644index 000000000..0adcd99c4--- /dev/null+++ b/packages/sie_server/src/sie_server/core/reasoning_effort.py@@ -0,0 +1,72 @@+"""Translate a chat request's OpenAI ``reasoning_effort`` into what the serving profile declares.++The caller's string never reaches a chat template or an upstream unread: each+profile declares the values it accepts and what each does, and every ingress+resolves the request against that declaration with these functions.+"""++from collections.abc import Mapping+from dataclasses import dataclass, field+from typing import Any, cast++from sie_server.adapters._generation_base import GenerationInvalidRequestError, GenerationUnsupportedFieldError+from sie_server.config.model import REASONING_EFFORT_VALUES, ModelConfig, ReasoningEffortValue++PARAM = "reasoning_effort"+MALFORMED_MESSAGE = f"'reasoning_effort' must be one of: {', '.join(REASONING_EFFORT_VALUES)}"+++@dataclass(frozen=True)+class AppliedReasoningEffort:+ """What an accepted value does: template kwargs SIE renders, or the value an upstream receives."""++ chat_template_kwargs: Mapping[str, str] = field(default_factory=dict)+ upstream: str | None = None+++def parse_reasoning_effort(raw: Any) -> str | None:+ """Return the request's value, ``None`` when it is absent or null.++ Raises:+ GenerationInvalidRequestError: When the value is not one of OpenAI's values.+ """+ if raw is None:+ return None+ if not isinstance(raw, str) or raw not in REASONING_EFFORT_VALUES:+ raise GenerationInvalidRequestError(PARAM, MALFORMED_MESSAGE)+ return raw+++def unsupported_message(model: str, accepted: tuple[str, ...], value: str) -> str:+ """The refusal text for ``value`` on a model that accepts ``accepted``, shared by every ingress."""+ if not accepted:+ return f"Model '{model}' does not support reasoning_effort"+ return f"Model '{model}' does not support reasoning_effort '{value}'. Supported values: {', '.join(accepted)}"+++def apply_reasoning_effort(+ config: ModelConfig | None, value: str | None, *, model: str+) -> AppliedReasoningEffort | None:+ """Resolve ``value`` against the declaration of ``config``'s default profile.++ ``None`` means nothing changes: the request named no value, or named+ ``none`` for a model that does not reason at all. The declared default is+ not applied to a request that names no value.++ Raises:+ GenerationUnsupportedFieldError: When the profile does not accept ``value``.+ """+ if value is None:+ return None+ declaration = config.reasoning_effort_for("default") if config is not None else None+ if declaration is None:+ if value == "none" and config is not None and config.declares_no_reasoning:+ return None+ raise GenerationUnsupportedFieldError(PARAM, unsupported_message(model, (), value))+ level = declaration.values.get(cast("ReasoningEffortValue", value))+ if level is None:+ raise GenerationUnsupportedFieldError(PARAM, unsupported_message(model, declaration.accepted, value))+ return AppliedReasoningEffort(+ chat_template_kwargs=dict(level.chat_template_kwargs or {}),+ upstream=level.upstream,+ )diff --git a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.pyindex f6ccf7bdc..ba9b63bbd 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py@@ -70,6 +70,7 @@ async def prepare_rendered_chat(or mode in {"required", "named"}or (body.get("n") or 1) > 1or response_format.get("type", "text") != "text"+ or body.get("reasoning_effort") is not Noneor body.get("logprobs")or body.get("logit_bias")or any(diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 5205eb362..700366391 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -80,6 +80,7 @@ from sie_server.adapters.remote.sie import SieUpstreamAdapterfrom sie_server.api.helpers import oom_retry_after_from_registryfrom sie_server.config.model import validate_chat_template_kwargsfrom sie_server.core.grammar_routing import resolve_grammar_serving_model+from sie_server.core.reasoning_effort import AppliedReasoningEffort, apply_reasoning_effort, parse_reasoning_effortfrom sie_server.core.runtime_options import apply_generation_runtime_optionsfrom sie_server.core.text_tokens import estimate_tokens_from_charsfrom sie_server.core.tokenizer import image_first_chat_message, load_image_token_id, load_tokenizer@@ -836,6 +837,9 @@ class _GenerateRequestParams:# ``reasoning_delta`` chunks instead of dropping it. Honoured only for a# model whose config declares reasoning.include_reasoning: bool = False+ # Chat ``reasoning_effort``: one of OpenAI's values, resolved against the+ # serving profile's declaration before rendering or the upstream call.+ reasoning_effort: str | None = None# Set only by the native ``/v1/generate`` route: a remote-backed model on# a chat-only upstream receives the prompt as one user message. Other# routes' prompts are raw continuations.@@ -877,13 +881,15 @@ def _remote_chat_parameters(*,images: bool = False,chat_template_kwargs: Mapping[str, Any] | None = None,+ reasoning_effort: str | None = None,) -> dict[str, Any]:"""Project validated queue parameters onto the upstream chat contract.``images`` admits message images, sent as base64 data-URI ``image_url``parts. ``chat_template_kwargs`` are the model's own template kwargs, sent- for the upstream to render with. Every refusal precedes image encoding,- which decodes each image and so runs off the event loop.+ for the upstream to render with. ``reasoning_effort`` is the value the+ remote profile declares for the request's value. Every refusal precedes+ image encoding, which decodes each image and so runs off the event loop."""assert isinstance(params.input, _MessagesInput)for field in ("top_k", "repetition_penalty", "min_tokens", "chat_template_kwargs", "lora_adapter"):@@ -921,6 +927,8 @@ def _remote_chat_parameters(}if chat_template_kwargs:body["chat_template_kwargs"] = dict(chat_template_kwargs)+ if reasoning_effort is not None:+ body["reasoning_effort"] = reasoning_effortfor field in ("stop", "frequency_penalty", "presence_penalty", "seed", "logit_bias", "top_logprobs"):value = getattr(params, field)if value is not None:@@ -1985,6 +1993,25 @@ class StreamingProcessor:msg=msg,)return+ effort: AppliedReasoningEffort | None = None+ try:+ if params.reasoning_effort is not None and not isinstance(params.input, _MessagesInput):+ raise GenerationUnsupportedFieldError(+ "reasoning_effort", "'reasoning_effort' needs a chat messages request"+ )+ effort = apply_reasoning_effort(config, params.reasoning_effort, model=model_id)+ except GenerationError as exc:+ await self._terminal_error_then_settle(+ reply_subject,+ request_id=request_id,+ attempt_id=attempt_id,+ seq=0,+ code=exc.code,+ message=str(exc),+ param=exc.param,+ msg=msg,+ )+ returnsuppress_thinking = thinking_blocks_must_be_hidden(config)keep_reasoning = params.include_reasoning and suppress_thinkingreasoning_format = resolve_reasoning_format(config, adapter)@@ -2007,6 +2034,7 @@ class StreamingProcessor:and ((config is not None and config.remote_backed)or params.grammar is not None+ or (effort is not None and effort.upstream is not None)or tool_choice_mode in ("required", "named")or any(tool.get("function", {}).get("strict") is True for tool in effective_tools or ())or (params.n is not None and params.n > 1)@@ -2043,6 +2071,7 @@ class StreamingProcessor:chat_template_kwargs=(generate_task.chat_template_kwargs if counted_upstream and generate_task is not None else None),+ reasoning_effort=effort.upstream if effort is not None else None,)try:assert isinstance(params.input, _MessagesInput)@@ -2174,6 +2203,7 @@ class StreamingProcessor:effective_tools,request_kwargs=params.chat_template_kwargs,response_format=params.grammar if params.schema_in_prompt else None,+ level_kwargs=effort.chat_template_kwargs if effort is not None else None,)if isinstance(rendered, _ValidationError):await self._terminal_error_then_settle(@@ -3677,6 +3707,10 @@ class StreamingProcessor:if include_reasoning_raw is not None and not isinstance(include_reasoning_raw, bool):return _ValidationError(code="invalid_request", message="'include_reasoning' must be a boolean")include_reasoning = bool(include_reasoning_raw)+ try:+ reasoning_effort = parse_reasoning_effort(params.get("reasoning_effort"))+ except GenerationInvalidRequestError as exc:+ return _ValidationError(code="invalid_request", message=str(exc))native_prompt_raw = params.get("native_prompt")if native_prompt_raw is not None and not isinstance(native_prompt_raw, bool):return _ValidationError(code="invalid_request", message="'native_prompt' must be a boolean")@@ -3827,6 +3861,7 @@ class StreamingProcessor:stream=stream,lora_adapter=lora_adapter,include_reasoning=include_reasoning,+ reasoning_effort=reasoning_effort,native_prompt=bool(native_prompt_raw),)@@ -3902,6 +3937,7 @@ class StreamingProcessor:tools: tuple[dict[str, Any], ...] | None = None,request_kwargs: dict[str, Any] | None = None,response_format: GrammarSpec | None = None,+ level_kwargs: Mapping[str, str] | None = None,) -> str | _ValidationError:"""Render a chat-message list into a prompt string via the tokenizer'schat template. Returns the rendered string or a validation error@@ -3922,6 +3958,10 @@ class StreamingProcessor:operator config is authoritative; per-request overrides onlyfill in keys the YAML didn't set.+ ``level_kwargs`` are the template kwargs the model's+ ``reasoning_effort`` declaration names for the request's value. They+ are operator configuration too, and are applied last.+``response_format`` is a ``json_schema`` grammar to show the model:it is written into the system message as a ``# Response Formats``section (see :mod:`sie_server.processors.schema_prompt`) unless a@@ -3958,6 +3998,8 @@ class StreamingProcessor:raw_kwargs = config.tasks.generate.chat_template_kwargsif isinstance(raw_kwargs, dict):kwargs.update(raw_kwargs)+ if level_kwargs:+ kwargs.update(level_kwargs)# Reject pathologically large message lists before the CPU-bound# render: ``apply_chat_template`` is input-sized and runs on thediff --git a/packages/sie_server/tests/api/test_anthropic_messages_route.py b/packages/sie_server/tests/api/test_anthropic_messages_route.pyindex 2aafcee29..fb09646d2 100644--- a/packages/sie_server/tests/api/test_anthropic_messages_route.py+++ b/packages/sie_server/tests/api/test_anthropic_messages_route.py@@ -279,11 +279,22 @@ def test_max_tokens_cuts_the_answer_with_a_max_tokens_stop(client: TestClient) -def test_a_translation_refusal_reaches_no_engine(client: TestClient, registry: MagicMock) -> None:+ registry.get.reset_mock()+ response = _post(client, _body(output_config={"format": {"type": "json_schema"}}))++ assert _error(response, 400, "invalid_request_error") == "output_config.format: Extra inputs are not permitted"+ assert response.headers["x-sie-error-code"] == "INVALID_REQUEST"+ registry.get.assert_not_called()+++def test_an_effort_the_model_does_not_accept_answers_the_recovery_wording(+ client: TestClient, registry: MagicMock+) -> None:registry.get.reset_mock()response = _post(client, _body(output_config={"effort": "high"}))assert _error(response, 400, "invalid_request_error") == "output_config.effort: Extra inputs are not permitted"- assert response.headers["x-sie-error-code"] == "INVALID_REQUEST"+ assert response.headers["x-sie-error-code"] == "unsupported_field"registry.get.assert_not_called()diff --git a/packages/sie_server/tests/api/test_anthropic_translation.py b/packages/sie_server/tests/api/test_anthropic_translation.pyindex 08fc0749d..42df96df1 100644--- a/packages/sie_server/tests/api/test_anthropic_translation.py+++ b/packages/sie_server/tests/api/test_anthropic_translation.py@@ -109,6 +109,7 @@ def test_a_captured_claude_code_request_translates_or_fails_with_the_recovery_woassert translation.chat["include_reasoning"] == chat["include_reasoning"]assert len(translation.chat.get("tools") or []) == chat["tool_count"]assert translation.chat.get("stop") == chat.get("stop")+ assert translation.chat.get("reasoning_effort") == chat.get("reasoning_effort")_chat_route_accepts(translation.chat)diff --git a/packages/sie_server/tests/core/test_reasoning_effort.py b/packages/sie_server/tests/core/test_reasoning_effort.pynew file mode 100644index 000000000..25a0e112f--- /dev/null+++ b/packages/sie_server/tests/core/test_reasoning_effort.py@@ -0,0 +1,215 @@+"""Chat ``reasoning_effort``: the per-profile declaration and its resolution at every ingress."""++from __future__ import annotations++import copy+import json+from pathlib import Path+from typing import Any++import pytest+from pydantic import ValidationError+from sie_server.adapters._generation_base import GenerationInvalidRequestError, GenerationUnsupportedFieldError+from sie_server.api.models import _resolve_capabilities+from sie_server.config.equivalence import canonical_digest+from sie_server.config.model import ModelConfig+from sie_server.core.loader import expand_profile_variants+from sie_server.core.reasoning_effort import MALFORMED_MESSAGE, apply_reasoning_effort, parse_reasoning_effort+from sie_server.processors.streaming import (+ _ChatMessage,+ _GenerateRequestParams,+ _MessagesInput,+ _remote_chat_parameters,+)++_VECTORS = json.loads(+ (Path(__file__).parents[4] / "conformance" / "openai_generation" / "reasoning_effort_vectors.json").read_text(+ encoding="utf-8"+ )+)+_LOCAL = "sie_server.adapters.fake.adapter:FakeAdapter"+_REMOTE = "sie_server.adapters.remote.openai:OpenAIUpstreamAdapter"+++def _config(name: str) -> ModelConfig:+ return ModelConfig.model_validate(copy.deepcopy(_VECTORS["models"][name]["config"]))+++def _hybrid(local: dict[str, Any] | None, remote: dict[str, Any] | None) -> dict[str, Any]:+ default: dict[str, Any] = {"adapter_path": _LOCAL, "max_batch_tokens": 8192, "kv_budget_tokens": 8192}+ relay: dict[str, Any] = {+ "adapter_path": _REMOTE,+ "max_batch_tokens": 8192,+ "adapter_options": {"loadtime": {"upstream": "acme-openai", "upstream_model": "acme/upstream-model"}},+ }+ if local is not None:+ default["reasoning_effort"] = local+ if remote is not None:+ relay["reasoning_effort"] = remote+ return {+ "sie_id": "acme/hybrid",+ "package_backed": True,+ "tasks": {"generate": {"context_length": 4096, "max_output_tokens": 256}},+ "profiles": {"default": default, "relay": relay},+ "routing": {"policy": "fallback", "fallback_profile": "relay"},+ }++[email protected]("case", _VECTORS["cases"], ids=lambda case: case["name"])+def test_shared_vectors_resolve_or_refuse(case: dict[str, Any]) -> None:+ config = _config(case["model"])+ if "message" in case:+ with pytest.raises(GenerationUnsupportedFieldError) as refused:+ apply_reasoning_effort(config, case["value"], model=case["model"])+ assert refused.value.param == "reasoning_effort"+ assert str(refused.value) == case["message"]+ return+ applied = apply_reasoning_effort(config, case["value"], model=case["model"])+ if case["applied"] is None:+ assert applied is None+ else:+ assert applied is not None+ assert dict(applied.chat_template_kwargs) == case["applied"]["chat_template_kwargs"]+ assert applied.upstream == case["applied"]["upstream"]++[email protected]("name", sorted(_VECTORS["models"]))+def test_shared_vectors_capability(name: str) -> None:+ capabilities = _resolve_capabilities(_config(name))+ assert capabilities is not None+ reasoning = capabilities.reasoning+ expected = _VECTORS["models"][name]["capability"]+ assert (reasoning.model_dump() if reasoning is not None else None) == expected++[email protected]("raw", _VECTORS["malformed"], ids=repr)+def test_a_value_outside_openais_set_is_malformed(raw: Any) -> None:+ with pytest.raises(GenerationInvalidRequestError) as refused:+ parse_reasoning_effort(raw)+ assert refused.value.param == "reasoning_effort"+ assert str(refused.value) == MALFORMED_MESSAGE == _VECTORS["malformed_message"]+++def test_absent_and_null_change_nothing() -> None:+ assert parse_reasoning_effort(None) is None+ assert apply_reasoning_effort(_config("acme/thinking"), None, model="acme/thinking") is None+++ ("declaration", "match"),+ [+ ({"values": {}}, "at least one value"),+ ({"values": {"extreme": {}}}, "values"),+ ({"default": "low", "values": {"high": {}}}, "is not one of its values"),+ ({"values": {"low": {"chat_template_kwargs": {"enable_thinking": "false"}}}}, "unsupported"),+ ({"values": {"low": {"chat_template_kwargs": {"reasoning_effort": "low; drop"}}}}, "letters, digits"),+ ({"values": {"low": {"budget": 512}}}, "budget"),+ ],+)+def test_malformed_declarations_fail_at_load(declaration: dict[str, Any], match: str) -> None:+ spec = copy.deepcopy(_VECTORS["models"]["acme/silent"]["config"])+ spec["tasks"]["generate"]["reasoning_effort"] = declaration+ with pytest.raises(ValidationError, match=match):+ ModelConfig.model_validate(spec)+++def test_a_remote_profile_cannot_name_template_kwargs() -> None:+ spec = copy.deepcopy(_VECTORS["models"]["acme/remote"]["config"])+ spec["tasks"]["generate"]["reasoning_effort"] = {+ "values": {"low": {"chat_template_kwargs": {"reasoning_effort": "low"}}}+ }+ with pytest.raises(ValidationError, match="is remote"):+ ModelConfig.model_validate(spec)+++def test_a_local_profile_cannot_name_an_upstream_value() -> None:+ spec = copy.deepcopy(_VECTORS["models"]["acme/silent"]["config"])+ spec["tasks"]["generate"]["reasoning_effort"] = {"values": {"low": {"upstream": "low"}}}+ with pytest.raises(ValidationError, match="is local"):+ ModelConfig.model_validate(spec)+++def test_a_declaration_needs_a_generate_task() -> None:+ spec = copy.deepcopy(_VECTORS["models"]["acme/silent"]["config"])+ spec["tasks"] = {"encode": {"dense": {"dim": 8}}}+ spec["profiles"]["default"].pop("kv_budget_tokens")+ spec["profiles"]["default"]["reasoning_effort"] = {"values": {"low": {}}}+ with pytest.raises(ValidationError, match="no generate task"):+ ModelConfig.model_validate(spec)+++def test_both_profiles_of_a_routed_model_accept_the_same_values() -> None:+ low_local = {"values": {"low": {"chat_template_kwargs": {"reasoning_effort": "low"}}}}+ low_remote = {"values": {"low": {"upstream": "low"}}}+ config = ModelConfig.model_validate(_hybrid(low_local, low_remote))+ assert apply_reasoning_effort(config, "low", model="acme/hybrid") is not None+ with pytest.raises(ValidationError, match="the same reasoning_effort values"):+ ModelConfig.model_validate(_hybrid(low_local, None))+ with pytest.raises(ValidationError, match="the same reasoning_effort values"):+ ModelConfig.model_validate(_hybrid(low_local, {"values": {"low": {}, "high": {}}}))+ with pytest.raises(ValidationError, match="the same reasoning_effort default"):+ ModelConfig.model_validate(_hybrid(low_local, {"default": "low", "values": {"low": {"upstream": "low"}}}))+++def test_a_variant_carries_its_profiles_declaration() -> None:+ low_local = {"values": {"low": {"chat_template_kwargs": {"reasoning_effort": "low"}}}}+ low_remote = {"values": {"low": {"upstream": "low"}}}+ configs = expand_profile_variants([ModelConfig.model_validate(_hybrid(low_local, low_remote))])+ applied = apply_reasoning_effort(configs["acme/hybrid:relay"], "low", model="acme/hybrid:relay")+ assert applied is not None+ assert applied.upstream == "low"+ assert dict(applied.chat_template_kwargs) == {}+ local = apply_reasoning_effort(configs["acme/hybrid"], "low", model="acme/hybrid")+ assert local is not None+ assert dict(local.chat_template_kwargs) == {"reasoning_effort": "low"}+++def test_a_profile_inherits_its_parents_declaration() -> None:+ spec = copy.deepcopy(_VECTORS["models"]["acme/profile-declared"]["config"])+ spec["profiles"]["long"] = {"extends": "default"}+ config = ModelConfig.model_validate(spec)+ assert config.reasoning_effort_for("long") == config.reasoning_effort_for("default")+ variant = expand_profile_variants([config])["acme/profile-declared:long"]+ assert apply_reasoning_effort(variant, "low", model="acme/profile-declared:long") is not None+++def test_an_undeclared_config_serializes_and_digests_as_before() -> None:+ config = _config("acme/silent")+ dumped = config.model_dump(mode="json")+ assert "reasoning_effort" not in dumped["tasks"]["generate"]+ assert "reasoning_effort" not in dumped["profiles"]["default"]+ spec = copy.deepcopy(_VECTORS["models"]["acme/silent"]["config"])+ spec["tasks"]["generate"]["reasoning_effort"] = None+ spec["profiles"]["default"]["reasoning_effort"] = None+ explicit_null = ModelConfig.model_validate(spec)+ assert canonical_digest(explicit_null.model_dump(mode="json")) == canonical_digest(dumped)+ declared = _config("acme/declared").model_dump(mode="json")+ assert declared["tasks"]["generate"]["reasoning_effort"]["default"] == "max"+++ ("name", "reasons"),+ [("acme/silent", False), ("acme/thinking", True), ("acme/declared", True), ("acme/remote", True)],+)+def test_declares_no_reasoning(name: str, reasons: bool) -> None:+ assert _config(name).declares_no_reasoning is not reasons+++def test_a_reasoning_parser_counts_as_reasoning() -> None:+ spec = copy.deepcopy(_VECTORS["models"]["acme/silent"]["config"])+ spec["profiles"]["default"]["adapter_options"] = {"loadtime": {"reasoning_parser": "qwen3"}}+ assert ModelConfig.model_validate(spec).declares_no_reasoning is False+++def _chat_params(**overrides: Any) -> _GenerateRequestParams:+ return _GenerateRequestParams(+ input=_MessagesInput(messages=(_ChatMessage(role="user", content="Classify this."),)),+ max_new_tokens=64,+ **overrides,+ )+++def test_the_relay_body_carries_only_the_declared_upstream_value() -> None:+ assert "reasoning_effort" not in _remote_chat_parameters(_chat_params())+ body = _remote_chat_parameters(_chat_params(reasoning_effort="max"), reasoning_effort="high")+ assert body["reasoning_effort"] == "high"diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 5be2fe148..cc241bf01 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -196,6 +196,8 @@ type OpenAiCompatModelKeys = Partial<Record<"id" | "object" | "created" | "ownedfunction toModelInfo(wire: WireModelInfo): ModelInfo {const {max_sequence_length,+ context_length,+ max_output_tokens,last_error,pending_generation,release_date,@@ -214,6 +216,8 @@ function toModelInfo(wire: WireModelInfo): ModelInfo {// caller `undefined` for a field `ModelInfo` declares as always present.aliases: aliases ?? [],...(max_sequence_length !== undefined ? { maxSequenceLength: max_sequence_length } : {}),+ ...(context_length !== undefined ? { contextLength: context_length } : {}),+ ...(max_output_tokens !== undefined ? { maxOutputTokens: max_output_tokens } : {}),...(last_error !== undefined ? { lastError: last_error } : {}),...(pending_generation !== undefined ? { pendingGeneration: pending_generation } : {}),...(release_date !== undefined ? { releaseDate: release_date } : {}),diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 88fdfff09..5b13b47c2 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -264,6 +264,20 @@ export interface ModelCapabilities {sql?: boolean;/** Generative guard model; backs model="guard" */guard?: boolean;+ /** How `reasoning_effort` steers the model's reasoning; null when nothing lets it reason */+ reasoning?: ModelReasoning | null;+}++/**+ * How a model's reasoning can be steered with the chat `reasoning_effort` field.+ */+export interface ModelReasoning {+ /** Accepted `reasoning_effort` values in OpenAI's order; empty means the field is refused */+ effort?: string[];+ /** The value the model runs at when a request names none; null when it is not a declared value */+ default_effort?: string | null;+ /** The hard reasoning-token ceiling of each value that has one; other values only instruct the model */+ budget_tokens?: Record<string, number>;}/**@@ -373,6 +387,10 @@ export interface ModelInfo {dims?: ModelDims;/** Maximum sequence length the model supports; null when the config pins none */maxSequenceLength?: number | null;+ /** Prompt plus completion tokens the route admits; null without a generate task */+ contextLength?: number | null;+ /** The largest output-token request the route admits; null without a generate task */+ maxOutputTokens?: number | null;/** Pinned HF commit SHA for the weights; null for unpinned/package-backed models */revision?: string | null;/** One line about the model; "" when the catalog sets none */@@ -404,7 +422,7 @@ export interface ModelInfo {/*** A `/v1/models` entry exactly as the gateway emits it, before the client- * camelCases the four renamed top-level keys.+ * camelCases the six renamed top-level keys.** Declared once here (rather than inline per call site) so `listModels` and* `getModel` cannot drift apart, and so the emitted key set has a single@@ -419,6 +437,8 @@ export interface WireModelInfo {outputs: string[];dims?: ModelDims;max_sequence_length?: number | null;+ context_length?: number | null;+ max_output_tokens?: number | null;revision?: string | null;description?: string;release_date?: string;@@ -440,12 +460,14 @@ export interface WireModelInfo {const MODEL_INFO_WIRE_FIELD_SET: Record<keyof WireModelInfo, true> = {aliases: true,capabilities: true,+ context_length: true,description: true,dims: true,inputs: true,last_error: true,loaded: true,lora_adapters: true,+ max_output_tokens: true,max_sequence_length: true,name: true,outputs: true,diff --git a/packages/sie_ts_sdk/tests/wireContract.test.ts b/packages/sie_ts_sdk/tests/wireContract.test.tsindex 926ee6d10..6603a9c93 100644--- a/packages/sie_ts_sdk/tests/wireContract.test.ts+++ b/packages/sie_ts_sdk/tests/wireContract.test.ts@@ -33,9 +33,11 @@ function jsonResponse(body: unknown): Response {});}-/** The four top-level keys the client camelCases; everything else passes through. */+/** The six top-level keys the client camelCases; everything else passes through. */const WIRE_TO_CLIENT_KEY: Record<string, string> = {max_sequence_length: "maxSequenceLength",+ context_length: "contextLength",+ max_output_tokens: "maxOutputTokens",last_error: "lastError",pending_generation: "pendingGeneration",release_date: "releaseDate",@@ -72,6 +74,8 @@ const FULL_WIRE_ENTRY = {outputs: ["dense", "sparse"],dims: { dense: 1024, sparse: 250002 },max_sequence_length: 8192,+ context_length: 8192,+ max_output_tokens: 1024,revision: "5617a9f61b028005a4858fdac845db406aefb181",description: "BAAI/bge-m3: embedding and reranking model.",release_date: "2024-07-03",@@ -189,6 +193,8 @@ describe("getModel wire mapping", () => {outputs: ["dense"],last_error: null,max_sequence_length: null,+ context_length: null,+ max_output_tokens: null,revision: null,capabilities: null,}),@@ -198,6 +204,8 @@ describe("getModel wire mapping", () => {expect(model.lastError).toBeNull();expect(model.maxSequenceLength).toBeNull();+ expect(model.contextLength).toBeNull();+ expect(model.maxOutputTokens).toBeNull();expect(model.revision).toBeNull();expect(model.capabilities).toBeNull();});diff --git a/packages/wire-fixtures/model_info.json b/packages/wire-fixtures/model_info.jsonindex f5d230df1..df08c7ce3 100644--- a/packages/wire-fixtures/model_info.json+++ b/packages/wire-fixtures/model_info.json@@ -15,12 +15,14 @@"typed": ["aliases","capabilities",+ "context_length","description","dims","inputs","last_error","loaded","lora_adapters",+ "max_output_tokens","max_sequence_length","name","outputs",@@ -39,10 +41,11 @@},"notes": {"excluded_scope": "The four excluded keys are merged in by GET /v1/models/{model} for vanilla OpenAI 'retrieve model' clients; on GET /v1/models they live in the sibling `data` array instead, never on a `models` entry.",- "optionality": "Python marks every typed key optional (`total=False`). TypeScript requires `name`, `loaded`, `inputs` and `outputs` on both `ModelInfo` and `WireModelInfo`; its remaining keys are optional. `pending_generation` is gateway-only. `last_error`/`max_sequence_length`/`revision`/`capabilities` are the four the emitters can send as an explicit null, so the SDK types admit null on each. The fixture pins which keys are declarable, not which are always present.",- "ts_renames": "The TS SDK camelCases four top-level keys \u2014 max_sequence_length -> maxSequenceLength, last_error -> lastError, pending_generation -> pendingGeneration, release_date -> releaseDate \u2014 and leaves nested objects wire-shaped. Its consumer test checks the wire-side names listed here.",+ "optionality": "Python marks every typed key optional (`total=False`). TypeScript requires `name`, `loaded`, `inputs` and `outputs` on both `ModelInfo` and `WireModelInfo`; its remaining keys are optional. `pending_generation` is gateway-only. `last_error`/`max_sequence_length`/`context_length`/`max_output_tokens`/`revision`/`capabilities` are the six the emitters can send as an explicit null, so the SDK types admit null on each. The fixture pins which keys are declarable, not which are always present.",+ "ts_renames": "The TS SDK camelCases six top-level keys \u2014 max_sequence_length -> maxSequenceLength, context_length -> contextLength, max_output_tokens -> maxOutputTokens, last_error -> lastError, pending_generation -> pendingGeneration, release_date -> releaseDate \u2014 and leaves nested objects wire-shaped. Its consumer test checks the wire-side names listed here.","aliases": "Short task-tier names resolving to this model. Always emitted, empty when the model has none, so callers can distinguish 'no aliases' from an older gateway. Only catalog- or operator-declared names appear; the gateway's compiled-in routing defaults are not public API and are never listed.","routing": "How the bare model name is served: `policy` (`remote_only`, `fallback`, `threshold`, or null for local only) and `upstream_kind` (`sie`, `openai`, or null). The single server and the gateway emit it on every entry.",- "lora_adapters": "Single-server only: ready served LoRA names, excluding loading or evicting adapters. Gateways omit this field because they do not aggregate worker residency; capabilities.lora_adapters remains the declared allowlist."+ "lora_adapters": "Single-server only: ready served LoRA names, excluding loading or evicting adapters. Gateways omit this field because they do not aggregate worker residency; capabilities.lora_adapters remains the declared allowlist.",+ "limits": "`context_length` and `max_output_tokens` are the generation limits the route admits, resolved for the listed id as admission resolves them, and null for a model without a generate task."}}