MCPcopy Create free account
hub / github.com/microsoft/TypeChat / TypeChatValidator

Class TypeChatValidator

python/src/typechat/_internal/validator.py:11–45  ·  view source on GitHub ↗

Validates an object against a given Python type.

Source from the content-addressed store, hash-verified

9T = TypeVar("T", covariant=True)
10
11class TypeChatValidator(Generic[T]):
12 """
13 Validates an object against a given Python type.
14 """
15
16 _adapted_type: pydantic.TypeAdapter[T]
17
18 def __init__(self, py_type: type[T]):
19 """
20 Args:
21
22 py_type: The schema type to validate against.
23 """
24 super().__init__()
25 self._adapted_type = pydantic.TypeAdapter(py_type)
26
27 def validate_object(self, obj: object) -> Result[T]:
28 """
29 Validates the given Python object according to the associated schema type.
30
31 Returns a `Success[T]` object containing the object if validation was successful.
32 Otherwise, returns a `Failure` object with a `message` property describing the error.
33 """
34 try:
35 # TODO: Switch to `validate_python` when validation modes are exposed.
36 # https://github.com/pydantic/pydantic-core/issues/712
37 # We'd prefer to keep `validate_object` as the core method and
38 # allow translators to concern themselves with the JSON instead.
39 # However, under Pydantic's `strict` mode, a `dict` isn't considered compatible
40 # with a dataclass. So for now, jump back to JSON and validate the string.
41 json_str = pydantic_core.to_json(obj)
42 typed_dict = self._adapted_type.validate_json(json_str, strict=True)
43 return Success(typed_dict)
44 except pydantic.ValidationError as validation_error:
45 return _handle_error(validation_error)
46
47
48def _handle_error(validation_error: pydantic.ValidationError) -> Failure:

Callers 10

mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…