Elffuss BraidHub

kikocis/llama-stack public

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