serve: validate JSON response formats before delivery

This commit is contained in:
Ricardo Ambrogi authored and Niko1221 committed 2026-10-01 08:27:08 +02:00
1 parent bd9a1bc126
commit c87a9cb0ce
4 files changed
+302 -2

No files matched your search

+19
View File
@@ -795,3 +795,22 @@ and **404** for an unknown model. Existing `/load` and `/unload` behavior is pre
Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached
stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still
times out, the server keeps ownership and reports an error rather than claiming the model was unloaded.
### JSON response formats
`POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or
`{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`.
The schema must describe an object at its root. Local `#` references work; remote references are refused.
`json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install
"jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the
server says so once.
This is **schema prompting followed by server validation**, not grammar-constrained decoding. One generation
is made per request, with no hidden retry. Successful responses contain a validated JSON object. Malformed JSON,
duplicate keys, non-finite numbers, schema violations and incomplete generations return **502** with
`error.code: structured_output_failed`; invalid request schemas return **400**. JSON formats combined with
tools/MCP are refused explicitly. Without `response_format`, ordinary text and tool behavior stays the same.
Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation,
then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas.
`/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior.
+40 -2
View File
@@ -51,6 +51,7 @@ from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_mess
images_of, openai_to_messages)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
from serve.winjob import contain # noqa: E402
from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402
IM_END = "<|im_end|>"
IMAGE_PAD = "<|image_pad|>"
@@ -968,6 +969,8 @@ class Service:
return {
"service": "strata", "model": self.model,
"loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"),
"structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate",
"constrained_decoding": False, "stream_buffered": True},
"engine": (getattr(self.engine, "info", {}) or {}).get("version"),
"started": int(self.started_at), "uptime_s": int(time.time() - self.started_at),
"cache_max_tokens": ctx,
@@ -1455,6 +1458,30 @@ def openai_collect(chunks) -> dict:
return out
def structured_chunks(chunks, validator):
"""Buffer structured streams so a client never receives unvalidated content."""
buffered = []
heartbeat = time.monotonic()
try:
for chunk in chunks:
if chunk is not None:
buffered.append(chunk)
if chunk is None or time.monotonic() - heartbeat >= 1:
heartbeat = time.monotonic()
yield None
result = openai_collect(buffered)
choice = result["choices"][0]
content = validated_json(choice["message"]["content"], validator, choice["finish_reason"])
yield buffered[0]
delta = {"content": content}
if choice["message"].get("reasoning_content"):
delta["reasoning_content"] = choice["message"]["reasoning_content"]
yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
yield buffered[-1]
finally:
chunks.close()
# ------------------------------------------------------------------------------------------------ Anthropic
def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel):
mid = "msg_" + uuid.uuid4().hex[:24]
@@ -1759,8 +1786,6 @@ def make_handler(svc: Service):
result = "loaded"
self._json(200, {"status": result, **svc.v1_status()})
return
if path in ("/v1/chat/completions", "/v1/messages"):
svc.load() # unloaded: load first (or 503 while the GPU is busy)
if path == "/v1/chat/completions":
self._openai(req)
elif path == "/v1/messages":
@@ -1773,6 +1798,9 @@ def make_handler(svc: Service):
self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})
except ModelBusy as e:
self._json(409, {"error": {"type": "model_busy", "message": str(e)}})
except StructuredOutputError as e:
self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed",
"message": str(e)}})
except GpuBusy as e:
self._json(503, {"error": {"type": "server_error", "message": str(e)}})
except EngineDied as e: # before the answer started (not streamed)
@@ -1848,6 +1876,10 @@ def make_handler(svc: Service):
def _openai(self, req):
req = svc.with_shared(req, "openai")
messages, tools, kw = openai_to_messages(req)
messages, validator = prepare_format(req.get("response_format"), messages)
if validator is not None and (tools or req.get("strata_mcp")):
raise ValueError("structured response_format with tools/MCP is not supported")
svc.load()
max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest
use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py)
own = {t.get("name") for t in tools or []}
@@ -1865,6 +1897,8 @@ def make_handler(svc: Service):
run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel,
{t["name"] for t in extra}) if use_mcp else None
chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run)
if validator is not None:
chunks = structured_chunks(chunks, validator)
if not req.get("stream"):
return self._json(200, openai_collect(chunks))
self._sse()
@@ -1882,6 +1916,9 @@ def make_handler(svc: Service):
except EngineDied as e: # mid-stream: say so, then end the stream properly
err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
except StructuredOutputError as e:
err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}}
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
except ValueError as e: # the engine's ERR after the stream started: the
err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
@@ -1895,6 +1932,7 @@ def make_handler(svc: Service):
self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))})
def _anthropic(self, req):
svc.load()
req = svc.with_shared(req, "anthropic")
messages, tools, kw = anthropic_to_messages(req)
max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context
+105
View File
@@ -0,0 +1,105 @@
"""JSON response formats at the HTTP boundary: prompt once, validate before delivery.
The native engine has no grammar decoder. Failed generations are errors, never
silently retried or returned as successful structured output.
"""
import json
from jsonschema import validators
from jsonschema.exceptions import SchemaError
from referencing import Registry
from referencing.exceptions import NoSuchResource
class StructuredOutputError(RuntimeError):
pass
def _no_remote(uri):
raise NoSuchResource(ref=uri)
def prepare_format(response_format, messages):
if response_format is None:
return messages, None
if not isinstance(response_format, dict):
raise ValueError("response_format must be an object")
kind = response_format.get("type")
if kind == "text":
return messages, None
if kind == "json_object":
schema = {"type": "object"}
elif kind == "json_schema":
spec = response_format.get("json_schema")
if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict):
raise ValueError("response_format.json_schema needs a schema object")
if not isinstance(spec.get("name"), str) or not spec["name"]:
raise ValueError("response_format.json_schema needs a name")
if "strict" in spec and not isinstance(spec["strict"], bool):
raise ValueError("response_format.json_schema.strict must be boolean")
schema = spec["schema"]
if schema.get("type") != "object":
raise ValueError("response_format schema must have type object at its root")
else:
raise ValueError("response_format.type must be text, json_object or json_schema")
def check_refs(node):
if isinstance(node, dict):
for key, value in node.items():
if key in ("$ref", "$dynamicRef") and isinstance(value, str) and not value.startswith("#"):
raise ValueError("response_format supports only local schema references (#...)")
check_refs(value)
elif isinstance(node, list):
for value in node:
check_refs(value)
check_refs(schema)
try:
cls = validators.validator_for(schema)
cls.check_schema(schema)
validator = cls(schema, registry=Registry(retrieve=_no_remote))
except SchemaError as exc:
raise ValueError(f"invalid response_format schema: {exc.message}") from exc
directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. "
"No Markdown, headings, code fences, commentary, or text outside the JSON. "
"Use every required field, correct types, and only allowed fields. "
"Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" +
json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":")))
messages = [dict(message) for message in messages]
if messages and messages[0].get("role") == "system":
content = messages[0].get("content") or ""
if isinstance(content, list):
messages[0]["content"] = content + [{"type": "text", "text": directive}]
else:
messages[0]["content"] = content + "\n\n" + directive
else:
messages.insert(0, {"role": "system", "content": directive})
return messages, validator
def validated_json(text, validator, finish):
def pairs(items):
obj = {}
for key, value in items:
if key in obj:
raise ValueError(f"duplicate JSON key: {key}")
obj[key] = value
return obj
def constant(value):
raise ValueError(f"invalid JSON constant: {value}")
if finish != "stop":
raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget")
try:
value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant)
canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
except (ValueError, TypeError) as exc:
raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc
try:
error = next(validator.iter_errors(value), None)
except Exception as exc:
raise StructuredOutputError(f"could not validate structured output: {exc}") from exc
if error is not None:
path = "/" + "/".join(str(part) for part in error.absolute_path)
raise StructuredOutputError(f"model output failed the JSON Schema at {path}: {error.message}")
return canonical
+138
View File
@@ -0,0 +1,138 @@
"""Exercise the JSON contract through HTTP, including H3's strict Story shape."""
import json
import unittest
import urllib.error
import urllib.request
from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, MockEngine, Service, serve
STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [],
"boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.",
"on_screen": ["Hailee"], "references": [], "ends": "She smiles."}], "suggestions": []}
def object_schema(properties):
return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False}
TEXT = {"type": "string"}
STORY_SCHEMA = object_schema({
"title": TEXT, "sheet": TEXT, "cast": {"type": "array", "items": object_schema({"name": TEXT,
"references": {"type": "array", "items": TEXT, "maxItems": 0}})},
"boxes": {"type": "array", "minItems": 1, "maxItems": 1, "items": object_schema({
"box": {"type": "integer", "minimum": 1, "maximum": 1},
"duration_ms": {"type": "integer", "minimum": 1, "maximum": 15000}, "new_shot": {"type": "boolean"},
"beat": TEXT, "on_screen": {"type": "array", "items": TEXT},
"references": {"type": "array", "items": TEXT, "maxItems": 0}, "ends": TEXT})},
"suggestions": {"type": "array", "items": object_schema({"what": TEXT, "why": TEXT,
"boxes": {"type": "array", "items": {"type": "integer"}}, "description": TEXT})}})
FORMAT = {"type": "json_schema", "json_schema": {"name": "h3_story", "strict": True, "schema": STORY_SCHEMA}}
class Structured(unittest.TestCase):
def request(self, path, body=None, headers=None):
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None,
headers={"Content-Type": "application/json", **(headers or {})})
try:
response = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
data = response.read().decode()
return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data)
def setUp(self):
self.tok = ByteTokenizer()
self.engine = MockEngine(self.tok, json.dumps(STORY), max_context=16384)
self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
def tearDown(self):
self.httpd.shutdown()
self.httpd.server_close()
def chat(self, script=None, **kwargs):
if script is not None:
self.engine = self.svc.engine = MockEngine(self.tok, script, max_context=16384)
req = {"messages": [{"role": "system", "content": "Write a film plan."},
{"role": "user", "content": "Photobooth. 15 seconds."}],
"response_format": FORMAT, "reasoning_effort": "none", **kwargs}
return self.request("/v1/chat/completions", req)
def test_h3_schema_success_and_stream_with_reasoning(self):
code, reply = self.chat()
self.assertEqual(code, 200)
self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), STORY)
prompt = self.tok.decode(self.engine.last_prompt)
self.assertIn("OUTPUT FORMAT REQUIREMENT", prompt)
self.assertIn('"duration_ms"', prompt)
code, raw = self.chat("Consider the shot.</think>\n" + json.dumps(STORY), stream=True, reasoning_effort="low")
self.assertEqual(code, 200)
chunks = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks)
self.assertEqual(json.loads(content), STORY)
self.assertIn("reasoning_content", raw)
self.assertIn("data: [DONE]", raw)
def test_invalid_generation_is_an_error_and_never_streams_content(self):
for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}',
json.dumps({**STORY, "extra": True}),
json.dumps({**STORY, "boxes": [{**STORY["boxes"][0], "duration_ms": "15000"}]})):
with self.subTest(script=script):
code, reply = self.chat(script)
self.assertEqual(code, 502)
self.assertEqual(reply["error"]["code"], "structured_output_failed")
_, raw = self.chat(script, stream=True)
self.assertIn('"structured_output_failed"', raw)
self.assertNotIn('"delta"', raw)
self.assertIn("data: [DONE]", raw)
def test_object_mode_strict_json_and_truncation(self):
fmt = {"type": "json_object"}
self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200)
for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'):
self.assertEqual(self.chat(script, response_format=fmt)[0], 502)
self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502)
# Plain text callers retain normal streaming, without a JSON validation gate.
self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200)
def test_rejected_schema_does_not_load_the_engine_or_retry(self):
with mock.patch.object(self.svc, "load") as load:
code, _ = self.chat(response_format={"type": "json_schema"})
self.assertEqual(code, 400)
load.assert_not_called()
self.engine = self.svc.engine = MockEngine(self.tok, "Markdown is not JSON", max_context=16384)
with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate:
self.assertEqual(self.chat()[0], 502)
self.assertEqual(generate.call_count, 1)
def test_invalid_schema_is_400_and_local_refs_work(self):
for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}},
{"type": "object", "$ref": "https://other.example/schema"}):
fmt = {"type": "json_schema", "json_schema": {"name": "test", "strict": True, "schema": schema}}
self.assertEqual(self.chat(response_format=fmt)[0], 400)
schema = object_schema({"answer": {"$ref": "#/$defs/n"}})
schema["$defs"] = {"n": {"type": "integer"}}
fmt = {"type": "json_schema", "json_schema": {"name": "local", "schema": schema}}
self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200)
def test_malformed_formats_and_tools_are_rejected_before_loading(self):
formats = ([], {"type": "unsupported"},
{"type": "json_schema", "json_schema": {"schema": {"type": "object"}}},
{"type": "json_schema", "json_schema": {"name": "x", "strict": "true", "schema": {"type": "object"}}})
with mock.patch.object(self.svc, "load") as load:
for fmt in formats:
with self.subTest(fmt=fmt):
self.assertEqual(self.chat(response_format=fmt)[0], 400)
self.assertEqual(self.chat(tools=[{"type": "function", "function": {"name": "search", "parameters": {"type": "object"}}}])[0], 400)
self.assertEqual(self.chat(strata_mcp=True)[0], 400)
self.assertEqual(self.request("/v1/chat/completions", [])[0], 400)
load.assert_not_called()
if __name__ == "__main__":
unittest.main()