Elffuss BraidHub

kikocis/llama-stack public

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