Elffuss BraidHub

kikocis/llama-stack public

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