Elffuss BraidHub

kikocis/llama-stack public

7b7b9b1ba243 · 24.1 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
7import hashlib
8import ipaddress
9import typing
10from typing import Any, Dict, Set, Union
11
12from strong_typing.core import JsonType
13from strong_typing.docstring import Docstring, parse_type
14from strong_typing.inspection import (
15 is_generic_list,
16 is_type_optional,
17 is_type_union,
18 unwrap_generic_list,
19 unwrap_optional_type,
20 unwrap_union_types,
21)
22from strong_typing.name import python_type_to_name
23from strong_typing.schema import (
24 get_schema_identifier,
25 JsonSchemaGenerator,
26 register_schema,
27 Schema,
28 SchemaOptions,
29)
30from strong_typing.serialization import json_dump_string, object_to_json
31
32from .operations import (
33 EndpointOperation,
34 get_endpoint_events,
35 get_endpoint_operations,
36 HTTPMethod,
37)
38from .options import *
39from .specification import (
40 Components,
41 Document,
42 Example,
43 ExampleRef,
44 MediaType,
45 Operation,
46 Parameter,
47 ParameterLocation,
48 PathItem,
49 RequestBody,
50 Response,
51 ResponseRef,
52 SchemaOrRef,
53 SchemaRef,
54 Tag,
55 TagGroup,
56)
57
58register_schema(
59 ipaddress.IPv4Address,
60 schema={
61 "type": "string",
62 "format": "ipv4",
63 "title": "IPv4 address",
64 "description": "IPv4 address, according to dotted-quad ABNF syntax as defined in RFC 2673, section 3.2.",
65 },
66 examples=["192.0.2.0", "198.51.100.1", "203.0.113.255"],
67)
68
69register_schema(
70 ipaddress.IPv6Address,
71 schema={
72 "type": "string",
73 "format": "ipv6",
74 "title": "IPv6 address",
75 "description": "IPv6 address, as defined in RFC 2373, section 2.2.",
76 },
77 examples=[
78 "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210",
79 "1080:0:0:0:8:800:200C:417A",
80 "1080::8:800:200C:417A",
81 "FF01::101",
82 "::1",
83 ],
84)
85
86
87def http_status_to_string(status_code: HTTPStatusCode) -> str:
88 "Converts an HTTP status code to a string."
89
90 if isinstance(status_code, HTTPStatus):
91 return str(status_code.value)
92 elif isinstance(status_code, int):
93 return str(status_code)
94 elif isinstance(status_code, str):
95 return status_code
96 else:
97 raise TypeError("expected: HTTP status code")
98
99
100class SchemaBuilder:
101 schema_generator: JsonSchemaGenerator
102 schemas: Dict[str, Schema]
103
104 def __init__(self, schema_generator: JsonSchemaGenerator) -> None:
105 self.schema_generator = schema_generator
106 self.schemas = {}
107
108 def classdef_to_schema(self, typ: type) -> Schema:
109 """
110 Converts a type to a JSON schema.
111 For nested types found in the type hierarchy, adds the type to the schema registry in the OpenAPI specification section `components`.
112 """
113
114 type_schema, type_definitions = self.schema_generator.classdef_to_schema(typ)
115
116 # append schema to list of known schemas, to be used in OpenAPI's Components Object section
117 for ref, schema in type_definitions.items():
118 self._add_ref(ref, schema)
119
120 return type_schema
121
122 def classdef_to_named_schema(self, name: str, typ: type) -> Schema:
123 schema = self.classdef_to_schema(typ)
124 self._add_ref(name, schema)
125 return schema
126
127 def classdef_to_ref(self, typ: type) -> SchemaOrRef:
128 """
129 Converts a type to a JSON schema, and if possible, returns a schema reference.
130 For composite types (such as classes), adds the type to the schema registry in the OpenAPI specification section `components`.
131 """
132
133 type_schema = self.classdef_to_schema(typ)
134 if typ is str or typ is int or typ is float:
135 # represent simple types as themselves
136 return type_schema
137
138 type_name = get_schema_identifier(typ)
139 if type_name is not None:
140 return self._build_ref(type_name, type_schema)
141
142 try:
143 type_name = python_type_to_name(typ)
144 return self._build_ref(type_name, type_schema)
145 except TypeError:
146 pass
147
148 return type_schema
149
150 def _build_ref(self, type_name: str, type_schema: Schema) -> SchemaRef:
151 self._add_ref(type_name, type_schema)
152 return SchemaRef(type_name)
153
154 def _add_ref(self, type_name: str, type_schema: Schema) -> None:
155 if type_name not in self.schemas:
156 self.schemas[type_name] = type_schema
157
158
159class ContentBuilder:
160 schema_builder: SchemaBuilder
161 schema_transformer: Optional[Callable[[SchemaOrRef], SchemaOrRef]]
162 sample_transformer: Optional[Callable[[JsonType], JsonType]]
163
164 def __init__(
165 self,
166 schema_builder: SchemaBuilder,
167 schema_transformer: Optional[Callable[[SchemaOrRef], SchemaOrRef]] = None,
168 sample_transformer: Optional[Callable[[JsonType], JsonType]] = None,
169 ) -> None:
170 self.schema_builder = schema_builder
171 self.schema_transformer = schema_transformer
172 self.sample_transformer = sample_transformer
173
174 def build_content(
175 self, payload_type: type, examples: Optional[List[Any]] = None
176 ) -> Dict[str, MediaType]:
177 "Creates the content subtree for a request or response."
178
179 if is_generic_list(payload_type):
180 media_type = "application/jsonl"
181 item_type = unwrap_generic_list(payload_type)
182 else:
183 media_type = "application/json"
184 item_type = payload_type
185
186 return {media_type: self.build_media_type(item_type, examples)}
187
188 def build_media_type(
189 self, item_type: type, examples: Optional[List[Any]] = None
190 ) -> MediaType:
191 schema = self.schema_builder.classdef_to_ref(item_type)
192 if self.schema_transformer:
193 schema_transformer: Callable[[SchemaOrRef], SchemaOrRef] = self.schema_transformer # type: ignore
194 schema = schema_transformer(schema)
195
196 if not examples:
197 return MediaType(schema=schema)
198
199 if len(examples) == 1:
200 return MediaType(schema=schema, example=self._build_example(examples[0]))
201
202 return MediaType(
203 schema=schema,
204 examples=self._build_examples(examples),
205 )
206
207 def _build_examples(
208 self, examples: List[Any]
209 ) -> Dict[str, Union[Example, ExampleRef]]:
210 "Creates a set of several examples for a media type."
211
212 if self.sample_transformer:
213 sample_transformer: Callable[[JsonType], JsonType] = self.sample_transformer # type: ignore
214 else:
215 sample_transformer = lambda sample: sample
216
217 results: Dict[str, Union[Example, ExampleRef]] = {}
218 for example in examples:
219 value = sample_transformer(object_to_json(example))
220
221 hash_string = (
222 hashlib.md5(json_dump_string(value).encode("utf-8")).digest().hex()
223 )
224 name = f"ex-{hash_string}"
225
226 results[name] = Example(value=value)
227
228 return results
229
230 def _build_example(self, example: Any) -> Any:
231 "Creates a single example for a media type."
232
233 if self.sample_transformer:
234 sample_transformer: Callable[[JsonType], JsonType] = self.sample_transformer # type: ignore
235 else:
236 sample_transformer = lambda sample: sample
237
238 return sample_transformer(object_to_json(example))
239
240
241@dataclass
242class ResponseOptions:
243 """
244 Configuration options for building a response for an operation.
245
246 :param type_descriptions: Maps each response type to a textual description (if available).
247 :param examples: A list of response examples.
248 :param status_catalog: Maps each response type to an HTTP status code.
249 :param default_status_code: HTTP status code assigned to responses that have no mapping.
250 """
251
252 type_descriptions: Dict[type, str]
253 examples: Optional[List[Any]]
254 status_catalog: Dict[type, HTTPStatusCode]
255 default_status_code: HTTPStatusCode
256
257
258@dataclass
259class StatusResponse:
260 status_code: str
261 types: List[type] = dataclasses.field(default_factory=list)
262 examples: List[Any] = dataclasses.field(default_factory=list)
263
264
265class ResponseBuilder:
266 content_builder: ContentBuilder
267
268 def __init__(self, content_builder: ContentBuilder) -> None:
269 self.content_builder = content_builder
270
271 def _get_status_responses(
272 self, options: ResponseOptions
273 ) -> Dict[str, StatusResponse]:
274 status_responses: Dict[str, StatusResponse] = {}
275
276 for response_type in options.type_descriptions.keys():
277 status_code = http_status_to_string(
278 options.status_catalog.get(response_type, options.default_status_code)
279 )
280
281 # look up response for status code
282 if status_code not in status_responses:
283 status_responses[status_code] = StatusResponse(status_code)
284 status_response = status_responses[status_code]
285
286 # append response types that are assigned the given status code
287 status_response.types.append(response_type)
288
289 # append examples that have the matching response type
290 if options.examples:
291 status_response.examples.extend(
292 example
293 for example in options.examples
294 if isinstance(example, response_type)
295 )
296
297 return dict(sorted(status_responses.items()))
298
299 def build_response(
300 self, options: ResponseOptions
301 ) -> Dict[str, Union[Response, ResponseRef]]:
302 """
303 Groups responses that have the same status code.
304 """
305
306 responses: Dict[str, Union[Response, ResponseRef]] = {}
307 status_responses = self._get_status_responses(options)
308 for status_code, status_response in status_responses.items():
309 response_types = tuple(status_response.types)
310 if len(response_types) > 1:
311 composite_response_type: type = Union[response_types] # type: ignore
312 else:
313 (response_type,) = response_types
314 composite_response_type = response_type
315
316 description = " **OR** ".join(
317 filter(
318 None,
319 (
320 options.type_descriptions[response_type]
321 for response_type in response_types
322 ),
323 )
324 )
325
326 responses[status_code] = self._build_response(
327 response_type=composite_response_type,
328 description=description,
329 examples=status_response.examples or None,
330 )
331
332 return responses
333
334 def _build_response(
335 self,
336 response_type: type,
337 description: str,
338 examples: Optional[List[Any]] = None,
339 ) -> Response:
340 "Creates a response subtree."
341
342 if response_type is not None:
343 return Response(
344 description=description,
345 content=self.content_builder.build_content(response_type, examples),
346 )
347 else:
348 return Response(description=description)
349
350
351def schema_error_wrapper(schema: SchemaOrRef) -> Schema:
352 "Wraps an error output schema into a top-level error schema."
353
354 return {
355 "type": "object",
356 "properties": {
357 "error": schema, # type: ignore
358 },
359 "additionalProperties": False,
360 "required": [
361 "error",
362 ],
363 }
364
365
366def sample_error_wrapper(error: JsonType) -> JsonType:
367 "Wraps an error output sample into a top-level error sample."
368
369 return {"error": error}
370
371
372class Generator:
373 endpoint: type
374 options: Options
375 schema_builder: SchemaBuilder
376 responses: Dict[str, Response]
377
378 def __init__(self, endpoint: type, options: Options) -> None:
379 self.endpoint = endpoint
380 self.options = options
381 schema_generator = JsonSchemaGenerator(
382 SchemaOptions(
383 definitions_path="#/components/schemas/",
384 use_examples=self.options.use_examples,
385 property_description_fun=options.property_description_fun,
386 )
387 )
388 self.schema_builder = SchemaBuilder(schema_generator)
389 self.responses = {}
390
391 def _build_type_tag(self, ref: str, schema: Schema) -> Tag:
392 definition = f'<SchemaDefinition schemaRef="#/components/schemas/{ref}" />'
393 title = typing.cast(str, schema.get("title"))
394 description = typing.cast(str, schema.get("description"))
395 return Tag(
396 name=ref,
397 description="\n\n".join(
398 s for s in (title, description, definition) if s is not None
399 ),
400 )
401
402 def _build_extra_tag_groups(
403 self, extra_types: Dict[str, List[type]]
404 ) -> Dict[str, List[Tag]]:
405 """
406 Creates a dictionary of tag group captions as keys, and tag lists as values.
407
408 :param extra_types: A dictionary of type categories and list of types in that category.
409 """
410
411 extra_tags: Dict[str, List[Tag]] = {}
412
413 for category_name, category_items in extra_types.items():
414 tag_list: List[Tag] = []
415
416 for extra_type in category_items:
417 name = python_type_to_name(extra_type)
418 schema = self.schema_builder.classdef_to_named_schema(name, extra_type)
419 tag_list.append(self._build_type_tag(name, schema))
420
421 if tag_list:
422 extra_tags[category_name] = tag_list
423
424 return extra_tags
425
426 def _build_operation(self, op: EndpointOperation) -> Operation:
427 doc_string = parse_type(op.func_ref)
428 doc_params = dict(
429 (param.name, param.description) for param in doc_string.params.values()
430 )
431
432 # parameters passed in URL component path
433 path_parameters = [
434 Parameter(
435 name=param_name,
436 in_=ParameterLocation.Path,
437 description=doc_params.get(param_name),
438 required=True,
439 schema=self.schema_builder.classdef_to_ref(param_type),
440 )
441 for param_name, param_type in op.path_params
442 ]
443
444 # parameters passed in URL component query string
445 query_parameters = []
446 for param_name, param_type in op.query_params:
447 if is_type_optional(param_type):
448 inner_type: type = unwrap_optional_type(param_type)
449 required = False
450 else:
451 inner_type = param_type
452 required = True
453
454 query_parameter = Parameter(
455 name=param_name,
456 in_=ParameterLocation.Query,
457 description=doc_params.get(param_name),
458 required=required,
459 schema=self.schema_builder.classdef_to_ref(inner_type),
460 )
461 query_parameters.append(query_parameter)
462
463 # parameters passed anywhere
464 parameters = path_parameters + query_parameters
465
466 # data passed in payload
467 if op.request_params:
468 builder = ContentBuilder(self.schema_builder)
469 first = next(iter(op.request_params))
470 request_name, request_type = first
471
472 from dataclasses import make_dataclass
473
474 op_name = "".join(word.capitalize() for word in op.name.split("_"))
475 request_name = f"{op_name}Request"
476 request_type = make_dataclass(request_name, op.request_params)
477
478 requestBody = RequestBody(
479 content={
480 "application/json": builder.build_media_type(
481 request_type, op.request_examples
482 )
483 },
484 description=doc_params.get(request_name),
485 required=True,
486 )
487 else:
488 requestBody = None
489
490 # success response types
491 if doc_string.returns is None and is_type_union(op.response_type):
492 # split union of return types into a list of response types
493 success_type_docstring: Dict[type, Docstring] = {
494 typing.cast(type, item): parse_type(item)
495 for item in unwrap_union_types(op.response_type)
496 }
497 success_type_descriptions = {
498 item: doc_string.short_description
499 for item, doc_string in success_type_docstring.items()
500 if doc_string.short_description
501 }
502 else:
503 # use return type as a single response type
504 success_type_descriptions = {
505 op.response_type: (
506 doc_string.returns.description if doc_string.returns else "OK"
507 )
508 }
509
510 response_examples = op.response_examples or []
511 success_examples = [
512 example
513 for example in response_examples
514 if not isinstance(example, Exception)
515 ]
516
517 content_builder = ContentBuilder(self.schema_builder)
518 response_builder = ResponseBuilder(content_builder)
519 response_options = ResponseOptions(
520 success_type_descriptions,
521 success_examples if self.options.use_examples else None,
522 self.options.success_responses,
523 "200",
524 )
525 responses = response_builder.build_response(response_options)
526
527 # failure response types
528 if doc_string.raises:
529 exception_types: Dict[type, str] = {
530 item.raise_type: item.description for item in doc_string.raises.values()
531 }
532 exception_examples = [
533 example
534 for example in response_examples
535 if isinstance(example, Exception)
536 ]
537
538 if self.options.error_wrapper:
539 schema_transformer = schema_error_wrapper
540 sample_transformer = sample_error_wrapper
541 else:
542 schema_transformer = None
543 sample_transformer = None
544
545 content_builder = ContentBuilder(
546 self.schema_builder,
547 schema_transformer=schema_transformer,
548 sample_transformer=sample_transformer,
549 )
550 response_builder = ResponseBuilder(content_builder)
551 response_options = ResponseOptions(
552 exception_types,
553 exception_examples if self.options.use_examples else None,
554 self.options.error_responses,
555 "500",
556 )
557 responses.update(response_builder.build_response(response_options))
558
559 if op.event_type is not None:
560 builder = ContentBuilder(self.schema_builder)
561 callbacks = {
562 f"{op.func_name}_callback": {
563 "{$request.query.callback}": PathItem(
564 post=Operation(
565 requestBody=RequestBody(
566 content=builder.build_content(op.event_type)
567 ),
568 responses={"200": Response(description="OK")},
569 )
570 )
571 }
572 }
573
574 else:
575 callbacks = None
576
577 return Operation(
578 tags=[op.defining_class.__name__],
579 summary=doc_string.short_description,
580 description=doc_string.long_description,
581 parameters=parameters,
582 requestBody=requestBody,
583 responses=responses,
584 callbacks=callbacks,
585 security=[] if op.public else None,
586 )
587
588 def generate(self) -> Document:
589 paths: Dict[str, PathItem] = {}
590 endpoint_classes: Set[type] = set()
591 for op in get_endpoint_operations(
592 self.endpoint, use_examples=self.options.use_examples
593 ):
594 endpoint_classes.add(op.defining_class)
595
596 operation = self._build_operation(op)
597
598 if op.http_method is HTTPMethod.GET:
599 pathItem = PathItem(get=operation)
600 elif op.http_method is HTTPMethod.PUT:
601 pathItem = PathItem(put=operation)
602 elif op.http_method is HTTPMethod.POST:
603 pathItem = PathItem(post=operation)
604 elif op.http_method is HTTPMethod.DELETE:
605 pathItem = PathItem(delete=operation)
606 elif op.http_method is HTTPMethod.PATCH:
607 pathItem = PathItem(patch=operation)
608 else:
609 raise NotImplementedError(f"unknown HTTP method: {op.http_method}")
610
611 route = op.get_route()
612 if route in paths:
613 paths[route].update(pathItem)
614 else:
615 paths[route] = pathItem
616
617 operation_tags: List[Tag] = []
618 for cls in endpoint_classes:
619 doc_string = parse_type(cls)
620 operation_tags.append(
621 Tag(
622 name=cls.__name__,
623 description=doc_string.long_description,
624 displayName=doc_string.short_description,
625 )
626 )
627
628 # types that are produced/consumed by operations
629 type_tags = [
630 self._build_type_tag(ref, schema)
631 for ref, schema in self.schema_builder.schemas.items()
632 ]
633
634 # types that are emitted by events
635 event_tags: List[Tag] = []
636 events = get_endpoint_events(self.endpoint)
637 for ref, event_type in events.items():
638 event_schema = self.schema_builder.classdef_to_named_schema(ref, event_type)
639 event_tags.append(self._build_type_tag(ref, event_schema))
640
641 # types that are explicitly declared
642 extra_tag_groups: Dict[str, List[Tag]] = {}
643 if self.options.extra_types is not None:
644 if isinstance(self.options.extra_types, list):
645 extra_tag_groups = self._build_extra_tag_groups(
646 {"AdditionalTypes": self.options.extra_types}
647 )
648 elif isinstance(self.options.extra_types, dict):
649 extra_tag_groups = self._build_extra_tag_groups(
650 self.options.extra_types
651 )
652 else:
653 raise TypeError(
654 f"type mismatch for collection of extra types: {type(self.options.extra_types)}"
655 )
656
657 # list all operations and types
658 tags: List[Tag] = []
659 tags.extend(operation_tags)
660 tags.extend(type_tags)
661 tags.extend(event_tags)
662 for extra_tag_group in extra_tag_groups.values():
663 tags.extend(extra_tag_group)
664
665 tag_groups = []
666 if operation_tags:
667 tag_groups.append(
668 TagGroup(
669 name=self.options.map("Operations"),
670 tags=sorted(tag.name for tag in operation_tags),
671 )
672 )
673 if type_tags:
674 tag_groups.append(
675 TagGroup(
676 name=self.options.map("Types"),
677 tags=sorted(tag.name for tag in type_tags),
678 )
679 )
680 if event_tags:
681 tag_groups.append(
682 TagGroup(
683 name=self.options.map("Events"),
684 tags=sorted(tag.name for tag in event_tags),
685 )
686 )
687 for caption, extra_tag_group in extra_tag_groups.items():
688 tag_groups.append(
689 TagGroup(
690 name=self.options.map(caption),
691 tags=sorted(tag.name for tag in extra_tag_group),
692 )
693 )
694
695 if self.options.default_security_scheme:
696 securitySchemes = {"Default": self.options.default_security_scheme}
697 else:
698 securitySchemes = None
699
700 return Document(
701 openapi=".".join(str(item) for item in self.options.version),
702 info=self.options.info,
703 jsonSchemaDialect=(
704 "https://json-schema.org/draft/2020-12/schema"
705 if self.options.version >= (3, 1, 0)
706 else None
707 ),
708 servers=[self.options.server],
709 paths=paths,
710 components=Components(
711 schemas=self.schema_builder.schemas,
712 responses=self.responses,
713 securitySchemes=securitySchemes,
714 ),
715 security=[{"Default": []}],
716 tags=tags,
717 tagGroups=tag_groups,
718 )