Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(generation): run grammar-constrained chat at a declared reasoning_effort (#990)

Krisztian Gajdarf01cb6802b4d
diff --git a/conformance/openai_generation/reasoning_effort_vectors.json b/conformance/openai_generation/reasoning_effort_vectors.json
index e903575aa..ac66c0dba 100644
--- a/conformance/openai_generation/reasoning_effort_vectors.json
+++ b/conformance/openai_generation/reasoning_effort_vectors.json
@@ -1,10 +1,11 @@
{
"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."
+ "Each model is a model config. A case names a model and the request's value, null when the",
+ "request names none. `grammar` true marks a grammar-constrained request, such as one with a",
+ "response_format. 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"}],
@@ -32,7 +33,7 @@
"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": {}}
+ "capability": {"effort": ["low", "high", "max"], "default_effort": "max", "grammar_effort": null, "budget_tokens": {}}
},
"acme/silent": {
"config": {
@@ -54,7 +55,7 @@
"default": {"adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter", "max_batch_tokens": 8192, "kv_budget_tokens": 8192}
}
},
- "capability": {"effort": [], "default_effort": null, "budget_tokens": {}}
+ "capability": {"effort": [], "default_effort": null, "grammar_effort": null, "budget_tokens": {}}
},
"acme/remote": {
"config": {
@@ -82,7 +83,37 @@
}
}
},
- "capability": {"effort": ["none", "low", "high"], "default_effort": "high", "budget_tokens": {}}
+ "capability": {"effort": ["none", "low", "high"], "default_effort": "high", "grammar_effort": null, "budget_tokens": {}}
+ },
+ "acme/remote-grammar": {
+ "config": {
+ "sie_id": "acme/remote-grammar",
+ "remote_backed": true,
+ "tasks": {
+ "generate": {
+ "context_length": 1000000,
+ "max_output_tokens": 32768,
+ "capabilities": {"grammar": ["json_schema"]},
+ "reasoning_effort": {
+ "default": "high",
+ "grammar": "none",
+ "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", "grammar_effort": "none", "budget_tokens": {}}
},
"acme/profile-declared": {
"config": {
@@ -98,7 +129,7 @@
}
}
},
- "capability": {"effort": ["low"], "default_effort": null, "budget_tokens": {}}
+ "capability": {"effort": ["low"], "default_effort": null, "grammar_effort": null, "budget_tokens": {}}
}
},
"cases": [
@@ -112,6 +143,14 @@
{"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"}
+ {"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 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"}},
+ {"name": "a grammar request on a model that restricts no value", "model": "acme/remote", "value": "high", "grammar": true, "applied": {"chat_template_kwargs": {}, "upstream": "high"}},
+ {"name": "a grammar request that names no value on a model that restricts none", "model": "acme/remote", "value": null, "grammar": true, "applied": null}
]
}
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 e8fbd8131..60f1e71bf 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.",
+ "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.",
"properties": {
"default": {
"anyOf": [
@@ -564,6 +564,27 @@
"default": null,
"title": "Default"
},
+ "grammar": {
+ "anyOf": [
+ {
+ "enum": [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Grammar"
+ },
"values": {
"additionalProperties": {
"$ref": "#/$defs/ReasoningEffortLevel"
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 39f214b98..0468ed4d8 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, 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 /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 /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 f0b1390ee..10d7bb133 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -2935,6 +2935,13 @@
"type": "string"
},
"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.",
+ "type": [
+ "string",
+ "null"
+ ]
}
},
"required": [
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index f5b2f329a..b264ab1eb 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -9677,7 +9677,9 @@ async fn proxy_chat_inner(
}
}
if let Some(value) = params.reasoning_effort.as_deref() {
- if let Some(message) = info.reasoning_effort_refusal(value, &model_name) {
+ if let Some(message) =
+ info.chat_reasoning_effort_refusal(value, params.grammar.is_some(), &model_name)
+ {
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -18892,6 +18894,108 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn chat_response_format_takes_only_the_declared_grammar_effort() {
+ use crate::types::model::{ModelConfig, ProfileConfig};
+
+ let (state, probe) = mixed_governed_generation_state(false).await;
+ 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 default: high\n grammar: none\n values:\n none:\n chat_template_kwargs:\n reasoning_effort: none\n high: {}\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 body = |value: Option<&str>| {
+ let mut body = json!({
+ "model": "org/g",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4,
+ "response_format": {"type": "json_object"},
+ });
+ if let Some(value) = value {
+ body["reasoning_effort"] = json!(value);
+ }
+ 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] {
+ *probe.worker_chunks.lock().unwrap() = vec![
+ reasoning_worker_chunk(0, json!({"text_delta": "{}", "is_first": true})),
+ reasoning_worker_terminal(1, json!({})),
+ ];
+ let accepted = proxy_chat(
+ State(Arc::clone(&state)),
+ json_request("/v1/chat/completions", body(value)),
+ )
+ .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, "{value:?}: {text}");
+ let generate = probe.take_params().generate.expect("generate");
+ assert!(generate.grammar.is_some(), "{value:?}");
+ assert_eq!(generate.reasoning_effort.as_deref(), value);
+ }
+ }
+
#[tokio::test]
async fn chat_include_reasoning_keeps_each_candidate_reasoning_on_its_choice() {
let (state, probe) = mixed_governed_generation_state(false).await;
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index 15f5f5289..3a1edb6bf 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -2919,6 +2919,10 @@ 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.
+ pub grammar_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>,
diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rs
index d8d5c1c7e..38f425af6 100644
--- a/packages/sie_gateway/src/state/model_registry.rs
+++ b/packages/sie_gateway/src/state/model_registry.rs
@@ -820,6 +820,15 @@ impl ModelRegistry {
if profile == "default" || profile_kind(profile).is_none() {
return Err("fallback routing requires a non-default remote profile".into());
}
+ let (local, remote) = (
+ Self::profile_grammar_effort(entry, "default"),
+ Self::profile_grammar_effort(entry, profile),
+ );
+ if local != remote {
+ return Err(format!(
+ "Profiles 'default' and '{profile}' serve one route, so they must declare the same reasoning_effort grammar value, got {local:?} and {remote:?}"
+ ));
+ }
Ok(())
}
@@ -881,9 +890,62 @@ impl ModelRegistry {
));
}
}
+ for profile_name in entry.profile_configs.keys() {
+ if let Some(target) = Self::grammar_target(entry, profile_name) {
+ Self::validate_grammar_effort_agrees(entry, profile_name, &target)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// The sibling profile that serves ``profile``'s grammar-constrained
+ /// requests, ``None`` when ``profile`` serves them itself.
+ fn grammar_target(entry: &ModelEntry, profile: &str) -> Option<String> {
+ let target = if profile == "default" {
+ entry
+ .info_extras
+ .grammar_profile
+ .clone()
+ .filter(|target| !Self::profile_is_grammar_compatible(entry, profile, target))
+ } else if Self::effective_adapter_path_from_entry(entry, profile)
+ .is_some_and(|path| path.starts_with(REMOTE_ADAPTER_MODULE_PREFIX))
+ {
+ None
+ } else {
+ Self::grammar_serving_profile(entry, profile)
+ };
+ target.filter(|target| target != profile && entry.profile_configs.contains_key(target))
+ }
+
+ /// A grammar fallback serves the grammar requests of ``source``, so it runs
+ /// them at the same ``reasoning_effort`` grammar value ``source`` reports.
+ fn validate_grammar_effort_agrees(
+ entry: &ModelEntry,
+ source: &str,
+ target: &str,
+ ) -> Result<(), String> {
+ let (source_grammar, target_grammar) = (
+ Self::profile_grammar_effort(entry, source),
+ Self::profile_grammar_effort(entry, target),
+ );
+ if source_grammar != target_grammar {
+ return Err(format!(
+ "Profile '{target}' serves grammar requests for '{source}', so they must declare the same reasoning_effort grammar value, got {source_grammar:?} and {target_grammar:?}"
+ ));
+ }
Ok(())
}
+ /// The ``reasoning_effort`` grammar value that governs ``profile``.
+ fn profile_grammar_effort(entry: &ModelEntry, profile: &str) -> Option<String> {
+ entry
+ .info_extras
+ .profile_reasoning_effort
+ .get(profile)
+ .or(entry.info_extras.reasoning_effort.as_ref())
+ .and_then(|declaration| declaration.grammar.clone())
+ }
+
fn normalize_model_pool(pool: Option<&str>) -> Result<Option<String>, String> {
let Some(raw_pool) = pool else {
return Ok(None);
@@ -1442,46 +1504,54 @@ impl ModelRegistry {
// hint). Strip the trailing ``:profile`` and read the base entry's hint.
let (base, source_profile) = canonical.rsplit_once(':')?;
let base_entry = snap.models.get(base)?;
+ Self::grammar_serving_profile(base_entry, source_profile)
+ .map(|target| (base.to_string(), target))
+ }
+
+ /// The profile of ``entry`` that serves grammar-constrained requests for
+ /// its non-default variant ``source_profile``: the profile itself when it
+ /// keeps them, ``None`` when nothing routes them.
+ fn grammar_serving_profile(entry: &ModelEntry, source_profile: &str) -> Option<String> {
// A declared profile-scoped fallback is already a concrete safe
// target. Keep it instead of applying the model-wide fallback again.
- if base_entry
+ if entry
.profile_configs
.values()
.any(|profile| profile.grammar_profile.as_deref() == Some(source_profile))
{
- return Some((base.to_string(), source_profile.to_string()));
+ return Some(source_profile.to_string());
}
- let scoped = base_entry
+ let scoped = entry
.profile_configs
.get(source_profile)
.and_then(|profile| profile.grammar_profile.clone());
if let Some(scoped) = scoped {
- return Some((base.to_string(), scoped));
+ return Some(scoped);
}
- let parent_grammar_profile = base_entry
+ let parent_grammar_profile = entry
.info_extras
.profile_parents
.get(source_profile)
- .and_then(|parent| base_entry.profile_configs.get(parent))
+ .and_then(|parent| entry.profile_configs.get(parent))
.and_then(|parent| parent.grammar_profile.as_deref());
if parent_grammar_profile.is_some_and(|parent_grammar_profile| {
- Self::profile_is_grammar_compatible(base_entry, source_profile, parent_grammar_profile)
+ Self::profile_is_grammar_compatible(entry, source_profile, parent_grammar_profile)
}) {
- return Some((base.to_string(), source_profile.to_string()));
+ return Some(source_profile.to_string());
}
- let gp = base_entry.info_extras.grammar_profile.clone()?;
- let target_profile = if base_entry
+ let gp = entry.info_extras.grammar_profile.clone()?;
+ let target_profile = if entry
.info_extras
.profile_parents
.get(source_profile)
.is_some_and(|parent| parent == &gp)
- && Self::profile_is_grammar_compatible(base_entry, source_profile, &gp)
+ && Self::profile_is_grammar_compatible(entry, source_profile, &gp)
{
source_profile.to_string()
} else {
gp
};
- Some((base.to_string(), target_profile))
+ Some(target_profile)
}
fn profile_scoped_grammar_fallback_is_compatible(
@@ -3379,6 +3449,32 @@ mod tests {
);
}
+ #[test]
+ fn fallback_routing_requires_the_same_grammar_effort() {
+ let (_dir, registry, _) = remote_routing_fixture();
+ let config = |remote_grammar: &str| -> ModelConfig {
+ serde_json::from_value(serde_json::json!({
+ "sie_id":"acme/hybrid",
+ "tasks":{"generate":{"reasoning_effort":{"grammar":"none", "values":{"none":{}, "high":{}}}}},
+ "profiles":{
+ "default":{"adapter_path":"sie_server.adapters.bge_m3:BgeM3Adapter"},
+ "remote":{"adapter_path":"sie_server.adapters.remote.sie:SieUpstreamAdapter",
+ "adapter_options":{"loadtime":{"upstream":"team-sie", "upstream_model":"acme/hybrid:default"}},
+ "reasoning_effort":{"grammar":remote_grammar,
+ "values":{"none":{"upstream":"none"}, "high":{"upstream":"high"}}}}
+ },
+ "routing":{"policy":"fallback", "fallback_profile":"remote"}
+ }))
+ .unwrap()
+ };
+ let error = registry.add_model_config(config("high")).unwrap_err();
+ assert!(
+ error.contains("must declare the same reasoning_effort grammar value"),
+ "{error}"
+ );
+ registry.add_model_config(config("none")).unwrap();
+ }
+
#[test]
fn remote_routing_invalid_delta_keeps_last_snapshot_and_triggers() {
let (_dir, registry, mut config) = remote_routing_fixture();
@@ -4375,6 +4471,91 @@ profiles:
assert!(error.contains("must not enable speculation"));
}
+ #[test]
+ fn test_grammar_target_must_declare_the_sources_grammar_effort() {
+ let config: ModelConfig = serde_saphyr::from_str(
+ r#"
+name: org/grammar-model
+tasks:
+ generate:
+ grammar_profile: safe
+ reasoning_effort:
+ grammar: none
+ values: {none: {}, high: {}}
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ safe:
+ extends: default
+ adapter_options:
+ loadtime:
+ speculative: {enabled: false}
+ reasoning_effort:
+ grammar: high
+ values: {none: {}, high: {}}
+"#,
+ )
+ .unwrap();
+ let error = ModelRegistry::model_entry_from_config(&config).unwrap_err();
+ assert!(
+ error.contains("must declare the same reasoning_effort grammar value"),
+ "{error}"
+ );
+ }
+
+ #[test]
+ fn test_a_sibling_on_the_grammar_target_must_declare_its_grammar_effort() {
+ let yaml = |fast_grammar: &str| {
+ format!(
+ r#"
+name: org/grammar-model
+tasks:
+ generate:
+ grammar_profile: safe
+ reasoning_effort:
+ grammar: none
+ values: {{none: {{}}, high: {{}}}}
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ safe:
+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ adapter_options:
+ loadtime:
+ speculative: {{enabled: false}}
+ fast:
+ extends: default
+ adapter_options:
+ loadtime:
+ speculative: {{enabled: true}}
+ reasoning_effort:
+ grammar: {fast_grammar}
+ values: {{none: {{}}, high: {{}}}}
+ child:
+ extends: safe
+ adapter_options:
+ loadtime:
+ speculative: {{enabled: false}}
+ reasoning_effort:
+ grammar: high
+ values: {{none: {{}}, high: {{}}}}
+"#
+ )
+ };
+ let config: ModelConfig = serde_saphyr::from_str(&yaml("high")).unwrap();
+ let error = ModelRegistry::model_entry_from_config(&config).unwrap_err();
+ assert!(
+ error.contains("Profile 'safe' serves grammar requests for 'fast'"),
+ "{error}"
+ );
+ let config: ModelConfig = serde_saphyr::from_str(&yaml("none")).unwrap();
+ let entry = ModelRegistry::model_entry_from_config(&config).unwrap();
+ assert_eq!(
+ ModelRegistry::grammar_serving_profile(&entry, "child").as_deref(),
+ Some("child")
+ );
+ }
+
#[test]
fn test_grammar_route_variant_matching_benign_launch_args() {
let config: ModelConfig = serde_saphyr::from_str(
diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rs
index a2b23f805..ba5814e3a 100644
--- a/packages/sie_gateway/src/types/model.rs
+++ b/packages/sie_gateway/src/types/model.rs
@@ -25,6 +25,9 @@ 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.
+ pub grammar: Option<String>,
}
impl ReasoningEffortDecl {
@@ -39,24 +42,32 @@ impl ReasoningEffortDecl {
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 })
+ let declared = |key: &str| {
+ declaration
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|named| accepted.iter().any(|value| value == named))
+ .map(str::to_owned)
+ };
+ let default = declared("default");
+ let grammar = declared("grammar");
+ Some(Self {
+ accepted,
+ default,
+ grammar,
+ })
}
/// 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.
+ /// only the accepted values, the default and the grammar value, 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})
+ json!({"default": self.default, "grammar": self.grammar, "values": values})
}
}
@@ -903,6 +914,25 @@ 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 {
@@ -914,6 +944,7 @@ impl ModelEntry {
json!({
"effort": declaration.map(|declaration| declaration.accepted.clone()).unwrap_or_default(),
"default_effort": declaration.and_then(|declaration| declaration.default.clone()),
+ "grammar_effort": declaration.and_then(|declaration| declaration.grammar.clone()),
"budget_tokens": {},
})
}
@@ -1533,7 +1564,10 @@ 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 refusal = entry.reasoning_effort_refusal(case["value"].as_str().unwrap(), model);
+ 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));
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 9a0084bef..99b3936b1 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -334,6 +334,12 @@ class ModelReasoning(TypedDict, total=False):
default_effort: str | None
"""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.
+
+ A request is grammar-constrained when its ``response_format`` is not ``text``, or when it carries a ``grammar``.
+ """
+
budget_tokens: dict[str, int]
"""The hard reasoning-token ceiling of each value that has one. Other values only instruct the model."""
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 14b93fddf..276860e31 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -2312,6 +2312,17 @@
],
"title": "Default Effort"
},
+ "grammar_effort": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Grammar Effort"
+ },
"budget_tokens": {
"additionalProperties": {
"type": "integer"
diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.py
index 389cd75c0..5ef8bdc27 100644
--- a/packages/sie_server/src/sie_server/api/models.py
+++ b/packages/sie_server/src/sie_server/api/models.py
@@ -65,6 +65,12 @@ class ModelReasoning(BaseModel):
default_effort: str | None = None
"""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.
+
+ A request is grammar-constrained when its ``response_format`` is not ``text``, or when it carries a ``grammar``.
+ """
+
budget_tokens: dict[str, int] = {}
"""The hard reasoning-token ceiling of each value that has one. Other values only instruct the model."""
@@ -252,7 +258,9 @@ def _resolve_reasoning(config: ModelConfig) -> ModelReasoning | None:
declaration = config.reasoning_effort_for("default")
if declaration is None:
return ModelReasoning()
- return ModelReasoning(effort=list(declaration.accepted), default_effort=declaration.default)
+ return ModelReasoning(
+ effort=list(declaration.accepted), default_effort=declaration.default, grammar_effort=declaration.grammar
+ )
def _profile_info(registry: "ModelRegistry | Any", name: str, config: ModelConfig, profile: str) -> ProfileInfo:
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index dbad2217a..051e10efa 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -1733,7 +1733,8 @@ async def _chat_completions(
device = registry.device
requested_key = denormalize_model_id(model)
registry_key = requested_key
- if _response_format_constrains_decoding(body.get("response_format")):
+ constrained = _response_format_constrains_decoding(body.get("response_format"))
+ if constrained:
try:
registry_key = resolve_grammar_serving_model(registry, registry_key)
except GenerationUnsupportedFieldError as exc:
@@ -1771,7 +1772,7 @@ async def _chat_completions(
)
try:
reasoning_effort = parse_reasoning_effort(body.get("reasoning_effort"))
- apply_reasoning_effort(config, reasoning_effort, model=model)
+ apply_reasoning_effort(config, reasoning_effort, model=model, grammar=constrained)
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 exc
@@ -1822,7 +1823,7 @@ async def _chat_completions(
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)
+ effort = apply_reasoning_effort(route_config, reasoning_effort, model=model, grammar=constrained)
except GenerationUnsupportedFieldError as exc:
raise _bad_request(str(exc), param=exc.param, code="unsupported_field") from exc
if _adapter_answers_chat(route_config) and isinstance(adapter, GenerationAdapter):
diff --git a/packages/sie_server/src/sie_server/config/grammar_profiles.py b/packages/sie_server/src/sie_server/config/grammar_profiles.py
new file mode 100644
index 000000000..0f02cd0cd
--- /dev/null
+++ b/packages/sie_server/src/sie_server/config/grammar_profiles.py
@@ -0,0 +1,93 @@
+"""Which profile of a model serves a profile's grammar-constrained requests.
+
+A model may declare ``tasks.generate.grammar_profile``, and a profile may
+declare a profile-scoped ``grammar_profile``, naming the sibling profile that
+honours decode-time grammar enforcement. Speculative decoding bypasses the
+grammar backend, so a grammar-constrained request must run on that sibling.
+The rules mirror the gateway's ``ModelRegistry::grammar_route_variant``.
+"""
+
+from collections.abc import Mapping
+from typing import Any
+
+_RAW_SPECULATIVE_FLAGS = frozenset({"--enable-multi-layer-eagle", "--config"})
+_GRAMMAR_SAFE_EXTRA_LAUNCH_ARGS = ("--quantization", "fp8")
+
+
+def model_grammar_profile(config: Any) -> str | None:
+ """The model-wide grammar profile, ``None`` when the model declares none."""
+ generate = getattr(getattr(config, "tasks", None), "generate", None)
+ grammar_profile = getattr(generate, "grammar_profile", None)
+ return grammar_profile if isinstance(grammar_profile, str) else None
+
+
+def grammar_serving_profile(config: Any, profile: str) -> str | None:
+ """The profile that serves grammar-constrained requests for the non-default variant ``profile``.
+
+ ``profile`` itself when it keeps them, ``None`` when nothing routes them.
+ """
+ profiles: Mapping[str, Any] = config.profiles
+ if any(candidate.grammar_profile == profile for candidate in profiles.values()):
+ return profile
+ source = profiles.get(profile)
+ if source is None:
+ return None
+ if source.grammar_profile is not None:
+ return source.grammar_profile
+ parent = profiles.get(source.extends)
+ parent_grammar_profile = None if parent is None else parent.grammar_profile
+ if parent_grammar_profile is not None and profile_is_grammar_compatible(config, profile, parent_grammar_profile):
+ return profile
+ grammar_profile = model_grammar_profile(config)
+ if grammar_profile is None:
+ return None
+ if source.extends == grammar_profile and profile_is_grammar_compatible(config, profile, grammar_profile):
+ return profile
+ return grammar_profile
+
+
+def profile_is_grammar_compatible(config: Any, profile: str, grammar_profile: str) -> bool:
+ """Whether ``profile`` already serves grammar requests the way ``grammar_profile`` does."""
+ try:
+ candidate = config.resolve_profile(profile)
+ grammar = config.resolve_profile(grammar_profile)
+ except ValueError:
+ return False
+ return (
+ candidate.adapter_path == grammar.adapter_path
+ and explicitly_disables_speculation(candidate)
+ and candidate.loadtime.get("grammar_backend") == grammar.loadtime.get("grammar_backend")
+ and _extra_launch_args_are_compatible(candidate.loadtime, grammar.loadtime)
+ )
+
+
+def explicitly_disables_speculation(profile: Any) -> bool:
+ """Whether a resolved profile turns speculative decoding off with no raw override."""
+ speculative = profile.loadtime.get("speculative")
+ return (
+ isinstance(speculative, Mapping)
+ and speculative.get("enabled") is False
+ and _has_no_raw_speculative_overrides(profile.loadtime)
+ )
+
+
+def _has_no_raw_speculative_overrides(loadtime: Mapping[str, Any]) -> bool:
+ args = loadtime.get("extra_launch_args")
+ if args is None:
+ return True
+ if not isinstance(args, list | tuple):
+ return False
+ for arg in args:
+ if not isinstance(arg, str):
+ return False
+ flag = arg.split("=", 1)[0]
+ if flag.startswith("--speculative-") or flag in _RAW_SPECULATIVE_FLAGS:
+ return False
+ return True
+
+
+def _extra_launch_args_are_compatible(candidate: Mapping[str, Any], grammar: Mapping[str, Any]) -> bool:
+ candidate_args = candidate.get("extra_launch_args")
+ if candidate_args == grammar.get("extra_launch_args"):
+ return True
+ return isinstance(candidate_args, list | tuple) and tuple(candidate_args) == _GRAMMAR_SAFE_EXTRA_LAUNCH_ARGS
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index 4ce8a7b91..03430d539 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -21,6 +21,11 @@ from pydantic import (
from sie_server.config.device_groups import validate_tensor_parallel_size
from sie_server.config.engine import ComputePrecision
+from sie_server.config.grammar_profiles import (
+ grammar_serving_profile,
+ model_grammar_profile,
+ profile_is_grammar_compatible,
+)
from sie_server.config.package_artifacts import (
PackageArtifactDeclaration,
has_package_artifact_declaration,
@@ -139,11 +144,17 @@ class ReasoningEffortDeclaration(BaseModel):
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.
+
+ ``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.
"""
model_config = ConfigDict(extra="forbid", frozen=True)
default: ReasoningEffortValue | None = None
+ grammar: ReasoningEffortValue | None = None
values: dict[ReasoningEffortValue, ReasoningEffortLevel]
@model_validator(mode="after")
@@ -152,6 +163,8 @@ class ReasoningEffortDeclaration(BaseModel):
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")
+ if self.grammar is not None and self.grammar not in self.values:
+ raise ValueError(f"reasoning_effort.grammar '{self.grammar}' is not one of its values")
return self
@property
@@ -1149,6 +1162,16 @@ class ModelConfig(BaseModel):
raise ValueError(msg)
return self
+ def _grammar_target(self, name: str) -> str | None:
+ grammar_profile = model_grammar_profile(self)
+ if name == "default":
+ if grammar_profile is None or profile_is_grammar_compatible(self, name, grammar_profile):
+ return None
+ return grammar_profile
+ if is_remote_adapter_path(self._declared_adapter_path(name)):
+ return None
+ return grammar_serving_profile(self, name)
+
def _declared_adapter_path(self, name: str) -> str | None:
profile = self.profiles[name]
if profile.adapter_path is not None or profile.extends is None:
@@ -1182,6 +1205,20 @@ class ModelConfig(BaseModel):
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)
+ for source in self.profiles:
+ target = self._grammar_target(source)
+ if target is None or target == source or target not in self.profiles:
+ continue
+ source_declaration = self.reasoning_effort_for(source)
+ target_declaration = self.reasoning_effort_for(target)
+ source_grammar = source_declaration.grammar if source_declaration is not None else None
+ target_grammar = target_declaration.grammar if target_declaration is not None else None
+ if source_grammar != target_grammar:
+ msg = (
+ f"Profile '{target}' serves grammar requests for '{source}', so they must declare the same "
+ f"reasoning_effort grammar value, got {source_grammar!r} and {target_grammar!r}"
+ )
+ 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")
@@ -1202,6 +1239,14 @@ class ModelConfig(BaseModel):
f"the same reasoning_effort default, got {local_default!r} and {remote_default!r}"
)
raise ValueError(msg)
+ local_grammar = local.grammar if local is not None else None
+ remote_grammar = remote.grammar if remote is not None else None
+ if local_grammar != remote_grammar:
+ msg = (
+ f"Profiles 'default' and '{routing.fallback_profile}' serve one route, so they must declare "
+ f"the same reasoning_effort grammar value, got {local_grammar!r} and {remote_grammar!r}"
+ )
+ raise ValueError(msg)
return self
def reasoning_effort_for(self, profile_name: str = "default") -> ReasoningEffortDeclaration | None:
diff --git a/packages/sie_server/src/sie_server/core/grammar_routing.py b/packages/sie_server/src/sie_server/core/grammar_routing.py
index 56b199719..f838a82de 100644
--- a/packages/sie_server/src/sie_server/core/grammar_routing.py
+++ b/packages/sie_server/src/sie_server/core/grammar_routing.py
@@ -13,6 +13,8 @@ The rules mirror the gateway's ``ModelRegistry::grammar_route_variant``:
- a model without a declared grammar profile keeps its id;
- a default profile that is already grammar compatible keeps its id;
- a request that names the grammar-safe variant keeps its id;
+- a variant served by a remote adapter keeps its id, since the upstream
+ enforces the grammar;
- a variant that directly extends the grammar profile and is grammar
compatible keeps its id;
- a non-speculative variant compatible with its parent's declared grammar
@@ -24,16 +26,19 @@ The rules mirror the gateway's ``ModelRegistry::grammar_route_variant``:
from __future__ import annotations
import logging
-from collections.abc import Mapping
from typing import Any, Protocol
from sie_server.adapters._generation_base import GenerationUnsupportedFieldError
+from sie_server.config.grammar_profiles import (
+ explicitly_disables_speculation,
+ grammar_serving_profile,
+ model_grammar_profile,
+ profile_is_grammar_compatible,
+)
+from sie_server.config.model import is_remote_adapter_path
logger = logging.getLogger(__name__)
-_RAW_SPECULATIVE_FLAGS = frozenset({"--enable-multi-layer-eagle", "--config"})
-_GRAMMAR_SAFE_EXTRA_LAUNCH_ARGS = ("--quantization", "fp8")
-
class ModelConfigSource(Protocol):
def has_model(self, name: str) -> bool: ...
@@ -55,7 +60,7 @@ def resolve_grammar_serving_model(registry: ModelConfigSource, model_id: str) ->
if target is None:
return model_id
base_id, grammar_profile = target
- if model_id == base_id and _profile_is_grammar_compatible(registry.get_config(base_id), "default", grammar_profile):
+ if model_id == base_id and profile_is_grammar_compatible(registry.get_config(base_id), "default", grammar_profile):
return model_id
target_id = f"{base_id}:{grammar_profile}"
if model_id == target_id:
@@ -80,34 +85,15 @@ def _grammar_target(registry: ModelConfigSource, model_id: str) -> tuple[str, st
config = registry.get_config(model_id)
source = getattr(config, "synthetic_profile_variant_source", None)
if not isinstance(source, tuple):
- grammar_profile = _model_grammar_profile(config)
+ grammar_profile = model_grammar_profile(config)
return None if grammar_profile is None else (model_id, grammar_profile)
base_id, source_profile = source
+ if is_remote_adapter_path(config.resolve_profile("default").adapter_path):
+ return base_id, source_profile
if not registry.has_model(base_id):
return _variant_only_target(config, base_id, source_profile)
- base = registry.get_config(base_id)
- profiles: Mapping[str, Any] = base.profiles
- if any(profile.grammar_profile == source_profile for profile in profiles.values()):
- return base_id, source_profile
- source_config = profiles.get(source_profile)
- if source_config is None:
- return None
- if source_config.grammar_profile is not None:
- return base_id, source_config.grammar_profile
- parent = profiles.get(source_config.extends)
- parent_grammar_profile = None if parent is None else parent.grammar_profile
- if parent_grammar_profile is not None and _profile_is_grammar_compatible(
- base, source_profile, parent_grammar_profile
- ):
- return base_id, source_profile
- grammar_profile = _model_grammar_profile(base)
- if grammar_profile is None:
- return None
- if source_config.extends == grammar_profile and _profile_is_grammar_compatible(
- base, source_profile, grammar_profile
- ):
- return base_id, source_profile
- return base_id, grammar_profile
+ serving_profile = grammar_serving_profile(registry.get_config(base_id), source_profile)
+ return None if serving_profile is None else (base_id, serving_profile)
def _variant_only_target(config: Any, base_id: str, source_profile: str) -> tuple[str, str] | None:
@@ -121,60 +107,9 @@ def _variant_only_target(config: Any, base_id: str, source_profile: str) -> tupl
scoped = getattr(own_profile, "grammar_profile", None)
if isinstance(scoped, str):
return base_id, scoped
- grammar_profile = _model_grammar_profile(config)
+ grammar_profile = model_grammar_profile(config)
if grammar_profile is None:
return None
- if _explicitly_disables_speculation(config.resolve_profile("default")):
+ if explicitly_disables_speculation(config.resolve_profile("default")):
return base_id, source_profile
return base_id, grammar_profile
-
-
-def _model_grammar_profile(config: Any) -> str | None:
- generate = getattr(getattr(config, "tasks", None), "generate", None)
- grammar_profile = getattr(generate, "grammar_profile", None)
- return grammar_profile if isinstance(grammar_profile, str) else None
-
-
-def _profile_is_grammar_compatible(config: Any, profile: str, grammar_profile: str) -> bool:
- try:
- candidate = config.resolve_profile(profile)
- grammar = config.resolve_profile(grammar_profile)
- except ValueError:
- return False
- return (
- candidate.adapter_path == grammar.adapter_path
- and _explicitly_disables_speculation(candidate)
- and candidate.loadtime.get("grammar_backend") == grammar.loadtime.get("grammar_backend")
- and _extra_launch_args_are_compatible(candidate.loadtime, grammar.loadtime)
- )
-
-
-def _explicitly_disables_speculation(profile: Any) -> bool:
- speculative = profile.loadtime.get("speculative")
- return (
- isinstance(speculative, Mapping)
- and speculative.get("enabled") is False
- and _has_no_raw_speculative_overrides(profile.loadtime)
- )
-
-
-def _has_no_raw_speculative_overrides(loadtime: Mapping[str, Any]) -> bool:
- args = loadtime.get("extra_launch_args")
- if args is None:
- return True
- if not isinstance(args, list | tuple):
- return False
- for arg in args:
- if not isinstance(arg, str):
- return False
- flag = arg.split("=", 1)[0]
- if flag.startswith("--speculative-") or flag in _RAW_SPECULATIVE_FLAGS:
- return False
- return True
-
-
-def _extra_launch_args_are_compatible(candidate: Mapping[str, Any], grammar: Mapping[str, Any]) -> bool:
- candidate_args = candidate.get("extra_launch_args")
- if candidate_args == grammar.get("extra_launch_args"):
- return True
- return isinstance(candidate_args, list | tuple) and tuple(candidate_args) == _GRAMMAR_SAFE_EXTRA_LAUNCH_ARGS
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 0adcd99c4..534778f1a 100644
--- a/packages/sie_server/src/sie_server/core/reasoning_effort.py
+++ b/packages/sie_server/src/sie_server/core/reasoning_effort.py
@@ -44,21 +44,33 @@ 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
+ config: ModelConfig | None, value: str | None, *, model: str, grammar: bool = False
) -> 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.
+ 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.
Raises:
GenerationUnsupportedFieldError: When the profile does not accept ``value``.
"""
- if value is None:
+ if value is None and not grammar:
return None
declaration = config.reasoning_effort_for("default") if config is not None else None
+ grammar_value = declaration.grammar if grammar and declaration is not None else None
+ if value is None:
+ if grammar_value is None:
+ return None
+ value = grammar_value
if declaration is None:
if value == "none" and config is not None and config.declares_no_reasoning:
return None
@@ -66,6 +78,8 @@ 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/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 700366391..0792cd6f4 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -1999,7 +1999,12 @@ class StreamingProcessor:
raise GenerationUnsupportedFieldError(
"reasoning_effort", "'reasoning_effort' needs a chat messages request"
)
- effort = apply_reasoning_effort(config, params.reasoning_effort, model=model_id)
+ effort = apply_reasoning_effort(
+ config,
+ params.reasoning_effort,
+ model=model_id,
+ grammar=params.grammar is not None and isinstance(params.input, _MessagesInput),
+ )
except GenerationError as exc:
await self._terminal_error_then_settle(
reply_subject,
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 60857bb24..0036add34 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -123,6 +123,7 @@ def _cuda_chat_client(
inputs=SimpleNamespace(video=video, image=image),
profiles={},
routing=None,
+ reasoning_effort_for=lambda _profile="default": None,
)
registry = MagicMock()
registry.device = "cuda:0"
@@ -179,6 +180,7 @@ def _mlx_chat_client(
inputs=SimpleNamespace(video=False, image=image),
profiles={},
routing=None,
+ reasoning_effort_for=lambda _profile="default": None,
)
registry = MagicMock()
registry.device = "mps"
diff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.py
index e30f8b7cb..56c89638d 100644
--- a/packages/sie_server/tests/api/test_remote_chat.py
+++ b/packages/sie_server/tests/api/test_remote_chat.py
@@ -23,7 +23,7 @@ from sie_server.api.generate import router as generate_router
from sie_server.api.openai_completions import router as completions_router
from sie_server.api.openai_local import _remote_chat_response, router
from sie_server.api.openai_responses import router as responses_router
-from sie_server.config.model import ModelConfig
+from sie_server.config.model import ModelConfig, ReasoningEffortDeclaration
from sie_server.config.upstreams import Upstream, install_upstreams
from sie_server.core.loader import expand_profile_variants
from sie_server.core.upstream_client import upstream_client
@@ -393,6 +393,55 @@ def test_strict_json_output_is_verified_after_remote_parsing(remote_chat: tuple,
assert result.json()["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"
+def _declare_grammar_effort(config: ModelConfig) -> None:
+ assert config.tasks.generate is not None
+ config.tasks.generate.reasoning_effort = ReasoningEffortDeclaration.model_validate(
+ {"default": "high", "grammar": "none", "values": {"none": {"upstream": "none"}, "high": {"upstream": "high"}}}
+ )
+
+
+ ("changes", "sent_effort"),
+ [
+ ({"response_format": {"type": "json_object"}}, "none"),
+ ({"response_format": {"type": "json_object"}, "reasoning_effort": "none"}, "none"),
+ (
+ {"response_format": {"type": "json_schema", "json_schema": {"name": "a", "schema": {"type": "object"}}}},
+ "none",
+ ),
+ ({"response_format": {"type": "text"}}, None),
+ ({"reasoning_effort": "high"}, "high"),
+ ({}, None),
+ ],
+)
+def test_a_constrained_request_runs_at_the_declared_grammar_effort(
+ remote_chat: tuple, changes: dict[str, Any], sent_effort: str | None
+) -> 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, **changes})
+ assert response.status_code == 200, response.text
+ assert len(requests) == 1
+ 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_grammar_routing.py b/packages/sie_server/tests/core/test_grammar_routing.py
index f07836926..3e803d8b4 100644
--- a/packages/sie_server/tests/core/test_grammar_routing.py
+++ b/packages/sie_server/tests/core/test_grammar_routing.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import shutil
+from collections.abc import Iterator
from copy import deepcopy
from pathlib import Path
from typing import Any
@@ -10,6 +11,7 @@ from typing import Any
import pytest
import yaml
from sie_server.adapters._generation_base import GenerationUnsupportedFieldError
+from sie_server.config.upstreams import Upstream, install_upstreams
from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.registry import ModelRegistry
@@ -197,3 +199,36 @@ def test_explicit_child_grammar_fallback_precedes_the_parent_hint(tmp_path: Path
else:
with pytest.raises(GenerationUnsupportedFieldError, match=f"'{fallback}'"):
resolve_grammar_serving_model(registry, requested)
+
+
+def relay_upstream() -> Iterator[None]:
+ upstream = Upstream.model_validate(
+ {
+ "kind": "sie",
+ "base_url": "http://127.0.0.1:8088",
+ "rate_cap": {"requests_per_minute": 60, "max_concurrency": 1},
+ }
+ )
+ install_upstreams({"relay": upstream})
+ try:
+ yield
+ finally:
+ install_upstreams({})
+
+
[email protected]("relay_upstream")
[email protected]("serve_base", [True, False])
+def test_a_remote_variant_keeps_its_grammar_requests(tmp_path: Path, serve_base: bool) -> None:
+ config = yaml.safe_load(_GEMMA_FILE.read_text(encoding="utf-8"))
+ config["profiles"]["relay"] = {
+ "adapter_path": "sie_server.adapters.remote.sie:SieUpstreamAdapter",
+ "max_batch_tokens": 16384,
+ "adapter_options": {"loadtime": {"upstream": "relay", "upstream_model": "google/gemma-4-31B-it"}},
+ "reasoning_effort": {"grammar": "none", "values": {"none": {"upstream": "none"}, "high": {"upstream": "high"}}},
+ }
+ requested = f"{_GEMMA_ID}:relay"
+ model_filter = [_GEMMA_ID, requested] if serve_base else [requested]
+ registry = _gemma_registry(tmp_path, config=config, model_filter=model_filter)
+
+ assert resolve_grammar_serving_model(registry, requested) == requested
diff --git a/packages/sie_server/tests/core/test_reasoning_effort.py b/packages/sie_server/tests/core/test_reasoning_effort.py
index 25a0e112f..89ee1acc8 100644
--- a/packages/sie_server/tests/core/test_reasoning_effort.py
+++ b/packages/sie_server/tests/core/test_reasoning_effort.py
@@ -12,6 +12,7 @@ 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.grammar_profiles import grammar_serving_profile
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
@@ -58,13 +59,14 @@ def _hybrid(local: dict[str, Any] | None, remote: dict[str, Any] | None) -> dict
@pytest.mark.parametrize("case", _VECTORS["cases"], ids=lambda case: case["name"])
def test_shared_vectors_resolve_or_refuse(case: dict[str, Any]) -> None:
config = _config(case["model"])
+ grammar = case.get("grammar", False)
if "message" in case:
with pytest.raises(GenerationUnsupportedFieldError) as refused:
- apply_reasoning_effort(config, case["value"], model=case["model"])
+ apply_reasoning_effort(config, case["value"], model=case["model"], grammar=grammar)
assert refused.value.param == "reasoning_effort"
assert str(refused.value) == case["message"]
return
- applied = apply_reasoning_effort(config, case["value"], model=case["model"])
+ applied = apply_reasoning_effort(config, case["value"], model=case["model"], grammar=grammar)
if case["applied"] is None:
assert applied is None
else:
@@ -101,6 +103,7 @@ def test_absent_and_null_change_nothing() -> None:
({"values": {}}, "at least one value"),
({"values": {"extreme": {}}}, "values"),
({"default": "low", "values": {"high": {}}}, "is not one of its values"),
+ ({"grammar": "none", "values": {"high": {}}}, "grammar 'none' 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"),
@@ -149,6 +152,8 @@ def test_both_profiles_of_a_routed_model_accept_the_same_values() -> None:
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"}}}))
+ with pytest.raises(ValidationError, match="the same reasoning_effort grammar value"):
+ ModelConfig.model_validate(_hybrid(low_local, {"grammar": "low", "values": {"low": {"upstream": "low"}}}))
def test_a_variant_carries_its_profiles_declaration() -> None:
@@ -209,6 +214,70 @@ def _chat_params(**overrides: Any) -> _GenerateRequestParams:
)
[email protected]("scope", ["model", "profile"])
+def test_a_grammar_fallback_declares_the_grammar_value_it_serves(scope: str) -> None:
+ spec = copy.deepcopy(_VECTORS["models"]["acme/declared"]["config"])
+ declaration = {**spec["tasks"]["generate"]["reasoning_effort"], "grammar": "low"}
+ spec["tasks"]["generate"]["reasoning_effort"] = declaration
+ spec["profiles"]["safe"] = {
+ "extends": "default",
+ "adapter_options": {"loadtime": {"speculative": {"enabled": False}}},
+ "reasoning_effort": {**declaration, "grammar": "high"},
+ }
+ if scope == "model":
+ spec["tasks"]["generate"]["grammar_profile"] = "safe"
+ else:
+ spec["profiles"]["long"] = {"extends": "default", "grammar_profile": "safe"}
+ with pytest.raises(ValidationError, match="must declare the same reasoning_effort grammar value"):
+ ModelConfig.model_validate(spec)
+ spec["profiles"]["safe"]["reasoning_effort"] = declaration
+ ModelConfig.model_validate(spec)
+
+
+def test_a_sibling_on_the_model_wide_grammar_fallback_declares_its_grammar_value() -> None:
+ spec = copy.deepcopy(_VECTORS["models"]["acme/declared"]["config"])
+ declaration = {**spec["tasks"]["generate"]["reasoning_effort"], "grammar": "low"}
+ spec["tasks"]["generate"]["reasoning_effort"] = declaration
+ spec["tasks"]["generate"]["grammar_profile"] = "safe"
+ spec["profiles"]["safe"] = {
+ "extends": "default",
+ "adapter_options": {"loadtime": {"speculative": {"enabled": False}}},
+ }
+ spec["profiles"]["fast"] = {"extends": "default", "reasoning_effort": {**declaration, "grammar": "high"}}
+ with pytest.raises(ValidationError, match="Profile 'safe' serves grammar requests for 'fast'"):
+ ModelConfig.model_validate(spec)
+ spec["profiles"]["fast"]["reasoning_effort"] = declaration
+ ModelConfig.model_validate(spec)
+
+
+def test_a_profile_that_keeps_its_grammar_requests_declares_its_own_grammar_value() -> None:
+ spec = copy.deepcopy(_VECTORS["models"]["acme/declared"]["config"])
+ declaration = {**spec["tasks"]["generate"]["reasoning_effort"], "grammar": "low"}
+ spec["tasks"]["generate"]["reasoning_effort"] = declaration
+ spec["tasks"]["generate"]["grammar_profile"] = "safe"
+ no_speculation = {"loadtime": {"speculative": {"enabled": False}}}
+ spec["profiles"]["safe"] = {**spec["profiles"]["default"], "adapter_options": no_speculation}
+ spec["profiles"]["child"] = {
+ "extends": "safe",
+ "adapter_options": no_speculation,
+ "reasoning_effort": {**declaration, "grammar": "high"},
+ }
+ config = ModelConfig.model_validate(spec)
+ assert grammar_serving_profile(config, "child") == "child"
+
+
+def test_a_grammar_value_reaches_a_variant_of_its_profile() -> None:
+ declaration = {"grammar": "low", "values": {"low": {"upstream": "low"}, "high": {"upstream": "high"}}}
+ spec = copy.deepcopy(_VECTORS["models"]["acme/remote"]["config"])
+ spec["profiles"]["relay"] = {"extends": "default", "reasoning_effort": declaration}
+ variant = expand_profile_variants([ModelConfig.model_validate(spec)])["acme/remote:relay"]
+ 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)
+
+
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")
diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.py
index 24aa323fa..3e6a4bffd 100644
--- a/packages/sie_server/tests/processors/test_remote_chat.py
+++ b/packages/sie_server/tests/processors/test_remote_chat.py
@@ -296,6 +296,53 @@ async def test_strict_schema_is_sent_and_finished_output_verified(remote: tuple)
}
+def _declare_grammar_effort(proc: StreamingProcessor) -> None:
+ config_data = proc._registry.get_config(MODEL).model_dump()
+ config_data["tasks"]["generate"]["reasoning_effort"] = {
+ "default": "high",
+ "grammar": "none",
+ "values": {"none": {"upstream": "none"}, "high": {"upstream": "high"}},
+ }
+ proc._registry.get_config.return_value = ModelConfig.model_validate(config_data)
+
+
+_OBJECT = {"kind": "json_schema", "value": {"type": "object"}, "label": "json_object"}
+
+
+ ("fields", "sent_effort"),
+ [
+ ({"grammar": _OBJECT}, "none"),
+ ({"grammar": _OBJECT, "reasoning_effort": "none"}, "none"),
+ ({"reasoning_effort": "high"}, "high"),
+ ({}, None),
+ ],
+)
+async def test_a_constrained_request_runs_at_the_declared_grammar_effort(
+ remote: tuple, fields: dict[str, Any], sent_effort: str | None
+) -> None:
+ _declare_grammar_effort(remote[1])
+ respond(remote)
+ msg, chunks = await run(remote, **fields)
+ assert chunks[-1]["done"]
+ assert "error" not in chunks[-1]
+ assert json.loads(remote[3][0].content).get("reasoning_effort") == sent_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 2e7338d8e..bcb68bd79 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -276,6 +276,8 @@ 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 */
+ 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>;
}