Elffuss BraidHub

kikocis/llama-stack public

371459e1ee27 · 24.4 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 if len(op.request_params) == 1 and "Request" in first[1].__name__:
475 # TODO(ashwin): Undo the "Request" hack and this entire block eventually
476 request_name = first[1].__name__ + "Wrapper"
477 request_type = make_dataclass(request_name, op.request_params)
478 else:
479 op_name = "".join(word.capitalize() for word in op.name.split("_"))
480 request_name = f"{op_name}Request"
481 request_type = make_dataclass(request_name, op.request_params)
482
483 requestBody = RequestBody(
484 content={
485 "application/json": builder.build_media_type(
486 request_type, op.request_examples
487 )
488 },
489 description=doc_params.get(request_name),
490 required=True,
491 )
492 else:
493 requestBody = None
494
495 # success response types
496 if doc_string.returns is None and is_type_union(op.response_type):
497 # split union of return types into a list of response types
498 success_type_docstring: Dict[type, Docstring] = {
499 typing.cast(type, item): parse_type(item)
500 for item in unwrap_union_types(op.response_type)
501 }
502 success_type_descriptions = {
503 item: doc_string.short_description
504 for item, doc_string in success_type_docstring.items()
505 if doc_string.short_description
506 }
507 else:
508 # use return type as a single response type
509 success_type_descriptions = {
510 op.response_type: (
511 doc_string.returns.description if doc_string.returns else "OK"
512 )
513 }
514
515 response_examples = op.response_examples or []
516 success_examples = [
517 example
518 for example in response_examples
519 if not isinstance(example, Exception)
520 ]
521
522 content_builder = ContentBuilder(self.schema_builder)
523 response_builder = ResponseBuilder(content_builder)
524 response_options = ResponseOptions(
525 success_type_descriptions,
526 success_examples if self.options.use_examples else None,
527 self.options.success_responses,
528 "200",
529 )
530 responses = response_builder.build_response(response_options)
531
532 # failure response types
533 if doc_string.raises:
534 exception_types: Dict[type, str] = {
535 item.raise_type: item.description for item in doc_string.raises.values()
536 }
537 exception_examples = [
538 example
539 for example in response_examples
540 if isinstance(example, Exception)
541 ]
542
543 if self.options.error_wrapper:
544 schema_transformer = schema_error_wrapper
545 sample_transformer = sample_error_wrapper
546 else:
547 schema_transformer = None
548 sample_transformer = None
549
550 content_builder = ContentBuilder(
551 self.schema_builder,
552 schema_transformer=schema_transformer,
553 sample_transformer=sample_transformer,
554 )
555 response_builder = ResponseBuilder(content_builder)
556 response_options = ResponseOptions(
557 exception_types,
558 exception_examples if self.options.use_examples else None,
559 self.options.error_responses,
560 "500",
561 )
562 responses.update(response_builder.build_response(response_options))
563
564 if op.event_type is not None:
565 builder = ContentBuilder(self.schema_builder)
566 callbacks = {
567 f"{op.func_name}_callback": {
568 "{$request.query.callback}": PathItem(
569 post=Operation(
570 requestBody=RequestBody(
571 content=builder.build_content(op.event_type)
572 ),
573 responses={"200": Response(description="OK")},
574 )
575 )
576 }
577 }
578
579 else:
580 callbacks = None
581
582 return Operation(
583 tags=[op.defining_class.__name__],
584 summary=doc_string.short_description,
585 description=doc_string.long_description,
586 parameters=parameters,
587 requestBody=requestBody,
588 responses=responses,
589 callbacks=callbacks,
590 security=[] if op.public else None,
591 )
592
593 def generate(self) -> Document:
594 paths: Dict[str, PathItem] = {}
595 endpoint_classes: Set[type] = set()
596 for op in get_endpoint_operations(
597 self.endpoint, use_examples=self.options.use_examples
598 ):
599 endpoint_classes.add(op.defining_class)
600
601 operation = self._build_operation(op)
602
603 if op.http_method is HTTPMethod.GET:
604 pathItem = PathItem(get=operation)
605 elif op.http_method is HTTPMethod.PUT:
606 pathItem = PathItem(put=operation)
607 elif op.http_method is HTTPMethod.POST:
608 pathItem = PathItem(post=operation)
609 elif op.http_method is HTTPMethod.DELETE:
610 pathItem = PathItem(delete=operation)
611 elif op.http_method is HTTPMethod.PATCH:
612 pathItem = PathItem(patch=operation)
613 else:
614 raise NotImplementedError(f"unknown HTTP method: {op.http_method}")
615
616 route = op.get_route()
617 if route in paths:
618 paths[route].update(pathItem)
619 else:
620 paths[route] = pathItem
621
622 operation_tags: List[Tag] = []
623 for cls in endpoint_classes:
624 doc_string = parse_type(cls)
625 operation_tags.append(
626 Tag(
627 name=cls.__name__,
628 description=doc_string.long_description,
629 displayName=doc_string.short_description,
630 )
631 )
632
633 # types that are produced/consumed by operations
634 type_tags = [
635 self._build_type_tag(ref, schema)
636 for ref, schema in self.schema_builder.schemas.items()
637 ]
638
639 # types that are emitted by events
640 event_tags: List[Tag] = []
641 events = get_endpoint_events(self.endpoint)
642 for ref, event_type in events.items():
643 event_schema = self.schema_builder.classdef_to_named_schema(ref, event_type)
644 event_tags.append(self._build_type_tag(ref, event_schema))
645
646 # types that are explicitly declared
647 extra_tag_groups: Dict[str, List[Tag]] = {}
648 if self.options.extra_types is not None:
649 if isinstance(self.options.extra_types, list):
650 extra_tag_groups = self._build_extra_tag_groups(
651 {"AdditionalTypes": self.options.extra_types}
652 )
653 elif isinstance(self.options.extra_types, dict):
654 extra_tag_groups = self._build_extra_tag_groups(
655 self.options.extra_types
656 )
657 else:
658 raise TypeError(
659 f"type mismatch for collection of extra types: {type(self.options.extra_types)}"
660 )
661
662 # list all operations and types
663 tags: List[Tag] = []
664 tags.extend(operation_tags)
665 tags.extend(type_tags)
666 tags.extend(event_tags)
667 for extra_tag_group in extra_tag_groups.values():
668 tags.extend(extra_tag_group)
669
670 tag_groups = []
671 if operation_tags:
672 tag_groups.append(
673 TagGroup(
674 name=self.options.map("Operations"),
675 tags=sorted(tag.name for tag in operation_tags),
676 )
677 )
678 if type_tags:
679 tag_groups.append(
680 TagGroup(
681 name=self.options.map("Types"),
682 tags=sorted(tag.name for tag in type_tags),
683 )
684 )
685 if event_tags:
686 tag_groups.append(
687 TagGroup(
688 name=self.options.map("Events"),
689 tags=sorted(tag.name for tag in event_tags),
690 )
691 )
692 for caption, extra_tag_group in extra_tag_groups.items():
693 tag_groups.append(
694 TagGroup(
695 name=self.options.map(caption),
696 tags=sorted(tag.name for tag in extra_tag_group),
697 )
698 )
699
700 if self.options.default_security_scheme:
701 securitySchemes = {"Default": self.options.default_security_scheme}
702 else:
703 securitySchemes = None
704
705 return Document(
706 openapi=".".join(str(item) for item in self.options.version),
707 info=self.options.info,
708 jsonSchemaDialect=(
709 "https://json-schema.org/draft/2020-12/schema"
710 if self.options.version >= (3, 1, 0)
711 else None
712 ),
713 servers=[self.options.server],
714 paths=paths,
715 components=Components(
716 schemas=self.schema_builder.schemas,
717 responses=self.responses,
718 securitySchemes=securitySchemes,
719 ),
720 security=[{"Default": []}],
721 tags=tags,
722 tagGroups=tag_groups,
723 )