|
1 | | -"""Schema-validation tool factory. |
| 1 | +"""Schema-validation tool factories. |
2 | 2 |
|
3 | | -Produces a plain callable the RLM can invoke inside the REPL to check its draft |
4 | | -JSON against the expected pydantic schema before emitting a final answer — the |
5 | | -generalised form of the original app's ``validate_vulnerability_report``. |
| 3 | +Two shapes, both consumer-facing base primitives: |
| 4 | +
|
| 5 | +- ``make_schema_validator(model)`` — a plain callable the RLM invokes inside the REPL to |
| 6 | + check its draft JSON against a pydantic schema before emitting a final answer (returns a |
| 7 | + human message). The generalised form of the original app's ``validate_vulnerability_report``. |
| 8 | +- ``make_json_schema_validator(schema)`` — validate a PARSED object against a JSON Schema |
| 9 | + (draft 2020-12) and return the violation messages, the generic base for the "validate |
| 10 | + against a vendored, version-pinned upstream JSON schema" pattern (a consumer vendors the |
| 11 | + schema + a refresh script; the kit owns the validator wiring). |
6 | 12 | """ |
7 | 13 |
|
8 | 14 | from __future__ import annotations |
9 | 15 |
|
10 | | -from typing import Callable, Type |
| 16 | +import json |
| 17 | +import os |
| 18 | +from typing import Callable, Type, Union |
11 | 19 |
|
12 | 20 | from pydantic import BaseModel |
13 | 21 |
|
14 | 22 |
|
| 23 | +def make_json_schema_validator( |
| 24 | + schema: Union[dict, str, os.PathLike], |
| 25 | + *, |
| 26 | + max_errors: int = 20, |
| 27 | +) -> Callable[[object], list[str]]: |
| 28 | + """Return a function that validates a PARSED object against a JSON Schema and returns a |
| 29 | + list of human-readable violation messages (empty list = valid). |
| 30 | +
|
| 31 | + ``schema`` is the JSON Schema as a dict, or a path to a ``.json`` schema file (read once, |
| 32 | + at factory time). The returned validator takes an already-parsed object (a dict from |
| 33 | + ``yaml.safe_load`` / ``json.loads``) — parsing is the consumer's job, so this composes with |
| 34 | + whatever extract/parse step precedes it. Each message is ``"<json/pointer/path>: <reason>"`` |
| 35 | + (root violations use ``"(root)"``); the list is truncated to ``max_errors`` (a huge invalid |
| 36 | + doc must not flood the trace). Deterministic ordering (by error path) so traces are stable. |
| 37 | +
|
| 38 | + This is the GENERIC base for the "validate against an official, vendored, version-pinned |
| 39 | + upstream JSON schema" pattern: a consumer vendors the schema file + a refresh script (the |
| 40 | + provider-specific half), and layers its own bespoke checks on top; the kit owns only this |
| 41 | + wiring. ``jsonschema`` is an OPTIONAL dependency (``rlm-kit[jsonschema]``) — imported lazily |
| 42 | + so ``import rlm_kit`` and the dspy-free ``tools`` package stay lean. |
| 43 | + """ |
| 44 | + try: |
| 45 | + from jsonschema import Draft202012Validator |
| 46 | + except ImportError as exc: # pragma: no cover - exercised only without the extra installed |
| 47 | + raise ImportError( |
| 48 | + "make_json_schema_validator needs the optional 'jsonschema' dependency. " |
| 49 | + "Install it with: pip install 'rlm-kit[jsonschema]'" |
| 50 | + ) from exc |
| 51 | + |
| 52 | + if isinstance(schema, (str, os.PathLike)): |
| 53 | + with open(schema, encoding="utf-8") as fh: |
| 54 | + schema = json.load(fh) |
| 55 | + validator = Draft202012Validator(schema) |
| 56 | + |
| 57 | + def validate(obj: object) -> list[str]: |
| 58 | + """Validate a parsed object against the JSON schema; return violation messages ([] = ok).""" |
| 59 | + errors: list[str] = [] |
| 60 | + for err in sorted(validator.iter_errors(obj), key=lambda e: list(e.absolute_path)): |
| 61 | + loc = "/".join(str(p) for p in err.absolute_path) or "(root)" |
| 62 | + errors.append(f"{loc}: {err.message}") |
| 63 | + if len(errors) >= max_errors: |
| 64 | + errors.append(f"… (schema errors truncated at {max_errors})") |
| 65 | + break |
| 66 | + return errors |
| 67 | + |
| 68 | + return validate |
| 69 | + |
| 70 | + |
15 | 71 | def make_schema_validator(model: Type[BaseModel]) -> Callable[[str], str]: |
16 | 72 | """Return a tool that validates a JSON string against ``model``. |
17 | 73 |
|
|
0 commit comments