Elffuss BraidHub

kikocis/llama-stack public

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