refactor(agent/utils): Clean up JSONSchema.validate_object signature & docstring

This commit is contained in:
Reinier van der Leer
2024-04-12 20:11:20 +02:00
parent e866a4ba04
commit cf033504c2
2 changed files with 9 additions and 16 deletions

View File

@@ -392,10 +392,7 @@ class OneShotAgentPromptStrategy(PromptStrategy):
f"{json.dumps(assistant_reply_dict, indent=4)}" f"{json.dumps(assistant_reply_dict, indent=4)}"
) )
_, errors = self.response_schema.validate_object( _, errors = self.response_schema.validate_object(assistant_reply_dict)
object=assistant_reply_dict,
logger=self.logger,
)
if errors: if errors:
raise InvalidAgentResponseError( raise InvalidAgentResponseError(
"Validation of response failed:\n " "Validation of response failed:\n "

View File

@@ -1,9 +1,8 @@
import enum import enum
from logging import Logger
from textwrap import indent from textwrap import indent
from typing import Literal, Optional from typing import Optional
from jsonschema import Draft7Validator from jsonschema import Draft7Validator, ValidationError
from pydantic import BaseModel from pydantic import BaseModel
@@ -84,27 +83,24 @@ class JSONSchema(BaseModel):
v.required = k in schema_node["required"] v.required = k in schema_node["required"]
return properties return properties
def validate_object( def validate_object(self, object: object) -> tuple[bool, list[ValidationError]]:
self, object: object, logger: Logger
) -> tuple[Literal[True], None] | tuple[Literal[False], list]:
""" """
Validates a dictionary object against the JSONSchema. Validates an object or a value against the JSONSchema.
Params: Params:
object: The dictionary object to validate. object: The value/object to validate.
schema (JSONSchema): The JSONSchema to validate against. schema (JSONSchema): The JSONSchema to validate against.
Returns: Returns:
tuple: A tuple where the first element is a boolean indicating whether the bool: Indicates whether the given value or object is valid for the schema.
object is valid or not, and the second element is a list of errors found list[ValidationError]: The issues with the value or object (if any).
in the object, or None if the object is valid.
""" """
validator = Draft7Validator(self.to_dict()) validator = Draft7Validator(self.to_dict())
if errors := sorted(validator.iter_errors(object), key=lambda e: e.path): if errors := sorted(validator.iter_errors(object), key=lambda e: e.path):
return False, errors return False, errors
return True, None return True, []
def to_typescript_object_interface(self, interface_name: str = "") -> str: def to_typescript_object_interface(self, interface_name: str = "") -> str:
if self.type != JSONSchema.Type.OBJECT: if self.type != JSONSchema.Type.OBJECT: