@@ -11,8 +11,9 @@ def make_schema_evaluator(schema: dict) -> Callable[[str, dict], bool]:
1111 Schema dict using ``jsonschema``. Useful for asserting that LLM outputs
1212 conform to a declared schema regardless of the specific values produced.
1313
14- The JSON schema is bound at factory-creation time so the same validator
15- can be reused across many evaluation rows without re-compiling.
14+ The JSON schema and validator are both bound at factory-creation time so
15+ the same validator can be reused across many evaluation rows without
16+ re-compiling or re-importing.
1617
1718 Parameters
1819 ----------
@@ -37,27 +38,24 @@ def make_schema_evaluator(schema: dict) -> Callable[[str, dict], bool]:
3738
3839 pip install 'jsonschema>=4.0'
3940 """
41+ try :
42+ import jsonschema
43+ except ImportError as exc :
44+ raise ImportError (
45+ "jsonschema is required to use make_schema_evaluator. "
46+ "Install it with: pip install 'jsonschema>=4.0'"
47+ ) from exc
48+
49+ validator = jsonschema .Draft7Validator (schema )
4050
4151 def schema_valid (output : str , expected : dict ) -> bool : # noqa: ARG001
4252 if output is None :
4353 return False
44- try :
45- import jsonschema
46- except ImportError as exc :
47- raise ImportError (
48- "jsonschema is required to use make_schema_evaluator. "
49- "Install it with: pip install 'jsonschema>=4.0'"
50- ) from exc
51-
5254 try :
5355 instance = json .loads (output )
5456 except (json .JSONDecodeError , TypeError ):
5557 return False
56- try :
57- jsonschema .validate (instance = instance , schema = schema )
58- except jsonschema .ValidationError :
59- return False
60- return True
58+ return validator .is_valid (instance )
6159
6260 schema_valid .__name__ = "schema_valid"
6361 return schema_valid
0 commit comments