Elffuss BraidHub

kikocis/llama-stack public

main · 25.2 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7"""
8Type-safe data interchange for Python data classes.
9
10:see: https://github.com/hunyadi/strong_typing
11"""
12
13import dataclasses
14import datetime
15import decimal
16import enum
17import functools
18import inspect
19import json
20import typing
21import uuid
22from copy import deepcopy
23from typing import (
24 Any,
25 Callable,
26 ClassVar,
27 Dict,
28 List,
29 Literal,
30 Optional,
31 overload,
32 Tuple,
33 Type,
34 TypeVar,
35 Union,
36)
37
38import jsonschema
39
40from . import docstring
41from .auxiliary import (
42 Alias,
43 get_auxiliary_format,
44 IntegerRange,
45 MaxLength,
46 MinLength,
47 Precision,
48)
49from .core import JsonArray, JsonObject, JsonType, Schema, StrictJsonType
50from .inspection import (
51 enum_value_types,
52 get_annotation,
53 get_class_properties,
54 is_type_enum,
55 is_type_like,
56 is_type_optional,
57 TypeLike,
58 unwrap_optional_type,
59)
60from .name import python_type_to_name
61from .serialization import object_to_json
62
63# determines the maximum number of distinct enum members up to which a Dict[EnumType, Any] is converted into a JSON
64# schema with explicitly listed properties (rather than employing a pattern constraint on property names)
65OBJECT_ENUM_EXPANSION_LIMIT = 4
66
67
68T = TypeVar("T")
69
70
71def get_class_docstrings(data_type: type) -> Tuple[Optional[str], Optional[str]]:
72 docstr = docstring.parse_type(data_type)
73
74 # check if class has a doc-string other than the auto-generated string assigned by @dataclass
75 if docstring.has_default_docstring(data_type):
76 return None, None
77
78 return docstr.short_description, docstr.long_description
79
80
81def get_class_property_docstrings(
82 data_type: type, transform_fun: Optional[Callable[[type, str, str], str]] = None
83) -> Dict[str, str]:
84 """
85 Extracts the documentation strings associated with the properties of a composite type.
86
87 :param data_type: The object whose properties to iterate over.
88 :param transform_fun: An optional function that maps a property documentation string to a custom tailored string.
89 :returns: A dictionary mapping property names to descriptions.
90 """
91
92 result = {}
93 for base in inspect.getmro(data_type):
94 docstr = docstring.parse_type(base)
95 for param in docstr.params.values():
96 if param.name in result:
97 continue
98
99 if transform_fun:
100 description = transform_fun(data_type, param.name, param.description)
101 else:
102 description = param.description
103
104 result[param.name] = description
105 return result
106
107
108def docstring_to_schema(data_type: type) -> Schema:
109 short_description, long_description = get_class_docstrings(data_type)
110 schema: Schema = {}
111 if short_description:
112 schema["title"] = short_description
113 if long_description:
114 schema["description"] = long_description
115 return schema
116
117
118def id_from_ref(data_type: Union[typing.ForwardRef, str, type]) -> str:
119 "Extracts the name of a possibly forward-referenced type."
120
121 if isinstance(data_type, typing.ForwardRef):
122 forward_type: typing.ForwardRef = data_type
123 return forward_type.__forward_arg__
124 elif isinstance(data_type, str):
125 return data_type
126 else:
127 return data_type.__name__
128
129
130def type_from_ref(data_type: Union[typing.ForwardRef, str, type]) -> Tuple[str, type]:
131 "Creates a type from a forward reference."
132
133 if isinstance(data_type, typing.ForwardRef):
134 forward_type: typing.ForwardRef = data_type
135 true_type = eval(forward_type.__forward_code__)
136 return forward_type.__forward_arg__, true_type
137 elif isinstance(data_type, str):
138 true_type = eval(data_type)
139 return data_type, true_type
140 else:
141 return data_type.__name__, data_type
142
143
144@dataclasses.dataclass
145class TypeCatalogEntry:
146 schema: Optional[Schema]
147 identifier: str
148 examples: Optional[JsonType] = None
149
150
151class TypeCatalog:
152 "Maintains an association of well-known Python types to their JSON schema."
153
154 _by_type: Dict[TypeLike, TypeCatalogEntry]
155 _by_name: Dict[str, TypeCatalogEntry]
156
157 def __init__(self) -> None:
158 self._by_type = {}
159 self._by_name = {}
160
161 def __contains__(self, data_type: TypeLike) -> bool:
162 if isinstance(data_type, typing.ForwardRef):
163 fwd: typing.ForwardRef = data_type
164 name = fwd.__forward_arg__
165 return name in self._by_name
166 else:
167 return data_type in self._by_type
168
169 def add(
170 self,
171 data_type: TypeLike,
172 schema: Optional[Schema],
173 identifier: str,
174 examples: Optional[List[JsonType]] = None,
175 ) -> None:
176 if isinstance(data_type, typing.ForwardRef):
177 raise TypeError("forward references cannot be used to register a type")
178
179 if data_type in self._by_type:
180 raise ValueError(f"type {data_type} is already registered in the catalog")
181
182 entry = TypeCatalogEntry(schema, identifier, examples)
183 self._by_type[data_type] = entry
184 self._by_name[identifier] = entry
185
186 def get(self, data_type: TypeLike) -> TypeCatalogEntry:
187 if isinstance(data_type, typing.ForwardRef):
188 fwd: typing.ForwardRef = data_type
189 name = fwd.__forward_arg__
190 return self._by_name[name]
191 else:
192 return self._by_type[data_type]
193
194
195@dataclasses.dataclass
196class SchemaOptions:
197 definitions_path: str = "#/definitions/"
198 use_descriptions: bool = True
199 use_examples: bool = True
200 property_description_fun: Optional[Callable[[type, str, str], str]] = None
201
202
203class JsonSchemaGenerator:
204 "Creates a JSON schema with user-defined type definitions."
205
206 type_catalog: ClassVar[TypeCatalog] = TypeCatalog()
207 types_used: Dict[str, TypeLike]
208 options: SchemaOptions
209
210 def __init__(self, options: Optional[SchemaOptions] = None):
211 if options is None:
212 self.options = SchemaOptions()
213 else:
214 self.options = options
215 self.types_used = {}
216
217 @functools.singledispatchmethod
218 def _metadata_to_schema(self, arg: object) -> Schema:
219 # unrecognized annotation
220 return {}
221
222 @_metadata_to_schema.register
223 def _(self, arg: IntegerRange) -> Schema:
224 return {"minimum": arg.minimum, "maximum": arg.maximum}
225
226 @_metadata_to_schema.register
227 def _(self, arg: Precision) -> Schema:
228 return {
229 "multipleOf": 10 ** (-arg.decimal_digits),
230 "exclusiveMinimum": -(10**arg.integer_digits),
231 "exclusiveMaximum": (10**arg.integer_digits),
232 }
233
234 @_metadata_to_schema.register
235 def _(self, arg: MinLength) -> Schema:
236 return {"minLength": arg.value}
237
238 @_metadata_to_schema.register
239 def _(self, arg: MaxLength) -> Schema:
240 return {"maxLength": arg.value}
241
242 def _with_metadata(
243 self, type_schema: Schema, metadata: Optional[Tuple[Any, ...]]
244 ) -> Schema:
245 if metadata:
246 for m in metadata:
247 type_schema.update(self._metadata_to_schema(m))
248 return type_schema
249
250 def _simple_type_to_schema(self, typ: TypeLike) -> Optional[Schema]:
251 """
252 Returns the JSON schema associated with a simple, unrestricted type.
253
254 :returns: The schema for a simple type, or `None`.
255 """
256
257 if typ is type(None):
258 return {"type": "null"}
259 elif typ is bool:
260 return {"type": "boolean"}
261 elif typ is int:
262 return {"type": "integer"}
263 elif typ is float:
264 return {"type": "number"}
265 elif typ is str:
266 return {"type": "string"}
267 elif typ is bytes:
268 return {"type": "string", "contentEncoding": "base64"}
269 elif typ is datetime.datetime:
270 # 2018-11-13T20:20:39+00:00
271 return {
272 "type": "string",
273 "format": "date-time",
274 }
275 elif typ is datetime.date:
276 # 2018-11-13
277 return {"type": "string", "format": "date"}
278 elif typ is datetime.time:
279 # 20:20:39+00:00
280 return {"type": "string", "format": "time"}
281 elif typ is decimal.Decimal:
282 return {"type": "number"}
283 elif typ is uuid.UUID:
284 # f81d4fae-7dec-11d0-a765-00a0c91e6bf6
285 return {"type": "string", "format": "uuid"}
286 elif typ is Any:
287 return {
288 "oneOf": [
289 {"type": "null"},
290 {"type": "boolean"},
291 {"type": "number"},
292 {"type": "string"},
293 {"type": "array"},
294 {"type": "object"},
295 ]
296 }
297 elif typ is JsonObject:
298 return {"type": "object"}
299 elif typ is JsonArray:
300 return {"type": "array"}
301 else:
302 # not a simple type
303 return None
304
305 def type_to_schema(self, data_type: TypeLike, force_expand: bool = False) -> Schema:
306 """
307 Returns the JSON schema associated with a type.
308
309 :param data_type: The Python type whose JSON schema to return.
310 :param force_expand: Forces a JSON schema to be returned even if the type is registered in the catalog of known types.
311 :returns: The JSON schema associated with the type.
312 """
313
314 # short-circuit for common simple types
315 schema = self._simple_type_to_schema(data_type)
316 if schema is not None:
317 return schema
318
319 # types registered in the type catalog of well-known types
320 type_catalog = JsonSchemaGenerator.type_catalog
321 if not force_expand and data_type in type_catalog:
322 # user-defined type
323 identifier = type_catalog.get(data_type).identifier
324 self.types_used.setdefault(identifier, data_type)
325 return {"$ref": f"{self.options.definitions_path}{identifier}"}
326
327 # unwrap annotated types
328 metadata = getattr(data_type, "__metadata__", None)
329 if metadata is not None:
330 # type is Annotated[T, ...]
331 typ = typing.get_args(data_type)[0]
332
333 schema = self._simple_type_to_schema(typ)
334 if schema is not None:
335 # recognize well-known auxiliary types
336 fmt = get_auxiliary_format(data_type)
337 if fmt is not None:
338 schema.update({"format": fmt})
339 return schema
340 else:
341 return self._with_metadata(schema, metadata)
342
343 else:
344 # type is a regular type
345 typ = data_type
346
347 if isinstance(typ, typing.ForwardRef) or isinstance(typ, str):
348 if force_expand:
349 identifier, true_type = type_from_ref(typ)
350 return self.type_to_schema(true_type, force_expand=True)
351 else:
352 try:
353 identifier, true_type = type_from_ref(typ)
354 self.types_used[identifier] = true_type
355 except NameError:
356 identifier = id_from_ref(typ)
357
358 return {"$ref": f"{self.options.definitions_path}{identifier}"}
359
360 if is_type_enum(typ):
361 enum_type: Type[enum.Enum] = typ
362 value_types = enum_value_types(enum_type)
363 if len(value_types) != 1:
364 raise ValueError(
365 f"enumerations must have a consistent member value type but several types found: {value_types}"
366 )
367 enum_value_type = value_types.pop()
368
369 enum_schema: Schema
370 if (
371 enum_value_type is bool
372 or enum_value_type is int
373 or enum_value_type is float
374 or enum_value_type is str
375 ):
376 if enum_value_type is bool:
377 enum_schema_type = "boolean"
378 elif enum_value_type is int:
379 enum_schema_type = "integer"
380 elif enum_value_type is float:
381 enum_schema_type = "number"
382 elif enum_value_type is str:
383 enum_schema_type = "string"
384
385 enum_schema = {
386 "type": enum_schema_type,
387 "enum": [object_to_json(e.value) for e in enum_type],
388 }
389 if self.options.use_descriptions:
390 enum_schema.update(docstring_to_schema(typ))
391 return enum_schema
392 else:
393 enum_schema = self.type_to_schema(enum_value_type)
394 if self.options.use_descriptions:
395 enum_schema.update(docstring_to_schema(typ))
396 return enum_schema
397
398 origin_type = typing.get_origin(typ)
399 if origin_type is list:
400 (list_type,) = typing.get_args(typ) # unpack single tuple element
401 return {"type": "array", "items": self.type_to_schema(list_type)}
402 elif origin_type is dict:
403 key_type, value_type = typing.get_args(typ)
404 if not (key_type is str or key_type is int or is_type_enum(key_type)):
405 raise ValueError(
406 "`dict` with key type not coercible to `str` is not supported"
407 )
408
409 dict_schema: Schema
410 value_schema = self.type_to_schema(value_type)
411 if is_type_enum(key_type):
412 enum_values = [str(e.value) for e in key_type]
413 if len(enum_values) > OBJECT_ENUM_EXPANSION_LIMIT:
414 dict_schema = {
415 "propertyNames": {
416 "pattern": "^(" + "|".join(enum_values) + ")$"
417 },
418 "additionalProperties": value_schema,
419 }
420 else:
421 dict_schema = {
422 "properties": {value: value_schema for value in enum_values},
423 "additionalProperties": False,
424 }
425 else:
426 dict_schema = {"additionalProperties": value_schema}
427
428 schema = {"type": "object"}
429 schema.update(dict_schema)
430 return schema
431 elif origin_type is set:
432 (set_type,) = typing.get_args(typ) # unpack single tuple element
433 return {
434 "type": "array",
435 "items": self.type_to_schema(set_type),
436 "uniqueItems": True,
437 }
438 elif origin_type is tuple:
439 args = typing.get_args(typ)
440 return {
441 "type": "array",
442 "minItems": len(args),
443 "maxItems": len(args),
444 "prefixItems": [
445 self.type_to_schema(member_type) for member_type in args
446 ],
447 }
448 elif origin_type is Union:
449 return {
450 "oneOf": [
451 self.type_to_schema(union_type)
452 for union_type in typing.get_args(typ)
453 ]
454 }
455 elif origin_type is Literal:
456 (literal_value,) = typing.get_args(typ) # unpack value of literal type
457 schema = self.type_to_schema(type(literal_value))
458 schema["const"] = literal_value
459 return schema
460 elif origin_type is type:
461 (concrete_type,) = typing.get_args(typ) # unpack single tuple element
462 return {"const": self.type_to_schema(concrete_type, force_expand=True)}
463
464 # dictionary of class attributes
465 members = dict(inspect.getmembers(typ, lambda a: not inspect.isroutine(a)))
466
467 property_docstrings = get_class_property_docstrings(
468 typ, self.options.property_description_fun
469 )
470
471 properties: Dict[str, Schema] = {}
472 required: List[str] = []
473 for property_name, property_type in get_class_properties(typ):
474 defaults = {}
475 if "model_fields" in members:
476 f = members["model_fields"]
477 defaults = {k: finfo.default for k, finfo in f.items()}
478
479 # rename property if an alias name is specified
480 alias = get_annotation(property_type, Alias)
481 if alias:
482 output_name = alias.name
483 else:
484 output_name = property_name
485
486 if is_type_optional(property_type):
487 optional_type: type = unwrap_optional_type(property_type)
488 property_def = self.type_to_schema(optional_type)
489 else:
490 property_def = self.type_to_schema(property_type)
491 required.append(output_name)
492
493 # check if attribute has a default value initializer
494 if defaults.get(property_name) is not None:
495 def_value = defaults[property_name]
496 # check if value can be directly represented in JSON
497 if isinstance(
498 def_value,
499 (
500 bool,
501 int,
502 float,
503 str,
504 enum.Enum,
505 datetime.datetime,
506 datetime.date,
507 datetime.time,
508 ),
509 ):
510 property_def["default"] = object_to_json(def_value)
511
512 # add property docstring if available
513 property_doc = property_docstrings.get(property_name)
514 if property_doc:
515 property_def.pop("title", None)
516 property_def["description"] = property_doc
517
518 properties[output_name] = property_def
519
520 schema = {"type": "object"}
521 if len(properties) > 0:
522 schema["properties"] = typing.cast(JsonType, properties)
523 schema["additionalProperties"] = False
524 if len(required) > 0:
525 schema["required"] = typing.cast(JsonType, required)
526 if self.options.use_descriptions:
527 schema.update(docstring_to_schema(typ))
528 return schema
529
530 def _type_to_schema_with_lookup(self, data_type: TypeLike) -> Schema:
531 """
532 Returns the JSON schema associated with a type that may be registered in the catalog of known types.
533
534 :param data_type: The type whose JSON schema we seek.
535 :returns: The JSON schema associated with the type.
536 """
537
538 entry = JsonSchemaGenerator.type_catalog.get(data_type)
539 if entry.schema is None:
540 type_schema = self.type_to_schema(data_type, force_expand=True)
541 else:
542 type_schema = deepcopy(entry.schema)
543
544 # add descriptive text (if present)
545 if self.options.use_descriptions:
546 if isinstance(data_type, type) and not isinstance(
547 data_type, typing.ForwardRef
548 ):
549 type_schema.update(docstring_to_schema(data_type))
550
551 # add example (if present)
552 if self.options.use_examples and entry.examples:
553 type_schema["examples"] = entry.examples
554
555 return type_schema
556
557 def classdef_to_schema(
558 self, data_type: TypeLike, force_expand: bool = False
559 ) -> Tuple[Schema, Dict[str, Schema]]:
560 """
561 Returns the JSON schema associated with a type and any nested types.
562
563 :param data_type: The type whose JSON schema to return.
564 :param force_expand: True if a full JSON schema is to be returned even for well-known types; false if a schema
565 reference is to be used for well-known types.
566 :returns: A tuple of the JSON schema, and a mapping between nested type names and their corresponding schema.
567 """
568
569 if not is_type_like(data_type):
570 raise TypeError(f"expected a type-like object but got: {data_type}")
571
572 self.types_used = {}
573 try:
574 type_schema = self.type_to_schema(data_type, force_expand=force_expand)
575
576 types_defined: Dict[str, Schema] = {}
577 while len(self.types_used) > len(types_defined):
578 # make a snapshot copy; original collection is going to be modified
579 types_undefined = {
580 sub_name: sub_type
581 for sub_name, sub_type in self.types_used.items()
582 if sub_name not in types_defined
583 }
584
585 # expand undefined types, which may lead to additional types to be defined
586 for sub_name, sub_type in types_undefined.items():
587 types_defined[sub_name] = self._type_to_schema_with_lookup(sub_type)
588
589 type_definitions = dict(sorted(types_defined.items()))
590 finally:
591 self.types_used = {}
592
593 return type_schema, type_definitions
594
595
596class Validator(enum.Enum):
597 "Defines constants for JSON schema standards."
598
599 Draft7 = jsonschema.Draft7Validator
600 Draft201909 = jsonschema.Draft201909Validator
601 Draft202012 = jsonschema.Draft202012Validator
602 Latest = jsonschema.Draft202012Validator
603
604
605def classdef_to_schema(
606 data_type: TypeLike,
607 options: Optional[SchemaOptions] = None,
608 validator: Validator = Validator.Latest,
609) -> Schema:
610 """
611 Returns the JSON schema corresponding to the given type.
612
613 :param data_type: The Python type used to generate the JSON schema
614 :returns: A JSON object that you can serialize to a JSON string with json.dump or json.dumps
615 :raises TypeError: Indicates that the generated JSON schema does not validate against the desired meta-schema.
616 """
617
618 # short-circuit with an error message when passing invalid data
619 if not is_type_like(data_type):
620 raise TypeError(f"expected a type-like object but got: {data_type}")
621
622 generator = JsonSchemaGenerator(options)
623 type_schema, type_definitions = generator.classdef_to_schema(data_type)
624
625 class_schema: Schema = {}
626 if type_definitions:
627 class_schema["definitions"] = typing.cast(JsonType, type_definitions)
628 class_schema.update(type_schema)
629
630 validator_id = validator.value.META_SCHEMA["$id"]
631 try:
632 validator.value.check_schema(class_schema)
633 except jsonschema.exceptions.SchemaError:
634 raise TypeError(
635 f"schema does not validate against meta-schema <{validator_id}>"
636 )
637
638 schema = {"$schema": validator_id}
639 schema.update(class_schema)
640 return schema
641
642
643def validate_object(data_type: TypeLike, json_dict: JsonType) -> None:
644 """
645 Validates if the JSON dictionary object conforms to the expected type.
646
647 :param data_type: The type to match against.
648 :param json_dict: A JSON object obtained with `json.load` or `json.loads`.
649 :raises jsonschema.exceptions.ValidationError: Indicates that the JSON object cannot represent the type.
650 """
651
652 schema_dict = classdef_to_schema(data_type)
653 jsonschema.validate(
654 json_dict, schema_dict, format_checker=jsonschema.FormatChecker()
655 )
656
657
658def print_schema(data_type: type) -> None:
659 """Pretty-prints the JSON schema corresponding to the type."""
660
661 s = classdef_to_schema(data_type)
662 print(json.dumps(s, indent=4))
663
664
665def get_schema_identifier(data_type: type) -> Optional[str]:
666 if data_type in JsonSchemaGenerator.type_catalog:
667 return JsonSchemaGenerator.type_catalog.get(data_type).identifier
668 else:
669 return None
670
671
672def register_schema(
673 data_type: T,
674 schema: Optional[Schema] = None,
675 name: Optional[str] = None,
676 examples: Optional[List[JsonType]] = None,
677) -> T:
678 """
679 Associates a type with a JSON schema definition.
680
681 :param data_type: The type to associate with a JSON schema.
682 :param schema: The schema to associate the type with. Derived automatically if omitted.
683 :param name: The name used for looking uo the type. Determined automatically if omitted.
684 :returns: The input type.
685 """
686
687 JsonSchemaGenerator.type_catalog.add(
688 data_type,
689 schema,
690 name if name is not None else python_type_to_name(data_type),
691 examples,
692 )
693 return data_type
694
695
696@overload
697def json_schema_type(cls: Type[T], /) -> Type[T]: ...
698
699
700@overload
701def json_schema_type(
702 cls: None, *, schema: Optional[Schema] = None
703) -> Callable[[Type[T]], Type[T]]: ...
704
705
706def json_schema_type(
707 cls: Optional[Type[T]] = None,
708 *,
709 schema: Optional[Schema] = None,
710 examples: Optional[List[JsonType]] = None,
711) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
712 """Decorator to add user-defined schema definition to a class."""
713
714 def wrap(cls: Type[T]) -> Type[T]:
715 return register_schema(cls, schema, examples=examples)
716
717 # see if decorator is used as @json_schema_type or @json_schema_type()
718 if cls is None:
719 # called with parentheses
720 return wrap
721 else:
722 # called as @json_schema_type without parentheses
723 return wrap(cls)
724
725
726register_schema(JsonObject, name="JsonObject")
727register_schema(JsonArray, name="JsonArray")
728
729register_schema(
730 JsonType,
731 name="JsonType",
732 examples=[
733 {
734 "property1": None,
735 "property2": True,
736 "property3": 64,
737 "property4": "string",
738 "property5": ["item"],
739 "property6": {"key": "value"},
740 }
741 ],
742)
743register_schema(
744 StrictJsonType,
745 name="StrictJsonType",
746 examples=[
747 {
748 "property1": True,
749 "property2": 64,
750 "property3": "string",
751 "property4": ["item"],
752 "property5": {"key": "value"},
753 }
754 ],
755)