Source code for langchain.evaluation.parsing.json_schema

from typing import Any, Union

from langchain_core.utils.json import parse_json_markdown

from langchain.evaluation.schema import StringEvaluator


[docs]class JsonSchemaEvaluator(StringEvaluator): """一个验证JSON预测与JSON模式引用的评估器。 该评估器检查给定的JSON预测是否符合提供的JSON模式。 如果预测有效,则得分为True(无错误)。否则,得分为False(发生错误)。 属性: requires_input(bool):评估器是否需要输入。 requires_reference(bool):评估器是否需要引用。 evaluation_name(str):评估的名称。 示例: 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: """初始化JsonSchemaEvaluator。 参数: **kwargs: 附加的关键字参数。 抛出: ImportError: 如果jsonschema包未安装。 """ super().__init__() try: import jsonschema # noqa: F401 except ImportError: raise ImportError( "The JsonSchemaEvaluator requires the jsonschema package." " Please install it with `pip install jsonschema`." )
@property def requires_input(self) -> bool: """返回评估器是否需要输入。""" return False @property def requires_reference(self) -> bool: """返回评估器是否需要引用。""" return True @property def evaluation_name(self) -> str: """返回评估的名称。""" return "json_schema_validation" def _parse_json(self, node: Any) -> Union[dict, list, None, float, bool, int, str]: if isinstance(node, str): return parse_json_markdown(node) elif hasattr(node, "schema") and callable(getattr(node, "schema")): # Pydantic model return getattr(node, "schema")() return node def _validate(self, prediction: Any, schema: Any) -> dict: from jsonschema import ValidationError, validate try: validate(instance=prediction, schema=schema) return { "score": True, } except ValidationError as e: 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) return self._validate(parsed_prediction, schema)