Elffuss BraidHub

kikocis/llama-stack public

main · 16.2 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 asyncio
8import inspect
9import json
10import signal
11import traceback
12
13from collections.abc import (
14 AsyncGenerator as AsyncGeneratorABC,
15 AsyncIterator as AsyncIteratorABC,
16)
17from contextlib import asynccontextmanager
18from http import HTTPStatus
19from ssl import SSLError
20from typing import (
21 Any,
22 AsyncGenerator,
23 AsyncIterator,
24 Dict,
25 get_type_hints,
26 List,
27 Optional,
28 Set,
29)
30
31import fire
32import httpx
33import yaml
34
35from fastapi import Body, FastAPI, HTTPException, Request, Response
36from fastapi.exceptions import RequestValidationError
37from fastapi.responses import JSONResponse, StreamingResponse
38from fastapi.routing import APIRoute
39from pydantic import BaseModel, ValidationError
40from termcolor import cprint
41from typing_extensions import Annotated
42
43from llama_stack.providers.utils.telemetry.tracing import (
44 end_trace,
45 setup_logger,
46 SpanStatus,
47 start_trace,
48)
49from llama_stack.distribution.datatypes import * # noqa: F403
50
51from llama_stack.distribution.distribution import (
52 api_endpoints,
53 api_providers,
54 builtin_automatically_routed_apis,
55)
56from llama_stack.distribution.request_headers import set_request_provider_data
57from llama_stack.distribution.utils.dynamic import instantiate_provider
58
59
60def is_async_iterator_type(typ):
61 if hasattr(typ, "__origin__"):
62 origin = typ.__origin__
63 if isinstance(origin, type):
64 return issubclass(
65 origin,
66 (AsyncIterator, AsyncGenerator, AsyncIteratorABC, AsyncGeneratorABC),
67 )
68 return False
69 return isinstance(
70 typ, (AsyncIterator, AsyncGenerator, AsyncIteratorABC, AsyncGeneratorABC)
71 )
72
73
74def create_sse_event(data: Any) -> str:
75 if isinstance(data, BaseModel):
76 data = data.json()
77 else:
78 data = json.dumps(data)
79
80 return f"data: {data}\n\n"
81
82
83async def global_exception_handler(request: Request, exc: Exception):
84 traceback.print_exception(exc)
85 http_exc = translate_exception(exc)
86
87 return JSONResponse(
88 status_code=http_exc.status_code, content={"error": {"detail": http_exc.detail}}
89 )
90
91
92def translate_exception(exc: Exception) -> Union[HTTPException, RequestValidationError]:
93 if isinstance(exc, ValidationError):
94 exc = RequestValidationError(exc.raw_errors)
95
96 if isinstance(exc, RequestValidationError):
97 return HTTPException(
98 status_code=400,
99 detail={
100 "errors": [
101 {
102 "loc": list(error["loc"]),
103 "msg": error["msg"],
104 "type": error["type"],
105 }
106 for error in exc.errors()
107 ]
108 },
109 )
110 elif isinstance(exc, ValueError):
111 return HTTPException(status_code=400, detail=f"Invalid value: {str(exc)}")
112 elif isinstance(exc, PermissionError):
113 return HTTPException(status_code=403, detail=f"Permission denied: {str(exc)}")
114 elif isinstance(exc, TimeoutError):
115 return HTTPException(status_code=504, detail=f"Operation timed out: {str(exc)}")
116 elif isinstance(exc, NotImplementedError):
117 return HTTPException(status_code=501, detail=f"Not implemented: {str(exc)}")
118 else:
119 return HTTPException(
120 status_code=500,
121 detail="Internal server error: An unexpected error occurred.",
122 )
123
124
125async def passthrough(
126 request: Request,
127 downstream_url: str,
128 downstream_headers: Optional[Dict[str, str]] = None,
129):
130 await start_trace(request.path, {"downstream_url": downstream_url})
131
132 headers = dict(request.headers)
133 headers.pop("host", None)
134 headers.update(downstream_headers or {})
135
136 content = await request.body()
137
138 client = httpx.AsyncClient()
139 erred = False
140 try:
141 req = client.build_request(
142 method=request.method,
143 url=downstream_url,
144 headers=headers,
145 content=content,
146 params=request.query_params,
147 )
148 response = await client.send(req, stream=True)
149
150 async def stream_response():
151 async for chunk in response.aiter_raw(chunk_size=64):
152 yield chunk
153
154 await response.aclose()
155 await client.aclose()
156
157 return StreamingResponse(
158 stream_response(),
159 status_code=response.status_code,
160 headers=dict(response.headers),
161 media_type=response.headers.get("content-type"),
162 )
163
164 except httpx.ReadTimeout:
165 erred = True
166 return Response(content="Downstream server timed out", status_code=504)
167 except httpx.NetworkError as e:
168 erred = True
169 return Response(content=f"Network error: {str(e)}", status_code=502)
170 except httpx.TooManyRedirects:
171 erred = True
172 return Response(content="Too many redirects", status_code=502)
173 except SSLError as e:
174 erred = True
175 return Response(content=f"SSL error: {str(e)}", status_code=502)
176 except httpx.HTTPStatusError as e:
177 erred = True
178 return Response(content=str(e), status_code=e.response.status_code)
179 except Exception as e:
180 erred = True
181 return Response(content=f"Unexpected error: {str(e)}", status_code=500)
182 finally:
183 await end_trace(SpanStatus.OK if not erred else SpanStatus.ERROR)
184
185
186def handle_sigint(*args, **kwargs):
187 print("SIGINT or CTRL-C detected. Exiting gracefully...")
188 loop = asyncio.get_event_loop()
189 for task in asyncio.all_tasks(loop):
190 task.cancel()
191 loop.stop()
192
193
194@asynccontextmanager
195async def lifespan(app: FastAPI):
196 print("Starting up")
197 yield
198 print("Shutting down")
199
200
201def create_dynamic_passthrough(
202 downstream_url: str, downstream_headers: Optional[Dict[str, str]] = None
203):
204 async def endpoint(request: Request):
205 return await passthrough(request, downstream_url, downstream_headers)
206
207 return endpoint
208
209
210def create_dynamic_typed_route(
211 func: Any, method: str, provider_data_validators: List[str]
212):
213 hints = get_type_hints(func)
214 response_model = hints.get("return")
215
216 # NOTE: I think it is better to just add a method within each Api
217 # "Protocol" / adapter-impl to tell what sort of a response this request
218 # is going to produce. /chat_completion can produce a streaming or
219 # non-streaming response depending on if request.stream is True / False.
220 is_streaming = is_async_iterator_type(response_model)
221
222 if is_streaming:
223
224 async def endpoint(request: Request, **kwargs):
225 await start_trace(func.__name__)
226
227 set_request_provider_data(request.headers, provider_data_validators)
228
229 async def sse_generator(event_gen):
230 try:
231 async for item in event_gen:
232 yield create_sse_event(item)
233 await asyncio.sleep(0.01)
234 except asyncio.CancelledError:
235 print("Generator cancelled")
236 await event_gen.aclose()
237 except Exception as e:
238 traceback.print_exception(e)
239 yield create_sse_event(
240 {
241 "error": {
242 "message": str(translate_exception(e)),
243 },
244 }
245 )
246 finally:
247 await end_trace()
248
249 return StreamingResponse(
250 sse_generator(func(**kwargs)), media_type="text/event-stream"
251 )
252
253 else:
254
255 async def endpoint(request: Request, **kwargs):
256 await start_trace(func.__name__)
257
258 set_request_provider_data(request.headers, provider_data_validators)
259
260 try:
261 return (
262 await func(**kwargs)
263 if asyncio.iscoroutinefunction(func)
264 else func(**kwargs)
265 )
266 except Exception as e:
267 traceback.print_exception(e)
268 raise translate_exception(e) from e
269 finally:
270 await end_trace()
271
272 sig = inspect.signature(func)
273 new_params = [
274 inspect.Parameter(
275 "request", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request
276 )
277 ]
278 new_params.extend(sig.parameters.values())
279
280 if method == "post":
281 # make sure every parameter is annotated with Body() so FASTAPI doesn't
282 # do anything too intelligent and ask for some parameters in the query
283 # and some in the body
284 new_params = [new_params[0]] + [
285 param.replace(annotation=Annotated[param.annotation, Body(..., embed=True)])
286 for param in new_params[1:]
287 ]
288
289 endpoint.__signature__ = sig.replace(parameters=new_params)
290
291 return endpoint
292
293
294def topological_sort(providers: List[ProviderSpec]) -> List[ProviderSpec]:
295 by_id = {x.api: x for x in providers}
296
297 def dfs(a: ProviderSpec, visited: Set[Api], stack: List[Api]):
298 visited.add(a.api)
299
300 for api in a.api_dependencies:
301 if api not in visited:
302 dfs(by_id[api], visited, stack)
303
304 stack.append(a.api)
305
306 visited = set()
307 stack = []
308
309 for a in providers:
310 if a.api not in visited:
311 dfs(a, visited, stack)
312
313 return [by_id[x] for x in stack]
314
315
316def snake_to_camel(snake_str):
317 return "".join(word.capitalize() for word in snake_str.split("_"))
318
319
320async def resolve_impls_with_routing(run_config: StackRunConfig) -> Dict[Api, Any]:
321 """
322 Does two things:
323 - flatmaps, sorts and resolves the providers in dependency order
324 - for each API, produces either a (local, passthrough or router) implementation
325 """
326 all_providers = api_providers()
327 specs = {}
328 configs = {}
329
330 for api_str, config in run_config.api_providers.items():
331 api = Api(api_str)
332
333 # TODO: check that these APIs are not in the routing table part of the config
334 providers = all_providers[api]
335
336 # skip checks for API whose provider config is specified in routing_table
337 if isinstance(config, PlaceholderProviderConfig):
338 continue
339
340 if config.provider_id not in providers:
341 raise ValueError(
342 f"Unknown provider `{config.provider_id}` is not available for API `{api}`"
343 )
344 specs[api] = providers[config.provider_id]
345 configs[api] = config
346
347 apis_to_serve = run_config.apis_to_serve or set(
348 list(specs.keys()) + list(run_config.routing_table.keys())
349 )
350 for info in builtin_automatically_routed_apis():
351 source_api = info.routing_table_api
352
353 assert (
354 source_api not in specs
355 ), f"Routing table API {source_api} specified in wrong place?"
356 assert (
357 info.router_api not in specs
358 ), f"Auto-routed API {info.router_api} specified in wrong place?"
359
360 if info.router_api.value not in apis_to_serve:
361 continue
362
363 print("router_api", info.router_api)
364 if info.router_api.value not in run_config.routing_table:
365 raise ValueError(f"Routing table for `{source_api.value}` is not provided?")
366
367 routing_table = run_config.routing_table[info.router_api.value]
368
369 providers = all_providers[info.router_api]
370
371 inner_specs = []
372 inner_deps = []
373 for rt_entry in routing_table:
374 if rt_entry.provider_id not in providers:
375 raise ValueError(
376 f"Unknown provider `{rt_entry.provider_id}` is not available for API `{api}`"
377 )
378 inner_specs.append(providers[rt_entry.provider_id])
379 inner_deps.extend(providers[rt_entry.provider_id].api_dependencies)
380
381 specs[source_api] = RoutingTableProviderSpec(
382 api=source_api,
383 module="llama_stack.distribution.routers",
384 api_dependencies=inner_deps,
385 inner_specs=inner_specs,
386 )
387 configs[source_api] = routing_table
388
389 specs[info.router_api] = AutoRoutedProviderSpec(
390 api=info.router_api,
391 module="llama_stack.distribution.routers",
392 routing_table_api=source_api,
393 api_dependencies=[source_api],
394 )
395 configs[info.router_api] = {}
396
397 sorted_specs = topological_sort(specs.values())
398 print(f"Resolved {len(sorted_specs)} providers in topological order")
399 for spec in sorted_specs:
400 print(f" {spec.api}: {spec.provider_id}")
401 print("")
402 impls = {}
403 for spec in sorted_specs:
404 api = spec.api
405 deps = {api: impls[api] for api in spec.api_dependencies}
406 impl = await instantiate_provider(spec, deps, configs[api])
407
408 impls[api] = impl
409
410 return impls, specs
411
412
413def main(yaml_config: str, port: int = 5000, disable_ipv6: bool = False):
414 with open(yaml_config, "r") as fp:
415 config = StackRunConfig(**yaml.safe_load(fp))
416
417 app = FastAPI()
418
419 # Health check is added to enable deploying the docker container image on Kubernetes which require
420 # a health check that can return 200 for readiness and liveness check
421 class HealthCheck(BaseModel):
422 status: str = "OK"
423
424 @app.get("/healthcheck", status_code=HTTPStatus.OK, response_model=HealthCheck)
425 async def healthcheck():
426 return HealthCheck(status="OK")
427
428 impls, specs = asyncio.run(resolve_impls_with_routing(config))
429 if Api.telemetry in impls:
430 setup_logger(impls[Api.telemetry])
431
432 all_endpoints = api_endpoints()
433
434 if config.apis_to_serve:
435 apis_to_serve = set(config.apis_to_serve)
436 for inf in builtin_automatically_routed_apis():
437 if inf.router_api.value in apis_to_serve:
438 apis_to_serve.add(inf.routing_table_api)
439 else:
440 apis_to_serve = set(impls.keys())
441
442 for api_str in apis_to_serve:
443 api = Api(api_str)
444
445 endpoints = all_endpoints[api]
446 impl = impls[api]
447
448 provider_spec = specs[api]
449 if (
450 isinstance(provider_spec, RemoteProviderSpec)
451 and provider_spec.adapter is None
452 ):
453 for endpoint in endpoints:
454 url = impl.__provider_config__.url.rstrip("/") + endpoint.route
455 getattr(app, endpoint.method)(endpoint.route)(
456 create_dynamic_passthrough(url)
457 )
458 else:
459 for endpoint in endpoints:
460 if not hasattr(impl, endpoint.name):
461 # ideally this should be a typing violation already
462 raise ValueError(
463 f"Could not find method {endpoint.name} on {impl}!!"
464 )
465
466 impl_method = getattr(impl, endpoint.name)
467
468 validators = []
469 if isinstance(provider_spec, AutoRoutedProviderSpec):
470 inner_specs = specs[provider_spec.routing_table_api].inner_specs
471 for spec in inner_specs:
472 if spec.provider_data_validator:
473 validators.append(spec.provider_data_validator)
474 elif not isinstance(provider_spec, RoutingTableProviderSpec):
475 if provider_spec.provider_data_validator:
476 validators.append(provider_spec.provider_data_validator)
477
478 getattr(app, endpoint.method)(endpoint.route, response_model=None)(
479 create_dynamic_typed_route(
480 impl_method,
481 endpoint.method,
482 validators,
483 )
484 )
485
486 for route in app.routes:
487 if isinstance(route, APIRoute):
488 cprint(
489 f"Serving {next(iter(route.methods))} {route.path}",
490 "white",
491 attrs=["bold"],
492 )
493
494 app.exception_handler(RequestValidationError)(global_exception_handler)
495 app.exception_handler(Exception)(global_exception_handler)
496 signal.signal(signal.SIGINT, handle_sigint)
497
498 import uvicorn
499
500 # FYI this does not do hot-reloads
501 listen_host = "::" if not disable_ipv6 else "0.0.0.0"
502 print(f"Listening on {listen_host}:{port}")
503 uvicorn.run(app, host=listen_host, port=port)
504
505
506if __name__ == "__main__":
507 fire.Fire(main)