diff --git a/serve/structured.py b/serve/structured.py index bc9ad786..b5f079cc 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -2,21 +2,53 @@ The native engine has no grammar decoder. Failed generations are errors, never silently retried or returned as successful structured output. + +`jsonschema` is optional (no new hard dependency of the server): json_object needs only the standard library, and +json_schema is checked against its schema when the package is installed - without it, only that the answer is one +JSON object, and the server says so once. """ import json - -from jsonschema import validators -from jsonschema.exceptions import SchemaError -from referencing import Registry -from referencing.exceptions import NoSuchResource +import threading class StructuredOutputError(RuntimeError): pass -def _no_remote(uri): - raise NoSuchResource(ref=uri) +class _ObjectOnly: + """The validator for json_object, and for json_schema without jsonschema: one JSON object.""" + + def iter_errors(self, value): + if not isinstance(value, dict): + yield _ObjectError() + + +class _ObjectError: + absolute_path = () + message = "the answer is not a JSON object" + + +_jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed +_jsonschema_lock = threading.Lock() + + +def jsonschema_modules(): + """jsonschema, imported on first use; None when it is not installed (said once, in the server window).""" + global _jsonschema + with _jsonschema_lock: + if _jsonschema is None: + try: + from jsonschema import validators + from jsonschema.exceptions import SchemaError + from referencing import Registry + from referencing.exceptions import NoSuchResource + _jsonschema = (validators, SchemaError, Registry, NoSuchResource) + except ImportError: + _jsonschema = False + print('[strata] response_format json_schema: the Python package jsonschema is not installed, so ' + 'answers are only checked to be one JSON object (python -m pip install "jsonschema>=4.23,<5")', + flush=True) + return _jsonschema or None def prepare_format(response_format, messages): @@ -29,6 +61,7 @@ def prepare_format(response_format, messages): return messages, None if kind == "json_object": schema = {"type": "object"} + modules = None # the standard library is enough for "one JSON object" elif kind == "json_schema": spec = response_format.get("json_schema") if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict): @@ -40,6 +73,7 @@ def prepare_format(response_format, messages): schema = spec["schema"] if schema.get("type") != "object": raise ValueError("response_format schema must have type object at its root") + modules = jsonschema_modules() else: raise ValueError("response_format.type must be text, json_object or json_schema") @@ -53,12 +87,20 @@ def prepare_format(response_format, messages): 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 + if modules is None: + validator = _ObjectOnly() + else: + validators, SchemaError, Registry, NoSuchResource = modules + + def no_remote(uri): + raise NoSuchResource(ref=uri) + + 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. " diff --git a/serve/test_structured.py b/serve/test_structured.py index 644a4b4e..cc157a76 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -7,8 +7,15 @@ from pathlib import Path from unittest import mock from serve.frontend import ChatTemplate +from serve import structured from serve.server import ByteTokenizer, MockEngine, Service, serve +try: + import jsonschema # noqa: F401 + HAVE_JSONSCHEMA = True +except ImportError: # optional: json_schema answers are then only checked to be one object + HAVE_JSONSCHEMA = False + STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [], "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.", @@ -79,6 +86,7 @@ class Structured(unittest.TestCase): self.assertIn("reasoning_content", raw) self.assertIn("data: [DONE]", raw) + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") 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}), @@ -111,6 +119,7 @@ class Structured(unittest.TestCase): self.assertEqual(self.chat()[0], 502) self.assertEqual(generate.call_count, 1) + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") 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"}): @@ -134,5 +143,25 @@ class Structured(unittest.TestCase): self.assertEqual(self.request("/v1/chat/completions", [])[0], 400) load.assert_not_called() + def test_without_jsonschema_an_object_is_still_required(self): + # jsonschema is optional: without it json_schema answers are checked to be one JSON object, json_object + # never needs it, and nothing is imported at server start + with mock.patch.object(structured, "_jsonschema", False): + self.assertEqual(self.chat()[0], 200) + for script in ("## Film Plan - Photobooth", "[1, 2]"): + code, reply = self.chat(script) + self.assertEqual(code, 502, script) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + + def test_the_server_does_not_import_jsonschema_at_start(self): + import subprocess + import sys + code = ("import sys; import serve.server; " + "sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)") + r = subprocess.run([sys.executable, "-c", code], cwd=str(Path(__file__).resolve().parents[1])) + self.assertEqual(r.returncode, 0) + + if __name__ == "__main__": unittest.main()