Elffuss BraidHub

kikocis/llama-stack public

bb9be718c121 · 13.9 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 collections.abc
8import enum
9import inspect
10import typing
11import uuid
12from dataclasses import dataclass
13from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union
14
15from termcolor import colored
16
17from ..strong_typing.inspection import (
18 get_signature,
19 is_type_enum,
20 is_type_optional,
21 unwrap_optional_type,
22)
23
24
25def split_prefix(
26 s: str, sep: str, prefix: Union[str, Iterable[str]]
27) -> Tuple[Optional[str], str]:
28 """
29 Recognizes a prefix at the beginning of a string.
30
31 :param s: The string to check.
32 :param sep: A separator between (one of) the prefix(es) and the rest of the string.
33 :param prefix: A string or a set of strings to identify as a prefix.
34 :return: A tuple of the recognized prefix (if any) and the rest of the string excluding the separator (or the entire string).
35 """
36
37 if isinstance(prefix, str):
38 if s.startswith(prefix + sep):
39 return prefix, s[len(prefix) + len(sep) :]
40 else:
41 return None, s
42
43 for p in prefix:
44 if s.startswith(p + sep):
45 return p, s[len(p) + len(sep) :]
46
47 return None, s
48
49
50def _get_annotation_type(annotation: Union[type, str], callable: Callable) -> type:
51 "Maps a stringized reference to a type, as if using `from __future__ import annotations`."
52
53 if isinstance(annotation, str):
54 return eval(annotation, callable.__globals__)
55 else:
56 return annotation
57
58
59class HTTPMethod(enum.Enum):
60 "HTTP method used to invoke an endpoint operation."
61
62 GET = "GET"
63 POST = "POST"
64 PUT = "PUT"
65 DELETE = "DELETE"
66 PATCH = "PATCH"
67
68
69OperationParameter = Tuple[str, type]
70
71
72class ValidationError(TypeError):
73 pass
74
75
76@dataclass
77class EndpointOperation:
78 """
79 Type information and metadata associated with an endpoint operation.
80
81 "param defining_class: The most specific class that defines the endpoint operation.
82 :param name: The short name of the endpoint operation.
83 :param func_name: The name of the function to invoke when the operation is triggered.
84 :param func_ref: The callable to invoke when the operation is triggered.
85 :param route: A custom route string assigned to the operation.
86 :param path_params: Parameters of the operation signature that are passed in the path component of the URL string.
87 :param query_params: Parameters of the operation signature that are passed in the query string as `key=value` pairs.
88 :param request_params: The parameter that corresponds to the data transmitted in the request body.
89 :param event_type: The Python type of the data that is transmitted out-of-band (e.g. via websockets) while the operation is in progress.
90 :param response_type: The Python type of the data that is transmitted in the response body.
91 :param http_method: The HTTP method used to invoke the endpoint such as POST, GET or PUT.
92 :param public: True if the operation can be invoked without prior authentication.
93 :param request_examples: Sample requests that the operation might take.
94 :param response_examples: Sample responses that the operation might produce.
95 """
96
97 defining_class: type
98 name: str
99 func_name: str
100 func_ref: Callable[..., Any]
101 route: Optional[str]
102 path_params: List[OperationParameter]
103 query_params: List[OperationParameter]
104 request_params: Optional[OperationParameter]
105 event_type: Optional[type]
106 response_type: type
107 http_method: HTTPMethod
108 public: bool
109 request_examples: Optional[List[Any]] = None
110 response_examples: Optional[List[Any]] = None
111
112 def get_route(self) -> str:
113 if self.route is not None:
114 return self.route
115
116 route_parts = ["", self.name]
117 for param_name, _ in self.path_params:
118 route_parts.append("{" + param_name + "}")
119 return "/".join(route_parts)
120
121
122class _FormatParameterExtractor:
123 "A visitor to exract parameters in a format string."
124
125 keys: List[str]
126
127 def __init__(self) -> None:
128 self.keys = []
129
130 def __getitem__(self, key: str) -> None:
131 self.keys.append(key)
132 return None
133
134
135def _get_route_parameters(route: str) -> List[str]:
136 extractor = _FormatParameterExtractor()
137 route.format_map(extractor)
138 return extractor.keys
139
140
141def _get_endpoint_functions(
142 endpoint: type, prefixes: List[str]
143) -> Iterator[Tuple[str, str, str, Callable]]:
144 if not inspect.isclass(endpoint):
145 raise ValueError(f"object is not a class type: {endpoint}")
146
147 functions = inspect.getmembers(endpoint, inspect.isfunction)
148 for func_name, func_ref in functions:
149 webmethod = getattr(func_ref, "__webmethod__", None)
150 if not webmethod:
151 continue
152
153 print(f"Processing {colored(func_name, 'white')}...")
154 operation_name = func_name
155 if operation_name.startswith("get_") or operation_name.endswith("/get"):
156 prefix = "get"
157 elif (
158 operation_name.startswith("delete_")
159 or operation_name.startswith("remove_")
160 or operation_name.endswith("/delete")
161 or operation_name.endswith("/remove")
162 ):
163 prefix = "delete"
164 else:
165 if webmethod.method == "GET":
166 prefix = "get"
167 elif webmethod.method == "DELETE":
168 prefix = "delete"
169 else:
170 # by default everything else is a POST
171 prefix = "post"
172
173 yield prefix, operation_name, func_name, func_ref
174
175
176def _get_defining_class(member_fn: str, derived_cls: type) -> type:
177 "Find the class in which a member function is first defined in a class inheritance hierarchy."
178
179 # iterate in reverse member resolution order to find most specific class first
180 for cls in reversed(inspect.getmro(derived_cls)):
181 for name, _ in inspect.getmembers(cls, inspect.isfunction):
182 if name == member_fn:
183 return cls
184
185 raise ValidationError(
186 f"cannot find defining class for {member_fn} in {derived_cls}"
187 )
188
189
190def get_endpoint_operations(
191 endpoint: type, use_examples: bool = True
192) -> List[EndpointOperation]:
193 """
194 Extracts a list of member functions in a class eligible for HTTP interface binding.
195
196 These member functions are expected to have a signature like
197 ```
198 async def get_object(self, uuid: str, version: int) -> Object:
199 ...
200 ```
201 where the prefix `get_` translates to an HTTP GET, `object` corresponds to the name of the endpoint operation,
202 `uuid` and `version` are mapped to route path elements in "/object/{uuid}/{version}", and `Object` becomes
203 the response payload type, transmitted as an object serialized to JSON.
204
205 If the member function has a composite class type in the argument list, it becomes the request payload type,
206 and the caller is expected to provide the data as serialized JSON in an HTTP POST request.
207
208 :param endpoint: A class with member functions that can be mapped to an HTTP endpoint.
209 :param use_examples: Whether to return examples associated with member functions.
210 """
211
212 result = []
213
214 for prefix, operation_name, func_name, func_ref in _get_endpoint_functions(
215 endpoint,
216 [
217 "create",
218 "delete",
219 "do",
220 "get",
221 "post",
222 "put",
223 "remove",
224 "set",
225 "update",
226 ],
227 ):
228 # extract routing information from function metadata
229 webmethod = getattr(func_ref, "__webmethod__", None)
230 if webmethod is not None:
231 route = webmethod.route
232 route_params = _get_route_parameters(route) if route is not None else None
233 public = webmethod.public
234 request_examples = webmethod.request_examples
235 response_examples = webmethod.response_examples
236 else:
237 route = None
238 route_params = None
239 public = False
240 request_examples = None
241 response_examples = None
242
243 # inspect function signature for path and query parameters, and request/response payload type
244 signature = get_signature(func_ref)
245
246 path_params = []
247 query_params = []
248 request_params = []
249
250 for param_name, parameter in signature.parameters.items():
251 param_type = _get_annotation_type(parameter.annotation, func_ref)
252
253 # omit "self" for instance methods
254 if param_name == "self" and param_type is inspect.Parameter.empty:
255 continue
256
257 # check if all parameters have explicit type
258 if parameter.annotation is inspect.Parameter.empty:
259 raise ValidationError(
260 f"parameter '{param_name}' in function '{func_name}' has no type annotation"
261 )
262
263 if is_type_optional(param_type):
264 inner_type: type = unwrap_optional_type(param_type)
265 else:
266 inner_type = param_type
267
268 if prefix == "get" and (
269 inner_type is bool
270 or inner_type is int
271 or inner_type is float
272 or inner_type is str
273 or inner_type is uuid.UUID
274 or is_type_enum(inner_type)
275 ):
276 if parameter.kind == inspect.Parameter.POSITIONAL_ONLY:
277 if route_params is not None and param_name not in route_params:
278 raise ValidationError(
279 f"positional parameter '{param_name}' absent from user-defined route '{route}' for function '{func_name}'"
280 )
281
282 # simple type maps to route path element, e.g. /study/{uuid}/{version}
283 path_params.append((param_name, param_type))
284 else:
285 if route_params is not None and param_name in route_params:
286 raise ValidationError(
287 f"query parameter '{param_name}' found in user-defined route '{route}' for function '{func_name}'"
288 )
289
290 # simple type maps to key=value pair in query string
291 query_params.append((param_name, param_type))
292 else:
293 if route_params is not None and param_name in route_params:
294 raise ValidationError(
295 f"user-defined route '{route}' for function '{func_name}' has parameter '{param_name}' of composite type: {param_type}"
296 )
297
298 request_params.append((param_name, param_type))
299
300 # check if function has explicit return type
301 if signature.return_annotation is inspect.Signature.empty:
302 raise ValidationError(
303 f"function '{func_name}' has no return type annotation"
304 )
305
306 return_type = _get_annotation_type(signature.return_annotation, func_ref)
307
308 # operations that produce events are labeled as Generator[YieldType, SendType, ReturnType]
309 # where YieldType is the event type, SendType is None, and ReturnType is the immediate response type to the request
310 if typing.get_origin(return_type) is collections.abc.Generator:
311 event_type, send_type, response_type = typing.get_args(return_type)
312 if send_type is not type(None):
313 raise ValidationError(
314 f"function '{func_name}' has a return type Generator[Y,S,R] and therefore looks like an event but has an explicit send type"
315 )
316 else:
317 event_type = None
318 response_type = return_type
319
320 # set HTTP request method based on type of request and presence of payload
321 if not request_params:
322 if prefix in ["delete", "remove"]:
323 http_method = HTTPMethod.DELETE
324 else:
325 http_method = HTTPMethod.GET
326 else:
327 if prefix == "set":
328 http_method = HTTPMethod.PUT
329 elif prefix == "update":
330 http_method = HTTPMethod.PATCH
331 else:
332 http_method = HTTPMethod.POST
333
334 result.append(
335 EndpointOperation(
336 defining_class=_get_defining_class(func_name, endpoint),
337 name=operation_name,
338 func_name=func_name,
339 func_ref=func_ref,
340 route=route,
341 path_params=path_params,
342 query_params=query_params,
343 request_params=request_params,
344 event_type=event_type,
345 response_type=response_type,
346 http_method=http_method,
347 public=public,
348 request_examples=request_examples if use_examples else None,
349 response_examples=response_examples if use_examples else None,
350 )
351 )
352
353 if not result:
354 raise ValidationError(f"no eligible endpoint operations in type {endpoint}")
355
356 return result
357
358
359def get_endpoint_events(endpoint: type) -> Dict[str, type]:
360 results = {}
361
362 for decl in typing.get_type_hints(endpoint).values():
363 # check if signature is Callable[...]
364 origin = typing.get_origin(decl)
365 if origin is None or not issubclass(origin, Callable): # type: ignore
366 continue
367
368 # check if signature is Callable[[...], Any]
369 args = typing.get_args(decl)
370 if len(args) != 2:
371 continue
372 params_type, return_type = args
373 if not isinstance(params_type, list):
374 continue
375
376 # check if signature is Callable[[...], None]
377 if not issubclass(return_type, type(None)):
378 continue
379
380 # check if signature is Callable[[EventType], None]
381 if len(params_type) != 1:
382 continue
383
384 param_type = params_type[0]
385 results[param_type.__name__] = param_type
386
387 return results