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): enforce strict function-tool arguments (#1023)

Jan Kadlecdc9389a67c76
diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md
index c6f938fc1..3a24a691b 100644
--- a/COMPATIBILITY.md
+++ b/COMPATIBILITY.md
@@ -25,6 +25,79 @@ reusing unflagged `C3 A9` bytes. Regenerate invalid flagged filenames using the
intended Unicode name. This migration applies to ZIP-backed NPZ/PTH checkpoints;
the Safetensors format is unaffected.
+## Chat function tools: `strict`
+
+`/v1/chat/completions` now enforces `tools[].function.strict: true`: every call
+to a strict tool that the response returns has arguments that match its
+`parameters` schema. Earlier releases accepted the flag and ignored it, so a
+strict tool could receive arguments of the wrong type, missing required keys,
+or undeclared keys.
+
+- **Validation is the guarantee.** When the turn ends, every strict call's
+ arguments are validated against the tool's full JSON Schema (Draft 2020-12,
+ the same verifier as a strict `response_format`). This runs for every model
+ the worker serves, whatever its tool-call format or grammar backend. A call
+ that breaks its schema ends the turn with a `MODEL_OUTPUT_PARSE_ERROR` error
+ instead of reaching the client. When streaming, a strict call's deltas, and
+ anything generated after them, are sent once the turn has been validated, so
+ a client never receives arguments that are then declared invalid.
+- **A grammar makes violations unlikely.** With the `xgrammar` backend and the
+ Qwen XML (`qwen3_coder`) or Hermes JSON (`qwen25`) tool-call format, the
+ worker also compiles each strict tool's schema into an XGrammar structural
+ tag. The tag applies with every `tool_choice`: with `auto` the model may
+ answer in text or call a tool, and any call it makes is constrained.
+ Required keys must be present and undeclared keys cannot appear. Optional
+ keys may be omitted, and nullable values (`anyOf: [T, {type: "null"}]`) may
+ be `null`. Values follow their own schema: types, `enum`, `const`,
+ `$ref`/`$defs`, object and array structure, and numeric bounds. A non-strict
+ tool in the same request keeps free arguments.
+
+ What the grammar cannot express is constrained less and left to validation.
+ It is never a reason to refuse the request:
+ - XGrammar 0.1.32 compiles some keywords without enforcing them, for example
+ `multipleOf`, `uniqueItems`, `not`, `if`/`then`, `oneOf` (compiled as
+ `anyOf`), `pattern` beside `format` or a length bound, assertions beside
+ `$ref`, and string assertions on Qwen XML parameters.
+ - A Qwen XML parameter whose value the layout cannot constrain is free text,
+ and the other parameters stay constrained. Examples: a union of a scalar
+ with another non-null type (`anyOf: [integer, string]`), an `enum` of mixed
+ types, a nullable string whose `enum` lists the string `"null"`.
+ - A tool the grammar would constrain to something else keeps a free argument
+ body, and the other tools stay constrained. Examples: a `$ref` outside
+ `#/$defs/...` or `#/definitions/...` (such as `"$ref": "#"`), a listed
+ value that does not match its `type`, and with Qwen XML a parameters
+ object that is not a plain object of named properties (a top-level `anyOf`,
+ `allOf`, `$ref`, `patternProperties`, more than 256 properties).
+ - A request without a structural tag runs with the grammar a non-strict
+ request gets: none for `auto`, the forcing grammar for `required` and a
+ named choice, and the `response_format` grammar when the request sets
+ one. This covers the other grammar backends, the Gemma 4, GLM and Muse
+ tool-call formats, a request that also sets `response_format`, and schemas
+ XGrammar's schema cache would conflate (two subschemas that differ only
+ under a property named `description`, `title`, `default` or a similar
+ annotation keyword).
+- **Routing.** A request with a strict tool, `tool_choice: "required"`, or a
+ named `tool_choice` now runs on the model's `grammar_profile` (for example
+ `:no-spec`), like a `response_format` grammar, because speculative decoding
+ bypasses the grammar backend. Before this change a forced `tool_choice` ran
+ on the requested speculative profile, where the forcing grammar did not
+ apply. With `tool_choice: "none"` no tool is called, so strict tools alone
+ do not change the profile. Roll out the gateway before the workers: a newer
+ worker behind an older gateway receives these requests on the base model and
+ resolves them to the grammar profile, which it may not have loaded.
+- **Rejection.** A strict tool fails the request with `400 unsupported_field`
+ before generation only when its arguments could not be validated:
+ - two function tools share a name;
+ - its `parameters` do not describe an object;
+ - the schema uses `unevaluatedProperties`, which the verifier cannot
+ evaluate within its pattern budget;
+ - the backend cannot compile the structural tag.
+
+ Strict tools are also refused on the direct SGLang and MLX
+ `/v1/chat/completions` routes of a standalone server, because those routes
+ return the engine's own tool calls without validating them. Remote-backed
+ models pass `strict` to their upstream unchanged.
+
This document defines SIE's compatibility commitments: what constitutes a breaking change, how deprecations are communicated, and what must be true before declaring 1.0.
---
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 320cb8031..a5ada93ac 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -6635,6 +6635,38 @@ struct ChatRequestParams {
}
impl ChatRequestParams {
+ /// Whether ``tools`` / ``tool_choice`` make the worker constrain decoding.
+ ///
+ /// A forced ``tool_choice`` (``"required"`` or a named function) compiles
+ /// a forcing grammar, and a ``strict`` function tool compiles a grammar
+ /// over its arguments. Speculative decoding bypasses the grammar backend,
+ /// so either must route to the grammar-safe profile exactly like
+ /// ``response_format``. Mirrors the worker's ``tools_require_grammar``.
+ fn tools_require_grammar(&self) -> bool {
+ let Some(tools) = self.tools.as_ref().filter(|tools| !tools.is_empty()) else {
+ return false;
+ };
+ if tool_choice_forces(self.tool_choice.as_ref()) {
+ return true;
+ }
+ self.tool_choice
+ .as_ref()
+ .and_then(serde_json::Value::as_str)
+ != Some("none")
+ && tools.iter().any(|tool| {
+ tool.get("function")
+ .and_then(|function| function.get("strict"))
+ .and_then(serde_json::Value::as_bool)
+ == Some(true)
+ })
+ }
+
+ /// Whether the request is grammar-constrained: a ``response_format``
+ /// grammar, a forced ``tool_choice``, or a ``strict`` tool.
+ fn constrains_decoding(&self) -> bool {
+ self.grammar.is_some() || self.tools_require_grammar()
+ }
+
/// The EXACT `WorkParams` a validated chat body dispatches with.
///
/// Extracted from the handler body (not copied) so the managed
@@ -8017,12 +8049,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
// the combination early with a clear 400 rather than letting the
// worker silently drop one. ``"auto"`` / ``"none"`` don't force a
// grammar, so they remain compatible with ``response_format``.
- let tool_choice_forces = match &tool_choice {
- Some(serde_json::Value::String(s)) => s == "required",
- Some(serde_json::Value::Object(_)) => true, // named {type:function,function:{name}}
- _ => false,
- };
- if tool_choice_forces && grammar.is_some() {
+ if tool_choice_forces(tool_choice.as_ref()) && grammar.is_some() {
return bad(
"'tool_choice' (\"required\" or a named function) cannot be combined with \
'response_format' — both constrain decoding",
@@ -8246,6 +8273,15 @@ fn validate_chat_tools(v: &serde_json::Value) -> Result<Vec<serde_json::Value>,
));
}
}
+ if let Some(strict) = func.get("strict") {
+ if !strict.is_boolean() && !strict.is_null() {
+ return Err(bad(
+ format!("tools[{i}].function.strict must be a boolean"),
+ &format!("tools[{i}].function.strict"),
+ oai_code::INVALID_REQUEST,
+ ));
+ }
+ }
if let Some(params) = func.get("parameters") {
if !params.is_null() {
let path = format!("tools[{i}].function.parameters");
@@ -8262,6 +8298,17 @@ fn validate_chat_tools(v: &serde_json::Value) -> Result<Vec<serde_json::Value>,
Ok(arr.clone())
}
+/// Whether a validated OpenAI ``tool_choice`` forces a call: ``"required"`` or a
+/// named function ``{type:"function", function:{name}}``. The worker compiles a
+/// forcing grammar for either.
+fn tool_choice_forces(tool_choice: Option<&serde_json::Value>) -> bool {
+ match tool_choice {
+ Some(serde_json::Value::String(choice)) => choice == "required",
+ Some(serde_json::Value::Object(_)) => true,
+ _ => false,
+ }
+}
+
/// Validate OpenAI ``tool_choice``: ``"auto"`` / ``"none"`` /
/// ``"required"`` or ``{type:"function", function:{name}}``. Returns
/// the value unchanged on success so the caller can plumb it verbatim.
@@ -9684,17 +9731,25 @@ async fn proxy_chat_inner(
// DISPLAY id (``model_name``) stays the requested model for the response
// body, success metrics, and audit log. Equal to ``model_name`` unless a
// grammar is present and a variant exists. See ``route_grammar_to_profile``.
+ // A forced ``tool_choice`` or a ``strict`` tool also compiles a grammar on
+ // the worker (see ``ChatRequestParams::tools_require_grammar``).
let mut dispatch_model = model_name.clone();
- if params.grammar.is_some() {
+ let constrains_decoding = params.constrains_decoding();
+ if constrains_decoding {
if let Err(unavailable) =
route_grammar_to_profile(&state.model_registry, &mut dispatch_model)
{
+ let param = if params.grammar.is_some() {
+ "response_format"
+ } else {
+ "tools"
+ };
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
unavailable.message(&model_name),
oai_type::INVALID_REQUEST,
- Some("response_format"),
+ Some(param),
oai_code::UNSUPPORTED_FIELD,
)),
)
@@ -9938,7 +9993,7 @@ async fn proxy_chat_inner(
&params.model,
&model_name,
&dispatch_model,
- if params.grammar.is_some() {
+ if constrains_decoding {
GenerationRequestIntent::Grammar
} else {
GenerationRequestIntent::Default
@@ -26727,6 +26782,75 @@ mod tests {
assert_eq!(p.max_new_tokens, 32);
}
+ // ── tools: strict function tools and forced tool_choice route like grammars ──
+
+ fn _chat_body_with_tool(strict: serde_json::Value) -> serde_json::Value {
+ let mut body = _chat_body_min("m");
+ body["tools"] = serde_json::json!([{
+ "type": "function",
+ "function": {
+ "name": "search",
+ "strict": strict,
+ "parameters": {"type": "object", "properties": {"q": {"type": "string"}}},
+ },
+ }]);
+ body
+ }
+
+ #[test]
+ fn test_chat_tools_require_grammar_for_strict_tools_and_forced_choices() {
+ let cases = [
+ (serde_json::json!(true), None, true),
+ (
+ serde_json::json!(true),
+ Some(serde_json::json!("auto")),
+ true,
+ ),
+ (
+ serde_json::json!(true),
+ Some(serde_json::json!("none")),
+ false,
+ ),
+ (serde_json::json!(false), None, false),
+ (
+ serde_json::json!(false),
+ Some(serde_json::json!("auto")),
+ false,
+ ),
+ (
+ serde_json::json!(false),
+ Some(serde_json::json!("required")),
+ true,
+ ),
+ (
+ serde_json::Value::Null,
+ Some(serde_json::json!({"type": "function", "function": {"name": "search"}})),
+ true,
+ ),
+ ];
+ for (strict, tool_choice, expected) in cases {
+ let mut body = _chat_body_with_tool(strict.clone());
+ if let Some(choice) = tool_choice.clone() {
+ body["tool_choice"] = choice;
+ }
+ let params = _expect_chat_ok(body);
+ assert_eq!(
+ params.tools_require_grammar(),
+ expected,
+ "strict={strict} tool_choice={tool_choice:?}"
+ );
+ assert_eq!(params.constrains_decoding(), expected);
+ }
+ assert!(!_expect_chat_ok(_chat_body_min("m")).constrains_decoding());
+ }
+
+ #[tokio::test]
+ async fn test_chat_tools_strict_must_be_boolean() {
+ let err = _expect_chat_err(_chat_body_with_tool(serde_json::json!("yes"))).await;
+ assert_eq!(err["error"]["param"], "tools[0].function.strict");
+ assert_eq!(err["error"]["code"], oai_code::INVALID_REQUEST);
+ }
+
// ── schema_in_prompt: json_schema response formats shown to the model ──
#[test]
diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rs
index 191abfb93..36466a400 100644
--- a/packages/sie_gateway/src/state/model_registry.rs
+++ b/packages/sie_gateway/src/state/model_registry.rs
@@ -1467,19 +1467,22 @@ impl ModelRegistry {
}
}
- /// Whether ``model`` is an explicit ``{base}:{profile}`` variant whose
- /// profile is served by a remote adapter. The server sends the grammar to
- /// that upstream and verifies the output, so the named profile is honoured.
+ /// Whether ``model`` names a profile served by a remote adapter: an
+ /// explicit ``{base}:{profile}`` variant, or a base model whose default
+ /// profile is remote. The server sends the grammar to that upstream and
+ /// verifies the output, so the named model is honoured (the worker's
+ /// ``core/grammar_routing.py`` keeps the same ids).
fn names_remote_profile(snap: &RegistrySnapshot, model: &str) -> bool {
let Some(canonical) = Self::canonical_model_name(snap, model) else {
return false;
};
- let Some((base, profile)) = canonical.rsplit_once(':') else {
- return false;
+ let (base, profile) = match canonical.rsplit_once(':') {
+ Some((base, profile)) if snap.models.contains_key(base) => (base, profile),
+ _ => (canonical.as_str(), "default"),
};
snap.models
.get(base)
- .filter(|entry| entry.profile_configs.contains_key(profile))
+ .filter(|entry| profile == "default" || entry.profile_configs.contains_key(profile))
.and_then(|entry| Self::effective_adapter_path_from_entry(entry, profile))
.is_some_and(|path| path.starts_with(REMOTE_ADAPTER_MODULE_PREFIX))
}
@@ -4012,6 +4015,21 @@ mod tests {
}))
.unwrap();
registry.add_model_config(remote_backed).unwrap();
+ // A remote-served base model keeps its id even when it declares a
+ // grammar profile, as on the worker.
+ let remote_with_grammar_profile: ModelConfig = serde_json::from_value(serde_json::json!({
+ "sie_id": "org/remote-gp",
+ "tasks": {"generate": {"grammar_profile": "alt"}},
+ "profiles": {"default": remote.clone(), "alt": remote.clone()},
+ }))
+ .unwrap();
+ registry
+ .add_model_config(remote_with_grammar_profile)
+ .unwrap();
+ assert_eq!(
+ registry.grammar_route_variant("org/remote-gp"),
+ GrammarRoute::Keep
+ );
for model in [
"org/g:relay",
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 886e0b637..66529ec6d 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -38,6 +38,7 @@ from pathlib import Path
from typing import Any, Literal, cast
import httpx
+import orjson
from sie_server.adapters._generation_base import (
REASONING_CONTROL_TOKENS,
@@ -48,6 +49,7 @@ from sie_server.adapters._generation_base import (
GenerationInputTooLongError,
GenerationInvalidRequestError,
GenerationResult,
+ GenerationUnsupportedFieldError,
ReasoningFormat,
reasoning_expected_after_prompt,
reasoning_starts_in_prompt,
@@ -369,9 +371,23 @@ async def _raise_for_sglang_http_error(
raise GenerationInvalidRequestError("grammar", OUTLINES_JSON_SCHEMA_TYPE_MESSAGE)
_raise_for_media_load_error(message)
_raise_for_window_refusal(message)
+ if (
+ grammar is not None
+ and grammar.kind == "structural_tag"
+ and isinstance(message, str)
+ and "structural_tag" in message
+ ):
+ raise _strict_tool_unsupported()
response.raise_for_status()
+def _strict_tool_unsupported() -> GenerationUnsupportedFieldError:
+ """A strict tool schema the backend cannot compile is unsupported, as OpenAI reports it."""
+ return GenerationUnsupportedFieldError(
+ "tools", "The generation backend cannot enforce a strict tool's parameters schema"
+ )
+
+
def _raise_for_sglang_event_error(
event: Any, *, grammar: GrammarSpec | None = None, grammar_backend: str | None = None, terminal: bool = False
) -> None:
@@ -399,6 +415,10 @@ def _raise_for_sglang_event_error(
and finish.get("message") == _JSON_SCHEMA_TYPE_DIAGNOSTIC
):
raise GenerationInvalidRequestError("grammar", OUTLINES_JSON_SCHEMA_TYPE_MESSAGE)
+ if grammar.kind == "structural_tag":
+ # Built from strict tool schemas; the only 400 abort for a
+ # grammar request that is not a window refusal is its compile.
+ raise _strict_tool_unsupported()
raise GenerationInvalidRequestError(
"grammar", f"The generation backend rejected the requested {grammar.kind} grammar"
)
@@ -1709,6 +1729,10 @@ class SGLangGenerationAdapter(SGLangLoraMixin, GenerationAdapter):
# The gateway has size-capped the source via ``MAX_EBNF_LEN``;
# further compile-time validation happens inside the backend.
sampling_params["ebnf"] = grammar.value
+ elif grammar.kind == "structural_tag":
+ # Built by the worker for ``strict`` function tools and only on
+ # an XGrammar backend, which compiles SGLang's ``structural_tag``.
+ sampling_params["structural_tag"] = orjson.dumps(grammar.value).decode()
thinking_budget = self._thinking_budget_spec(prompt) if require_reasoning else None
if thinking_budget is not None:
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 15a95ac7f..38a9a5b56 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -126,6 +126,7 @@ from sie_server.processors.strict_grammar import (
first_output_violation,
unverifiable_schema_keyword,
)
+from sie_server.processors.tool_call_grammar import is_strict_tool, tools_require_grammar
from sie_server.types.grammar import GrammarSpec
from sie_server.types.inputs import InvalidInputError, InvalidMediaError, Item, decode_image, item_size_error
from sie_server.types.openapi import OpenAIGenerationErrorResponse
@@ -701,6 +702,24 @@ def _validate_chat_tools(body: dict[str, Any]) -> None:
raise _bad_request("'tool_choice' must name a declared function", param="tool_choice")
+def _reject_strict_tools(body: dict[str, Any]) -> None:
+ """Refuse ``strict`` tools on a route whose engine would not enforce them.
+
+ The engine's own chat endpoint parses tool calls without constraining
+ their arguments for these models, so accepting ``strict`` would promise a
+ schema guarantee nothing checks. The queued route enforces it.
+ """
+ if body.get("tool_choice") == "none":
+ return
+ for index, tool in enumerate(body.get("tools") or []):
+ if is_strict_tool(tool):
+ raise _bad_request(
+ "strict function tools are not enforced on this route for this model",
+ param=f"tools[{index}].function.strict",
+ code="unsupported_field",
+ )
+
+
def _validate_mlx_chat_body(body: dict[str, Any]) -> None:
unknown_fields = body.keys() - _MLX_CHAT_FIELDS
if unknown_fields:
@@ -708,6 +727,7 @@ def _validate_mlx_chat_body(body: dict[str, Any]) -> None:
raise _bad_request(f"field '{unknown}' is not supported", param=unknown, code="unsupported_field")
_validate_common_chat_body(body)
+ _reject_strict_tools(body)
choice = body.get("tool_choice")
if choice is not None and choice not in ("auto", "none"):
raise _bad_request(
@@ -1021,6 +1041,7 @@ def _prepare_sglang_body(
param="tool_choice",
code="unsupported_field",
)
+ _reject_strict_tools(body)
proxied = _prepare_chat_body(
body,
config=config,
@@ -1754,11 +1775,14 @@ async def _chat_completions(
requested_key = denormalize_model_id(model)
registry_key = requested_key
constrained = _response_format_constrains_decoding(body.get("response_format"))
- if constrained:
+ # A forced tool_choice or a strict tool compiles a grammar too.
+ constrained_decoding = constrained or tools_require_grammar(body.get("tools"), body.get("tool_choice"))
+ if constrained_decoding:
try:
registry_key = resolve_grammar_serving_model(registry, registry_key)
except GenerationUnsupportedFieldError as exc:
- raise _bad_request(str(exc), param="response_format", code="unsupported_field") from exc
+ param = "response_format" if constrained else "tools"
+ raise _bad_request(str(exc), param=param, code="unsupported_field") from exc
strict_grammar = _strict_response_format_grammar(body.get("response_format"))
if strict_grammar is not None and (keyword := unverifiable_schema_keyword(strict_grammar.value)) is not None:
raise _bad_request(
@@ -1792,7 +1816,7 @@ async def _chat_completions(
)
try:
reasoning_effort = parse_reasoning_effort(body.get("reasoning_effort"))
- apply_reasoning_effort(config, reasoning_effort, model=model, grammar=constrained)
+ apply_reasoning_effort(config, reasoning_effort, model=model, grammar=constrained_decoding)
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
@@ -1843,7 +1867,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, grammar=constrained)
+ effort = apply_reasoning_effort(route_config, reasoning_effort, model=model, grammar=constrained_decoding)
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/core/grammar_routing.py b/packages/sie_server/src/sie_server/core/grammar_routing.py
index f838a82de..b711391a3 100644
--- a/packages/sie_server/src/sie_server/core/grammar_routing.py
+++ b/packages/sie_server/src/sie_server/core/grammar_routing.py
@@ -85,6 +85,9 @@ 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):
+ # A remote upstream enforces the request itself, so it keeps its id.
+ if is_remote_adapter_path(getattr(config.resolve_profile("default"), "adapter_path", None)):
+ return None
grammar_profile = model_grammar_profile(config)
return None if grammar_profile is None else (model_id, grammar_profile)
base_id, source_profile = source
diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.py
index 1d47e16bf..445e302a9 100644
--- a/packages/sie_server/src/sie_server/ipc_server.py
+++ b/packages/sie_server/src/sie_server/ipc_server.py
@@ -79,6 +79,7 @@ from sie_server.ipc_types import (
)
from sie_server.processors.admission import resolve_admission_enabled
from sie_server.processors.generate_params import extract_generate_params
+from sie_server.processors.tool_call_grammar import request_constrains_decoding
from sie_server.queue_executor import QueueExecutor
from sie_server.types.responses import ErrorCode
@@ -1014,7 +1015,13 @@ class IpcServer:
if expected_hash and valid:
generate = extract_generate_params(work_item)
valid = work_item.get("model_id") == req.model_id
- if valid and isinstance(generate, dict) and generate.get("grammar") is not None:
+ if (
+ valid
+ and isinstance(generate, dict)
+ and request_constrains_decoding(
+ generate.get("grammar"), generate.get("tools"), generate.get("tool_choice")
+ )
+ ):
try:
valid = resolve_grammar_serving_model(self._executor.registry, req.model_id) == req.model_id
except GenerationUnsupportedFieldError:
diff --git a/packages/sie_server/src/sie_server/observability/worker_telemetry.py b/packages/sie_server/src/sie_server/observability/worker_telemetry.py
index 4b75d9ff4..1442afc0d 100644
--- a/packages/sie_server/src/sie_server/observability/worker_telemetry.py
+++ b/packages/sie_server/src/sie_server/observability/worker_telemetry.py
@@ -201,7 +201,7 @@ _EVICTION_REASONS: Final = frozenset(
}
)
_P50_KINDS: Final = frozenset({"observed", "target"})
-_GRAMMAR_MODES: Final = frozenset({"none", "json_schema", "regex", "ebnf", _OTHER})
+_GRAMMAR_MODES: Final = frozenset({"none", "json_schema", "regex", "ebnf", "structural_tag", _OTHER})
_GRAMMAR_BACKENDS: Final = frozenset({"outlines", "xgrammar", "llguidance", _OTHER})
_GRAMMAR_PHASES: Final = frozenset({"request", "prewarm", _OTHER})
_GRAMMAR_OUTCOMES: Final = frozenset({"success", "error", "timeout", _OTHER})
diff --git a/packages/sie_server/src/sie_server/processors/grammar_compile.py b/packages/sie_server/src/sie_server/processors/grammar_compile.py
index 5946a7def..2d0b66778 100644
--- a/packages/sie_server/src/sie_server/processors/grammar_compile.py
+++ b/packages/sie_server/src/sie_server/processors/grammar_compile.py
@@ -202,7 +202,8 @@ def compile_outlines(tokenizer: Any, grammar: GrammarSpec) -> Any:
# (tokenizer, grammar) pair as "ready"; SGLang stays the source of
# truth for EBNF validity (a genuinely malformed grammar surfaces as an
# HTTP 500 → ``finish_reason: "error"`` chunk via the adapter).
- if grammar.kind == "ebnf":
+ # Structural tags (strict tools) compile only in SGLang's XGrammar backend.
+ if grammar.kind in ("ebnf", "structural_tag"):
return True
json_factory, regex_factory = _get_factories()
# The factories require an Outlines ``Tokenizer`` adapter, not a raw
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.py
index ba9b63bbd..05a5b0440 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
@@ -29,7 +29,7 @@ from sie_server.config.model import ModelConfig
from sie_server.core.runtime_options import bound_generation, resolve_generation_timeouts
from sie_server.core.tokenizer import load_tokenizer
from sie_server.processors.remote_chat import _check_tools
-from sie_server.processors.tool_call_grammar import normalize_tool_choice
+from sie_server.processors.tool_call_grammar import has_strict_tools, normalize_tool_choice
from sie_server.processors.tool_call_parser import (
ToolCallFormat,
parse_tool_call_stream,
@@ -77,7 +77,7 @@ async def prepare_rendered_chat(
body.get(field) is not None
for field in ("min_p", "repetition_context_size", "role_mapping", "user", "safety_identifier")
)
- or (mode != "none" and any(tool.get("function", {}).get("strict") is True for tool in body.get("tools") or []))
+ or (mode != "none" and has_strict_tools(body.get("tools")))
):
return None
source = config.hf_id or config.weights_path
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index d7d1e9bdf..a2d5183af 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -104,11 +104,17 @@ from sie_server.processors.schema_prompt import (
starts_with_system_message,
with_response_format,
)
-from sie_server.processors.strict_grammar import enforce_strict_grammar
+from sie_server.processors.strict_grammar import enforce_strict_grammar, enforce_strict_tool_arguments
from sie_server.processors.tool_call_grammar import (
+ StrictToolError,
ToolChoiceError,
+ build_strict_tool_grammar,
build_tool_choice_grammar,
+ check_strict_tools,
+ has_strict_tools,
normalize_tool_choice,
+ request_constrains_decoding,
+ strict_tool_schemas,
)
from sie_server.processors.tool_call_parser import (
ToolCallFormat,
@@ -1416,6 +1422,28 @@ class StreamingProcessor:
return "auto"
return tool_call_format_for_parser(loadtime.get("tool_call_parser"))
+ @staticmethod
+ def _strict_tool_grammar(
+ adapter: GenerationAdapter,
+ params: _GenerateRequestParams,
+ tools: tuple[dict[str, Any], ...],
+ tool_call_format: ToolCallFormat,
+ ) -> GrammarSpec | None:
+ """Build the grammar for a request with ``strict`` tools.
+
+ Strict arguments are guaranteed by the end-of-turn validation, which
+ runs on every backend and tool-call format. The structural tag only
+ steers generation and needs XGrammar and the whole decode, so without
+ XGrammar, or beside a ``response_format`` grammar, the request keeps
+ the grammar a non-strict request gets.
+ """
+ if params.grammar is None and getattr(adapter, "_grammar_backend", None) == "xgrammar":
+ return build_strict_tool_grammar(
+ tools, params.tool_choice, tool_call_format, parallel_tool_calls=params.parallel_tool_calls
+ )
+ check_strict_tools(tools)
+ return build_tool_choice_grammar(tools, params.tool_choice, tool_call_format)
+
@staticmethod
def _grammar_backend_for_model_config(config: Any) -> str | None:
"""Resolve configured SGLang grammar backend for prewarm.
@@ -1832,7 +1860,10 @@ class StreamingProcessor:
)
return
- if (self._extract_generate_params(wi) or {}).get("grammar") is not None:
+ raw_params = self._extract_generate_params(wi) or {}
+ if request_constrains_decoding(
+ raw_params.get("grammar"), raw_params.get("tools"), raw_params.get("tool_choice")
+ ):
try:
model_id = resolve_grammar_serving_model(self._registry, model_id)
except GenerationError as exc:
@@ -2003,7 +2034,8 @@ class StreamingProcessor:
config,
params.reasoning_effort,
model=model_id,
- grammar=params.grammar is not None and isinstance(params.input, _MessagesInput),
+ grammar=request_constrains_decoding(params.grammar, params.tools, params.tool_choice)
+ and isinstance(params.input, _MessagesInput),
)
except GenerationError as exc:
await self._terminal_error_then_settle(
@@ -2041,7 +2073,7 @@ class StreamingProcessor:
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 has_strict_tools(effective_tools)
or (params.n is not None and params.n > 1)
or (
isinstance(adapter, OpenAIUpstreamAdapter)
@@ -2318,15 +2350,20 @@ class StreamingProcessor:
forcing_grammar: GrammarSpec | None = None
if effective_tools and not remote_chat:
try:
- forcing_grammar = build_tool_choice_grammar(effective_tools, params.tool_choice, tool_call_format)
- except ToolChoiceError as exc:
+ if has_strict_tools(effective_tools):
+ forcing_grammar = self._strict_tool_grammar(adapter, params, effective_tools, tool_call_format)
+ else:
+ forcing_grammar = build_tool_choice_grammar(effective_tools, params.tool_choice, tool_call_format)
+ except (StrictToolError, ToolChoiceError) as exc:
+ param = exc.param if isinstance(exc, StrictToolError) else None
await self._terminal_error_then_settle(
reply_subject,
request_id=request_id,
attempt_id=attempt_id,
seq=0,
- code="invalid_request",
+ code="invalid_request" if param is None else "unsupported_field",
message=str(exc),
+ param=param,
msg=msg,
)
return
@@ -2610,6 +2647,9 @@ class StreamingProcessor:
parallel_tool_calls=parallel_tool_calls,
tools=tools,
)
+ # The grammar constrains strict tool arguments while they are
+ # generated; this guarantees each call against its full schema.
+ chunks_iter = enforce_strict_tool_arguments(chunks_iter, strict_tool_schemas(tools))
chunks_iter = enforce_strict_grammar(chunks_iter, grammar)
# Bounded chunk queue + a single publisher task drains it. If the
diff --git a/packages/sie_server/src/sie_server/processors/strict_grammar.py b/packages/sie_server/src/sie_server/processors/strict_grammar.py
index 37b1b7f5a..01eca722d 100644
--- a/packages/sie_server/src/sie_server/processors/strict_grammar.py
+++ b/packages/sie_server/src/sie_server/processors/strict_grammar.py
@@ -72,12 +72,17 @@ def requires_output_validation(grammar: GrammarSpec | None) -> bool:
return grammar is not None and grammar.strict is True and grammar.kind in VERIFIABLE_GRAMMAR_KINDS
-def output_violation(grammar: GrammarSpec, text: str) -> str | None:
- """Return a client-safe violation message, or ``None`` when ``text`` conforms."""
+def output_violation(grammar: GrammarSpec, text: str, *, check_formats: bool = False) -> str | None:
+ """Return a client-safe violation message, or ``None`` when ``text`` conforms.
+
+ ``check_formats`` also asserts ``format`` (``jsonschema`` treats it as an
+ annotation by default); strict tool arguments use it because their grammar
+ cannot always enforce a format.
+ """
token = _pattern_deadline.set(time.monotonic() + _PATTERN_BUDGET_S)
try:
if grammar.kind == "json_schema" and isinstance(grammar.value, dict):
- return _json_schema_violation(grammar.value, text)
+ return _json_schema_violation(grammar.value, text, check_formats=check_formats)
if grammar.kind == "regex" and isinstance(grammar.value, str):
return _regex_violation(grammar.value, text)
return _UNVERIFIABLE_MESSAGE
@@ -162,6 +167,119 @@ async def _validated_chunks(
)
+def enforce_strict_tool_arguments(
+ chunks: AsyncIterator[GenerationChunk],
+ schemas: Mapping[str, dict[str, Any]],
+) -> AsyncIterator[GenerationChunk]:
+ """Return ``chunks`` with every strict tool call's arguments validated at the terminal.
+
+ ``schemas`` maps each strict tool's name to its parameters schema. The
+ grammar backend constrains the arguments while they are generated; this
+ check guarantees the result against the full schema, including keywords
+ the backend does not enforce. A violation replaces the terminal with a
+ ``MODEL_OUTPUT_PARSE_ERROR`` terminal, as for a strict ``response_format``.
+ Apply it after tool-call parsing.
+ """
+ if not schemas:
+ return chunks
+ return _validated_tool_calls(chunks, schemas)
+
+
+async def _validated_tool_calls(
+ chunks: AsyncIterator[GenerationChunk],
+ schemas: Mapping[str, dict[str, Any]],
+) -> AsyncIterator[GenerationChunk]:
+ names: dict[tuple[int, int], str] = {}
+ # Arguments of strict calls only; other calls are never validated.
+ arguments: dict[tuple[int, int], list[str]] = {}
+ # From the first strict call on, chunks are held back until the terminal
+ # check passes, so a client never receives arguments that are then
+ # declared invalid. Holding everything after that point keeps the order.
+ held: list[GenerationChunk] = []
+ terminal_outcome_selected = False
+
+ async def violation(terminal: GenerationChunk) -> str | None:
+ calls = [(names[key], "".join(parts)) for key, parts in arguments.items()]
+ calls.extend(_candidate_tool_calls(terminal))
+ return await asyncio.to_thread(_first_tool_arguments_violation, schemas, calls)
+
+ try:
+ async for chunk in chunks:
+ delta = chunk.tool_call_delta
+ if delta is not None:
+ key = (chunk.choice_index, delta.index)
+ if delta.function_name:
+ names[key] = delta.function_name
+ if names.get(key) in schemas:
+ arguments.setdefault(key, []).append(delta.arguments_delta or "")
+ held.append(chunk)
+ continue
+ if not chunk.done:
+ if held:
+ held.append(chunk)
+ else:
+ yield chunk
+ continue
+ terminal_outcome_selected = True
+ if chunk.error_code is not None:
+ # The turn failed upstream; held arguments were never validated.
+ yield chunk
+ continue
+ message = await violation(chunk)
+ if message is not None:
+ yield replace(chunk, finish_reason="error", error_code=MODEL_OUTPUT_PARSE_ERROR, error_message=message)
+ continue
+ for pending in held:
+ yield pending
+ held.clear()
+ yield chunk
+ if not terminal_outcome_selected:
+ # Consumers settle an iterator that ends without a terminal as a
+ # natural stop, so the held calls are verified here.
+ implicit_stop = GenerationChunk(text_delta="", done=True)
+ message = await violation(implicit_stop)
+ if message is not None:
+ terminal_outcome_selected = True
+ yield replace(
+ implicit_stop, finish_reason="error", error_code=MODEL_OUTPUT_PARSE_ERROR, error_message=message
+ )
+ else:
+ for pending in held:
+ yield pending
+ finally:
+ await aclose_with_error_precedence(
+ chunks,
+ outcome_selected=terminal_outcome_selected,
+ context="strict tool arguments upstream iterator",
+ )
+
+
+def _candidate_tool_calls(chunk: GenerationChunk) -> list[tuple[str, str]]:
+ """Return ``(name, arguments)`` for the tool calls on non-streamed candidates."""
+ calls: list[tuple[str, str]] = []
+ for candidate in chunk.candidates or ():
+ for call in candidate.get("tool_calls") or ():
+ function = call.get("function") if isinstance(call, dict) else None
+ if isinstance(function, dict):
+ calls.append((str(function.get("name") or ""), str(function.get("arguments") or "")))
+ return calls
+
+
+def _first_tool_arguments_violation(
+ schemas: Mapping[str, dict[str, Any]], calls: Sequence[tuple[str, str]]
+) -> str | None:
+ for name, text in calls:
+ schema = schemas.get(name)
+ if schema is None:
+ continue
+ violation = output_violation(
+ GrammarSpec(kind="json_schema", value=schema, strict=True), text or "{}", check_formats=True
+ )
+ if violation is not None:
+ return f"arguments of strict tool {name!r}: {violation.removeprefix('generated output ')}"
+ return None
+
+
def _terminal_outputs(
chunk: GenerationChunk,
texts: Mapping[int, Sequence[str]],
@@ -199,24 +317,56 @@ def unverifiable_schema_keyword(schema: Any) -> str | None:
standard-library ``re`` engine inside ``jsonschema``, outside the bounded
``regex`` engine used for every other pattern keyword.
"""
- return _find_schema_keyword(schema, "schema")
+ return find_schema_keyword(schema, _UNVERIFIABLE_SCHEMA_KEYWORDS)
+
+
+def find_schema_keyword(schema: Any, keywords: Iterable[str]) -> str | None:
+ """Return the first of ``keywords`` used as a keyword anywhere in ``schema``.
+
+ Property names, definition names and ``enum`` / ``const`` data are not
+ keywords, so a property called ``not`` does not match.
+ """
+ wanted = tuple(keywords)
+ for subschema in iter_subschemas(schema):
+ for keyword in wanted:
+ if keyword in subschema:
+ return keyword
+ return None
-def _find_schema_keyword(value: Any, context: str) -> str | None:
+def iter_subschemas(schema: Any) -> Iterator[dict[str, Any]]:
+ """Yield ``schema`` and every schema object nested in it, skipping instance data."""
+ yield from _iter_subschemas(schema, "schema")
+
+
+def _iter_subschemas(value: Any, context: str) -> Iterator[dict[str, Any]]:
if isinstance(value, dict):
if context == "schema":
- for keyword in _UNVERIFIABLE_SCHEMA_KEYWORDS:
- if keyword in value:
- return keyword
+ yield value
for key, child in value.items():
- if found := _find_schema_keyword(child, _schema_child_context(context, key)):
- return found
+ yield from _iter_subschemas(child, _schema_child_context(context, key))
elif isinstance(value, list):
child_context = "schema" if context == "schema" else "other"
for item in value:
- if found := _find_schema_keyword(item, child_context):
- return found
- return None
+ yield from _iter_subschemas(item, child_context)
+
+
+def without_schema_keywords(schema: Any, keywords: frozenset[str]) -> Any:
+ """Return ``schema`` without ``keywords`` in any schema object; property names and instance data stay."""
+ return _without_keywords(schema, keywords, "schema")
+
+
+def _without_keywords(value: Any, keywords: frozenset[str], context: str) -> Any:
+ if isinstance(value, dict):
+ return {
+ key: _without_keywords(child, keywords, _schema_child_context(context, key))
+ for key, child in value.items()
+ if not (context == "schema" and key in keywords)
+ }
+ if isinstance(value, list):
+ child_context = "schema" if context == "schema" else "other"
+ return [_without_keywords(item, keywords, child_context) for item in value]
+ return value
def _schema_child_context(parent: str, key: str) -> str:
@@ -232,7 +382,7 @@ def _schema_child_context(parent: str, key: str) -> str:
return "schema"
-def _json_schema_violation(schema: dict[str, Any], text: str) -> str | None:
+def _json_schema_violation(schema: dict[str, Any], text: str, *, check_formats: bool = False) -> str | None:
try:
instance = json.loads(text, parse_constant=_reject_json_constant)
except (ValueError, RecursionError):
@@ -240,7 +390,9 @@ def _json_schema_violation(schema: dict[str, Any], text: str) -> str | None:
if unverifiable_schema_keyword(schema) is not None:
return _UNVERIFIABLE_MESSAGE
validator_class = _bounded_validator_class(validators.validator_for(schema, default=Draft202012Validator))
- error = next(validator_class(schema, registry=_LOCAL_REFERENCES).iter_errors(instance), None)
+ format_checker = validator_class.FORMAT_CHECKER if check_formats else None
+ validator = validator_class(schema, registry=_LOCAL_REFERENCES, format_checker=format_checker)
+ error = next(validator.iter_errors(instance), None)
if error is None:
return None
path = error.json_path
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py b/packages/sie_server/src/sie_server/processors/tool_call_grammar.py
index 967b99b71..1d6a11380 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_grammar.py
@@ -29,9 +29,27 @@ calls parse and stop cleanly, including when the model does not want the call
from __future__ import annotations
import re
+from collections.abc import Callable, Hashable, Iterator
from typing import Any
-from sie_server.processors.tool_call_parser import ToolCallFormat
+import orjson
+from jsonschema import Draft202012Validator
+from jsonschema.exceptions import UndefinedTypeCheck
+
+from sie_server.adapters._generation_base import REASONING_CONTROL_TOKENS
+from sie_server.processors.strict_grammar import (
+ iter_subschemas,
+ unverifiable_schema_keyword,
+ without_schema_keywords,
+)
+from sie_server.processors.tool_call_parser import (
+ MAX_XML_PARAMS,
+ XML_PARAM_CLOSE,
+ ToolCallFormat,
+ resolve_schema_ref,
+ schema_allows_null,
+ schema_conversion_type,
+)
from sie_server.types.grammar import GrammarSpec
@@ -44,6 +62,20 @@ class ToolChoiceError(ValueError):
"""
+class StrictToolError(ValueError):
+ """Raised when a ``strict`` function tool cannot be served or constrained.
+
+ From :func:`check_strict_tools` the tool's arguments could not be
+ validated, and the worker surfaces a terminal ``unsupported_field`` chunk
+ naming ``param``. From a tag builder the grammar cannot express the
+ schema, and the caller constrains less and leaves the call to validation.
+ """
+
+ def __init__(self, param: str, message: str) -> None:
+ super().__init__(message)
+ self.param = param
+
+
def normalize_tool_choice(
tool_choice: dict[str, Any] | str | None,
) -> tuple[str, str | None]:
@@ -264,3 +296,612 @@ def _gemma4_force_regex(names: list[str]) -> str:
body = r'(?:[^\s<"]|' + string + r")*"
block = r"<\|tool_call>call:" + _name_alternation(names) + r"\{" + body + r"\}<tool_call\|>"
return r"(?:" + block + r")+"
+
+
+# ---------------------------------------------------------------------------
+# Strict function tools
+# ---------------------------------------------------------------------------
+#
+# A tool with ``"strict": true`` promises that every generated call's
+# arguments match its ``parameters`` schema. The regex forcing above pins only
+# the function name, so strict tools compile to an XGrammar structural tag
+# instead: the call layout is fixed text and each argument value is
+# constrained by its own schema. The tag also covers ``tool_choice: "auto"``,
+# where a ``triggered_tags`` format lets the model write free text until it
+# opens a call. Reasoning stays unconstrained: SGLang applies the grammar only
+# after the reasoning block when the request expects one.
+
+_JSON_KINDS = frozenset({"integer", "number", "boolean", "object", "array", "null"})
+_SCALAR_KINDS = frozenset({"integer", "number", "boolean"})
+# Object-level keywords the Qwen XML layout cannot express on the parameters
+# object, which it writes as one tag per declared property.
+_UNSUPPORTED_PARAMETERS_KEYWORDS = (
+ "anyOf",
+ "allOf",
+ "patternProperties",
+ "propertyNames",
+ "minProperties",
+ "maxProperties",
+ "const",
+ "enum",
+ # A root reference would hide the properties the layout reads.
+ "$ref",
+)
+_DEFINITION_KEYWORDS = ("$defs", "definitions")
+# Keys XGrammar 0.1.32 drops from every object when it caches a subschema,
+# property names included (measured).
+_XGRAMMAR_CACHE_SKIPPED_KEYS = frozenset(
+ {"description", "title", "default", "examples", "$comment", "deprecated", "readOnly", "writeOnly", "$schema"}
+)
+_DEFINITION_REF_PREFIXES = ("#/$defs/", "#/definitions/")
+# Parameter names the XML parser reads back intact (see ``_XML_PARAM_OPEN_RE``).
+_XML_PARAMETER_NAME = re.compile(r"[^<>\s](?:[^<>\n]*[^<>\s])?")
+# Characters XGrammar's regex dialect treats as syntax. ``re.escape`` is not
+# used because it also escapes spaces and writes a backslash before a literal
+# newline, escapes outside that dialect's documented set.
+_REGEX_SPECIAL = frozenset("\\^$.|?*+()[]{}/-")
+_REGEX_ESCAPES = {"\n": r"\n", "\t": r"\t", "\r": r"\r"}
+# Bound on nested unions followed when checking a scalar parameter.
+_MAX_UNION_DEPTH = 8
+# Every call tag begins with the trigger, as ``triggered_tags`` requires.
+_TRIGGER = "<tool_call>"
+_QWEN_CALL_START = _TRIGGER + "\n<function="
+_QWEN_CALL_END = "</function>\n</tool_call>"
+_HERMES_CALL_START = _TRIGGER + '\n{"name": '
+_HERMES_CALL_END = "}\n</tool_call>"
+# Text a raw XML string value cannot contain: the closing tags the parsers end on.
+_RAW_VALUE_EXCLUDES = (XML_PARAM_CLOSE, "</tool_call>")
+_REASONING_DELIMITERS = frozenset(token for pair in REASONING_CONTROL_TOKENS.values() for token in pair)
+
+
+def is_strict_tool(tool: Any) -> bool:
+ """Return whether one OpenAI tool definition sets ``function.strict: true``."""
+ function = tool.get("function") if isinstance(tool, dict) else None
+ return isinstance(function, dict) and function.get("strict") is True
+
+
+def has_strict_tools(tools: tuple[dict[str, Any], ...] | list[dict[str, Any]] | None) -> bool:
+ """Return whether any tool in ``tools`` is strict."""
+ return any(is_strict_tool(tool) for tool in tools or ())
+
+
+def strict_tool_schemas(tools: tuple[dict[str, Any], ...] | list[dict[str, Any]] | None) -> dict[str, dict[str, Any]]:
+ """Map each strict tool's name to the parameters schema its arguments must satisfy."""
+ schemas: dict[str, dict[str, Any]] = {}
+ for tool in tools or ():
+ if not is_strict_tool(tool):
+ continue
+ function = tool["function"]
+ name = function.get("name")
+ parameters = function.get("parameters")
+ if isinstance(name, str) and name:
+ schemas[name] = parameters if isinstance(parameters, dict) else {"type": "object", "properties": {}}
+ return schemas
+
+
+def tools_require_grammar(tools: Any, tool_choice: Any) -> bool:
+ """Return whether ``tools`` / ``tool_choice`` make the worker constrain decoding.
+
+ A forced ``tool_choice`` (``required`` or a named function) and any
+ ``strict`` tool both compile a grammar, so such a request must run on the
+ model's grammar-safe profile: speculative decoding bypasses the grammar
+ backend. Mirrors the gateway's routing rule for ``/v1/chat/completions``.
+ """
+ if not isinstance(tools, list | tuple) or not tools:
+ return False
+ mode, _ = normalize_tool_choice(tool_choice)
+ return mode in ("required", "named") or (mode != "none" and has_strict_tools(tools))
+
+
+def request_constrains_decoding(grammar: Any, tools: Any, tool_choice: Any) -> bool:
+ """Return whether a generation request runs under a grammar.
+
+ True for a ``response_format`` / native grammar and for the tool grammars
+ of :func:`tools_require_grammar`. Every worker ingress uses this to pick
+ the grammar-safe profile and the profile's grammar reasoning effort.
+ """
+ return grammar is not None or tools_require_grammar(tools, tool_choice)
+
+
+def check_strict_tools(tools: tuple[dict[str, Any], ...] | list[dict[str, Any]]) -> None:
+ """Refuse strict tools whose arguments could not be validated.
+
+ Every strict call is validated against its schema when the turn ends
+ (:func:`~sie_server.processors.strict_grammar.enforce_strict_tool_arguments`),
+ on every tool-call format and grammar backend. That validation is the
+ guarantee, so a request is refused only when it cannot run: two tools
+ share the name a call is validated by, the arguments schema does not
+ describe an object, or it uses a keyword the verifier cannot evaluate.
+
+ Raises:
+ StrictToolError: A strict tool cannot be validated.
+ """
+ names = extract_tool_names(tools)
+ duplicates = sorted({tool_name for tool_name in names if names.count(tool_name) > 1})
+ if duplicates:
+ raise StrictToolError("tools", f"function names must be unique for strict tools; repeated: {duplicates!r}")
+ for index, tool in enumerate(tools):
+ if not is_strict_tool(tool):
+ continue
+ path = f"tools[{index}].function.parameters"
+ parameters = _function_parameters(tool["function"], path)
+ if parameters.get("type") not in (None, "object"):
+ raise StrictToolError(path, f"'{path}' must describe an object for a strict tool")
+ keyword = unverifiable_schema_keyword(parameters)
+ if keyword is not None:
+ raise StrictToolError(path, f"'{keyword}' in '{path}' is not supported for strict tools")
+
+
+def build_strict_tool_grammar(
+ tools: tuple[dict[str, Any], ...] | list[dict[str, Any]],
+ tool_choice: dict[str, Any] | str | None,
+ tool_call_format: ToolCallFormat,
+ *,
+ parallel_tool_calls: bool = True,
+) -> GrammarSpec | None:
+ """Build the grammar for a request with strict tools.
+
+ Every strict tool's arguments are constrained by its schema as far as the
+ model's tool-call format can express it; a non-strict tool in the same
+ request keeps a free argument body. ``auto`` admits free text or calls,
+ ``required`` and the named form admit only calls, and
+ ``parallel_tool_calls=False`` stops after the first call. Returns ``None``
+ for ``tool_choice: "none"``.
+
+ The grammar steers generation; the end-of-turn validation guarantees the
+ arguments. So what the grammar cannot express is constrained less, never
+ refused: a parameter becomes free text, a tool gets a free argument body,
+ and a format without a structural tag keeps the grammar of a non-strict
+ request (:func:`build_tool_choice_grammar`).
+
+ Raises:
+ StrictToolError: A strict tool cannot be validated
+ (:func:`check_strict_tools`).
+ ToolChoiceError: The ``tool_choice`` cannot be satisfied.
+ """
+ mode, name = normalize_tool_choice(tool_choice)
+ if mode == "none":
+ return None
+ check_strict_tools(tools)
+ build_tag = _STRICT_TAG_BUILDERS.get(tool_call_format)
+ if build_tag is None:
+ return build_tool_choice_grammar(tuple(tools), tool_choice, tool_call_format)
+ names = extract_tool_names(tools)
+ if not names:
+ raise ToolChoiceError("strict function tools require a non-empty 'tools' array with named functions")
+ if mode == "named" and name not in names:
+ raise ToolChoiceError(f"tool_choice names function {name!r}, which is not in tools {names!r}")
+
+ tags: list[dict[str, Any]] = []
+ for index, tool in enumerate(tools):
+ function = tool.get("function") if isinstance(tool, dict) else None
+ if not isinstance(function, dict) or not isinstance(function.get("name"), str) or not function["name"]:
+ continue
+ if mode == "named" and function["name"] != name:
+ continue
+ path = f"tools[{index}].function.parameters"
+ try:
+ tag = build_tag(function, strict=is_strict_tool(tool), path=path)
+ except StrictToolError:
+ tag = build_tag(function, strict=False, path=path)
+ tags.append(tag)
+ try:
+ _check_schema_cache_collisions(tags)
+ except StrictToolError:
+ return build_tool_choice_grammar(tuple(tools), tool_choice, tool_call_format)
+
+ stop_after_first = not parallel_tool_calls
+ if mode == "auto":
+ structure: dict[str, Any] = {
+ "type": "triggered_tags",
+ "triggers": [_TRIGGER],
+ "tags": tags,
+ "stop_after_first": stop_after_first,
+ }
+ else:
+ # Calls only. Up to two leading newlines match the chat templates,
+ # which open a call on a fresh line; the bound keeps greedy decoding
+ # from padding the reply with whitespace.
+ structure = {
+ "type": "sequence",
+ "elements": [
+ {"type": "regex", "pattern": r"\n{0,2}"},
+ {
+ "type": "tags_with_separator",
+ "tags": tags,
+ "separator": "\n",
+ "at_least_one": True,
+ "stop_after_first": stop_after_first,
+ },
+ ],
+ }
+ return GrammarSpec(
+ kind="structural_tag",
+ value={"type": "structural_tag", "format": structure},
+ label=f"tool_strict:{mode}",
+ )
+
+
+def _check_schema_cache_collisions(tags: list[dict[str, Any]]) -> None:
+ """Reject schemas XGrammar would conflate in its schema cache.
+
+ XGrammar 0.1.32 keys cached subschemas with ``_XGRAMMAR_CACHE_SKIPPED_KEYS``
+ removed from every object, property names included. Two subschemas that
+ differ only under a property such as ``description`` therefore share one
+ grammar, and the second is constrained by the first one's types.
+ """
+ first_with_key: dict[bytes, dict[str, Any]] = {}
+ for schema in _json_schema_contents(tags):
+ for subschema in iter_subschemas(schema):
+ cache_key = orjson.dumps(
+ _without_keys(subschema, _XGRAMMAR_CACHE_SKIPPED_KEYS), option=orjson.OPT_SORT_KEYS
+ )
+ first = first_with_key.setdefault(cache_key, subschema)
+ if first is not subschema and _schema_meaning(first) != _schema_meaning(subschema):
+ raise StrictToolError(
+ "tools",
+ "strict tool schemas contain subschemas that differ only under a property named "
+ f"one of {sorted(_XGRAMMAR_CACHE_SKIPPED_KEYS)}, which this model's grammar backend "
+ "cannot tell apart",
+ )
+
+
+def _schema_meaning(schema: dict[str, Any]) -> bytes:
+ """``schema`` without annotation keywords, property names kept."""
+ return orjson.dumps(without_schema_keywords(schema, _XGRAMMAR_CACHE_SKIPPED_KEYS), option=orjson.OPT_SORT_KEYS)
+
+
+def _json_schema_contents(value: Any) -> Iterator[dict[str, Any]]:
+ if isinstance(value, dict):
+ if value.get("type") == "json_schema" and isinstance(value.get("json_schema"), dict):
+ yield value["json_schema"]
+ return
+ for child in value.values():
+ yield from _json_schema_contents(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _json_schema_contents(child)
+
+
+def _without_keys(value: Any, keys: frozenset[str]) -> Any:
+ if isinstance(value, dict):
+ return {key: _without_keys(child, keys) for key, child in value.items() if key not in keys}
+ if isinstance(value, list):
+ return [_without_keys(child, keys) for child in value]
+ return value
+
+
+def _function_parameters(function: dict[str, Any], path: str) -> dict[str, Any]:
+ parameters = function.get("parameters")
+ if parameters is None:
+ return {"type": "object", "properties": {}}
+ if not isinstance(parameters, dict):
+ raise StrictToolError(path, f"'{path}' must be a JSON Schema object")
+ return parameters
+
+
+def _hermes_json_tool_tag(function: dict[str, Any], *, strict: bool, path: str) -> dict[str, Any]:
+ """Return the tag for one Hermes JSON call.
+
+ The call is ``<tool_call>``, a newline, ``{"name": "NAME", "arguments": ARGS}``,
+ a newline, and ``</tool_call>``.
+ """
+ begin = _HERMES_CALL_START + orjson.dumps(function["name"]).decode() + ', "arguments": '
+ if strict:
+ schema = _function_parameters(function, path)
+ _check_constrainable(schema, path)
+ # Strict arguments never carry undeclared keys, as with Qwen XML; an
+ # open object would let the backend generate them.
+ schema = {**schema, "additionalProperties": False}
+ else:
+ # XGrammar treats an object without ``additionalProperties`` as closed.
+ schema = {"type": "object", "additionalProperties": True}
+ return {
+ "type": "tag",
+ "begin": begin,
+ "content": {"type": "json_schema", "json_schema": schema},
+ "end": _HERMES_CALL_END,
+ }
+
+
+def _qwen_xml_tool_tag(function: dict[str, Any], *, strict: bool, path: str) -> dict[str, Any]:
+ """Return the tag for one Qwen3(-Coder) XML call.
+
+ The layout is exactly what the chat template renders::
+
+ <tool_call>
+ <function=NAME>
+ <parameter=KEY>
+ VALUE
+ </parameter>
+ </function>
+ </tool_call>
+
+ A strict tool's parameters appear in schema order; required ones are
+ mandatory and undeclared ones cannot appear.
+ """
+ begin = _QWEN_CALL_START + function["name"] + ">\n"
+ if not strict:
+ # A free body must not close the call and open another, which would
+ # let a strict call appear without its grammar.
+ free = {"type": "any_text", "excludes": [_TRIGGER, "</tool_call>"]}
+ return {"type": "tag", "begin": begin, "content": free, "end": _QWEN_CALL_END}
+ parameters = _function_parameters(function, path)
+ _check_constrainable(parameters, path)
+ properties, required = _object_properties(parameters, path)
+ if len(properties) > MAX_XML_PARAMS:
+ # The parser reads at most this many parameters from one call.
+ raise StrictToolError(path, f"'{path}' declares more than {MAX_XML_PARAMS} properties")
+ elements: list[dict[str, Any]] = []
+ for key, schema in properties.items():
+ if not _XML_PARAMETER_NAME.fullmatch(key):
+ raise StrictToolError(path, f"parameter name {key!r} cannot be written in this model's tool-call format")
+ try:
+ content = _qwen_xml_value_format(schema, parameters, f"{path}.properties.{key}")
+ except StrictToolError:
+ # The other parameters stay constrained; this one is validated.
+ content = _raw_text_format()
+ parameter: dict[str, Any] = {
+ "type": "tag",
+ "begin": f"<parameter={key}>\n",
+ "content": content,
+ "end": "\n</parameter>\n",
+ }
+ if key not in required:
+ parameter = {"type": "or", "elements": [parameter, {"type": "const_string", "value": ""}]}
+ elements.append(parameter)
+ content: dict[str, Any] = (
+ {"type": "sequence", "elements": elements} if elements else {"type": "const_string", "value": ""}
+ )
+ return {"type": "tag", "begin": begin, "content": content, "end": _QWEN_CALL_END}
+
+
+def _check_constrainable(parameters: dict[str, Any], path: str) -> None:
+ """Raise for a schema the grammar would constrain to something else.
+
+ A keyword the grammar backend drops (``multipleOf``, ``pattern`` beside
+ ``format``, an assertion beside ``$ref``) only loosens the grammar and is
+ left to the end-of-turn validation. A reference the per-parameter grammar
+ would resolve elsewhere, or listed values no argument can match, would
+ make it generate arguments that cannot validate, so the tool keeps a free
+ argument body instead.
+ """
+ for subschema in iter_subschemas(parameters):
+ _check_reference(subschema.get("$ref"), path)
+ _check_listed_values(subschema, path)
+
+
+def _check_reference(ref: Any, path: str) -> None:
+ """Accept only references into the definition maps.
+
+ A parameter's schema is compiled on its own, with the tool's definitions
+ attached, so a pointer to any other location would resolve elsewhere.
+ """
+ if ref is not None and not (isinstance(ref, str) and ref.startswith(_DEFINITION_REF_PREFIXES)):
+ raise StrictToolError(path, f"'$ref' {ref!r} in '{path}' must point into '$defs' for strict tools")
+ # XGrammar looks up escaped pointer segments (``~0`` / ``~1``) literally.
+ if isinstance(ref, str) and "~" in ref:
+ raise StrictToolError(path, f"'$ref' {ref!r} in '{path}' uses an escaped pointer, unsupported for strict tools")
+
+
+def _json_key(value: Any) -> Hashable:
+ """A key under which two values are equal exactly when JSON Schema finds them equal.
+
+ Numbers compare by value (``1`` equals ``1.0``) and never equal a boolean
+ (``true`` is not ``1``), at every nesting level.
+ """
+ if isinstance(value, bool):
+ return ("boolean", value)
+ if isinstance(value, int | float):
+ return ("number", value)
+ if isinstance(value, list):
+ return ("array", tuple(_json_key(item) for item in value))
+ if isinstance(value, dict):
+ return ("object", frozenset((key, _json_key(item)) for key, item in value.items()))
+ return (type(value).__name__, value)
+
+
+def _check_listed_values(subschema: dict[str, Any], path: str) -> None:
+ """Reject ``enum`` / ``const`` values no argument can match.
+
+ A ``const`` outside its ``enum`` or a listed value of the wrong ``type``
+ leaves no conforming argument, so every call would fail validation.
+ """
+ if "enum" not in subschema and "const" not in subschema:
+ return
+ enum = subschema.get("enum")
+ values = enum if isinstance(enum, list) else []
+ if "const" in subschema:
+ if "enum" in subschema and _json_key(subschema["const"]) not in {_json_key(value) for value in values}:
+ raise StrictToolError(path, f"'const' in '{path}' is not one of its 'enum' values")
+ values = [subschema["const"]]
+ # A profile that hides reasoning strips these delimiters from the output
+ # before the tool parser reads it, which would alter the declared value.
+ for value in values:
+ if isinstance(value, str) and any(token in value for token in _REASONING_DELIMITERS):
+ raise StrictToolError(path, f"listed value {value!r} in '{path}' contains a reasoning delimiter")
+ declared = subschema.get("type")
+ if declared is None:
+ return
+ kinds = {declared} if isinstance(declared, str) else set(declared) if isinstance(declared, list) else set()
+ if subschema.get("nullable") is True:
+ kinds.add("null")
+ for value in values:
+ if not any(_json_value_has_type(value, kind) for kind in kinds):
+ raise StrictToolError(path, f"value {value!r} in '{path}' does not match its 'type'")
+
+
+def _json_value_has_type(value: Any, kind: Any) -> bool:
+ """JSON Schema's type test, the one the argument validator applies (``1.0`` is an integer)."""
+ try:
+ return Draft202012Validator.TYPE_CHECKER.is_type(value, kind)
+ except UndefinedTypeCheck:
+ return False
+
+
+def _object_properties(parameters: dict[str, Any], path: str) -> tuple[dict[str, Any], set[str]]:
+ """Return a strict tool's declared properties and required keys."""
+ for keyword in _UNSUPPORTED_PARAMETERS_KEYWORDS:
+ if keyword in parameters:
+ raise StrictToolError(path, f"'{keyword}' in '{path}' is not supported for strict tools on this model")
+ properties = parameters.get("properties", {})
+ if not isinstance(properties, dict):
+ raise StrictToolError(path, f"'{path}.properties' must be an object")
+ required = parameters.get("required", [])
+ if not isinstance(required, list) or not all(isinstance(key, str) for key in required):
+ raise StrictToolError(path, f"'{path}.required' must be an array of strings")
+ missing = [key for key in required if key not in properties]
+ if missing:
+ raise StrictToolError(path, f"'{path}' requires undeclared properties {missing!r}")
+ return properties, {str(key) for key in required}
+
+
+def _qwen_xml_value_format(schema: Any, root: dict[str, Any], path: str) -> dict[str, Any]:
+ """Constrain one XML parameter value so the parser converts it to a conforming value.
+
+ The tool-call parser converts each raw value by the type it infers from the
+ schema (:func:`schema_conversion_type`): string-typed values stay raw text,
+ a bare ``null`` becomes JSON null where the schema allows it, and every
+ other type is read as JSON. The value grammar follows the same split, so an
+ accepted value always converts to a conforming argument.
+ """
+ resolved = resolve_schema_ref(schema, root)
+ if resolved is True or resolved == {}:
+ return _raw_text_format()
+ if not isinstance(resolved, dict):
+ raise StrictToolError(path, f"'{path}' must be a JSON Schema object with resolvable references")
+ kind = schema_conversion_type(resolved, root)
+ if kind is None or kind == "string":
+ return _raw_string_format(resolved, root, path)
+ if kind not in _JSON_KINDS:
+ raise StrictToolError(path, f"type {kind!r} at '{path}' is not supported for strict tools")
+ if kind in _SCALAR_KINDS and not _is_scalar_or_null(resolved, root, kind):
+ # The parser reads a scalar with ``int()`` / ``float()`` / true|false,
+ # so a union with a non-null type would not convert back to JSON.
+ raise StrictToolError(path, f"'{path}' mixes {kind} with other types, which strict tools cannot enforce here")
+ value_schema = dict(resolved)
+ if any("$ref" in subschema for subschema in iter_subschemas(value_schema)):
+ # References point into the tool's definitions, but XGrammar resolves
+ # them against the value schema's own root, so that root carries the
+ # tool's definitions in place of any the value declares itself.
+ for keyword in _DEFINITION_KEYWORDS:
+ if keyword in root:
+ value_schema[keyword] = root[keyword]
+ else:
+ value_schema.pop(keyword, None)
+ return {"type": "json_schema", "json_schema": value_schema}
+
+
+def _is_scalar_or_null(
+ schema: Any, root: dict[str, Any], kind: str, depth: int = 0, seen: dict[tuple[int, int], bool] | None = None
+) -> bool:
+ """Return whether every value ``schema`` admits is a ``kind`` scalar or null.
+
+ ``seen`` memoizes each resolved schema: unions over shared definitions would
+ otherwise be walked once per path, exponentially in their depth.
+ """
+ seen = {} if seen is None else seen
+ schema = resolve_schema_ref(schema, root)
+ if not isinstance(schema, dict) or depth > _MAX_UNION_DEPTH or "allOf" in schema or "not" in schema:
+ return False
+ key = (id(schema), depth)
+ if key in seen:
+ return seen[key]
+ if "anyOf" in schema:
+ variants = schema["anyOf"]
+ seen[key] = isinstance(variants, list) and all(
+ _is_scalar_or_null(variant, root, kind, depth + 1, seen) for variant in variants
+ )
+ return seen[key]
+ declared = schema.get("type")
+ if declared is None:
+ # A typeless branch admits exactly its listed values, and the parser
+ # converts them by ``kind``.
+ enum = schema.get("enum")
+ values = [schema["const"]] if "const" in schema else enum if isinstance(enum, list) else None
+ return values is not None and all(value is None or _json_value_has_type(value, kind) for value in values)
+ if isinstance(declared, str):
+ return declared in (kind, "null")
+ return isinstance(declared, list) and set(declared) <= {kind, "null"}
+
+
+def _raw_string_format(schema: dict[str, Any], root: dict[str, Any], path: str) -> dict[str, Any]:
+ """Raw string value: free text, or one of the declared string values (plus ``null`` when allowed)."""
+ # Optional strings (``anyOf: [{type: string}, {type: null}]``) and unions of
+ # string enums, possibly behind ``$ref``, stay raw text. Assertions the raw
+ # grammar cannot express (``pattern``, ``format``, lengths, ...) are left to
+ # the end-of-turn argument validation.
+ variants: list[Any] = [schema]
+ if isinstance(schema.get("anyOf"), list):
+ variants = [resolve_schema_ref(variant, root) for variant in schema["anyOf"]]
+ choices: list[str] = []
+ for variant in variants:
+ if not isinstance(variant, dict):
+ raise StrictToolError(path, f"'{path}' must be a JSON Schema object with resolvable references")
+ declared = variant.get("type")
+ if declared in ("null", ["null"]):
+ values = _allowed_values(variant, path)
+ if values is None or None in values:
+ choices.append("null")
+ continue
+ if declared not in (None, "string") and not (
+ isinstance(declared, list) and set(declared) <= {"string", "null"}
+ ):
+ raise StrictToolError(path, f"'{path}' mixes string with other types, which strict tools cannot enforce")
+ values = _allowed_values(variant, path)
+ if values is None:
+ # Free text; the parser maps a bare ``null`` to JSON null when the
+ # schema allows it, and keeps it as the string otherwise.
+ return _raw_text_format()
+ # ``enum`` / ``const`` restrict the values independently of ``type``,
+ # so ``null`` is allowed only when it is listed and the type admits it.
+ null_type = (
+ declared is None or variant.get("nullable") is True or (isinstance(declared, list) and "null" in declared)
+ )
+ for value in values:
+ if isinstance(value, str):
+ if any(tag in value for tag in _RAW_VALUE_EXCLUDES):
+ raise StrictToolError(path, f"'{path}' enum values cannot contain a closing tag")
+ if value.strip().lower() == "null" and schema_allows_null(schema, root):
+ # The parser reads a bare ``null`` as JSON null here.
+ raise StrictToolError(path, f"'{path}' allows null, so its enum cannot list the string {value!r}")
+ choices.append(value)
+ elif value is None and null_type:
+ choices.append("null")
+ if not choices:
+ raise StrictToolError(path, f"'{path}' admits no string value")
+ pattern = "(?:" + "|".join(_regex_literal(choice) for choice in dict.fromkeys(choices)) + ")"
+ return {"type": "regex", "pattern": pattern}
+
+
+def _allowed_values(variant: dict[str, Any], path: str) -> list[Any] | None:
+ """Return the values ``enum`` and ``const`` together allow, or ``None`` when neither is set."""
+ enum = variant.get("enum")
+ if enum is not None and (
+ not isinstance(enum, list) or not all(isinstance(value, str) or value is None for value in enum)
+ ):
+ raise StrictToolError(path, f"'{path}' enum values must be strings")
+ if "const" not in variant:
+ return enum
+ const = variant["const"]
+ if not (isinstance(const, str) or const is None):
+ raise StrictToolError(path, f"'{path}' const must be a string")
+ # ``_check_listed_values`` already rejected a ``const`` outside its ``enum``.
+ return [const]
+
+
+def _raw_text_format() -> dict[str, Any]:
+ # The parser ends a value at the first ``</parameter>``, and the stream
+ # parser ends the whole call at the first ``</tool_call>``.
+ return {"type": "any_text", "excludes": list(_RAW_VALUE_EXCLUDES)}
+
+
+def _regex_literal(text: str) -> str:
+ return "".join("\\" + char if char in _REGEX_SPECIAL else _REGEX_ESCAPES.get(char, char) for char in text)
+
+
+# The tool-call formats whose strict tools can be enforced, and the tag each builds.
+_STRICT_TAG_BUILDERS: dict[str, Callable[..., dict[str, Any]]] = {
+ "qwen_xml": _qwen_xml_tool_tag,
+ "hermes_json": _hermes_json_tool_tag,
+}
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
index 81d104ec5..170dc2343 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
@@ -153,7 +153,7 @@ def tool_parameter_schemas(tools: Sequence[Mapping[str, Any]] | None) -> dict[st
return schemas
-def _resolve_ref(schema: Any, root: Mapping[str, Any]) -> Any:
+def resolve_schema_ref(schema: Any, root: Mapping[str, Any]) -> Any:
"""Follow local ``#/...`` JSON pointers. An unresolvable reference yields ``None``."""
for _ in range(_MAX_SCHEMA_DEPTH):
if not isinstance(schema, Mapping):
@@ -196,7 +196,7 @@ def _enum_type(values: list[object]) -> str:
return kinds.pop() if len(kinds) == 1 else "string"
-def _schema_type(
+def schema_conversion_type(
schema: Any, root: Mapping[str, Any], depth: int = 0, seen: dict[tuple[int, int], str | None] | None = None
) -> str | None:
"""Infer one conversion type from a parameter schema, as SGLang's ``infer_type_from_json_schema`` does.
@@ -206,7 +206,7 @@ def _schema_type(
once per path, exponentially in its depth; with it each schema is inferred at most once per depth.
"""
seen = {} if seen is None else seen
- schema = _resolve_ref(schema, root)
+ schema = resolve_schema_ref(schema, root)
if not isinstance(schema, Mapping) or depth > _MAX_SCHEMA_DEPTH:
return None
key = (id(schema), depth)
@@ -226,7 +226,9 @@ def _infer_schema_type(
return non_null[0].strip().lower() if non_null else "string"
variants = schema.get("anyOf") or schema.get("oneOf")
if isinstance(variants, list):
- kinds = [kind for kind in (_schema_type(variant, root, depth + 1, seen) for variant in variants) if kind]
+ kinds = [
+ kind for kind in (schema_conversion_type(variant, root, depth + 1, seen) for variant in variants) if kind
+ ]
if kinds:
distinct = set(kinds)
if len(distinct) == 1:
@@ -240,7 +242,7 @@ def _infer_schema_type(
all_of = schema.get("allOf")
if isinstance(all_of, list):
for variant in all_of:
- kind = _schema_type(variant, root, depth + 1, seen)
+ kind = schema_conversion_type(variant, root, depth + 1, seen)
if kind and kind != "string":
return kind
return "string"
@@ -251,12 +253,12 @@ def _infer_schema_type(
return None
-def _schema_allows_null(
+def schema_allows_null(
schema: Any, root: Mapping[str, Any], depth: int = 0, seen: dict[tuple[int, int], bool] | None = None
) -> bool:
- """Whether a parameter schema admits ``null``; ``seen`` memoizes as in :func:`_schema_type`."""
+ """Whether a parameter schema admits ``null``; ``seen`` memoizes as in :func:`schema_conversion_type`."""
seen = {} if seen is None else seen
- schema = _resolve_ref(schema, root)
+ schema = resolve_schema_ref(schema, root)
if not isinstance(schema, Mapping) or depth > _MAX_SCHEMA_DEPTH:
return False
key = (id(schema), depth)
@@ -272,10 +274,10 @@ def _schema_admits_null(
if schema.get("nullable") is True or declared == "null" or (isinstance(declared, list) and "null" in declared):
return True
enum = schema.get("enum")
- if isinstance(enum, list) and None in enum:
+ if (isinstance(enum, list) and None in enum) or ("const" in schema and schema["const"] is None):
return True
return any(
- isinstance(variants, list) and any(_schema_allows_null(variant, root, depth + 1, seen) for variant in variants)
+ isinstance(variants, list) and any(schema_allows_null(variant, root, depth + 1, seen) for variant in variants)
for variants in (schema.get("anyOf"), schema.get("oneOf"))
)
@@ -284,8 +286,11 @@ def _reject_constant(constant: str) -> object:
raise ValueError(f"non-finite JSON constant {constant}")
+_JSON_DECODER = json.JSONDecoder(parse_constant=_reject_constant)
+
+
def _loads_json(text: str) -> object:
- return json.loads(text, parse_constant=_reject_constant)
+ return _JSON_DECODER.decode(text)
def _convert_argument(raw: str, schema: Any, root: Mapping[str, Any]) -> object:
@@ -297,9 +302,9 @@ def _convert_argument(raw: str, schema: Any, root: Mapping[str, Any]) -> object:
"""
if schema is None:
return raw
- kind = _schema_type(schema, root) or "string"
+ kind = schema_conversion_type(schema, root) or "string"
text = raw.strip()
- if text.lower() == "null" and (kind not in _STRING_TYPES or _schema_allows_null(schema, root)):
+ if text.lower() == "null" and (kind not in _STRING_TYPES or schema_allows_null(schema, root)):
return None
if kind in _STRING_TYPES:
return raw
@@ -989,7 +994,9 @@ def _tool_call_deltas(
if arguments is None:
arguments = {}
try:
- arguments_json = json.dumps(arguments, separators=(",", ":"), ensure_ascii=False)
+ # ``allow_nan=False``: an overflowing number such as ``1e999`` would otherwise
+ # serialise as ``Infinity``, which is not JSON.
+ arguments_json = json.dumps(arguments, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
size = len(arguments_json.encode())
except (TypeError, ValueError) as exc:
raise ValueError(f"tool-call 'arguments' is not JSON-serialisable: {exc}") from exc
@@ -1025,10 +1032,11 @@ _XML_FUNC_RE = re.compile(r"<function=([^>\s]+)\s*>")
# rather than a ``(.*?)...</parameter>`` group, which on a 256 KiB buffer of garbled
# output (many openers, no closers) is O(n²) and runs INLINE on the event loop.
_XML_PARAM_OPEN_RE = re.compile(r"<parameter=([^<>]*[^<>\s])\s*>")
-_XML_PARAM_CLOSE = "</parameter>"
+XML_PARAM_CLOSE = "</parameter>"
+_XML_FUNC_CLOSE = "</function>"
# Hard cap on parameters parsed from one XML tool call. Defends against an
# adversarial buffer packed with openers; well-formed calls have a handful.
-_MAX_XML_PARAMS = 256
+MAX_XML_PARAMS = 256
def _parse_xml_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[str, dict[str, object]]:
@@ -1056,24 +1064,62 @@ def _parse_xml_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[
# ``str.find`` (no regex backtracking). Worst case is O(n) over ``raw``.
pos = 0
count = 0
- while count < _MAX_XML_PARAMS:
+ while count < MAX_XML_PARAMS:
om = _XML_PARAM_OPEN_RE.search(raw, pos)
if om is None:
break
key = om.group(1)
val_start = om.end()
- close_idx = raw.find(_XML_PARAM_CLOSE, val_start)
+ schema, root = _parameter_schema(schemas or {}, name, key)
+ close_idx = _xml_value_end(raw, val_start, schema, root)
if close_idx == -1:
- # Unterminated parameter — stop; well-formed input always closes.
+ # An opener that never closes ends the scan with the arguments read
+ # so far, as before; strict calls are then checked against their
+ # schema at the end of the turn.
break
val = raw[val_start:close_idx].removeprefix("\n").removesuffix("\n")
- schema, root = _parameter_schema(schemas or {}, name, key)
arguments[key] = _convert_argument(val, schema, root)
- pos = close_idx + len(_XML_PARAM_CLOSE)
+ pos = close_idx + len(XML_PARAM_CLOSE)
count += 1
return name, arguments
+def _xml_value_end(raw: str, start: int, schema: Any, root: Mapping[str, Any]) -> int:
+ """Return the index of the ``</parameter>`` that closes the value starting at ``start``.
+
+ A container value is JSON, and its strings may contain ``</parameter>``, so
+ it is decoded once from ``start`` (linear in its length) and ends at the
+ closing tag right after the decoded value. A ``</parameter>`` inside a JSON
+ string that never terminates means the block was cut at a ``</tool_call>``
+ inside that string, so the tag found belongs to the string and the call
+ fails. ``-1`` means no closing tag at all. Other values, and a container
+ value that is not JSON, end at the first closing tag.
+
+ Raises:
+ ValueError: The block was cut inside a JSON string.
+ """
+ first = raw.find(XML_PARAM_CLOSE, start)
+ kind = schema_conversion_type(schema, root) if schema is not None else None
+ if first == -1 or kind is None or not (kind in _CONTAINER_TYPES or kind.startswith(_CONTAINER_TYPE_PREFIXES)):
+ return first
+ begin = _skip_whitespace(raw, start)
+ try:
+ _, end = _JSON_DECODER.raw_decode(raw, begin)
+ except json.JSONDecodeError as exc:
+ # A closed call ends with ``</function>``; a block cut at a
+ # ``</tool_call>`` inside the string does not, so only that case fails.
+ cut = (
+ exc.msg.startswith("Unterminated string") and exc.pos < first and not raw.rstrip().endswith(_XML_FUNC_CLOSE)
+ )
+ if cut:
+ raise ValueError("malformed XML tool-call: a <parameter> value was cut inside a JSON string") from exc
+ return first
+ except (ValueError, RecursionError):
+ return first
+ close = _skip_whitespace(raw, end)
+ return close if raw.startswith(XML_PARAM_CLOSE, close) else first
+
+
_GLM_KEY_OPEN = "<arg_key>"
_GLM_KEY_CLOSE = "</arg_key>"
_GLM_VALUE_OPEN = "<arg_value>"
@@ -1100,7 +1146,7 @@ def _parse_glm_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[
template writes ``<arg_value>{value}</arg_value>`` with nothing around the
value, so the text is kept verbatim and converted by its declared parameter
type in ``schemas``. The scan is linear, and a call with more than
- ``_MAX_XML_PARAMS`` pairs is rejected rather than truncated.
+ ``MAX_XML_PARAMS`` pairs is rejected rather than truncated.
"""
first_key = raw.find(_GLM_KEY_OPEN)
name = (raw if first_key == -1 else raw[:first_key]).strip()
@@ -1109,7 +1155,7 @@ def _parse_glm_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[
arguments: dict[str, object] = {}
pos = len(raw) if first_key == -1 else first_key
count = 0
- while (pos := _skip_whitespace(raw, pos)) < len(raw) and count < _MAX_XML_PARAMS:
+ while (pos := _skip_whitespace(raw, pos)) < len(raw) and count < MAX_XML_PARAMS:
if not raw.startswith(_GLM_KEY_OPEN, pos):
raise ValueError("malformed GLM tool-call: expected <arg_key>")
key_close = raw.find(_GLM_KEY_CLOSE, pos)
@@ -1130,7 +1176,7 @@ def _parse_glm_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[
pos = value_close + len(_GLM_VALUE_CLOSE)
count += 1
if _skip_whitespace(raw, pos) < len(raw):
- raise ValueError(f"malformed GLM tool-call: more than {_MAX_XML_PARAMS} arguments")
+ raise ValueError(f"malformed GLM tool-call: more than {MAX_XML_PARAMS} arguments")
return name, arguments
@@ -1207,8 +1253,8 @@ class _GemmaArgumentParser:
if key in result:
raise _gemma_error(f"duplicate key {key[:64]!r}")
if top_level:
- if len(result) >= _MAX_XML_PARAMS:
- raise _gemma_error(f"more than {_MAX_XML_PARAMS} arguments")
+ if len(result) >= MAX_XML_PARAMS:
+ raise _gemma_error(f"more than {MAX_XML_PARAMS} arguments")
result[key], pos = self.argument(pos, key)
else:
result[key], pos = self.value(pos, depth)
@@ -1261,7 +1307,7 @@ class _GemmaArgumentParser:
type.
"""
schema, root = _parameter_schema(self.schemas, self.name, key)
- kind = None if schema is None else _schema_type(schema, root)
+ kind = None if schema is None else schema_conversion_type(schema, root)
if self.text.startswith(_GEMMA_STRING, pos):
text, end = self.string(pos)
if kind is None or kind in _STRING_TYPES:
diff --git a/packages/sie_server/src/sie_server/types/grammar.py b/packages/sie_server/src/sie_server/types/grammar.py
index 3865c1581..2688530b8 100644
--- a/packages/sie_server/src/sie_server/types/grammar.py
+++ b/packages/sie_server/src/sie_server/types/grammar.py
@@ -37,7 +37,7 @@ from typing import Literal
# Backend literal kept here (and not in :mod:`grammar_cache`) so callers
# building cache keys don't import the cache module just for the tag.
-GrammarKind = Literal["json_schema", "regex", "ebnf"]
+GrammarKind = Literal["json_schema", "regex", "ebnf", "structural_tag"]
OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC = "'type' must be a string"
OUTLINES_JSON_SCHEMA_TYPE_MESSAGE = (
@@ -55,7 +55,10 @@ class GrammarSpec:
Schema object (``dict``); ``"regex"`` and ``"ebnf"`` mean
``value`` is a string (regex pattern or EBNF source).
Mutual exclusivity is enforced by the gateway before this
- dataclass is built.
+ dataclass is built. ``"structural_tag"`` is worker-internal:
+ the worker builds it for ``strict`` function tools (see
+ :func:`~sie_server.processors.tool_call_grammar.build_strict_tool_grammar`)
+ and ``value`` is an XGrammar structural-tag object (``dict``).
value: The schema or grammar payload itself. Type depends on
``kind`` — ``dict`` for ``json_schema``, ``str`` for
``regex`` and ``ebnf``. The gateway has already enforced
diff --git a/packages/sie_server/tests/adapters/test_sglang_chat_tools.py b/packages/sie_server/tests/adapters/test_sglang_chat_tools.py
index 1ee4db799..be2cca510 100644
--- a/packages/sie_server/tests/adapters/test_sglang_chat_tools.py
+++ b/packages/sie_server/tests/adapters/test_sglang_chat_tools.py
@@ -106,7 +106,9 @@ _STRICT = {
"name": "lookup",
"description": "Look one key up.",
"parameters": {"type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"]},
- "strict": True,
+ # A strict tool is refused on the single-server route, which cannot enforce it;
+ # an explicit ``strict: false`` still has to render the same on both routes.
+ "strict": False,
},
}
_ASK = {"role": "user", "content": "What is the weather in Paris right now? Use the get_weather tool."}
@@ -125,7 +127,7 @@ _REQUESTS: dict[str, dict[str, Any]] = {
"messages": [{"role": "system", "content": "Answer briefly."}, _ASK, _CALL, _RESULT],
"tools": [_WEATHER, _PING],
},
- "strict_tool": {"messages": [_ASK], "tools": [_STRICT, _WEATHER]},
+ "strict_false_tool": {"messages": [_ASK], "tools": [_STRICT, _WEATHER]},
"named_tool_choice": {
"messages": [_ASK],
"tools": [_PING, _WEATHER],
@@ -328,6 +330,7 @@ def _single_server_prompts(
inputs=SimpleNamespace(video=False),
profiles={},
routing=None,
+ reasoning_effort_for=lambda _profile="default": None,
)
registry = MagicMock()
registry.device = "cuda:0"
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 30be4b94b..fb718b290 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -2180,6 +2180,25 @@ def _serve_grammar_routed_configs(registry: MagicMock, *, without: tuple[str, ..
registry.get_config.side_effect = configs.__getitem__
+def test_cuda_chat_refuses_strict_tools_before_the_child(monkeypatch: pytest.MonkeyPatch) -> None:
+ """SGLang's own chat endpoint does not constrain tool arguments, so the direct route refuses strict tools."""
+
+ def _handler(_request: httpx.Request) -> httpx.Response:
+ raise AssertionError("a strict tool must not reach the child")
+
+ client, _registry = _cuda_chat_client(monkeypatch, _handler)
+ strict_tool = {**_WEATHER_TOOL, "function": {**_WEATHER_TOOL["function"], "strict": True}}
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "upstream/repo", "messages": [{"role": "user", "content": "hi"}], "tools": [strict_tool]},
+ )
+
+ assert response.status_code == 400
+ error = response.json()["error"]
+ assert error["code"] == "unsupported_field"
+ assert error["param"] == "tools[0].function.strict"
+
+
def test_cuda_chat_strict_schema_with_unevaluated_properties_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
def _handler(_request: httpx.Request) -> httpx.Response:
raise AssertionError("an unverifiable strict schema must not reach the child")
diff --git a/packages/sie_server/tests/core/test_grammar_routing.py b/packages/sie_server/tests/core/test_grammar_routing.py
index 3e803d8b4..ebebfff13 100644
--- a/packages/sie_server/tests/core/test_grammar_routing.py
+++ b/packages/sie_server/tests/core/test_grammar_routing.py
@@ -11,6 +11,7 @@ from typing import Any
import pytest
import yaml
from sie_server.adapters._generation_base import GenerationUnsupportedFieldError
+from sie_server.config.model import is_remote_adapter_path
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
@@ -232,3 +233,27 @@ def test_a_remote_variant_keeps_its_grammar_requests(tmp_path: Path, serve_base:
registry = _gemma_registry(tmp_path, config=config, model_filter=model_filter)
assert resolve_grammar_serving_model(registry, requested) == requested
+
+
[email protected]("relay_upstream")
+def test_a_remote_base_model_keeps_its_grammar_requests(tmp_path: Path) -> None:
+ """A model served by a remote upstream keeps its id even when it declares a grammar profile."""
+ config = yaml.safe_load(_GEMMA_FILE.read_text(encoding="utf-8"))
+ config["profiles"] = {
+ "default": {
+ "adapter_path": "sie_server.adapters.remote.sie:SieUpstreamAdapter",
+ "max_batch_tokens": 16384,
+ "adapter_options": {"loadtime": {"upstream": "relay", "upstream_model": _GEMMA_ID}},
+ },
+ "no-spec": {"extends": "default"},
+ }
+ config["tasks"]["generate"]["grammar_profile"] = "no-spec"
+ registry = _gemma_registry(tmp_path, config=config, model_filter=[_GEMMA_ID])
+
+ # The resolver also keeps the id of an unknown model, so first pin that this
+ # one registered as remote-served with a grammar profile.
+ assert registry.has_model(_GEMMA_ID)
+ served = registry.get_config(_GEMMA_ID)
+ assert is_remote_adapter_path(served.resolve_profile("default").adapter_path)
+ assert served.tasks.generate.grammar_profile == "no-spec"
+ assert resolve_grammar_serving_model(registry, _GEMMA_ID) == _GEMMA_ID
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index 5a0b402b5..0783f8f62 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -2838,6 +2838,283 @@ async def test_streaming_tool_choice_required_forwards_forcing_grammar() -> None
assert "get_weather" in grammar.value
+_STRICT_WEATHER_TOOLS = (
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "strict": True,
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}, "days": {"type": "integer"}},
+ "required": ["city", "days"],
+ "additionalProperties": False,
+ },
+ },
+ },
+)
+
+
+def _strict_tool_processor(
+ script: list[GenerationChunk], *, backend: str | None, parser: str = "qwen3_coder"
+) -> tuple[StreamingProcessor, AsyncMock, dict[str, Any]]:
+ nc = AsyncMock()
+ adapter = _FakeGenAdapter(script)
+ if backend is not None:
+ adapter._grammar_backend = backend # type: ignore[attr-defined]
+ captured: dict[str, Any] = {}
+ original = adapter.generate
+
+ async def _capture(prompt, *, max_new_tokens, temperature=1.0, top_p=1.0, stop=None, **kwargs):
+ captured.update(kwargs)
+ captured["calls"] = captured.get("calls", 0) + 1
+ async for chunk in original(
+ prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p, stop=stop
+ ):
+ yield chunk
+
+ adapter.generate = _capture # type: ignore[method-assign]
+ registry = _make_registry(adapter)
+ resolved = MagicMock()
+ resolved.loadtime = {"tool_call_parser": parser}
+ registry.get_config.return_value.resolve_profile.return_value = resolved
+ return StreamingProcessor(nc=nc, registry=registry, worker_id="w1"), nc, captured
+
+
[email protected]("tool_choice", [None, "auto", "required"])
+async def test_streaming_strict_tool_forwards_structural_tag(tool_choice: str | None) -> None:
+ """A strict tool constrains its arguments under every enforcing tool_choice, including auto."""
+ call = "<tool_call>\n<function=get_weather>\n<parameter=city>\nTokyo\n</parameter>\n"
+ call += "<parameter=days>\n3\n</parameter>\n</function>\n</tool_call>"
+ proc, nc, captured = _strict_tool_processor(
+ [
+ GenerationChunk(text_delta=call, is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ],
+ backend="xgrammar",
+ )
+ generate: dict[str, Any] = {"prompt": "weather?", "max_new_tokens": 64, "tools": list(_STRICT_WEATHER_TOOLS)}
+ if tool_choice is not None:
+ generate["tool_choice"] = tool_choice
+
+ await proc.process(_make_msg(_make_work_item(generate=generate)), "test/model")
+
+ grammar = captured.get("grammar")
+ assert grammar is not None
+ assert grammar.kind == "structural_tag"
+ expected = "sequence" if tool_choice == "required" else "triggered_tags"
+ assert grammar.value["format"]["type"] == expected
+ tcs = _tool_call_deltas(_decode_chunks(nc))
+ assert tcs[1]["function"]["arguments"] == '{"city":"Tokyo","days":3}'
+ terminals = [chunk for chunk in _decode_chunks(nc) if chunk.get("done") is True]
+ assert terminals[-1].get("error") is None
+
+
+async def test_streaming_strict_tool_arguments_are_validated_against_the_full_schema() -> None:
+ """A call the grammar let through but the schema forbids errors the turn instead of reaching the client as valid."""
+ call = "<tool_call>\n<function=get_weather>\n<parameter=city>\nTokyo\n</parameter>\n</function>\n</tool_call>"
+ proc, nc, _captured = _strict_tool_processor(
+ [
+ GenerationChunk(text_delta=call, is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ],
+ backend="xgrammar",
+ )
+ generate = {"prompt": "weather?", "max_new_tokens": 64, "tools": list(_STRICT_WEATHER_TOOLS)}
+
+ await proc.process(_make_msg(_make_work_item(generate=generate)), "test/model")
+
+ terminals = [chunk for chunk in _decode_chunks(nc) if chunk.get("done") is True]
+ assert len(terminals) == 1
+ assert terminals[0]["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"
+ assert "'get_weather'" in terminals[0]["error"]["message"]
+
+
+_STRICT_MEASURE_TOOLS = (
+ {
+ "type": "function",
+ "function": {
+ "name": "measure",
+ "strict": True,
+ "parameters": {
+ "type": "object",
+ "properties": {"value": {"type": "number"}, "tags": {"type": "array", "items": {"type": "string"}}},
+ "required": ["value"],
+ "additionalProperties": False,
+ },
+ },
+ },
+)
+
+
+async def _run_strict_measure(call: str) -> list[dict[str, Any]]:
+ proc, nc, _captured = _strict_tool_processor(
+ [
+ GenerationChunk(text_delta=call, is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ],
+ backend="xgrammar",
+ )
+ generate = {"prompt": "measure", "max_new_tokens": 64, "tools": list(_STRICT_MEASURE_TOOLS)}
+ await proc.process(_make_msg(_make_work_item(generate=generate)), "test/model")
+ return _decode_chunks(nc)
+
+
+def _measure_call(*parameters: tuple[str, str]) -> str:
+ body = "".join(f"<parameter={key}>\n{value}\n</parameter>\n" for key, value in parameters)
+ return f"<tool_call>\n<function=measure>\n{body}</function>\n</tool_call>"
+
+
+ "call",
+ [
+ # The parser keeps an overflowing number as its text, which the schema rejects.
+ _measure_call(("value", "1e999")),
+ # A JSON string holding the closing tags: the stream parser ends the call at the
+ # first ``</tool_call>`` and the array comes back as raw text.
+ _measure_call(("value", "1"), ("tags", '["a</parameter></function></tool_call>b"]')),
+ ],
+ ids=["overflowing-number", "closing-tags-in-a-string"],
+)
+async def test_streaming_invalid_strict_arguments_never_reach_the_client(call: str) -> None:
+ chunks = await _run_strict_measure(call)
+
+ assert _tool_call_deltas(chunks) == []
+ terminals = [chunk for chunk in chunks if chunk.get("done") is True]
+ assert len(terminals) == 1
+ assert terminals[0]["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"
+
+
+async def test_streaming_valid_strict_arguments_are_released() -> None:
+ chunks = await _run_strict_measure(_measure_call(("value", "1.5")))
+
+ assert _tool_call_deltas(chunks)[1]["function"]["arguments"] == '{"value":1.5}'
+ assert [chunk for chunk in chunks if chunk.get("done") is True][-1].get("error") is None
+
+
+_QWEN_WEATHER_CALL = (
+ "<tool_call>\n<function=get_weather>\n<parameter=city>\nTokyo\n</parameter>\n"
+ "<parameter=days>\n{days}\n</parameter>\n</function>\n</tool_call>"
+)
+_GEMMA_WEATHER_CALL = '<|tool_call>call:get_weather{{city:<|"|>Tokyo<|"|>,days:{days}}}<tool_call|>'
+_UNCONSTRAINED_STRICT_REQUESTS = [
+ pytest.param("outlines", "qwen3_coder", {}, _QWEN_WEATHER_CALL, "soon", id="outlines-backend"),
+ pytest.param(None, "qwen3_coder", {}, _QWEN_WEATHER_CALL, "soon", id="no-grammar-backend"),
+ pytest.param("xgrammar", "gemma4", {}, _GEMMA_WEATHER_CALL, '<|"|>soon<|"|>', id="format-without-a-tag"),
+ pytest.param(
+ "xgrammar",
+ "qwen3_coder",
+ {"grammar": {"kind": "json_schema", "value": {"type": "object"}}},
+ _QWEN_WEATHER_CALL,
+ "soon",
+ id="with-response-format",
+ ),
+]
+
+
+async def _run_unconstrained_strict_weather(
+ backend: str | None, parser: str, extra: dict[str, Any], call: str
+) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ proc, nc, captured = _strict_tool_processor(
+ [
+ GenerationChunk(text_delta=call, is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ],
+ backend=backend,
+ parser=parser,
+ )
+ generate = {"prompt": "weather?", "max_new_tokens": 64, "tools": list(_STRICT_WEATHER_TOOLS), **extra}
+ await proc.process(_make_msg(_make_work_item(generate=generate)), "test/model")
+ return _decode_chunks(nc), captured
+
+
[email protected](("backend", "parser", "extra", "call", "bad_days"), _UNCONSTRAINED_STRICT_REQUESTS)
+async def test_streaming_strict_tool_without_a_structural_tag_is_served(
+ backend: str | None, parser: str, extra: dict[str, Any], call: str, bad_days: str
+) -> None:
+ """Where the structural tag cannot apply, the request keeps the grammar a non-strict one gets."""
+ chunks, captured = await _run_unconstrained_strict_weather(backend, parser, extra, call.format(days="3"))
+
+ grammar = captured.get("grammar")
+ assert (grammar.kind if grammar is not None else None) == (extra["grammar"]["kind"] if extra else None)
+ assert _tool_call_deltas(chunks)[1]["function"]["arguments"] == '{"city":"Tokyo","days":3}'
+ assert [chunk for chunk in chunks if chunk.get("done") is True][-1].get("error") is None
+
+
[email protected](("backend", "parser", "extra", "call", "bad_days"), _UNCONSTRAINED_STRICT_REQUESTS)
+async def test_streaming_strict_tool_without_a_structural_tag_is_still_validated(
+ backend: str | None, parser: str, extra: dict[str, Any], call: str, bad_days: str
+) -> None:
+ chunks, _captured = await _run_unconstrained_strict_weather(backend, parser, extra, call.format(days=bad_days))
+
+ assert _tool_call_deltas(chunks) == []
+ terminals = [chunk for chunk in chunks if chunk.get("done") is True]
+ assert len(terminals) == 1
+ assert terminals[0]["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"
+ assert "'get_weather'" in terminals[0]["error"]["message"]
+
+
+async def test_streaming_strict_tool_that_cannot_be_validated_is_rejected() -> None:
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "strict": True,
+ "parameters": {"type": "object", "properties": {"city": {}}, "unevaluatedProperties": False},
+ },
+ }
+ ]
+ proc, nc, captured = _strict_tool_processor(
+ [GenerationChunk(text_delta="never", done=True, finish_reason="stop")], backend="outlines", parser="gemma4"
+ )
+
+ await proc.process(
+ _make_msg(_make_work_item(generate={"prompt": "weather?", "max_new_tokens": 64, "tools": tools})), "test/model"
+ )
+
+ assert "calls" not in captured
+ terminals = [chunk for chunk in _decode_chunks(nc) if chunk.get("done") is True]
+ assert len(terminals) == 1
+ assert terminals[0]["error"]["code"] == "unsupported_field"
+ assert terminals[0]["error"].get("param") == "tools[0].function.parameters"
+
+
+async def test_streaming_strict_tool_with_tool_choice_none_is_unconstrained() -> None:
+ proc, nc, captured = _strict_tool_processor(
+ [
+ GenerationChunk(text_delta="Sunny.", is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ],
+ backend="outlines",
+ )
+ generate = {
+ "prompt": "weather?",
+ "max_new_tokens": 64,
+ "tools": list(_STRICT_WEATHER_TOOLS),
+ "tool_choice": "none",
+ }
+
+ await proc.process(_make_msg(_make_work_item(generate=generate)), "test/model")
+
+ # Generation ran, unconstrained, and finished without an error.
+ assert captured.get("calls") == 1
+ assert captured.get("grammar") is None
+ decoded = _decode_chunks(nc)
+ assert "".join(chunk.get("text_delta") or "" for chunk in decoded) == "Sunny."
+ terminals = [chunk for chunk in decoded if chunk.get("done") is True]
+ assert len(terminals) == 1
+ assert terminals[0].get("error") is None
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("parser", "call"),
diff --git a/packages/sie_server/tests/processors/test_strict_grammar.py b/packages/sie_server/tests/processors/test_strict_grammar.py
index 0bfddf57c..30f142bc8 100644
--- a/packages/sie_server/tests/processors/test_strict_grammar.py
+++ b/packages/sie_server/tests/processors/test_strict_grammar.py
@@ -12,6 +12,7 @@ from sie_server.processors import strict_grammar
from sie_server.processors.strict_grammar import (
MODEL_OUTPUT_PARSE_ERROR,
enforce_strict_grammar,
+ enforce_strict_tool_arguments,
output_violation,
requires_output_validation,
)
@@ -449,3 +450,130 @@ async def test_closing_the_wrapper_closes_the_upstream_iterator() -> None:
await wrapped.aclose() # type: ignore[attr-defined]
assert closed is True
+
+
+# -- strict function-tool arguments ---------------------------------------------
+
+# ``minimum`` and ``pattern`` are among the keywords the grammar backend can drop,
+# so the terminal check is what guarantees them.
+_TOOL_SCHEMAS = {
+ "lookup": {**_SCHEMA, "properties": {**_SCHEMA["properties"], "count": {"type": "integer", "minimum": 1}}}
+}
+
+
+def _tool_call(name: str, arguments: str) -> list[GenerationChunk]:
+ return [
+ GenerationChunk(text_delta="", tool_call_delta=ToolCallDelta(index=0, id="call_1", function_name=name)),
+ GenerationChunk(text_delta="", tool_call_delta=ToolCallDelta(index=0, arguments_delta=arguments)),
+ GenerationChunk(text_delta="", done=True, finish_reason="tool_calls"),
+ ]
+
+
+async def test_strict_tool_arguments_that_violate_the_schema_error_the_terminal() -> None:
+ upstream = _tool_call("lookup", '{"name": "Ada", "count": 0}')
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
+
+ assert chunks[-1].finish_reason == "error"
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+ assert "'lookup'" in (chunks[-1].error_message or "")
+ assert "minimum" in (chunks[-1].error_message or "")
+
+
+async def test_invalid_strict_tool_arguments_are_never_streamed() -> None:
+ """The deltas of a strict call are held until the terminal check, so a violation reaches no client."""
+ upstream = _tool_call("lookup", '{"name": "Ada", "count": 0}')
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
+
+ assert [chunk.tool_call_delta for chunk in chunks] == [None]
+ assert chunks[0].error_code == MODEL_OUTPUT_PARSE_ERROR
+
+
+async def test_strict_tool_deltas_are_released_in_order_once_valid() -> None:
+ text = GenerationChunk(text_delta="Looking it up.")
+ trailing = GenerationChunk(text_delta=" Done.")
+ calls = _tool_call("lookup", '{"name": "Ada", "count": 2}')
+ upstream = [text, *calls[:2], trailing, calls[2]]
+ released: list[GenerationChunk] = []
+
+ async for chunk in enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS):
+ released.append(chunk)
+ if chunk is text:
+ # Text before any strict call is not delayed.
+ assert len(released) == 1
+
+ assert released == upstream
+
+
+async def test_a_choice_finish_after_a_strict_call_is_held_until_validation() -> None:
+ """With ``n > 1`` a choice closes before the terminal; it must not close on an invalid call."""
+ calls = _tool_call("lookup", '{"name": "Ada", "count": 0}')
+ choice_finish = GenerationChunk(text_delta="", finish_reason="tool_calls")
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream([*calls[:2], choice_finish, calls[2]]), _TOOL_SCHEMAS))
+
+ assert [chunk.finish_reason for chunk in chunks] == ["error"]
+
+
[email protected](("day", "valid"), [("2026-01-01", True), ("tomorrow", False)])
+async def test_strict_tool_argument_formats_are_checked(day: str, valid: bool) -> None:
+ schemas = {"book": {"type": "object", "properties": {"day": {"type": "string", "format": "date"}}}}
+ upstream = _tool_call("book", f'{{"day": "{day}"}}')
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), schemas))
+
+ assert (chunks[-1].error_code is None) is valid
+
+
+async def test_an_upstream_error_drops_the_unvalidated_strict_call() -> None:
+ calls = _tool_call("lookup", '{"name": "Ada", "count": 2}')
+ failed = GenerationChunk(text_delta="", done=True, finish_reason="error", error_code="upstream_error")
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream([*calls[:2], failed]), _TOOL_SCHEMAS))
+
+ assert chunks == [failed]
+
+
+async def test_conforming_strict_tool_arguments_keep_the_terminal() -> None:
+ upstream = _tool_call("lookup", '{"name": "Ada", "count": 2}')
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
+
+ assert chunks == upstream
+
+
+async def test_non_strict_tool_calls_are_not_validated() -> None:
+ upstream = _tool_call("other", '{"anything": true}')
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
+
+ assert chunks[-1].error_code is None
+
+
+async def test_strict_tool_calls_on_candidates_are_validated() -> None:
+ function = {"name": "lookup", "arguments": '{"name": "ada", "count": 1}'}
+ call = {"id": "call_1", "type": "function", "function": function}
+ terminal = GenerationChunk(
+ text_delta="", done=True, finish_reason="tool_calls", candidates=({"tool_calls": [call]},)
+ )
+
+ chunks = await _drain(enforce_strict_tool_arguments(_stream([terminal]), _TOOL_SCHEMAS))
+
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+ assert "pattern" in (chunks[-1].error_message or "")
+
+
+def test_no_strict_tools_return_the_stream_unchanged() -> None:
+ upstream = _stream([])
+
+ assert enforce_strict_tool_arguments(upstream, {}) is upstream
diff --git a/packages/sie_server/tests/processors/test_tool_call_grammar_strict.py b/packages/sie_server/tests/processors/test_tool_call_grammar_strict.py
new file mode 100644
index 000000000..30b5d6e1a
--- /dev/null
+++ b/packages/sie_server/tests/processors/test_tool_call_grammar_strict.py
@@ -0,0 +1,872 @@
+"""Strict function tools compile to an XGrammar structural tag.
+
+Shape tests run everywhere. Acceptance tests compile the tag with XGrammar,
+the backend SGLang uses for it, and run when ``xgrammar`` is installed.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import orjson
+import pytest
+from sie_server.processors.tool_call_grammar import (
+ StrictToolError,
+ ToolChoiceError,
+ build_strict_tool_grammar,
+ build_tool_choice_grammar,
+ has_strict_tools,
+ tools_require_grammar,
+)
+from sie_server.processors.tool_call_parser import MAX_XML_PARAMS, _tool_call_deltas, tool_parameter_schemas
+from sie_server.processors.tool_call_parser import _parse_xml_tool_call as parse_xml_tool_call
+
+SEARCH = {
+ "type": "object",
+ "properties": {
+ "keywords": {"type": "array", "items": {"type": "string"}},
+ "exact": {"type": "boolean"},
+ "filter": {
+ "type": "object",
+ "properties": {"measures": {"type": "array", "items": {"type": "string"}}},
+ "required": ["measures"],
+ "additionalProperties": False,
+ },
+ "limit": {"type": "integer"},
+ },
+ "required": ["keywords", "exact", "filter", "limit"],
+ "additionalProperties": False,
+}
+
+# OpenAI strict schemas express optional fields as required and nullable.
+# Same shapes as Pydantic ``model_json_schema()`` output.
+LOOKUP = {
+ "type": "object",
+ "$defs": {
+ "Kind": {"type": "string", "enum": ["metric", "fact", "label"]},
+ "Spec": {
+ "type": "object",
+ "properties": {"id": {"type": "string"}, "type": {"type": "string", "const": "label"}},
+ "required": ["id", "type"],
+ "additionalProperties": False,
+ },
+ },
+ "properties": {
+ "keywords": {"anyOf": [{"type": "array", "items": {"type": "string"}}, {"type": "null"}]},
+ "kinds": {"type": "array", "items": {"$ref": "#/$defs/Kind"}},
+ "limit": {"anyOf": [{"type": "integer", "minimum": 1, "maximum": 100}, {"type": "null"}]},
+ "spec": {"anyOf": [{"$ref": "#/$defs/Spec"}, {"type": "null"}]},
+ "eligible": {"anyOf": [{"type": "boolean"}, {"type": "null"}]},
+ "note": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": None},
+ "kind": {"anyOf": [{"$ref": "#/$defs/Kind"}, {"type": "null"}]},
+ "explicit": {"type": "boolean"},
+ },
+ "required": ["keywords", "kinds", "limit", "spec", "eligible", "note", "kind", "explicit"],
+ "additionalProperties": False,
+}
+
+_PART_NAMES = ("text", "chart", "table", "doc", "kda", "alert", "patch", "board", "what_if", "results")
+ANSWER = {
+ "type": "object",
+ "$defs": {
+ **{
+ f"{name.title()}Part": {
+ "type": "object",
+ "properties": {f"{name}_ref": {"type": "string"}},
+ "required": [f"{name}_ref"],
+ }
+ for name in _PART_NAMES
+ },
+ "Mood": {"type": "string", "enum": ["positive", "negative", "neutral"]},
+ },
+ "properties": {
+ "parts": {
+ "type": "array",
+ "items": {"anyOf": [{"$ref": f"#/$defs/{name.title()}Part"} for name in _PART_NAMES]},
+ },
+ "status": {"type": "string", "enum": ["partial", "final"], "default": "final"},
+ "mood": {"anyOf": [{"$ref": "#/$defs/Mood"}, {"type": "null"}], "default": None},
+ },
+ "required": ["parts"],
+}
+
+
+def _tool(name: str, parameters: dict[str, Any] | None, *, strict: bool = True) -> dict[str, Any]:
+ function: dict[str, Any] = {"name": name, "strict": strict}
+ if parameters is not None:
+ function["parameters"] = parameters
+ return {"type": "function", "function": function}
+
+
+TOOLS = [_tool("search", SEARCH), _tool("lookup", LOOKUP), _tool("final_answer", ANSWER)]
+
+
+def _call(name: str, arguments: list[tuple[str, str]]) -> str:
+ body = "".join(f"<parameter={key}>\n{value}\n</parameter>\n" for key, value in arguments)
+ return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"
+
+
+GOOD_SEARCH = _call(
+ "search",
+ [("keywords", '["revenue"]'), ("exact", "true"), ("filter", '{"measures": ["revenue"]}'), ("limit", "5")],
+)
+# The probe's violating call: a string for a boolean, a string for an object, no limit.
+BAD_SEARCH = _call("search", [("keywords", '["revenue"]'), ("exact", "yes"), ("filter", "revenue")])
+LOOKUP_VALUES = {
+ "keywords": '["revenue"]',
+ "kinds": '["metric", "fact"]',
+ "limit": "10",
+ "spec": "null",
+ "eligible": "true",
+ "note": "null",
+ "kind": "metric",
+ "explicit": "false",
+}
+GOOD_LOOKUP = _call("lookup", list(LOOKUP_VALUES.items()))
+GOOD_ANSWER = _call(
+ "final_answer",
+ [("parts", '[{"text_ref": "t1"}, {"chart_ref": "c1"}]'), ("status", "final"), ("mood", "null")],
+)
+
+
+def _format(spec: Any) -> dict[str, Any]:
+ assert spec is not None
+ assert spec.kind == "structural_tag"
+ return spec.value["format"]
+
+
+def _calls_format(spec: Any) -> dict[str, Any]:
+ """The format holding the call tags (``required`` wraps it after a newline prefix)."""
+ fmt = _format(spec)
+ return fmt["elements"][1] if fmt["type"] == "sequence" else fmt
+
+
+def _tags(spec: Any) -> list[dict[str, Any]]:
+ return _calls_format(spec)["tags"]
+
+
+def _parameter_contents(tag: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ contents: dict[str, dict[str, Any]] = {}
+ for element in tag["content"]["elements"]:
+ parameter = element["elements"][0] if element["type"] == "or" else element
+ key = parameter["begin"].removeprefix("<parameter=").removesuffix(">\n")
+ contents[key] = parameter["content"]
+ return contents
+
+
+# -- detection and routing ------------------------------------------------------
+
+
+def test_has_strict_tools() -> None:
+ assert has_strict_tools(TOOLS)
+ assert not has_strict_tools([_tool("search", SEARCH, strict=False)])
+ assert not has_strict_tools(None)
+
+
+ ("tools", "choice", "expected"),
+ [
+ ([_tool("search", SEARCH)], None, True),
+ ([_tool("search", SEARCH)], "auto", True),
+ ([_tool("search", SEARCH)], "none", False),
+ ([_tool("search", SEARCH, strict=False)], "auto", False),
+ ([_tool("search", SEARCH, strict=False)], "required", True),
+ ([_tool("search", SEARCH, strict=False)], {"type": "function", "function": {"name": "search"}}, True),
+ (None, "required", False),
+ ([], "required", False),
+ ],
+)
+def test_tools_require_grammar(tools: Any, choice: Any, expected: bool) -> None:
+ assert tools_require_grammar(tools, choice) is expected
+
+
+# -- structure ------------------------------------------------------------------
+
+
+def test_auto_uses_triggered_tags_over_every_tool() -> None:
+ spec = build_strict_tool_grammar(TOOLS, "auto", "qwen_xml")
+ fmt = _format(spec)
+ assert fmt["type"] == "triggered_tags"
+ assert fmt["triggers"] == ["<tool_call>"]
+ assert [tag["begin"] for tag in fmt["tags"]] == [
+ "<tool_call>\n<function=search>\n",
+ "<tool_call>\n<function=lookup>\n",
+ "<tool_call>\n<function=final_answer>\n",
+ ]
+ assert fmt["stop_after_first"] is False
+ assert spec is not None
+ assert spec.label == "tool_strict:auto"
+
+
+def test_required_admits_only_calls() -> None:
+ fmt = _format(build_strict_tool_grammar(TOOLS, "required", "qwen_xml"))
+ assert fmt["type"] == "sequence"
+ calls = fmt["elements"][1]
+ assert calls["type"] == "tags_with_separator"
+ assert calls["at_least_one"] is True
+
+
+def test_named_pins_one_tool() -> None:
+ spec = build_strict_tool_grammar(TOOLS, {"type": "function", "function": {"name": "lookup"}}, "qwen_xml")
+ assert [tag["begin"] for tag in _tags(spec)] == ["<tool_call>\n<function=lookup>\n"]
+
+
[email protected]("choice", ["auto", "required"])
+def test_parallel_tool_calls_false_stops_after_first_call(choice: str) -> None:
+ spec = build_strict_tool_grammar(TOOLS, choice, "qwen_xml", parallel_tool_calls=False)
+ assert _calls_format(spec)["stop_after_first"] is True
+
+
+def test_none_builds_no_grammar() -> None:
+ assert build_strict_tool_grammar(TOOLS, "none", "qwen_xml") is None
+
+
+def test_named_tool_must_exist() -> None:
+ with pytest.raises(ToolChoiceError):
+ build_strict_tool_grammar(TOOLS, {"type": "function", "function": {"name": "nope"}}, "qwen_xml")
+
+
+def test_qwen_xml_parameters_follow_schema_order_and_requiredness() -> None:
+ tag = _tags(build_strict_tool_grammar([_tool("final_answer", ANSWER)], "required", "qwen_xml"))[0]
+ elements = tag["content"]["elements"]
+ assert elements[0]["type"] == "tag"
+ assert elements[0]["begin"] == "<parameter=parts>\n"
+ assert elements[0]["end"] == "\n</parameter>\n"
+ # ``status`` and ``mood`` are optional: each may be skipped.
+ assert [element["type"] for element in elements[1:]] == ["or", "or"]
+ assert elements[1]["elements"][1] == {"type": "const_string", "value": ""}
+ assert tag["end"] == "</function>\n</tool_call>"
+
+
+def test_qwen_xml_value_rules_per_type() -> None:
+ contents = _parameter_contents(_tags(build_strict_tool_grammar([_tool("lookup", LOOKUP)], "auto", "qwen_xml"))[0])
+ # Nullable array, object behind ``$ref`` and the bounded integer are JSON.
+ assert contents["keywords"]["type"] == "json_schema"
+ assert contents["spec"]["type"] == "json_schema"
+ assert contents["spec"]["json_schema"]["$defs"] == LOOKUP["$defs"]
+ assert contents["limit"]["json_schema"]["anyOf"][0] == {"type": "integer", "minimum": 1, "maximum": 100}
+ assert contents["eligible"]["type"] == "json_schema"
+ assert contents["explicit"] == {"type": "json_schema", "json_schema": {"type": "boolean"}}
+ # Strings stay raw text; a string enum behind ``$ref`` is an alternation.
+ assert contents["note"] == {"type": "any_text", "excludes": ["</parameter>", "</tool_call>"]}
+ assert contents["kind"] == {"type": "regex", "pattern": "(?:metric|fact|label|null)"}
+
+
+def test_enum_values_are_regex_escaped() -> None:
+ schema = {"type": "object", "properties": {"op": {"enum": ["a.b", "c|d", "(x)"]}}, "required": ["op"]}
+ contents = _parameter_contents(_tags(build_strict_tool_grammar([_tool("f", schema)], "required", "qwen_xml"))[0])
+ assert contents["op"]["pattern"] == r"(?:a\.b|c\|d|\(x\))"
+
+
+def test_tool_without_parameters_admits_empty_call() -> None:
+ tag = _tags(build_strict_tool_grammar([_tool("ping", None)], "required", "qwen_xml"))[0]
+ assert tag["content"] == {"type": "const_string", "value": ""}
+
+
+def test_non_strict_tool_keeps_free_arguments() -> None:
+ tools = [_tool("search", SEARCH), _tool("free", {"type": "object"}, strict=False)]
+ tags = _tags(build_strict_tool_grammar(tools, "auto", "qwen_xml"))
+ assert tags[1]["content"] == {"type": "any_text", "excludes": ["<tool_call>", "</tool_call>"]}
+
+
+def test_hermes_json_constrains_arguments_by_schema() -> None:
+ tag = _tags(build_strict_tool_grammar([_tool("search", SEARCH)], "required", "hermes_json"))[0]
+ assert tag["begin"] == '<tool_call>\n{"name": "search", "arguments": '
+ assert tag["content"] == {"type": "json_schema", "json_schema": SEARCH}
+ assert tag["end"] == "}\n</tool_call>"
+
+
+def test_hermes_json_closes_an_open_strict_arguments_object() -> None:
+ open_schema = {**SEARCH, "additionalProperties": True}
+ tag = _tags(build_strict_tool_grammar([_tool("search", open_schema)], "required", "hermes_json"))[0]
+ assert tag["content"]["json_schema"]["additionalProperties"] is False
+ assert open_schema["additionalProperties"] is True # the request's schema is not mutated
+
+
+def test_parser_rejects_a_call_cut_inside_a_value() -> None:
+ """A ``</tool_call>`` inside a JSON string ends the block early.
+
+ When a ``</parameter>`` sits inside the cut string, taking it as the
+ value's end would report a wrong value, so the call fails. Without one the
+ scan stops as for any unclosed parameter, and the end-of-turn schema check
+ covers strict calls.
+ """
+ tools = [_tool("f", {"type": "object", "properties": {"tags": {"type": "array", "items": {"type": "string"}}}})]
+ schemas = tool_parameter_schemas(tools)
+ with pytest.raises(ValueError, match="cut inside a JSON string"):
+ parse_xml_tool_call('<function=f>\n<parameter=tags>\n["a</parameter>b', schemas)
+ assert parse_xml_tool_call('<function=f>\n<parameter=tags>\n["a', schemas) == ("f", {})
+
+
[email protected]("kind", ["dict", "list[str]"])
+def test_parser_reads_closing_tags_inside_json_for_container_type_names(kind: str) -> None:
+ value = '{"k": "a</parameter>b"}' if kind == "dict" else '["a</parameter>b"]'
+ tools = [_tool("f", {"type": "object", "properties": {"x": {"type": kind}}}, strict=False)]
+ body = f"<function=f>\n<parameter=x>\n{value}\n</parameter>\n</function>"
+ _, arguments = parse_xml_tool_call(body, tool_parameter_schemas(tools))
+ assert arguments["x"] == orjson.loads(value)
+
+
+def test_structural_tag_serializes() -> None:
+ spec = build_strict_tool_grammar(TOOLS, "auto", "qwen_xml")
+ assert spec is not None
+ assert orjson.loads(orjson.dumps(spec.value)) == spec.value
+
+
+def test_non_strict_requests_keep_the_forcing_regex() -> None:
+ spec = build_tool_choice_grammar([_tool("search", SEARCH, strict=False)], "required", "qwen_xml")
+ assert spec is not None
+ assert spec.kind == "regex"
+
+
+# -- what the grammar cannot express is constrained less, not refused -----------
+#
+# The end-of-turn validation guarantees a strict call on every format, so these
+# requests run; only a tool that cannot be validated is refused.
+
+_RAW_TEXT = {"type": "any_text", "excludes": ["</parameter>", "</tool_call>"]}
+_FREE_BODY = {"type": "any_text", "excludes": ["<tool_call>", "</tool_call>"]}
+
+
[email protected]("fmt", ["glm_xml", "muse_atem", "gemma4"])
+def test_format_without_a_structural_tag_keeps_the_non_strict_grammar(fmt: Any) -> None:
+ assert build_strict_tool_grammar(TOOLS, "auto", fmt) is None
+ forced = build_strict_tool_grammar(TOOLS, "required", fmt)
+ assert forced is not None
+ assert forced.kind == "regex"
+ assert forced == build_tool_choice_grammar(tuple(TOOLS), "required", fmt)
+
+
+def test_unresolved_format_keeps_the_non_strict_behaviour() -> None:
+ assert build_strict_tool_grammar(TOOLS, "auto", "auto") is None
+ with pytest.raises(ToolChoiceError):
+ build_strict_tool_grammar(TOOLS, "required", "auto")
+
+
+ "schema",
+ [
+ {"anyOf": [{"type": "integer"}, {"type": "string"}]},
+ {"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}}]},
+ {"anyOf": [{"type": "integer"}, {"type": "object"}]},
+ {"anyOf": [{"type": "integer"}, {"const": True}]},
+ {"enum": ["a", 1]},
+ {"$ref": "#/$defs/missing"},
+ {"type": "uuid"},
+ {"type": "string", "enum": ["a</parameter>b"]},
+ {"type": "string", "enum": ["a</tool_call>b"]},
+ {"type": ["string", "null"], "enum": ["null"]},
+ {"anyOf": [{"type": "string", "enum": ["NULL"]}, {"type": "null"}]},
+ ],
+)
+def test_parameter_the_layout_cannot_constrain_is_free_text(schema: dict[str, Any]) -> None:
+ parameters = {
+ "type": "object",
+ "properties": {"value": schema, "exact": {"type": "boolean"}},
+ "required": ["value", "exact"],
+ }
+ contents = _parameter_contents(_tags(build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml"))[0])
+ assert contents["value"] == _RAW_TEXT
+ assert contents["exact"] == {"type": "json_schema", "json_schema": {"type": "boolean"}}
+
+
+ "schema",
+ [
+ {"type": "string", "const": 1},
+ {"type": "string", "enum": ["a"], "const": "b"},
+ {"type": "string", "enum": ["x", None]},
+ {"type": "integer", "enum": [1, "a"]},
+ {"$ref": "#/properties/other"},
+ {"type": "array", "items": {"$ref": "#/$defs/T~1"}},
+ {"const": True, "enum": [1]},
+ {"const": [True], "enum": [[1]]},
+ {"type": "string", "enum": ["a<think>b"]},
+ {"type": "array", "items": {"const": "</think>"}},
+ {"anyOf": [{"type": "string", "enum": ["x"]}, {"type": "null", "enum": ["x"]}]},
+ ],
+)
[email protected]("fmt", ["qwen_xml", "hermes_json"])
+def test_tool_the_grammar_would_misconstrain_keeps_a_free_body(schema: dict[str, Any], fmt: Any) -> None:
+ parameters = {"type": "object", "properties": {"value": schema}, "required": ["value"]}
+ tags = _tags(build_strict_tool_grammar([_tool("f", parameters), _tool("search", SEARCH)], "auto", fmt))
+ free = build_strict_tool_grammar([_tool("f", parameters, strict=False)], "auto", fmt)
+ assert tags[0] == _tags(free)[0]
+ assert tags[1]["content"] != tags[0]["content"]
+
+
+def test_parameters_the_verifier_cannot_evaluate_are_rejected() -> None:
+ parameters = {"type": "object", "properties": {"a": {}}, "unevaluatedProperties": False}
+ for fmt in ("qwen_xml", "hermes_json", "glm_xml", "gemma4", "auto"):
+ with pytest.raises(StrictToolError, match="'unevaluatedProperties'") as excinfo:
+ build_strict_tool_grammar([_tool("search", SEARCH), _tool("f", parameters)], "auto", fmt)
+ assert excinfo.value.param == "tools[1].function.parameters"
+
+
+# Keywords XGrammar 0.1.32 compiles without enforcing. They are accepted: the
+# grammar still constrains what it can, and every call's arguments are checked
+# against the full schema when the turn ends (``enforce_strict_tool_arguments``).
+_LOOSENED_BY_THE_BACKEND = [
+ {"type": "string", "pattern": "^a+$"},
+ {"type": "string", "format": "date"},
+ {"type": "string", "maxLength": 3},
+ {"type": "integer", "enum": [1, 2], "minimum": 2},
+ {"type": "string", "const": "abc", "maxLength": 1},
+ {"type": "integer", "minimum": 10, "exclusiveMinimum": 0},
+ {"type": "number", "exclusiveMinimum": 0, "maximum": 1},
+ {"type": "array", "items": {"type": "string", "pattern": "^a+$", "maxLength": 1}},
+ {"type": "array", "items": {"minimum": 10}},
+ {"type": "array", "items": {"type": "string", "format": "date", "pattern": "^2025-"}},
+ {"type": "integer", "multipleOf": 2},
+ {"type": "array", "items": {"type": "integer"}, "uniqueItems": True},
+ {"type": "array", "items": {"type": "integer"}, "contains": {"const": 5}},
+ {"type": "object", "properties": {"a": {"type": "integer"}}, "not": {"required": ["a"]}},
+ {"type": "object", "properties": {"a": {"type": "integer"}}, "dependentRequired": {"a": ["a"]}},
+ {"type": "object", "if": {"required": ["a"]}, "then": {"required": ["b"]}},
+ {"type": "array", "items": {"oneOf": [{"enum": [1, 2]}, {"enum": [2, 3]}]}},
+ {"type": "array", "items": {"$ref": "#/$defs/I", "maximum": 3}},
+ {"anyOf": [{"type": "integer"}, {"type": "null"}], "maximum": 3},
+ {"$ref": "#/$defs/I", "maximum": 3},
+]
+
+
[email protected]("schema", _LOOSENED_BY_THE_BACKEND)
[email protected]("fmt", ["qwen_xml", "hermes_json"])
+def test_keywords_the_backend_loosens_are_accepted(schema: dict[str, Any], fmt: Any) -> None:
+ parameters = {
+ "type": "object",
+ "$defs": {"S": {"type": "string"}, "I": {"type": "integer"}},
+ "properties": {"value": schema},
+ "required": ["value"],
+ }
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", fmt) is not None
+
+
+def test_annotations_beside_a_reference_or_union_are_allowed() -> None:
+ parameters = {
+ "type": "object",
+ "$defs": {"S": {"type": "string"}},
+ "properties": {
+ "a": {"$ref": "#/$defs/S", "description": "a string"},
+ "b": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": None, "title": "B"},
+ },
+ "required": ["a", "b"],
+ }
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml") is not None
+
+
+def test_scalar_check_over_shared_references_is_not_exponential() -> None:
+ defs: dict[str, Any] = {"A0": {"type": "integer"}}
+ for level in range(1, 9):
+ defs[f"A{level}"] = {"anyOf": [{"$ref": f"#/$defs/A{level - 1}"}] * 20}
+ parameters = {"type": "object", "$defs": defs, "properties": {"n": {"$ref": "#/$defs/A8"}}, "required": ["n"]}
+ contents = _parameter_contents(_tags(build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml"))[0])
+ assert contents["n"]["type"] == "json_schema"
+
+
+def test_keyword_names_used_as_property_names_are_not_rejected() -> None:
+ parameters = {
+ "type": "object",
+ "properties": {"not": {"type": "string"}, "contains": {"type": "string", "enum": ["oneOf"]}},
+ "required": ["not", "contains"],
+ }
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml") is not None
+
+
+ ("schema", "pattern"),
+ [
+ ({"type": "string", "enum": ["a", "b"], "const": "a"}, "(?:a)"),
+ ({"type": ["string", "null"], "enum": ["x"]}, "(?:x)"),
+ ({"type": ["string", "null"], "enum": ["x", None]}, "(?:x|null)"),
+ ({"anyOf": [{"type": "string", "enum": ["x"]}, {"type": "null"}]}, "(?:x|null)"),
+ ({"anyOf": [{"type": "string", "enum": ["x"]}, {"type": "null", "enum": [None]}]}, "(?:x|null)"),
+ ({"type": ["null"]}, "(?:null)"),
+ # Without null in the schema the parser keeps the text ``null`` as a string.
+ ({"type": "string", "enum": ["null"]}, "(?:null)"),
+ ],
+)
+def test_string_choices_honour_enum_const_and_null(schema: dict[str, Any], pattern: str) -> None:
+ parameters = {"type": "object", "properties": {"value": schema}, "required": ["value"]}
+ contents = _parameter_contents(_tags(build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml"))[0])
+ assert contents["value"] == {"type": "regex", "pattern": pattern}
+
+
+ "parameters",
+ [
+ {"anyOf": [{"type": "object"}]},
+ {"type": "object", "patternProperties": {"^x": {"type": "string"}}},
+ {"type": "object", "properties": {}, "required": ["missing"]},
+ {"type": "object", "properties": {"bad name": {"type": "string"}, "a<b": {"type": "string"}}},
+ {"type": "object", "properties": {"x": {"type": "string"}}, "required": ["x"], "const": {"x": "a"}},
+ {"type": "object", "properties": {"x": {"type": "string"}}, "required": ["x"], "enum": [{"x": "a"}]},
+ {"type": "object", "properties": {f"p{index}": {"type": "string"} for index in range(MAX_XML_PARAMS + 1)}},
+ {
+ "$ref": "#/$defs/Args",
+ "$defs": {"Args": {"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]}},
+ },
+ ],
+)
+def test_parameters_object_the_xml_layout_cannot_write_keeps_a_free_body(parameters: dict[str, Any]) -> None:
+ tag = _tags(build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml"))[0]
+ assert tag["content"] == _FREE_BODY
+
+
[email protected]("fmt", ["qwen_xml", "hermes_json", "glm_xml", "gemma4"])
+def test_parameters_must_describe_an_object(fmt: Any) -> None:
+ with pytest.raises(StrictToolError, match="must describe an object"):
+ build_strict_tool_grammar([_tool("f", {"type": "array"})], "auto", fmt)
+
+
+def test_unvalidatable_strict_tool_is_rejected_even_when_not_named() -> None:
+ bad = {"type": "object", "properties": {"d": {}}, "unevaluatedProperties": False}
+ tools = [_tool("search", SEARCH), _tool("bad", bad)]
+ with pytest.raises(StrictToolError):
+ build_strict_tool_grammar(tools, {"type": "function", "function": {"name": "search"}}, "qwen_xml")
+
+
+# -- the parser reads every accepted value back as a conforming argument --------
+
+
+def test_parser_converts_constrained_values_to_schema_types() -> None:
+ schemas = tool_parameter_schemas(TOOLS)
+ body = GOOD_LOOKUP.removeprefix("<tool_call>\n").removesuffix("\n</tool_call>")
+ assert parse_xml_tool_call(body, schemas) == (
+ "lookup",
+ {
+ "keywords": ["revenue"],
+ "kinds": ["metric", "fact"],
+ "limit": 10,
+ "spec": None,
+ "eligible": True,
+ "note": None,
+ "kind": "metric",
+ "explicit": False,
+ },
+ )
+
+
+def test_parser_reads_a_closing_tag_inside_a_json_string() -> None:
+ """A JSON string may contain ``</parameter>``; the value ends where the JSON is complete."""
+ tools = [_tool("f", {"type": "object", "properties": {"tags": {"type": "array", "items": {"type": "string"}}}})]
+ call = _call("f", [("tags", '["a</parameter>b", "c"]')])
+ body = call.removeprefix("<tool_call>\n").removesuffix("\n</tool_call>")
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"tags": ["a</parameter>b", "c"]})
+
+
+def test_parser_keeps_a_closed_malformed_array_value_raw() -> None:
+ """A closed call whose array value is not JSON keeps the raw text instead of failing."""
+ tools = [_tool("f", {"type": "object", "properties": {"tags": {"type": "array"}}}, strict=False)]
+ body = '<function=f>\n<parameter=tags>\n["a, b]\n</parameter>\n</function>'
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"tags": '["a, b]'})
+
+
[email protected]("schema", [{"type": "integer", "exclusiveMinimum": 0}, {"type": "number", "minimum": 0}])
+def test_bounds_the_backend_enforces_are_accepted(schema: dict[str, Any]) -> None:
+ parameters = {"type": "object", "properties": {"value": schema}, "required": ["value"]}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json") is not None
+
+
+def test_parser_reads_a_typeless_null_const_as_json_null() -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"x": {"const": None}}, "required": ["x"]})]
+ contents = _parameter_contents(_tags(build_strict_tool_grammar(tools, "auto", "qwen_xml"))[0])
+ assert contents["x"] == {"type": "regex", "pattern": "(?:null)"}
+ body = "<function=f>\n<parameter=x>\nnull\n</parameter>\n</function>"
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"x": None})
+
+
+ ("payload", "fmt"),
+ [
+ ('{"name": "f", "arguments": {"x": 1e999}}', "hermes_json"),
+ ("<function=f>\n<parameter=xs>\n[1e999]\n</parameter>\n</function>", "qwen_xml"),
+ ],
+)
+def test_an_overflowing_number_fails_the_call_instead_of_emitting_infinity(payload: str, fmt: Any) -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"x": {"type": "number"}, "xs": {"type": "array"}}})]
+ with pytest.raises(ValueError, match="not JSON-serialisable"):
+ _tool_call_deltas(payload, 0, fmt, tool_parameter_schemas(tools))
+
+
[email protected](("value", "accepted"), [(1, True), (1.0, True), (1.5, False), (True, False)])
+def test_integer_listed_values_follow_json_schema_equality(value: Any, accepted: bool) -> None:
+ parameters = {"type": "object", "properties": {"x": {"type": "integer", "const": value}}, "required": ["x"]}
+ content = _tags(build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json"))[0]["content"]
+ # A listed value outside its ``type`` leaves the arguments to validation.
+ constrained = content["json_schema"] != {"type": "object", "additionalProperties": True}
+ assert constrained is accepted
+
+
[email protected]("fmt", ["hermes_json", "glm_xml"])
+def test_duplicate_function_names_are_rejected(fmt: Any) -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"x": {"type": "integer"}}}), _tool("f", None, strict=False)]
+ with pytest.raises(StrictToolError, match="unique"):
+ build_strict_tool_grammar(tools, "auto", fmt)
+
+
+def _box(kind: str, description: str = "") -> dict[str, Any]:
+ field: dict[str, Any] = {"type": kind}
+ if description:
+ field["description"] = description
+ return {"type": "object", "properties": {"description": field}, "required": ["description"]}
+
+
+def test_subschemas_the_backend_cache_would_conflate_drop_the_structural_tag() -> None:
+ """XGrammar's cache key drops property names such as ``description``, so these two would share one grammar."""
+ parameters = {"type": "object", "properties": {"a": _box("integer"), "b": _box("string")}, "required": ["a", "b"]}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json") is None
+ forced = build_strict_tool_grammar([_tool("f", parameters)], "required", "hermes_json")
+ assert forced is not None
+ assert forced.kind == "regex"
+
+
+def test_subschemas_differing_only_in_annotations_are_accepted() -> None:
+ parameters = {
+ "type": "object",
+ "properties": {"a": _box("integer", "first"), "b": _box("integer", "second"), "c": _box("string")},
+ "required": ["a", "b", "c"],
+ }
+ parameters["properties"]["c"] = {"type": "object", "properties": {"description": {"type": "string"}, "x": {}}}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json") is not None
+
+
+def test_a_single_property_named_description_is_accepted() -> None:
+ parameters = {"type": "object", "properties": {"description": {"type": "string"}}, "required": ["description"]}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json") is not None
+
+
[email protected](("text", "expected"), [("1.5", 1.5), ("2", 2)])
+def test_parser_keeps_finite_numbers(text: str, expected: float) -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"x": {"type": "number"}}, "required": ["x"]})]
+ body = f"<function=f>\n<parameter=x>\n{text}\n</parameter>\n</function>"
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"x": expected})
+
+
+def test_parser_reads_many_closing_tags_inside_a_json_string() -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"tags": {"type": "array", "items": {"type": "string"}}}})]
+ tag = "</parameter>" * 40
+ call = _call("f", [("tags", orjson.dumps([tag, "c"]).decode()), ("tail", "x")])
+ body = call.removeprefix("<tool_call>\n").removesuffix("\n</tool_call>")
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"tags": [tag, "c"], "tail": "x"})
+
+
+def test_values_resolve_references_against_the_tool_definitions() -> None:
+ """A parameter's own ``$defs`` cannot shadow the tool's: ``#`` is the tool's parameters object."""
+ parameters = {
+ "type": "object",
+ "$defs": {"Base": {"type": "integer"}},
+ "properties": {
+ "box": {
+ "type": "object",
+ "$defs": {"Base": {"type": "string"}},
+ "properties": {"copy": {"$ref": "#/$defs/Base"}},
+ "required": ["copy"],
+ }
+ },
+ "required": ["box"],
+ }
+ contents = _parameter_contents(_tags(build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml"))[0])
+ assert contents["box"]["json_schema"]["$defs"] == {"Base": {"type": "integer"}}
+
+
+ "schema",
+ [{"const": 1, "enum": [1.0]}, {"type": "array", "const": [1, {"a": 2}], "enum": [[1.0, {"a": 2.0}]]}],
+)
+def test_const_numerically_equal_to_an_enum_value_is_accepted(schema: dict[str, Any]) -> None:
+ parameters = {"type": "object", "properties": {"value": schema}, "required": ["value"]}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "qwen_xml") is not None
+
+
+# -- acceptance with the real backend -------------------------------------------
+
+
[email protected](scope="module")
+def xgr() -> Any:
+ return pytest.importorskip("xgrammar")
+
+
+def _accepts(xgr: Any, spec: Any, text: str) -> bool:
+ from xgrammar.testing import _is_grammar_accept_string
+
+ grammar = xgr.Grammar.from_structural_tag(orjson.dumps(spec.value).decode())
+ return bool(_is_grammar_accept_string(grammar, text))
+
+
[email protected]("choice", ["auto", "required"])
[email protected]("text", [GOOD_SEARCH, GOOD_LOOKUP, GOOD_ANSWER])
+def test_backend_accepts_conforming_calls(xgr: Any, choice: str, text: str) -> None:
+ assert _accepts(xgr, build_strict_tool_grammar(TOOLS, choice, "qwen_xml"), text)
+
+
+ "text",
+ [
+ pytest.param(BAD_SEARCH, id="probe-violation"),
+ pytest.param(GOOD_SEARCH.replace("<parameter=limit>\n5\n</parameter>\n", ""), id="missing-required"),
+ pytest.param(GOOD_SEARCH.replace("</function>", "<parameter=extra>\nx\n</parameter>\n</function>"), id="extra"),
+ pytest.param(GOOD_LOOKUP.replace("\n10\n", "\n500\n"), id="integer-above-maximum"),
+ pytest.param(GOOD_LOOKUP.replace("\nmetric\n", "\nmeasure\n"), id="enum-outside-ref"),
+ pytest.param(GOOD_LOOKUP.replace('["metric", "fact"]', '["dashboard"]'), id="array-item-enum"),
+ pytest.param(GOOD_ANSWER.replace('{"chart_ref": "c1"}', '{"nope": 1}'), id="union-without-match"),
+ pytest.param(GOOD_ANSWER.replace("\nfinal\n", "\ndone\n"), id="string-enum"),
+ pytest.param(
+ GOOD_LOOKUP.replace("<parameter=note>\nnull\n", "<parameter=note>\na</parameter>b\n"),
+ id="closing-tag-in-raw-string",
+ ),
+ pytest.param(
+ GOOD_LOOKUP.replace("<parameter=note>\nnull\n", "<parameter=note>\na</tool_call>b\n"),
+ id="call-closing-tag-in-raw-string",
+ ),
+ ],
+)
[email protected]("choice", ["auto", "required"])
+def test_backend_rejects_violating_calls(xgr: Any, choice: str, text: str) -> None:
+ assert not _accepts(xgr, build_strict_tool_grammar(TOOLS, choice, "qwen_xml"), text)
+
+
+def test_backend_and_parser_round_trip_a_closing_tag_inside_a_json_string(xgr: Any) -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"tags": {"type": "array", "items": {"type": "string"}}}})]
+ call = _call("f", [("tags", '["a</parameter>b"]')])
+ assert _accepts(xgr, build_strict_tool_grammar(tools, "required", "qwen_xml"), call)
+ body = call.removeprefix("<tool_call>\n").removesuffix("\n</tool_call>")
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"tags": ["a</parameter>b"]})
+
+
+def test_backend_and_parser_round_trip_many_closing_tags_inside_a_json_string(xgr: Any) -> None:
+ tools = [_tool("f", {"type": "object", "properties": {"tags": {"type": "array", "items": {"type": "string"}}}})]
+ tags = ["</parameter>" * 20]
+ call = _call("f", [("tags", orjson.dumps(tags).decode())])
+ assert _accepts(xgr, build_strict_tool_grammar(tools, "required", "qwen_xml"), call)
+ body = call.removeprefix("<tool_call>\n").removesuffix("\n</tool_call>")
+ assert parse_xml_tool_call(body, tool_parameter_schemas(tools)) == ("f", {"tags": tags})
+
+
+def test_backend_resolves_references_against_the_tool_definitions(xgr: Any) -> None:
+ parameters = {
+ "type": "object",
+ "$defs": {"Base": {"type": "integer"}},
+ "properties": {
+ "box": {
+ "type": "object",
+ "$defs": {"Base": {"type": "string"}},
+ "properties": {"copy": {"$ref": "#/$defs/Base"}},
+ "required": ["copy"],
+ }
+ },
+ "required": ["box"],
+ }
+ spec = build_strict_tool_grammar([_tool("f", parameters)], "required", "qwen_xml")
+ assert _accepts(xgr, spec, _call("f", [("box", '{"copy": 1}')]))
+ assert not _accepts(xgr, spec, _call("f", [("box", '{"copy": "bad"}')]))
+
+
[email protected]("schema", _LOOSENED_BY_THE_BACKEND)
[email protected]("fmt", ["qwen_xml", "hermes_json"])
+def test_backend_compiles_schemas_it_only_loosens(xgr: Any, schema: dict[str, Any], fmt: Any) -> None:
+ parameters = {
+ "type": "object",
+ "$defs": {"S": {"type": "string"}, "I": {"type": "integer"}},
+ "properties": {"value": schema},
+ "required": ["value"],
+ }
+ spec = build_strict_tool_grammar([_tool("f", parameters)], "required", fmt)
+ assert not _accepts(xgr, spec, "plain text")
+
+
+def test_backend_auto_admits_text_and_required_does_not(xgr: Any) -> None:
+ assert _accepts(xgr, build_strict_tool_grammar(TOOLS, "auto", "qwen_xml"), "The answer is 42.")
+ assert not _accepts(xgr, build_strict_tool_grammar(TOOLS, "required", "qwen_xml"), "The answer is 42.")
+
+
+def test_backend_required_admits_parallel_calls_and_a_leading_newline(xgr: Any) -> None:
+ spec = build_strict_tool_grammar(TOOLS, "required", "qwen_xml")
+ assert _accepts(xgr, spec, "\n" + GOOD_SEARCH + "\n" + GOOD_ANSWER)
+ single = build_strict_tool_grammar(TOOLS, "required", "qwen_xml", parallel_tool_calls=False)
+ assert not _accepts(xgr, single, GOOD_SEARCH + "\n" + GOOD_ANSWER)
+
+
+def test_const_equal_to_an_enum_value_is_accepted() -> None:
+ parameters = {"type": "object", "properties": {"flag": {"const": True, "enum": [True]}}, "required": ["flag"]}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json") is not None
+
+
+def test_backend_non_strict_body_cannot_smuggle_a_strict_call(xgr: Any) -> None:
+ """A free body may not close its call and open a strict one that skips required arguments."""
+ tools = [_tool("free", {"type": "object"}, strict=False), _tool("lookup", LOOKUP)]
+ missing_limit = _call("lookup", [(key, value) for key, value in LOOKUP_VALUES.items() if key != "limit"])
+ smuggled = "<tool_call>\n<function=free>\nx\n</tool_call>\n" + missing_limit + "\n</function>\n</tool_call>"
+ spec = build_strict_tool_grammar(tools, "auto", "qwen_xml")
+ assert not _accepts(xgr, spec, smuggled)
+ assert _accepts(
+ xgr, spec, "<tool_call>\n<function=free>\n<parameter=q>\nx\n</parameter>\n</function>\n</tool_call>"
+ )
+
+
+def test_backend_named_rejects_other_tools(xgr: Any) -> None:
+ spec = build_strict_tool_grammar(TOOLS, {"type": "function", "function": {"name": "final_answer"}}, "qwen_xml")
+ assert _accepts(xgr, spec, GOOD_ANSWER)
+ assert not _accepts(xgr, spec, GOOD_SEARCH)
+
+
+def test_backend_accepts_omitted_optional_parameters(xgr: Any) -> None:
+ spec = build_strict_tool_grammar(TOOLS, "required", "qwen_xml")
+ assert _accepts(xgr, spec, _call("final_answer", [("parts", "[]")]))
+ assert _accepts(xgr, spec, _call("final_answer", [("parts", "[]"), ("mood", "neutral")]))
+ assert _accepts(xgr, build_strict_tool_grammar([_tool("ping", None)], "required", "qwen_xml"), _call("ping", []))
+
+
+def test_backend_hermes_non_strict_tool_keeps_free_arguments(xgr: Any) -> None:
+ tools = [_tool("search", SEARCH), _tool("free", {"type": "object"}, strict=False)]
+ spec = build_strict_tool_grammar(tools, "auto", "hermes_json")
+ free_call = '<tool_call>\n{"name": "free", "arguments": {"query": "x", "n": 2}}\n</tool_call>'
+ assert _accepts(xgr, spec, free_call)
+
+
+def test_hermes_strict_parameters_must_describe_an_object() -> None:
+ with pytest.raises(StrictToolError, match="must describe an object"):
+ build_strict_tool_grammar([_tool("f", {"type": "array"})], "auto", "hermes_json")
+
+
+def test_hermes_compiles_the_whole_arguments_schema_without_xml_layout_limits() -> None:
+ """Hermes compiles the arguments object as one JSON schema, so a root union is allowed (and validated)."""
+ parameters = {"anyOf": [{"type": "object", "properties": {"a": {"type": "integer"}}}]}
+ assert build_strict_tool_grammar([_tool("f", parameters)], "auto", "hermes_json") is not None
+
+
+def test_backend_hermes_json(xgr: Any) -> None:
+ spec = build_strict_tool_grammar(TOOLS, "required", "hermes_json")
+ good = '{"keywords": ["a"], "exact": true, "filter": {"measures": []}, "limit": 1}'
+ bad = '{"keywords": ["a"], "exact": "yes", "filter": "x"}'
+ assert _accepts(xgr, spec, '<tool_call>\n{"name": "search", "arguments": ' + good + "}\n</tool_call>")
+ assert not _accepts(xgr, spec, '<tool_call>\n{"name": "search", "arguments": ' + bad + "}\n</tool_call>")
+
+
+def test_backend_constrains_the_siblings_of_a_free_text_parameter(xgr: Any) -> None:
+ parameters = {
+ "type": "object",
+ "properties": {"id": {"anyOf": [{"type": "integer"}, {"type": "string"}]}, "exact": {"type": "boolean"}},
+ "required": ["id", "exact"],
+ }
+ spec = build_strict_tool_grammar([_tool("f", parameters)], "required", "qwen_xml")
+ assert _accepts(xgr, spec, _call("f", [("id", "abc"), ("exact", "true")]))
+ assert _accepts(xgr, spec, _call("f", [("id", "7"), ("exact", "false")]))
+ assert not _accepts(xgr, spec, _call("f", [("id", "abc"), ("exact", "yes")]))
+ assert not _accepts(xgr, spec, _call("f", [("exact", "true")]))
+
+
[email protected]("fmt", ["qwen_xml", "hermes_json"])
+def test_backend_constrains_the_other_tools_beside_a_free_body(xgr: Any, fmt: Any) -> None:
+ recursive = {"type": "object", "properties": {"child": {"$ref": "#"}}}
+ spec = build_strict_tool_grammar([_tool("tree", recursive), _tool("search", SEARCH)], "required", fmt)
+ if fmt == "qwen_xml":
+ free, good, bad = _call("tree", [("child", '{"child": {}}')]), GOOD_SEARCH, BAD_SEARCH
+ else:
+ free = '<tool_call>\n{"name": "tree", "arguments": {"child": {"child": {}}}}\n</tool_call>'
+ arguments = '{"keywords": ["revenue"], "exact": %s, "filter": {"measures": ["revenue"]}, "limit": 5}'
+ good = '<tool_call>\n{"name": "search", "arguments": ' + arguments % "true" + "}\n</tool_call>"
+ bad = '<tool_call>\n{"name": "search", "arguments": ' + arguments % '"yes"' + "}\n</tool_call>"
+ assert _accepts(xgr, spec, free)
+ assert _accepts(xgr, spec, good)
+ assert not _accepts(xgr, spec, bad)
diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.py
index 6da1101a7..f0d750946 100644
--- a/packages/sie_server/tests/processors/test_tool_call_parser.py
+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py
@@ -511,21 +511,21 @@ def test_xml_param_scan_stops_at_unterminated_parameter() -> None:
def test_xml_param_scan_bounds_param_count() -> None:
"""Adversarial buffer with a huge number of openers parses at most
- ``_MAX_XML_PARAMS`` and returns in linear time (no O(n^2) backtracking).
+ ``MAX_XML_PARAMS`` and returns in linear time (no O(n^2) backtracking).
"""
import time
- from sie_server.processors.tool_call_parser import _MAX_XML_PARAMS, _parse_xml_tool_call
+ from sie_server.processors.tool_call_parser import MAX_XML_PARAMS, _parse_xml_tool_call
# Far more params than the cap, each well-formed.
- n = _MAX_XML_PARAMS + 5_000
+ n = MAX_XML_PARAMS + 5_000
body = "".join(f"<parameter=p{i}>\n{i}\n</parameter>" for i in range(n))
raw = "<function=f>" + body + "</function>"
t0 = time.monotonic()
name, args = _parse_xml_tool_call(raw)
elapsed = time.monotonic() - t0
assert name == "f"
- assert len(args) == _MAX_XML_PARAMS
+ assert len(args) == MAX_XML_PARAMS
# Generous ceiling: linear parse of this buffer is milliseconds.
assert elapsed < 2.0
@@ -697,20 +697,20 @@ async def test_glm_xml_misplaced_tags_are_terminal_parse_errors(raw: str, reason
def test_glm_argument_scan_bounds_argument_count() -> None:
import time
- from sie_server.processors.tool_call_parser import _MAX_XML_PARAMS, _parse_glm_tool_call
+ from sie_server.processors.tool_call_parser import MAX_XML_PARAMS, _parse_glm_tool_call
- n = _MAX_XML_PARAMS + 5_000
+ n = MAX_XML_PARAMS + 5_000
raw = "f" + "".join(f"<arg_key>p{i}</arg_key><arg_value>{i}</arg_value>" for i in range(n))
t0 = time.monotonic()
- with pytest.raises(ValueError, match=f"more than {_MAX_XML_PARAMS} arguments"):
+ with pytest.raises(ValueError, match=f"more than {MAX_XML_PARAMS} arguments"):
_parse_glm_tool_call(raw)
elapsed = time.monotonic() - t0
assert elapsed < 2.0
- at_cap = "f" + "".join(f"<arg_key>p{i}</arg_key><arg_value>{i}</arg_value>" for i in range(_MAX_XML_PARAMS))
+ at_cap = "f" + "".join(f"<arg_key>p{i}</arg_key><arg_value>{i}</arg_value>" for i in range(MAX_XML_PARAMS))
name, args = _parse_glm_tool_call(at_cap)
assert name == "f"
- assert len(args) == _MAX_XML_PARAMS
+ assert len(args) == MAX_XML_PARAMS
# ── Per-choice (n>1) streaming (H5) ──────────────────────────────────────
@@ -1013,9 +1013,9 @@ def test_a_definition_first_reached_at_the_depth_limit_is_inferred_again_nearer_
parameter = {combinator: [{"$ref": "#/$defs/C0"}, {"$ref": "#/$defs/Shared"}]}
definitions["Leaf"] = {"type": "integer"}
- assert tool_call_parser._schema_type(parameter, root) == "integer"
+ assert tool_call_parser.schema_conversion_type(parameter, root) == "integer"
definitions["Leaf"] = {"type": "null"}
- assert tool_call_parser._schema_allows_null({"anyOf": parameter[combinator]}, root)
+ assert tool_call_parser.schema_allows_null({"anyOf": parameter[combinator]}, root)
@pytest.mark.asyncio