Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(server): show json_schema response formats to the model (#697)

svonavaf5eac2b644db
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index b1a99f58a..46e861d51 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -519,6 +519,13 @@
"null"
]
},
+ "schema_in_prompt": {
+ "description": "SIE extension. A `json_schema` `response_format` constrains decoding and, as with OpenAI, is also shown to the model: it is appended to the system message as a `# Response Formats` section with the compact schema, unless a message already contains the schema as JSON. `false` leaves the prompt as sent (the grammar still applies). Absent: the serving profile decides (default on).",
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
"seed": {
"description": "Optional signed 64-bit per-request sampling seed. Reproducibility is best effort, not guaranteed, and depends on the active generation backend and deployment configuration. Non-integer or out-of-range values reject with 400 invalid_request.",
"format": "int64",
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 81d9c5d7b..7f129580d 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -6386,6 +6386,11 @@ struct ChatRequestParams {
/// :func:`chat_params_from_json`. ``None`` when the request omits
/// ``response_format``.
grammar: Option<publisher::GrammarSpec>,
+ /// SIE extension ``schema_in_prompt``: ``false`` stops the worker
+ /// from also writing a ``json_schema`` response format into the
+ /// rendered prompt. ``None`` leaves it to the serving profile
+ /// (default on).
+ schema_in_prompt: Option<bool>,
/// OpenAI ``stream`` flag. ``true`` switches the handler to the
/// SSE response branch; ``false`` (default) uses the existing
/// aggregating path. Parsed by :func:`chat_params_from_json`;
@@ -6468,6 +6473,7 @@ impl ChatRequestParams {
min_tokens: self.min_tokens,
chat_template_kwargs: self.chat_template_kwargs,
grammar: self.grammar,
+ schema_in_prompt: self.schema_in_prompt,
routing_key: self.routing_key.clone(),
prompt_cache_key: self.prompt_cache_key.clone(),
tools: self.tools,
@@ -7717,6 +7723,20 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
);
}
};
+ // SIE extension: ``schema_in_prompt: false`` keeps a ``json_schema``
+ // response format out of the rendered prompt (the grammar still
+ // constrains decoding). Absent or ``null`` → the profile decides.
+ let schema_in_prompt = match obj.get("schema_in_prompt") {
+ None | Some(serde_json::Value::Null) => None,
+ Some(serde_json::Value::Bool(b)) => Some(*b),
+ Some(_) => {
+ return bad(
+ "'schema_in_prompt' must be a boolean",
+ Some("schema_in_prompt"),
+ oai_code::INVALID_REQUEST,
+ );
+ }
+ };
// ``tool_choice`` without ``tools`` is meaningless; OpenAI itself
// returns a 400 in that case. We mirror the behaviour so SDKs that
// accidentally send ``tool_choice: "auto"`` on a plain chat call
@@ -7790,6 +7810,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
"prompt_cache_key",
"routing_key",
"response_format",
+ "schema_in_prompt",
"stream",
"tools",
"tool_choice",
@@ -7840,6 +7861,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
routing_key,
prompt_cache_key,
grammar,
+ schema_in_prompt,
stream,
stream_include_usage,
tools,
@@ -13999,6 +14021,9 @@ fn generate_params_from_json(
min_tokens: None,
chat_template_kwargs: None,
grammar,
+ // The native route is a thin wrapper over the caller's prompt: a
+ // grammar constrains decoding but is not written into the prompt.
+ schema_in_prompt: Some(false),
routing_key,
prompt_cache_key,
// OpenAI tool-calling fields are exposed only via the chat
@@ -14428,6 +14453,9 @@ fn generate_params_from_rmpv(
min_tokens: None,
chat_template_kwargs: None,
grammar,
+ // The native route is a thin wrapper over the caller's prompt: a
+ // grammar constrains decoding but is not written into the prompt.
+ schema_in_prompt: Some(false),
routing_key,
prompt_cache_key,
tools: None,
@@ -25205,6 +25233,67 @@ mod tests {
assert_eq!(p.max_new_tokens, 32);
}
+ // ── schema_in_prompt: json_schema response formats shown to the model ──
+
+ #[test]
+ fn test_chat_schema_in_prompt_is_forwarded_and_defaults_to_the_profile() {
+ let mut body = _chat_body_min("m");
+ body["response_format"] = serde_json::json!({
+ "type": "json_schema",
+ "json_schema": {"name": "cvss", "schema": {"type": "object", "properties": {
+ "weakness": {"type": "string", "enum": ["cross-site scripting", "SQL injection"]}
+ }}},
+ });
+ let default = _expect_chat_ok(body.clone()).into_work_params();
+ let generate = default.generate.expect("generate params");
+ assert_eq!(generate.schema_in_prompt, None);
+ assert!(matches!(
+ generate.grammar,
+ Some(publisher::GrammarSpec::JsonSchema { .. })
+ ));
+ let wire = serde_json::to_value(&generate).unwrap();
+ assert!(wire.get("schema_in_prompt").is_none());
+
+ for (value, expected) in [
+ (serde_json::json!(false), Some(false)),
+ (serde_json::json!(true), Some(true)),
+ (serde_json::Value::Null, None),
+ ] {
+ body["schema_in_prompt"] = value;
+ let generate = _expect_chat_ok(body.clone())
+ .into_work_params()
+ .generate
+ .expect("generate params");
+ assert_eq!(generate.schema_in_prompt, expected);
+ }
+ body["schema_in_prompt"] = serde_json::json!(false);
+ let generate = _expect_chat_ok(body).into_work_params().generate.unwrap();
+ let wire = serde_json::to_value(&generate).unwrap();
+ assert_eq!(wire["schema_in_prompt"], serde_json::json!(false));
+ }
+
+ #[tokio::test]
+ async fn test_chat_schema_in_prompt_must_be_a_boolean() {
+ let mut body = _chat_body_min("m");
+ body["schema_in_prompt"] = serde_json::json!("no");
+ let err = _expect_chat_err(body).await;
+ assert_eq!(err["error"]["param"], "schema_in_prompt");
+ assert_eq!(err["error"]["code"], "invalid_request");
+ }
+
+ #[test]
+ fn test_native_generate_keeps_the_grammar_out_of_the_prompt() {
+ let body = serde_json::json!({
+ "prompt": "Pick one.",
+ "max_new_tokens": 8,
+ "grammar": {"json_schema": {"type": "object", "properties": {
+ "label": {"type": "string", "enum": ["a", "b"]}
+ }}},
+ });
+ let params = _expect_generate_ok(&body);
+ assert_eq!(params.schema_in_prompt, Some(false));
+ }
+
// ── chat response_format regex/EBNF + developer role (roadmap 1.7) ──
#[test]
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index f8c92fe91..87f72224c 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -775,6 +775,18 @@ fn patch_chat_request_schema(value: &mut Value) {
"type": ["boolean", "null"],
}),
);
+ properties.insert(
+ "schema_in_prompt".to_string(),
+ json!({
+ "description": "SIE extension. A `json_schema` `response_format` constrains \
+ decoding and, as with OpenAI, is also shown to the model: it is \
+ appended to the system message as a `# Response Formats` section \
+ with the compact schema, unless a message already contains the \
+ schema as JSON. `false` leaves the prompt as sent (the grammar \
+ still applies). Absent: the serving profile decides (default on).",
+ "type": ["boolean", "null"],
+ }),
+ );
// response_format: {type:"text"|"json_object"|"json_schema", json_schema?:{...}}.
properties.insert(
"response_format".to_string(),
@@ -2335,6 +2347,14 @@ pub struct ChatCompletionRequest {
/// competing grammars on one request reject with 400 ``invalid_request``.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response_format: Option<Value>,
+ /// SIE extension. A ``json_schema`` ``response_format`` constrains
+ /// decoding and, as with OpenAI, is also shown to the model: it is
+ /// appended to the system message as a ``# Response Formats`` section
+ /// with the compact schema, unless a message already contains the schema
+ /// as JSON. ``false`` leaves the prompt as sent (the grammar still
+ /// applies). Absent: the serving profile decides (default on).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub schema_in_prompt: Option<bool>,
/// SSE streaming. When ``true``, the response is a stream of
/// ``chat.completion.chunk`` events terminated by ``data: [DONE]``.
/// For ``n > 1``, per-``choice_index`` delta chunks include a per-choice
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 504facae1..5d1392e58 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -433,6 +433,14 @@ pub struct GenerateParams {
/// after all gateway-side safety caps have passed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grammar: Option<GrammarSpec>,
+ /// Whether the worker also writes a ``json_schema`` grammar into the
+ /// chat prompt it renders, so the model reads the schema it must
+ /// follow (OpenAI ``response_format`` semantics). ``None`` leaves it to
+ /// the serving profile (default on); chat sends the caller's
+ /// ``schema_in_prompt``; the native ``/v1/generate`` route sends
+ /// ``Some(false)`` because its caller owns the prompt.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub schema_in_prompt: Option<bool>,
/// Caller-supplied routing affinity hint. Highest-priority input
/// to the HRW key resolution in `crate::routing::key`.
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index b182c4f67..78856291b 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -8,7 +8,9 @@ directly in either the Apple-Silicon or CUDA image.
Apple Silicon and SGLang on CUDA. Chat templating, streaming, tool parsing,
and structured output remain owned by that already-loaded child. The proxy
pins the request to the child's loopback URL and served model identity; a
- client cannot select another upstream. Remote generation profiles use their
+ client cannot select another upstream. A ``json_schema`` response format is
+ also written into the messages the SGLang child renders, as queued
+ generation does (:mod:`sie_server.processors.schema_prompt`). Remote generation profiles use their
adapter's normalized chat methods instead; the operator-configured upstream
owns chat rendering, and the worker retains validation and output policy.
- ``/v1/rerank`` wraps the in-process score adapter in the Cohere/OpenAI rerank
@@ -30,6 +32,7 @@ import logging
import math
import os
from collections.abc import AsyncIterator
+from pathlib import Path
from typing import Annotated, Any, cast
from urllib.parse import urlsplit
@@ -55,6 +58,7 @@ from sie_server.adapters.remote._http import RemoteUpstreamError
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
from sie_server.api.generate import (
_generation_http_exception,
+ _load_native_tokenizer_coalesced,
_validate_logit_bias,
_validate_logprobs,
_validate_schema_shape,
@@ -86,6 +90,15 @@ from sie_server.core.video_frames import (
)
from sie_server.observability.tracing import tracer
from sie_server.processors.remote_chat_prompt import collect_rendered_chat, prepare_rendered_chat
+from sie_server.processors.schema_prompt import (
+ json_schema_response_format,
+ profile_schema_in_prompt,
+ renders_system_role,
+ response_format_section,
+ schema_in_messages,
+ starts_with_system_message,
+ with_response_format,
+)
from sie_server.processors.streaming import _decode_data_uri_image
from sie_server.processors.strict_grammar import (
MODEL_OUTPUT_PARSE_ERROR,
@@ -149,6 +162,7 @@ _CUDA_CHAT_FIELDS = frozenset(
"top_logprobs",
"logit_bias",
"response_format",
+ "schema_in_prompt",
"stream",
"tools",
"tool_choice",
@@ -516,7 +530,7 @@ def _validate_common_chat_body(body: dict[str, Any]) -> None:
isinstance(stop, str) or (isinstance(stop, list) and all(isinstance(value, str) for value in stop))
):
raise _bad_request("'stop' must be a string or array of strings", param="stop")
- for field in ("parallel_tool_calls",):
+ for field in ("parallel_tool_calls", "schema_in_prompt"):
if body.get(field) is not None and not isinstance(body[field], bool):
raise _bad_request(f"'{field}' must be a boolean", param=field)
for field in ("user", "safety_identifier"):
@@ -740,6 +754,7 @@ def _prepare_chat_body(
# SIE owns these edge-only identifiers; do not send unknown metadata into
# the engine process.
proxied.pop("safety_identifier", None)
+ proxied.pop("schema_in_prompt", None)
if proxied.get("parallel_tool_calls") is None:
proxied.pop("parallel_tool_calls", None)
@@ -799,6 +814,50 @@ def _prepare_chat_body(
return proxied
+_SYSTEM_ROLE_RENDERING: dict[tuple[str, str | None], bool] = {}
+
+
+async def _template_renders_system_role(config: Any) -> bool:
+ """Whether the model's chat template keeps a system message (cached per tokenizer)."""
+ hf_id = getattr(config, "hf_id", None)
+ source = hf_id or getattr(config, "weights_path", None)
+ if not isinstance(source, str | Path):
+ return True
+ revision = getattr(config, "hf_revision", None) if hf_id else None
+ key = (str(source), revision if isinstance(revision, str) else None)
+ cached = _SYSTEM_ROLE_RENDERING.get(key)
+ if cached is not None:
+ return cached
+ try:
+ tokenizer = await asyncio.to_thread(_load_native_tokenizer_coalesced, key[0], key[1])
+ except Exception: # noqa: BLE001 - without a local template the child decides
+ logger.info("no local tokenizer to probe the system role of %s; using a system message", key[0])
+ return True
+ supported = await asyncio.to_thread(renders_system_role, tokenizer.apply_chat_template)
+ _SYSTEM_ROLE_RENDERING[key] = supported
+ return supported
+
+
+async def _messages_showing_response_format(body: dict[str, Any], config: Any, messages: list[Any]) -> list[Any]:
+ """Write a ``json_schema`` response format into the messages the child renders.
+
+ The child's grammar backend still constrains decoding; this lets the model
+ read the schema too. ``schema_in_prompt: false`` (request) or
+ ``adapter_options.runtime.schema_in_prompt: false`` (profile) turns it off.
+ """
+ grammar = json_schema_response_format(body.get("response_format"))
+ section = response_format_section(grammar)
+ if section is None or grammar is None or not isinstance(grammar.value, dict):
+ return messages
+ requested = body.get("schema_in_prompt")
+ if requested is False or (requested is None and not profile_schema_in_prompt(config)):
+ return messages
+ if await asyncio.to_thread(schema_in_messages, messages, grammar.value):
+ return messages
+ system_role = starts_with_system_message(messages) or await _template_renders_system_role(config)
+ return with_response_format(messages, section, system_role=system_role)
+
+
def _prepare_sglang_body(
body: dict[str, Any],
*,
@@ -1426,6 +1485,7 @@ async def _chat_completions(
max_tokens=max_tokens,
seed=seed,
)
+ proxied["messages"] = await _messages_showing_response_format(body, config, proxied["messages"])
else:
raise _unsupported_chat(model, device)
diff --git a/packages/sie_server/src/sie_server/processors/schema_prompt.py b/packages/sie_server/src/sie_server/processors/schema_prompt.py
new file mode 100644
index 000000000..b46612921
--- /dev/null
+++ b/packages/sie_server/src/sie_server/processors/schema_prompt.py
@@ -0,0 +1,188 @@
+"""Show a JSON Schema response format to the model, as OpenAI-compatible servers do.
+
+A JSON Schema grammar only constrains decoding. It removes the tokens that would
+break the schema, but the model never reads the schema: field descriptions and
+the options of an ``enum`` stay invisible, and a model that has not been told
+the options tends to pick the first one the grammar allows. OpenAI and
+Anthropic put the schema in the model's context, so OpenAI-compatible callers
+expect the model to see it.
+
+When SIE renders the chat template itself, a ``json_schema`` response format is
+therefore appended to the system message as the ``# Response Formats`` section
+of OpenAI's harmony prompt format (the one gpt-oss models are trained on), with
+the schema as compact JSON::
+
+ <caller's system message>
+
+ # Response Formats
+
+ ## <response_format.json_schema.name>
+
+ {"type":"object","properties":{...}}
+
+The grammar still constrains decoding. Without a system message the section
+becomes one. A chat template that cannot render a system message (it raises,
+or drops the text) gets the section at the start of the first user message
+instead, the way such templates fold a system prompt themselves.
+
+The section is left out when:
+
+* the request opts out (``schema_in_prompt: false``) or the serving profile
+ does (``adapter_options.runtime.schema_in_prompt: false``);
+* a message already contains the schema as JSON. Whitespace is ignored and
+ keys may be in the schema's own or sorted order, so ``json.dumps`` and
+ ``JSON.stringify`` renderings at any indent are found. A schema written any
+ other way (YAML, prose, other key orders, a ``$ref`` the gateway inlined) is
+ not detected; such callers opt out per request;
+* the grammar says nothing beyond "a JSON object" (``json_object`` mode).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any
+
+from sie_server.types.grammar import GrammarSpec
+
+logger = logging.getLogger(__name__)
+
+RESPONSE_FORMATS_HEADING = "# Response Formats"
+SCHEMA_IN_PROMPT_OPTION = "schema_in_prompt"
+
+_DEFAULT_FORMAT_NAME = "response"
+_SYSTEM_ROLES = frozenset({"system", "developer"})
+# The schemas ``response_format: {"type": "json_object"}`` stands for. They
+# carry nothing a model could use beyond "answer with a JSON object".
+_GENERIC_OBJECT_SCHEMAS: tuple[dict[str, Any], ...] = (
+ {"type": "object"},
+ {"type": "object", "additionalProperties": True},
+)
+_SYSTEM_ROLE_PROBE = "sie-system-role-probe-6f1d2c"
+
+
+def response_format_section(grammar: GrammarSpec | None) -> str | None:
+ """Render ``grammar`` as a ``# Response Formats`` prompt section.
+
+ Returns ``None`` for anything other than an informative JSON Schema.
+ """
+ if grammar is None or grammar.kind != "json_schema" or not isinstance(grammar.value, dict):
+ return None
+ if grammar.value in _GENERIC_OBJECT_SCHEMAS:
+ return None
+ name = " ".join((grammar.label or "").split()) or _DEFAULT_FORMAT_NAME
+ schema = json.dumps(grammar.value, ensure_ascii=False, separators=(",", ":"))
+ return f"{RESPONSE_FORMATS_HEADING}\n\n## {name}\n\n{schema}"
+
+
+def _content_text(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "".join(part["text"] for part in content if isinstance(part, dict) and isinstance(part.get("text"), str))
+ return ""
+
+
+def _squash(text: str) -> str:
+ return "".join(text.split())
+
+
+def schema_in_messages(messages: Sequence[Mapping[str, Any]], schema: Mapping[str, Any]) -> bool:
+ """Whether a message's text already contains ``schema`` as JSON.
+
+ Whitespace is ignored on both sides, and the schema is looked for in its
+ own key order and in sorted order, with and without ASCII escaping.
+ """
+ needles = {
+ _squash(json.dumps(schema, ensure_ascii=ascii_only, sort_keys=sort_keys))
+ for ascii_only in (False, True)
+ for sort_keys in (False, True)
+ }
+ for message in messages:
+ text = _squash(_content_text(message.get("content")))
+ if any(needle in text for needle in needles):
+ return True
+ return False
+
+
+def _append_text(content: Any, section: str) -> Any:
+ if isinstance(content, list):
+ separator = "\n\n" if _content_text(content).strip() else ""
+ return [*content, {"type": "text", "text": separator + section}]
+ text = content if isinstance(content, str) else ""
+ return f"{text.rstrip()}\n\n{section}" if text.strip() else section
+
+
+def _prepend_text(content: Any, section: str) -> Any:
+ if isinstance(content, list):
+ return [{"type": "text", "text": f"{section}\n\n"}, *content]
+ text = content if isinstance(content, str) else ""
+ return f"{section}\n\n{text}" if text else section
+
+
+def with_response_format(
+ messages: Sequence[Mapping[str, Any]],
+ section: str,
+ *,
+ system_role: bool,
+) -> list[dict[str, Any]]:
+ """Return a copy of ``messages`` that carries ``section``.
+
+ The section is appended to a leading system (or developer) message, else
+ it becomes a new leading system message. When the template cannot render
+ a system message (``system_role`` false) it opens the first user message
+ instead. The input messages are not modified.
+ """
+ out = [dict(message) for message in messages]
+ if out and out[0].get("role") in _SYSTEM_ROLES:
+ out[0]["content"] = _append_text(out[0].get("content"), section)
+ return out
+ if system_role:
+ return [{"role": "system", "content": section}, *out]
+ for message in out:
+ if message.get("role") == "user":
+ message["content"] = _prepend_text(message.get("content"), section)
+ return out
+ return out
+
+
+def starts_with_system_message(messages: Sequence[Mapping[str, Any]]) -> bool:
+ return bool(messages) and messages[0].get("role") in _SYSTEM_ROLES
+
+
+def renders_system_role(apply_chat_template: Callable[..., Any]) -> bool:
+ """Whether a chat template keeps the text of a leading system message.
+
+ Some templates raise on a system role, others drop it silently; both mean
+ the section has to travel in a user message.
+ """
+ probe = [{"role": "system", "content": _SYSTEM_ROLE_PROBE}, {"role": "user", "content": "Hi"}]
+ try:
+ rendered = apply_chat_template(probe, tokenize=False, add_generation_prompt=True)
+ except Exception: # noqa: BLE001 - a template that cannot render a system message
+ logger.debug("chat template does not render a system role", exc_info=True)
+ return False
+ return isinstance(rendered, str) and _SYSTEM_ROLE_PROBE in rendered
+
+
+def profile_schema_in_prompt(config: Any) -> bool:
+ """The serving profile's default; ``adapter_options.runtime.schema_in_prompt: false`` turns it off."""
+ try:
+ runtime = config.resolve_profile("default").runtime
+ except (AttributeError, KeyError, ValueError):
+ return True
+ if not isinstance(runtime, Mapping):
+ return True
+ return runtime.get(SCHEMA_IN_PROMPT_OPTION) is not False
+
+
+def json_schema_response_format(response_format: Any) -> GrammarSpec | None:
+ """The JSON Schema of an OpenAI ``response_format``, or ``None``."""
+ if not isinstance(response_format, dict) or response_format.get("type") != "json_schema":
+ return None
+ json_schema = response_format.get("json_schema")
+ if not isinstance(json_schema, dict) or not isinstance(json_schema.get("schema"), dict):
+ return None
+ name = json_schema.get("name")
+ return GrammarSpec(kind="json_schema", value=json_schema["schema"], label=name if isinstance(name, str) else None)
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index ad6513224..4c46e9ce4 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -91,6 +91,14 @@ from sie_server.processors.grammar_cache import GrammarLRU
from sie_server.processors.grammar_compile import compile_outlines
from sie_server.processors.hybrid_usage import HybridCount, count_hybrid_usage
from sie_server.processors.remote_chat import remote_chat_chunks
+from sie_server.processors.schema_prompt import (
+ profile_schema_in_prompt,
+ renders_system_role,
+ response_format_section,
+ schema_in_messages,
+ starts_with_system_message,
+ with_response_format,
+)
from sie_server.processors.strict_grammar import enforce_strict_grammar
from sie_server.processors.tool_call_grammar import (
ToolChoiceError,
@@ -766,6 +774,11 @@ class _GenerateRequestParams:
# defaults apply.
chat_template_kwargs: dict[str, Any] | None = None
grammar: GrammarSpec | None = None
+ # Whether a ``json_schema`` grammar is also shown to the model in the
+ # rendered prompt (see :mod:`sie_server.processors.schema_prompt`). The
+ # request's ``schema_in_prompt`` wins over the profile's
+ # ``adapter_options.runtime.schema_in_prompt``; both default to on.
+ schema_in_prompt: bool = True
# OpenAI tools / tool_choice. The gateway has already shape-validated
# the schemas; the worker uses ``tools is not None`` as the flag that
# turns on :func:`parse_tool_call_stream` between the adapter and the
@@ -955,6 +968,10 @@ class StreamingProcessor:
# plain dict lookups (no contention).
self._tokenizers: dict[str, TokenizerLike] = {}
self._tokenizer_lock = asyncio.Lock()
+ # Per-model answer to "does the chat template render a system
+ # message?", probed once when a response format has to be shown to
+ # the model and the request has no system message of its own.
+ self._renders_system_role: dict[str, bool] = {}
# Per-process LRU of validated grammar compiles. The
# default cap (64) is plenty for realistic workloads — schemas
# tend to concentrate on a handful of canonical shapes. Inject
@@ -1998,6 +2015,7 @@ class StreamingProcessor:
params.input.messages,
effective_tools,
request_kwargs=params.chat_template_kwargs,
+ response_format=params.grammar if params.schema_in_prompt else None,
)
if isinstance(rendered, _ValidationError):
await self._terminal_error_then_settle(
@@ -3429,6 +3447,17 @@ class StreamingProcessor:
message="'chat_template_kwargs' must be an object",
)
+ # Whether a ``json_schema`` grammar is also written into the prompt.
+ # An explicit request value wins; otherwise the profile decides.
+ schema_in_prompt_raw = params.get("schema_in_prompt")
+ if schema_in_prompt_raw is not None and not isinstance(schema_in_prompt_raw, bool):
+ return _ValidationError(code="invalid_request", message="'schema_in_prompt' must be a boolean")
+ schema_in_prompt = (
+ schema_in_prompt_raw
+ if schema_in_prompt_raw is not None
+ else (config is None or profile_schema_in_prompt(config))
+ )
+
# OpenAI ``seed`` / ``logit_bias`` / ``logprobs`` / ``top_logprobs``
# round-trips. Gateway is the authority for shape validation
# (signed i64 / range / cap); the worker only coerces defensively.
@@ -3552,6 +3581,7 @@ class StreamingProcessor:
min_tokens=min_tokens,
chat_template_kwargs=chat_template_kwargs,
grammar=grammar,
+ schema_in_prompt=schema_in_prompt,
tools=tools,
tool_choice=tool_choice,
parallel_tool_calls=parallel_tool_calls,
@@ -3636,6 +3666,7 @@ class StreamingProcessor:
messages: tuple[_ChatMessage, ...],
tools: tuple[dict[str, Any], ...] | None = None,
request_kwargs: dict[str, Any] | None = None,
+ response_format: GrammarSpec | None = None,
) -> str | _ValidationError:
"""Render a chat-message list into a prompt string via the tokenizer's
chat template. Returns the rendered string or a validation error
@@ -3655,6 +3686,12 @@ class StreamingProcessor:
reasoning on a one-off basis). The YAML wins on conflict —
operator config is authoritative; per-request overrides only
fill in keys the YAML didn't set.
+
+ ``response_format`` is a ``json_schema`` grammar to show the model:
+ it is written into the system message as a ``# Response Formats``
+ section (see :mod:`sie_server.processors.schema_prompt`) unless a
+ message already contains the schema. ``None`` leaves the messages
+ as sent.
"""
try:
tok = await self._get_tokenizer(model_id)
@@ -3735,24 +3772,34 @@ class StreamingProcessor:
# ``parse_tool_call_stream`` then converts to OpenAI tool_calls.
if tools:
kwargs["tools"] = list(tools)
+ section = response_format_section(response_format)
+ system_role = True
+ if section is not None and not starts_with_system_message(message_dicts):
+ system_role = await self._template_renders_system_role(model_id, tok)
+
+ def _render() -> Any:
+ rendered_messages: list[dict[str, Any]] = message_dicts
+ if (
+ section is not None
+ and isinstance(response_format, GrammarSpec)
+ and isinstance(response_format.value, dict)
+ and not schema_in_messages(message_dicts, response_format.value)
+ ):
+ rendered_messages = with_response_format(message_dicts, section, system_role=system_role)
+ return tok.apply_chat_template(
+ rendered_messages,
+ tokenize=False,
+ add_generation_prompt=True,
+ **kwargs,
+ )
+
try:
# Route through the bounded ``_GRAMMAR_EXECUTOR`` rather than
# the shared default ``asyncio.to_thread`` pool: this call is
# CPU-bound and input-sized, so a burst on the default pool
# could starve the rest of the worker (tokenizer loads, etc.).
- # ``run_in_executor`` takes no kwargs, so bind them in a
- # closure (matching the ``lambda`` style in
- # ``_check_context_length``).
loop = asyncio.get_running_loop()
- rendered = await loop.run_in_executor(
- _GRAMMAR_EXECUTOR,
- lambda: tok.apply_chat_template(
- message_dicts,
- tokenize=False,
- add_generation_prompt=True,
- **kwargs,
- ),
- )
+ rendered = await loop.run_in_executor(_GRAMMAR_EXECUTOR, _render)
except Exception: # noqa: BLE001
logger.warning(
"Chat template render failed for %s",
@@ -3770,6 +3817,16 @@ class StreamingProcessor:
)
return rendered
+ async def _template_renders_system_role(self, model_id: str, tok: TokenizerLike) -> bool:
+ """Probe once per model whether its chat template keeps a system message."""
+ cached = self._renders_system_role.get(model_id)
+ if cached is not None:
+ return cached
+ loop = asyncio.get_running_loop()
+ supported = await loop.run_in_executor(_GRAMMAR_EXECUTOR, renders_system_role, tok.apply_chat_template)
+ self._renders_system_role[model_id] = supported
+ return supported
+
async def _check_request_videos(self, model_id: str, videos: list[VideoInput]) -> _ValidationError | None:
"""Gate video on ``inputs.video`` and bound the runtime's decode work.
diff --git a/packages/sie_server/tests/api/test_openai_local_schema_prompt.py b/packages/sie_server/tests/api/test_openai_local_schema_prompt.py
new file mode 100644
index 000000000..363650318
--- /dev/null
+++ b/packages/sie_server/tests/api/test_openai_local_schema_prompt.py
@@ -0,0 +1,135 @@
+"""The direct ``/v1/chat/completions`` route shows a json_schema response format to the SGLang child's model."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import httpx
+import pytest
+from sie_server.api import openai_local
+
+from .test_openai_local import _chat_completion, _cuda_chat_client
+
+SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {"weakness": {"type": "string", "enum": ["cross-site scripting", "SQL injection", "path traversal"]}},
+ "required": ["weakness"],
+ "additionalProperties": False,
+}
+RESPONSE_FORMAT = {"type": "json_schema", "json_schema": {"name": "cvss", "strict": True, "schema": SCHEMA}}
+SECTION = "# Response Formats\n\n## cvss\n\n" + json.dumps(SCHEMA, separators=(",", ":"))
+
+
+def _forwarded(monkeypatch: pytest.MonkeyPatch, body: dict[str, Any]) -> dict[str, Any]:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, json=_chat_completion('{"weakness": "path traversal"}'))
+
+ client, _ = _cuda_chat_client(monkeypatch, _handler)
+ response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3-0.6B", "max_tokens": 8, **body})
+ assert response.status_code == 200, response.text
+ return seen["body"]
+
+
+def test_schema_is_appended_to_the_system_message(monkeypatch: pytest.MonkeyPatch) -> None:
+ messages = [{"role": "system", "content": "Classify."}, {"role": "user", "content": "../../etc/passwd"}]
+ forwarded = _forwarded(monkeypatch, {"messages": messages, "response_format": RESPONSE_FORMAT})
+ assert forwarded["messages"] == [
+ {"role": "system", "content": "Classify.\n\n" + SECTION},
+ {"role": "user", "content": "../../etc/passwd"},
+ ]
+ assert forwarded["response_format"] == RESPONSE_FORMAT
+ assert "schema_in_prompt" not in forwarded
+
+
+def test_schema_becomes_the_system_message(monkeypatch: pytest.MonkeyPatch) -> None:
+ messages = [{"role": "user", "content": "../../etc/passwd"}]
+ forwarded = _forwarded(monkeypatch, {"messages": messages, "response_format": RESPONSE_FORMAT})
+ assert forwarded["messages"][0] == {"role": "system", "content": SECTION}
+
+
+def test_template_without_system_role_gets_the_schema_in_the_user_turn(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _NoSystemTokenizer:
+ def apply_chat_template(self, messages: list[dict[str, Any]], **_kwargs: Any) -> str:
+ if any(message["role"] == "system" for message in messages):
+ raise ValueError("System role not supported")
+ return "rendered"
+
+ monkeypatch.setattr(openai_local, "_load_native_tokenizer_coalesced", lambda *_a: _NoSystemTokenizer())
+ monkeypatch.setattr(openai_local, "_SYSTEM_ROLE_RENDERING", {})
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, json=_chat_completion('{"weakness": "path traversal"}'))
+
+ client, registry = _cuda_chat_client(monkeypatch, _handler)
+ config = registry.get_config.return_value
+ config.hf_id, config.hf_revision, config.weights_path = "google/gemma-2-2b-it", "abc123", None
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3-0.6B",
+ "max_tokens": 8,
+ "messages": [{"role": "user", "content": "../../etc/passwd"}],
+ "response_format": RESPONSE_FORMAT,
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert seen["body"]["messages"] == [{"role": "user", "content": SECTION + "\n\n../../etc/passwd"}]
+
+
+def test_request_opt_out_forwards_the_messages_as_sent(monkeypatch: pytest.MonkeyPatch) -> None:
+ messages = [{"role": "user", "content": "../../etc/passwd"}]
+ forwarded = _forwarded(
+ monkeypatch, {"messages": messages, "response_format": RESPONSE_FORMAT, "schema_in_prompt": False}
+ )
+ assert forwarded["messages"] == messages
+ assert forwarded["response_format"] == RESPONSE_FORMAT
+ assert "schema_in_prompt" not in forwarded
+
+
+def test_profile_opt_out_forwards_the_messages_as_sent(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, json=_chat_completion('{"weakness": "path traversal"}'))
+
+ client, registry = _cuda_chat_client(monkeypatch, _handler)
+ registry.get_config.return_value.resolve_profile.return_value.runtime["schema_in_prompt"] = False
+ messages = [{"role": "user", "content": "../../etc/passwd"}]
+ body = {"model": "Qwen/Qwen3-0.6B", "max_tokens": 8, "messages": messages, "response_format": RESPONSE_FORMAT}
+ assert client.post("/v1/chat/completions", json=body).status_code == 200
+ assert seen["body"]["messages"] == messages
+
+
+def test_schema_already_in_the_prompt_is_not_repeated(monkeypatch: pytest.MonkeyPatch) -> None:
+ system = "Classify. Answer with JSON matching:\n" + json.dumps(SCHEMA, indent=2)
+ messages = [{"role": "system", "content": system}, {"role": "user", "content": "../../etc/passwd"}]
+ forwarded = _forwarded(monkeypatch, {"messages": messages, "response_format": RESPONSE_FORMAT})
+ assert forwarded["messages"] == messages
+
+
+def test_json_object_mode_is_not_rendered(monkeypatch: pytest.MonkeyPatch) -> None:
+ messages = [{"role": "user", "content": "Reply in JSON"}]
+ forwarded = _forwarded(monkeypatch, {"messages": messages, "response_format": {"type": "json_object"}})
+ assert forwarded["messages"] == messages
+
+
+def test_non_boolean_opt_out_is_refused(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, _ = _cuda_chat_client(monkeypatch, lambda _request: pytest.fail("must not reach the child"))
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3-0.6B",
+ "messages": [{"role": "user", "content": "hi"}],
+ "response_format": RESPONSE_FORMAT,
+ "schema_in_prompt": "no",
+ },
+ )
+ assert response.status_code == 400
+ assert response.json()["error"]["param"] == "schema_in_prompt"
diff --git a/packages/sie_server/tests/processors/test_schema_prompt.py b/packages/sie_server/tests/processors/test_schema_prompt.py
new file mode 100644
index 000000000..58b6874b8
--- /dev/null
+++ b/packages/sie_server/tests/processors/test_schema_prompt.py
@@ -0,0 +1,345 @@
+"""A json_schema response format is shown to the model as well as enforced by the grammar."""
+
+from __future__ import annotations
+
+import json
+from types import MappingProxyType
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from sie_server.processors import streaming as streaming_mod
+from sie_server.processors.schema_prompt import (
+ json_schema_response_format,
+ profile_schema_in_prompt,
+ renders_system_role,
+ response_format_section,
+ schema_in_messages,
+ with_response_format,
+)
+from sie_server.processors.streaming import StreamingProcessor
+from sie_server.types.grammar import GrammarSpec
+
+from .test_streaming import (
+ _decode_chunks,
+ _make_msg,
+ _make_registry_with_chat_config,
+ _make_work_item,
+ _PreflightGenAdapter,
+)
+
+WEAKNESSES = ["cross-site scripting", "SQL injection", "memory corruption", "path traversal"]
+SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "weakness": {"type": "string", "enum": WEAKNESSES},
+ "attack_vector": {"type": "string", "enum": ["network", "adjacent", "local", "physical"]},
+ },
+ "required": ["weakness", "attack_vector"],
+ "additionalProperties": False,
+}
+GRAMMAR = GrammarSpec(kind="json_schema", value=SCHEMA, label="cvss", strict=True)
+_SECTION = response_format_section(GRAMMAR)
+assert _SECTION is not None
+SECTION: str = _SECTION
+
+
+# -- rendering -------------------------------------------------------------------------------------------------
+
+
+def test_section_is_the_response_formats_block_with_compact_schema() -> None:
+ compact = json.dumps(SCHEMA, ensure_ascii=False, separators=(",", ":"))
+ assert compact == SECTION.removeprefix("# Response Formats\n\n## cvss\n\n")
+ assert SECTION.startswith("# Response Formats\n\n## cvss\n\n")
+ for option in WEAKNESSES:
+ assert json.dumps(option) in SECTION
+
+
+def test_section_names_an_unlabelled_format_response() -> None:
+ section = response_format_section(GrammarSpec(kind="json_schema", value=SCHEMA))
+ assert section is not None
+ assert section.startswith("# Response Formats\n\n## response\n\n")
+
+
+ "grammar",
+ [
+ None,
+ GrammarSpec(kind="regex", value="^(yes|no)$"),
+ GrammarSpec(kind="ebnf", value='root ::= "a"'),
+ GrammarSpec(kind="json_schema", value={"type": "object", "additionalProperties": True}, label="json_object"),
+ GrammarSpec(kind="json_schema", value={"type": "object"}),
+ ],
+)
+def test_nothing_to_show_without_an_informative_schema(grammar: GrammarSpec | None) -> None:
+ assert response_format_section(grammar) is None
+
+
+def test_openai_response_format_reads_the_json_schema() -> None:
+ grammar = json_schema_response_format(
+ {"type": "json_schema", "json_schema": {"name": "cvss", "schema": SCHEMA, "strict": True}}
+ )
+ assert grammar == GrammarSpec(kind="json_schema", value=SCHEMA, label="cvss")
+ assert json_schema_response_format({"type": "json_object"}) is None
+ assert json_schema_response_format({"type": "json_schema", "json_schema": {"name": "x"}}) is None
+ assert json_schema_response_format(None) is None
+
+
+# -- placement -------------------------------------------------------------------------------------------------
+
+
+def test_section_is_appended_to_the_system_message() -> None:
+ messages = [{"role": "system", "content": "Score the report."}, {"role": "user", "content": "XSS in IBM Db2"}]
+ out = with_response_format(messages, SECTION, system_role=True)
+ assert out[0] == {"role": "system", "content": "Score the report.\n\n" + SECTION}
+ assert out[1] == messages[1]
+ assert messages[0]["content"] == "Score the report." # input untouched
+
+
+def test_section_is_appended_to_a_developer_message_and_to_text_parts() -> None:
+ messages = [{"role": "developer", "content": [{"type": "text", "text": "Be terse."}]}]
+ out = with_response_format(messages, SECTION, system_role=True)
+ assert out[0]["content"] == [{"type": "text", "text": "Be terse."}, {"type": "text", "text": "\n\n" + SECTION}]
+
+
+def test_section_becomes_the_system_message_when_there_is_none() -> None:
+ messages = [{"role": "user", "content": "XSS in IBM Db2"}]
+ assert with_response_format(messages, SECTION, system_role=True) == [
+ {"role": "system", "content": SECTION},
+ {"role": "user", "content": "XSS in IBM Db2"},
+ ]
+
+
+def test_section_opens_the_first_user_message_without_a_system_role() -> None:
+ messages = [
+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is on screen?"}]},
+ {"role": "assistant", "content": "A form."},
+ {"role": "user", "content": "Extract it."},
+ ]
+ out = with_response_format(messages, SECTION, system_role=False)
+ assert out[0]["content"] == [
+ {"type": "text", "text": SECTION + "\n\n"},
+ {"type": "image"},
+ {"type": "text", "text": "What is on screen?"},
+ ]
+ assert out[1:] == messages[1:]
+ plain = with_response_format([{"role": "user", "content": "Extract it."}], SECTION, system_role=False)
+ assert plain == [{"role": "user", "content": SECTION + "\n\nExtract it."}]
+
+
+# -- the caller already shows the schema ------------------------------------------------------------------------
+
+
+ "rendering",
+ [
+ json.dumps(SCHEMA, indent=2),
+ json.dumps(SCHEMA),
+ json.dumps(SCHEMA, separators=(",", ":")),
+ json.dumps(SCHEMA, indent=4, sort_keys=True),
+ ],
+)
+def test_schema_already_in_the_prompt_is_found(rendering: str) -> None:
+ messages = [{"role": "system", "content": f"Score the report.\n\nJSON schema:\n{rendering}"}]
+ assert schema_in_messages(messages, SCHEMA)
+
+
+def test_schema_in_a_user_text_part_is_found_including_non_ascii() -> None:
+ schema = {"type": "object", "properties": {"größe": {"type": "string", "enum": ["klein", "groß"]}}}
+ for ascii_only in (False, True):
+ text = "Respond with JSON matching this schema:\n" + json.dumps(schema, indent=2, ensure_ascii=ascii_only)
+ messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": text}]}]
+ assert schema_in_messages(messages, schema)
+
+
+def test_a_different_schema_is_not_mistaken_for_this_one() -> None:
+ other = {**SCHEMA, "required": ["weakness"]}
+ messages = [{"role": "system", "content": "JSON schema:\n" + json.dumps(other, indent=2)}]
+ assert not schema_in_messages(messages, SCHEMA)
+ assert not schema_in_messages([{"role": "user", "content": "weakness attack_vector network"}], SCHEMA)
+
+
+# -- templates and profiles --------------------------------------------------------------------------------------
+
+
+def _template(*, system: str) -> Any:
+ def apply_chat_template(messages: list[dict[str, Any]], **_kwargs: Any) -> str:
+ parts = []
+ for message in messages:
+ if message["role"] == "system":
+ if system == "raise":
+ raise ValueError("System role not supported")
+ if system == "drop":
+ continue
+ parts.append(f"<{message['role']}>{message['content']}")
+ return "".join(parts)
+
+ return apply_chat_template
+
+
+def test_system_role_probe() -> None:
+ assert renders_system_role(_template(system="keep"))
+ assert not renders_system_role(_template(system="raise"))
+ assert not renders_system_role(_template(system="drop"))
+
+
+def test_profile_runtime_opt_out() -> None:
+ def config(runtime: dict[str, Any]) -> Any:
+ profile = MagicMock()
+ profile.runtime = MappingProxyType(runtime)
+ cfg = MagicMock()
+ cfg.resolve_profile.return_value = profile
+ return cfg
+
+ assert profile_schema_in_prompt(config({}))
+ assert profile_schema_in_prompt(config({"schema_in_prompt": True}))
+ assert not profile_schema_in_prompt(config({"schema_in_prompt": False}))
+
+
+# -- queued generation (gateway and sidecar path) ----------------------------------------------------------------
+
+
+class _RecordingTokenizer:
+ def __init__(self, *, system: str = "keep") -> None:
+ self.system = system
+ self.rendered: list[list[dict[str, Any]]] = []
+
+ def apply_chat_template(self, messages: list[dict[str, Any]], *, tokenize: bool, add_generation_prompt: bool, **_):
+ assert tokenize is False
+ assert add_generation_prompt is True
+ rendered = _template(system=self.system)(messages)
+ self.rendered.append([dict(m) for m in messages])
+ return rendered
+
+ def encode(self, text: str, *, add_special_tokens: bool) -> list[int]:
+ return [0] * len(text.split())
+
+
+async def _run(
+ monkeypatch: pytest.MonkeyPatch,
+ generate: dict[str, Any],
+ *,
+ tokenizer: _RecordingTokenizer | None = None,
+ profile_runtime: dict[str, Any] | None = None,
+) -> tuple[_RecordingTokenizer, _PreflightGenAdapter, AsyncMock]:
+ tok = tokenizer or _RecordingTokenizer()
+ adapter = _PreflightGenAdapter()
+ registry = _make_registry_with_chat_config(adapter)
+ profile = registry.get_config.return_value.resolve_profile.return_value
+ profile.runtime = MappingProxyType(profile_runtime or {})
+ monkeypatch.setattr(streaming_mod, "load_tokenizer", lambda *_a, **_kw: tok)
+ nc = AsyncMock()
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ await proc.process(_make_msg(_make_work_item(generate=generate)), "test/model")
+ return tok, adapter, nc
+
+
+def _request(system: str | None = "Score the report.", **extra: Any) -> dict[str, Any]:
+ messages = [{"role": "user", "content": "IBM Db2 Mirror could allow cross-site scripting."}]
+ if system is not None:
+ messages.insert(0, {"role": "system", "content": system})
+ return {
+ "messages": messages,
+ "max_new_tokens": 64,
+ "temperature": 0.0,
+ "grammar": {"kind": "json_schema", "value": SCHEMA, "label": "cvss", "strict": True},
+ **extra,
+ }
+
+
+def _system_texts(tok: _RecordingTokenizer) -> list[str]:
+ """System texts of the request render (the probe render, if any, comes first)."""
+ return [m["content"] for m in tok.rendered[-1] if m["role"] == "system"]
+
+
+async def test_queued_request_shows_the_schema_and_keeps_the_grammar(monkeypatch: pytest.MonkeyPatch) -> None:
+ tok, adapter, _ = await _run(monkeypatch, _request())
+
+ (system,) = _system_texts(tok)
+ assert system == "Score the report.\n\n" + SECTION
+ for option in WEAKNESSES:
+ assert option in system
+ assert adapter.dispatched_parameters is not None
+ assert adapter.dispatched_parameters["grammar"] == GRAMMAR
+ assert "# Response Formats" in adapter.dispatched_parameters["prompt"]
+
+
+async def test_queued_request_without_system_message_gets_one(monkeypatch: pytest.MonkeyPatch) -> None:
+ tok, _, _ = await _run(monkeypatch, _request(system=None))
+ assert tok.rendered[-1][0] == {"role": "system", "content": SECTION}
+
+
[email protected]("system", ["raise", "drop"])
+async def test_template_without_system_role_gets_the_schema_in_the_user_turn(
+ monkeypatch: pytest.MonkeyPatch, system: str
+) -> None:
+ tok, adapter, _ = await _run(monkeypatch, _request(system=None), tokenizer=_RecordingTokenizer(system=system))
+ (user,) = tok.rendered[-1]
+ assert user["role"] == "user"
+ assert user["content"] == SECTION + "\n\nIBM Db2 Mirror could allow cross-site scripting."
+ assert adapter.dispatched_parameters is not None
+
+
+async def test_request_opt_out_leaves_the_prompt_as_sent(monkeypatch: pytest.MonkeyPatch) -> None:
+ tok, adapter, _ = await _run(monkeypatch, _request(schema_in_prompt=False))
+ assert _system_texts(tok) == ["Score the report."]
+ assert adapter.dispatched_parameters is not None
+ assert adapter.dispatched_parameters["grammar"] == GRAMMAR
+
+
+async def test_profile_opt_out_and_request_override(monkeypatch: pytest.MonkeyPatch) -> None:
+ tok, _, _ = await _run(monkeypatch, _request(), profile_runtime={"schema_in_prompt": False})
+ assert _system_texts(tok) == ["Score the report."]
+
+ tok, _, _ = await _run(monkeypatch, _request(schema_in_prompt=True), profile_runtime={"schema_in_prompt": False})
+ assert _system_texts(tok) == ["Score the report.\n\n" + SECTION]
+
+
+async def test_schema_the_caller_already_sent_is_not_repeated(monkeypatch: pytest.MonkeyPatch) -> None:
+ system = "Score the report.\n\nJSON schema:\n" + json.dumps(SCHEMA, indent=2)
+ tok, _, _ = await _run(monkeypatch, _request(system=system))
+ assert _system_texts(tok) == [system]
+
+
+async def test_requests_without_a_json_schema_are_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:
+ regex = {**_request(), "grammar": {"kind": "regex", "value": "^(yes|no)$"}}
+ tok, _, _ = await _run(monkeypatch, regex)
+ assert _system_texts(tok) == ["Score the report."]
+
+ plain = {key: value for key, value in _request().items() if key != "grammar"}
+ tok, _, _ = await _run(monkeypatch, plain)
+ assert _system_texts(tok) == ["Score the report."]
+
+
+async def test_non_boolean_opt_out_is_refused(monkeypatch: pytest.MonkeyPatch) -> None:
+ tok, adapter, nc = await _run(monkeypatch, _request(schema_in_prompt="no"))
+ terminal = _decode_chunks(nc)[-1]
+ assert terminal["error"]["code"] == "invalid_request"
+ assert "schema_in_prompt" in terminal["error"]["message"]
+ assert adapter.dispatched_parameters is None
+ assert tok.rendered == []
+
+
+async def test_system_role_probe_runs_once_per_model(monkeypatch: pytest.MonkeyPatch) -> None:
+ tok = _RecordingTokenizer(system="raise")
+ adapter = _PreflightGenAdapter()
+ registry = _make_registry_with_chat_config(adapter)
+ registry.get_config.return_value.resolve_profile.return_value.runtime = MappingProxyType({})
+ monkeypatch.setattr(streaming_mod, "load_tokenizer", lambda *_a, **_kw: tok)
+ proc = StreamingProcessor(nc=AsyncMock(), registry=registry, worker_id="w1")
+ probes = MagicMock(wraps=streaming_mod.renders_system_role)
+ monkeypatch.setattr(streaming_mod, "renders_system_role", probes)
+ for _ in range(2):
+ registry.get.return_value = _PreflightGenAdapter()
+ await proc.process(_make_msg(_make_work_item(generate=_request(system=None))), "test/model")
+ assert probes.call_count == 1
+ assert tok.rendered[-1][0]["content"].startswith(SECTION)