Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(generation): run a named reasoning_effort on grammar-constrained chat (#991)

Krisztian Gajdar17ed3d77786f
diff --git a/conformance/openai_generation/reasoning_effort_vectors.json b/conformance/openai_generation/reasoning_effort_vectors.json
index ac66c0dba..03cd3e1d6 100644
--- a/conformance/openai_generation/reasoning_effort_vectors.json
+++ b/conformance/openai_generation/reasoning_effort_vectors.json
@@ -146,7 +146,7 @@
{"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"},
{"name": "a grammar request that names no value runs at the grammar value", "model": "acme/remote-grammar", "value": null, "grammar": true, "applied": {"chat_template_kwargs": {}, "upstream": "none"}},
{"name": "a grammar request that names the grammar value", "model": "acme/remote-grammar", "value": "none", "grammar": true, "applied": {"chat_template_kwargs": {}, "upstream": "none"}},
- {"name": "a grammar request that names another declared value", "model": "acme/remote-grammar", "value": "high", "grammar": true, "message": "Model 'acme/remote-grammar' supports response_format only with reasoning_effort 'none'"},
+ {"name": "a grammar request that names another declared value runs at it", "model": "acme/remote-grammar", "value": "high", "grammar": true, "applied": {"chat_template_kwargs": {}, "upstream": "high"}},
{"name": "a grammar request that names an undeclared value", "model": "acme/remote-grammar", "value": "medium", "grammar": true, "message": "Model 'acme/remote-grammar' does not support reasoning_effort 'medium'. Supported values: none, low, high"},
{"name": "a request without grammar that names no value changes nothing", "model": "acme/remote-grammar", "value": null, "applied": null},
{"name": "a request without grammar keeps every declared value", "model": "acme/remote-grammar", "value": "high", "applied": {"chat_template_kwargs": {}, "upstream": "high"}},
diff --git a/packages/sie_config/src/sie_config/model_config.schema.json b/packages/sie_config/src/sie_config/model_config.schema.json
index 60f1e71bf..64126b364 100644
--- a/packages/sie_config/src/sie_config/model_config.schema.json
+++ b/packages/sie_config/src/sie_config/model_config.schema.json
@@ -541,7 +541,7 @@
},
"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.\n\n``grammar`` names the only value a grammar-constrained chat request runs\nat, for a model that cannot reason and constrain its answer together. Such\na request that names no value runs at it, and one that names another value\nis refused. ``None`` leaves grammar-constrained requests to the rules above.",
+ "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.\n\n``grammar`` names the value a grammar-constrained chat request runs at\nwhen it names none, for an upstream that does not answer such a request at\nits own default. A request that names a value runs at that value. ``None``\nleaves grammar-constrained requests to the rules above.",
"properties": {
"default": {
"anyOf": [
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 0468ed4d8..5aa89c436 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -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`, …). `context_length` and `max_output_tokens` are the limits the route admits, and `capabilities.reasoning` lists the `reasoning_effort` values it accepts and, as `grammar_effort`, the one value a grammar-constrained request (a `response_format` other than `text`) runs at when the model declares one, read from the same model config the chat gate checks. The chat gate refuses such a request that names another value with `400 unsupported_field`, and the worker runs one that names none at that value. 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 and, as `grammar_effort`, the value a grammar-constrained request (a `response_format` other than `text`) runs at when it names none, read from the same model config the chat gate checks. The worker runs such a request that names no value at `grammar_effort`, and one that names an accepted value at that value. 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.json
index 10d7bb133..05a18e0b2 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -2937,7 +2937,7 @@
"type": "array"
},
"grammar_effort": {
- "description": "The only value a grammar-constrained request (a ``response_format``\nother than ``text``, or a ``grammar``) runs at, also when it names\nnone; ``null`` when such a request follows the rules above.",
+ "description": "The value a grammar-constrained request (a ``response_format`` other\nthan ``text``, or a ``grammar``) runs at when it names none; ``null``\nwhen such a request follows ``default_effort``.",
"type": [
"string",
"null"
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index b264ab1eb..3990cb45b 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -9677,9 +9677,7 @@ async fn proxy_chat_inner(
}
}
if let Some(value) = params.reasoning_effort.as_deref() {
- if let Some(message) =
- info.chat_reasoning_effort_refusal(value, params.grammar.is_some(), &model_name)
- {
+ if let Some(message) = info.reasoning_effort_refusal(value, &model_name) {
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -18895,7 +18893,7 @@ mod tests {
}
#[tokio::test]
- async fn chat_response_format_takes_only_the_declared_grammar_effort() {
+ async fn chat_response_format_forwards_a_named_effort_beside_the_grammar_effort() {
use crate::types::model::{ModelConfig, ProfileConfig};
let (state, probe) = mixed_governed_generation_state(false).await;
@@ -18952,26 +18950,7 @@ mod tests {
body
};
- let refused = proxy_chat(
- State(Arc::clone(&state)),
- json_request("/v1/chat/completions", body(Some("high"))),
- )
- .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' supports response_format only with reasoning_effort 'none'"
- );
-
- for value in [Some("none"), None] {
+ for value in [Some("high"), Some("none"), None] {
*probe.worker_chunks.lock().unwrap() = vec![
reasoning_worker_chunk(0, json!({"text_delta": "{}", "is_first": true})),
reasoning_worker_terminal(1, json!({})),
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index 3a1edb6bf..ab8e9e461 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -2919,9 +2919,9 @@ pub struct ModelReasoningWire {
/// 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 only value a grammar-constrained request (a ``response_format``
- /// other than ``text``, or a ``grammar``) runs at, also when it names
- /// none; ``null`` when such a request follows the rules above.
+ /// The value a grammar-constrained request (a ``response_format`` other
+ /// than ``text``, or a ``grammar``) runs at when it names none; ``null``
+ /// when such a request follows ``default_effort``.
pub grammar_effort: Option<String>,
/// The hard reasoning-token ceiling of each value that has one. Other
/// values only instruct the model.
diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rs
index ba5814e3a..f1ed9dc66 100644
--- a/packages/sie_gateway/src/types/model.rs
+++ b/packages/sie_gateway/src/types/model.rs
@@ -25,8 +25,7 @@ pub struct ReasoningEffortDecl {
pub accepted: Vec<String>,
/// The value the route runs at when a request names none.
pub default: Option<String>,
- /// The only value a grammar-constrained request runs at, when the route
- /// restricts one.
+ /// The value a grammar-constrained request runs at when it names none.
pub grammar: Option<String>,
}
@@ -914,25 +913,6 @@ impl ModelEntry {
}
}
- /// The refusal text for ``value`` on a chat request to this route, ``None``
- /// when the route accepts it. A grammar-constrained request may name only
- /// the route's grammar value, when it declares one.
- pub fn chat_reasoning_effort_refusal(
- &self,
- value: &str,
- grammar: bool,
- model_name: &str,
- ) -> Option<String> {
- self.reasoning_effort_refusal(value, model_name).or_else(|| {
- let restricted = self.effective_reasoning_effort()?.grammar.as_deref()?;
- (grammar && value != restricted).then(|| {
- format!(
- "Model '{model_name}' supports response_format only with reasoning_effort '{restricted}'"
- )
- })
- })
- }
-
/// ``capabilities.reasoning`` on ``/v1/models``: null for a model without a
/// generate task or one that cannot reason.
fn reasoning_capability_value(&self) -> Value {
@@ -1564,10 +1544,9 @@ profiles:
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 grammar = case["grammar"].as_bool().unwrap_or(false);
let refusal = case["value"]
.as_str()
- .and_then(|value| entry.chat_reasoning_effort_refusal(value, grammar, model));
+ .and_then(|value| entry.reasoning_effort_refusal(value, model));
assert_eq!(
refusal.as_deref(),
case.get("message").and_then(Value::as_str),
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index 99b3936b1..df845fac8 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -335,7 +335,7 @@ class ModelReasoning(TypedDict, total=False):
"""The value the model runs at when a request names none, ``None`` when it is not a declared value."""
grammar_effort: str | None
- """The only value a grammar-constrained request runs at, also when it names none. ``None`` when not restricted.
+ """The value a grammar-constrained request runs at when it names none. ``None`` when it follows ``default_effort``.
A request is grammar-constrained when its ``response_format`` is not ``text``, or when it carries a ``grammar``.
"""
diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.py
index 5ef8bdc27..d90ca8272 100644
--- a/packages/sie_server/src/sie_server/api/models.py
+++ b/packages/sie_server/src/sie_server/api/models.py
@@ -66,7 +66,7 @@ class ModelReasoning(BaseModel):
"""The value the model runs at when a request names none, ``None`` when it is not a declared value."""
grammar_effort: str | None = None
- """The only value a grammar-constrained request runs at, also when it names none. ``None`` when not restricted.
+ """The value a grammar-constrained request runs at when it names none. ``None`` when it follows ``default_effort``.
A request is grammar-constrained when its ``response_format`` is not ``text``, or when it carries a ``grammar``.
"""
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index 03430d539..24cd0b355 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -145,10 +145,10 @@ class ReasoningEffortDeclaration(BaseModel):
is reported on ``/v1/models`` and never applied, so a request without the
field renders and calls its upstream exactly as before.
- ``grammar`` names the only value a grammar-constrained chat request runs
- at, for a model that cannot reason and constrain its answer together. Such
- a request that names no value runs at it, and one that names another value
- is refused. ``None`` leaves grammar-constrained requests to the rules above.
+ ``grammar`` names the value a grammar-constrained chat request runs at
+ when it names none, for an upstream that does not answer such a request at
+ its own default. A request that names a value runs at that value. ``None``
+ leaves grammar-constrained requests to the rules above.
"""
model_config = ConfigDict(extra="forbid", frozen=True)
diff --git a/packages/sie_server/src/sie_server/core/reasoning_effort.py b/packages/sie_server/src/sie_server/core/reasoning_effort.py
index 534778f1a..8d3175f85 100644
--- a/packages/sie_server/src/sie_server/core/reasoning_effort.py
+++ b/packages/sie_server/src/sie_server/core/reasoning_effort.py
@@ -44,11 +44,6 @@ def unsupported_message(model: str, accepted: tuple[str, ...], value: str) -> st
return f"Model '{model}' does not support reasoning_effort '{value}'. Supported values: {', '.join(accepted)}"
-def grammar_message(model: str, grammar: str) -> str:
- """The refusal text for a grammar-constrained request that names a value other than ``grammar``."""
- return f"Model '{model}' supports response_format only with reasoning_effort '{grammar}'"
-
-
def apply_reasoning_effort(
config: ModelConfig | None, value: str | None, *, model: str, grammar: bool = False
) -> AppliedReasoningEffort | None:
@@ -58,7 +53,7 @@ def apply_reasoning_effort(
``none`` for a model that does not reason at all. The declared default is
not applied to a request that names no value. ``grammar`` marks a
grammar-constrained chat request, which runs at the declaration's
- ``grammar`` value when it declares one.
+ ``grammar`` value when it names none.
Raises:
GenerationUnsupportedFieldError: When the profile does not accept ``value``.
@@ -78,8 +73,6 @@ def apply_reasoning_effort(
level = declaration.values.get(cast("ReasoningEffortValue", value))
if level is None:
raise GenerationUnsupportedFieldError(PARAM, unsupported_message(model, declaration.accepted, value))
- if grammar_value is not None and value != grammar_value:
- raise GenerationUnsupportedFieldError(PARAM, grammar_message(model, grammar_value))
return AppliedReasoningEffort(
chat_template_kwargs=dict(level.chat_template_kwargs or {}),
upstream=level.upstream,
diff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.py
index 56c89638d..676dcc2ac 100644
--- a/packages/sie_server/tests/api/test_remote_chat.py
+++ b/packages/sie_server/tests/api/test_remote_chat.py
@@ -405,6 +405,7 @@ def _declare_grammar_effort(config: ModelConfig) -> None:
[
({"response_format": {"type": "json_object"}}, "none"),
({"response_format": {"type": "json_object"}, "reasoning_effort": "none"}, "none"),
+ ({"response_format": {"type": "json_object"}, "reasoning_effort": "high"}, "high"),
(
{"response_format": {"type": "json_schema", "json_schema": {"name": "a", "schema": {"type": "object"}}}},
"none",
@@ -414,7 +415,7 @@ def _declare_grammar_effort(config: ModelConfig) -> None:
({}, None),
],
)
-def test_a_constrained_request_runs_at_the_declared_grammar_effort(
+def test_a_constrained_request_runs_at_the_declared_grammar_effort_unless_it_names_one(
remote_chat: tuple, changes: dict[str, Any], sent_effort: str | None
) -> None:
client, _, config, requests = remote_chat
@@ -426,22 +427,6 @@ def test_a_constrained_request_runs_at_the_declared_grammar_effort(
assert json.loads(requests[0].content).get("reasoning_effort") == sent_effort
-def test_a_constrained_request_that_names_another_effort_never_dispatches(remote_chat: tuple) -> None:
- client, _, config, requests = remote_chat
- _declare_grammar_effort(config)
- answer_with(remote_chat, json_response(200, completion()))
- response = client.post(
- "/v1/chat/completions",
- json={**BODY, "response_format": {"type": "json_object"}, "reasoning_effort": "high"},
- )
- assert response.status_code == 400
- error = response.json()["error"]
- assert error["param"] == "reasoning_effort"
- assert error["code"] == "unsupported_field"
- assert error["message"] == f"Model '{MODEL}' supports response_format only with reasoning_effort 'none'"
- assert not requests
-
-
def test_strict_invalid_first_event_preserves_the_buffered_error_before_200(remote_chat: tuple) -> None:
client, _, _, _ = remote_chat
stream = ChatStream([{"choices": [{"index": 0, "delta": {"content": "answer"}, "finish_reason": "stop"}]}])
diff --git a/packages/sie_server/tests/core/test_reasoning_effort.py b/packages/sie_server/tests/core/test_reasoning_effort.py
index 89ee1acc8..2d150efd3 100644
--- a/packages/sie_server/tests/core/test_reasoning_effort.py
+++ b/packages/sie_server/tests/core/test_reasoning_effort.py
@@ -274,8 +274,9 @@ def test_a_grammar_value_reaches_a_variant_of_its_profile() -> None:
applied = apply_reasoning_effort(variant, None, model="acme/remote:relay", grammar=True)
assert applied is not None
assert applied.upstream == "low"
- with pytest.raises(GenerationUnsupportedFieldError, match="only with reasoning_effort 'low'"):
- apply_reasoning_effort(variant, "high", model="acme/remote:relay", grammar=True)
+ named = apply_reasoning_effort(variant, "high", model="acme/remote:relay", grammar=True)
+ assert named is not None
+ assert named.upstream == "high"
def test_the_relay_body_carries_only_the_declared_upstream_value() -> None:
diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.py
index 3e6a4bffd..4f924927a 100644
--- a/packages/sie_server/tests/processors/test_remote_chat.py
+++ b/packages/sie_server/tests/processors/test_remote_chat.py
@@ -314,11 +314,12 @@ _OBJECT = {"kind": "json_schema", "value": {"type": "object"}, "label": "json_ob
[
({"grammar": _OBJECT}, "none"),
({"grammar": _OBJECT, "reasoning_effort": "none"}, "none"),
+ ({"grammar": _OBJECT, "reasoning_effort": "high"}, "high"),
({"reasoning_effort": "high"}, "high"),
({}, None),
],
)
-async def test_a_constrained_request_runs_at_the_declared_grammar_effort(
+async def test_a_constrained_request_runs_at_the_declared_grammar_effort_unless_it_names_one(
remote: tuple, fields: dict[str, Any], sent_effort: str | None
) -> None:
_declare_grammar_effort(remote[1])
@@ -330,19 +331,6 @@ async def test_a_constrained_request_runs_at_the_declared_grammar_effort(
msg.ack.assert_awaited_once()
-async def test_a_constrained_request_that_names_another_effort_refuses_without_dispatch(remote: tuple) -> None:
- _declare_grammar_effort(remote[1])
- respond(remote)
- msg, chunks = await run(remote, grammar=_OBJECT, reasoning_effort="high")
- assert chunks[-1]["error"]["code"] == "unsupported_field"
- assert chunks[-1]["error"]["param"] == "reasoning_effort"
- assert (
- chunks[-1]["error"]["message"] == f"Model '{MODEL}' supports response_format only with reasoning_effort 'none'"
- )
- assert remote[3] == []
- msg.ack.assert_awaited_once()
-
-
async def test_regex_refuses_without_dispatch(remote: tuple) -> None:
respond(remote)
_msg, chunks = await run(remote, grammar={"kind": "regex", "value": "[a-z]+"})
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index bcb68bd79..f1e7a47af 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -276,7 +276,7 @@ export interface ModelReasoning {
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 only value a grammar-constrained request (a `response_format` other than `text`) runs at, also when it names none; null when not restricted */
+ /** The value a grammar-constrained request (a `response_format` other than `text`) runs at when it names none; null when it follows `default_effort` */
grammar_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>;