[docs]classJsonSchemaEvaluator(StringEvaluator):"""An evaluator that validates a JSON prediction against a JSON schema reference. This evaluator checks if a given JSON prediction conforms to the provided JSON schema. If the prediction is valid, the score is True (no errors). Otherwise, the score is False (error occurred). Attributes: requires_input (bool): Whether the evaluator requires input. requires_reference (bool): Whether the evaluator requires reference. evaluation_name (str): The name of the evaluation. Examples: evaluator = JsonSchemaEvaluator() result = evaluator.evaluate_strings( prediction='{"name": "John", "age": 30}', reference={ "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} } } ) assert result["score"] is not None """# noqa: E501
[docs]def__init__(self,**kwargs:Any)->None:"""Initializes the JsonSchemaEvaluator. Args: kwargs: Additional keyword arguments. Raises: ImportError: If the jsonschema package is not installed. """super().__init__()try:importjsonschema# noqa: F401exceptImportError:raiseImportError("The JsonSchemaEvaluator requires the jsonschema package."" Please install it with `pip install jsonschema`.")
@propertydefrequires_input(self)->bool:"""Returns whether the evaluator requires input."""returnFalse@propertydefrequires_reference(self)->bool:"""Returns whether the evaluator requires reference."""returnTrue@propertydefevaluation_name(self)->str:"""Returns the name of the evaluation."""return"json_schema_validation"def_parse_json(self,node:Any)->Union[dict,list,None,float,bool,int,str]:ifisinstance(node,str):returnparse_json_markdown(node)elifhasattr(node,"schema")andcallable(getattr(node,"schema")):# Pydantic modelreturngetattr(node,"schema")()returnnodedef_validate(self,prediction:Any,schema:Any)->dict:fromjsonschemaimportValidationError,validatetry:validate(instance=prediction,schema=schema)return{"score":True,}exceptValidationErrorase:return{"score":False,"reasoning":repr(e)}def_evaluate_strings(self,prediction:Union[str,Any],input:Union[str,Any]=None,reference:Union[str,Any]=None,**kwargs:Any,)->dict:parsed_prediction=self._parse_json(prediction)schema=self._parse_json(reference)returnself._validate(parsed_prediction,schema)