#334 follow-up: jsonschema is an optional, lazily imported package (no new hard dependency)
- The rebase keeps 0.1.31's requirements.txt install in setup.py and the Dockerfile: jsonschema is not added. - serve/structured.py imports jsonschema on the first json_schema request, not at server start (a server without it started fine before #334 and still does). json_object never needs it; json_schema without it is checked to be one JSON object, and the server window says once how to get full schema validation. - test_structured: the two schema-violation tests skip without jsonschema; new tests for the object-only fallback and for "import serve.server" not importing jsonschema. docs/DETAILS.md says it is optional.
This commit is contained in:
1 parent
c87a9cb0ce
commit
d3bf912ea0
2 files changed
+84
-13
No files matched your search
+55
-13
@@ -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. "
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user