Home / File/ json_schema.py — langchain Source File

json_schema.py — langchain Source File

Architecture documentation for json_schema.py, a python file in the langchain codebase. 5 imports, 0 dependents.

Entity Profile

Dependency Diagram

graph LR
  b4b3c835_bb1d_7469_e4cc_b53cd7b6be10["json_schema.py"]
  feec1ec4_6917_867b_d228_b134d0ff8099["typing"]
  b4b3c835_bb1d_7469_e4cc_b53cd7b6be10 --> feec1ec4_6917_867b_d228_b134d0ff8099
  1e4f206f_c5d6_57b9_9194_b86d8eff032d["langchain_core.utils.json"]
  b4b3c835_bb1d_7469_e4cc_b53cd7b6be10 --> 1e4f206f_c5d6_57b9_9194_b86d8eff032d
  f85fae70_1011_eaec_151c_4083140ae9e5["typing_extensions"]
  b4b3c835_bb1d_7469_e4cc_b53cd7b6be10 --> f85fae70_1011_eaec_151c_4083140ae9e5
  37291248_07a6_a05c_821a_71cc0592429f["langchain_classic.evaluation.schema"]
  b4b3c835_bb1d_7469_e4cc_b53cd7b6be10 --> 37291248_07a6_a05c_821a_71cc0592429f
  cce151bd_e760_61e6_c300_c9def6aaee78["jsonschema"]
  b4b3c835_bb1d_7469_e4cc_b53cd7b6be10 --> cce151bd_e760_61e6_c300_c9def6aaee78
  style b4b3c835_bb1d_7469_e4cc_b53cd7b6be10 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

from typing import Any

from langchain_core.utils.json import parse_json_markdown
from typing_extensions import override

from langchain_classic.evaluation.schema import StringEvaluator


class JsonSchemaEvaluator(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: Whether the evaluator requires input.
        requires_reference: Whether the evaluator requires reference.
        evaluation_name: 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

    def __init__(self, **_: Any) -> None:
        """Initializes the JsonSchemaEvaluator.

        Raises:
            ImportError: If the jsonschema package is not installed.
        """
        super().__init__()
        try:
            import jsonschema  # noqa: F401
        except ImportError as e:
            msg = (
                "The JsonSchemaEvaluator requires the jsonschema package."
                " Please install it with `pip install jsonschema`."
            )
            raise ImportError(msg) from e

    @property
    def requires_input(self) -> bool:
        """Returns whether the evaluator requires input."""
        return False

    @property
    def requires_reference(self) -> bool:
        """Returns whether the evaluator requires reference."""
        return True

    @property
    def evaluation_name(self) -> str:
        """Returns the name of the evaluation."""
        return "json_schema_validation"

    def _parse_json(self, node: Any) -> dict | list | None | float | bool | int | str:
        if isinstance(node, str):
            return parse_json_markdown(node)
        if hasattr(node, "model_json_schema") and callable(node.model_json_schema):
            # Pydantic v2 model
            return node.model_json_schema()
        if hasattr(node, "schema") and callable(node.schema):
            # Pydantic v1 model
            return node.schema()
        return node

    def _validate(self, prediction: Any, schema: Any) -> dict:
        from jsonschema import ValidationError, validate

        try:
            validate(instance=prediction, schema=schema)
        except ValidationError as e:
            return {"score": False, "reasoning": repr(e)}
        return {"score": True}

    @override
    def _evaluate_strings(
        self,
        prediction: str | Any,
        input: str | Any = None,
        reference: str | Any = None,
        **kwargs: Any,
    ) -> dict:
        parsed_prediction = self._parse_json(prediction)
        schema = self._parse_json(reference)
        return self._validate(parsed_prediction, schema)

Domain

Subdomains

Dependencies

  • jsonschema
  • langchain_classic.evaluation.schema
  • langchain_core.utils.json
  • typing
  • typing_extensions

Frequently Asked Questions

What does json_schema.py do?
json_schema.py is a source file in the langchain codebase, written in python. It belongs to the LangChainCore domain, MessageInterface subdomain.
What does json_schema.py depend on?
json_schema.py imports 5 module(s): jsonschema, langchain_classic.evaluation.schema, langchain_core.utils.json, typing, typing_extensions.
Where is json_schema.py in the architecture?
json_schema.py is located at libs/langchain/langchain_classic/evaluation/parsing/json_schema.py (domain: LangChainCore, subdomain: MessageInterface, directory: libs/langchain/langchain_classic/evaluation/parsing).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free