Elffuss BraidHub

kikocis/llama-stack public

f788015f9412 · 11.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
12from collections.abc import (
13 AsyncGenerator as AsyncGeneratorABC,
14 AsyncIterator as AsyncIteratorABC,
15)
16from contextlib import asynccontextmanager
17from ssl import SSLError
18from typing import (
19 Any,
20 AsyncGenerator,
21 AsyncIterator,
22 Dict,
23 get_type_hints,
24 List,
25 Optional,
26 Set,
27)
28
29import fire
30import httpx
31import yaml
32
33from fastapi import Body, FastAPI, HTTPException, Request, Response
34from fastapi.exceptions import RequestValidationError
35from fastapi.responses import JSONResponse, StreamingResponse
36from fastapi.routing import APIRoute
37from pydantic import BaseModel, ValidationError
38from termcolor import cprint
39from typing_extensions import Annotated
40
41from llama_toolchain.telemetry.tracing import (
42 end_trace,
43 setup_logger,
44 SpanStatus,
45 start_trace,
46)
47
48from .datatypes import Api, InlineProviderSpec, ProviderSpec, RemoteProviderSpec
49from .distribution import api_endpoints, api_providers
50from .dynamic import instantiate_provider
51
52
53def is_async_iterator_type(typ):
54 if hasattr(typ, "__origin__"):
55 origin = typ.__origin__
56 if isinstance(origin, type):
57 return issubclass(
58 origin,
59 (AsyncIterator, AsyncGenerator, AsyncIteratorABC, AsyncGeneratorABC),
60 )
61 return False
62 return isinstance(
63 typ, (AsyncIterator, AsyncGenerator, AsyncIteratorABC, AsyncGeneratorABC)
64 )
65
66
67def create_sse_event(data: Any) -> str:
68 if isinstance(data, BaseModel):
69 data = data.json()
70 else:
71 data = json.dumps(data)
72
73 return f"data: {data}\n\n"
74
75
76async def global_exception_handler(request: Request, exc: Exception):
77 traceback.print_exception(exc)
78 http_exc = translate_exception(exc)
79
80 return JSONResponse(
81 status_code=http_exc.status_code, content={"error": {"detail": http_exc.detail}}
82 )
83
84
85def translate_exception(exc: Exception) -> HTTPException:
86 if isinstance(exc, ValidationError):
87 return RequestValidationError(exc.raw_errors)
88
89 # Add more custom exception translations here
90 return HTTPException(status_code=500, detail="Internal server error")
91
92
93async def passthrough(
94 request: Request,
95 downstream_url: str,
96 downstream_headers: Optional[Dict[str, str]] = None,
97):
98 await start_trace(request.path, {"downstream_url": downstream_url})
99
100 headers = dict(request.headers)
101 headers.pop("host", None)
102 headers.update(downstream_headers or {})
103
104 content = await request.body()
105
106 client = httpx.AsyncClient()
107 erred = False
108 try:
109 req = client.build_request(
110 method=request.method,
111 url=downstream_url,
112 headers=headers,
113 content=content,
114 params=request.query_params,
115 )
116 response = await client.send(req, stream=True)
117
118 async def stream_response():
119 async for chunk in response.aiter_raw(chunk_size=64):
120 yield chunk
121
122 await response.aclose()
123 await client.aclose()
124
125 return StreamingResponse(
126 stream_response(),
127 status_code=response.status_code,
128 headers=dict(response.headers),
129 media_type=response.headers.get("content-type"),
130 )
131
132 except httpx.ReadTimeout:
133 erred = True
134 return Response(content="Downstream server timed out", status_code=504)
135 except httpx.NetworkError as e:
136 erred = True
137 return Response(content=f"Network error: {str(e)}", status_code=502)
138 except httpx.TooManyRedirects:
139 erred = True
140 return Response(content="Too many redirects", status_code=502)
141 except SSLError as e:
142 erred = True
143 return Response(content=f"SSL error: {str(e)}", status_code=502)
144 except httpx.HTTPStatusError as e:
145 erred = True
146 return Response(content=str(e), status_code=e.response.status_code)
147 except Exception as e:
148 erred = True
149 return Response(content=f"Unexpected error: {str(e)}", status_code=500)
150 finally:
151 await end_trace(SpanStatus.OK if not erred else SpanStatus.ERROR)
152
153
154def handle_sigint(*args, **kwargs):
155 print("SIGINT or CTRL-C detected. Exiting gracefully...")
156 loop = asyncio.get_event_loop()
157 for task in asyncio.all_tasks(loop):
158 task.cancel()
159 loop.stop()
160
161
162@asynccontextmanager
163async def lifespan(app: FastAPI):
164 print("Starting up")
165 yield
166 print("Shutting down")
167
168
169def create_dynamic_passthrough(
170 downstream_url: str, downstream_headers: Optional[Dict[str, str]] = None
171):
172 async def endpoint(request: Request):
173 return await passthrough(request, downstream_url, downstream_headers)
174
175 return endpoint
176
177
178def create_dynamic_typed_route(func: Any, method: str):
179 hints = get_type_hints(func)
180 response_model = hints.get("return")
181
182 # NOTE: I think it is better to just add a method within each Api
183 # "Protocol" / adapter-impl to tell what sort of a response this request
184 # is going to produce. /chat_completion can produce a streaming or
185 # non-streaming response depending on if request.stream is True / False.
186 is_streaming = is_async_iterator_type(response_model)
187
188 if is_streaming:
189
190 async def endpoint(**kwargs):
191 await start_trace(func.__name__)
192
193 async def sse_generator(event_gen):
194 try:
195 async for item in event_gen:
196 yield create_sse_event(item)
197 await asyncio.sleep(0.01)
198 except asyncio.CancelledError:
199 print("Generator cancelled")
200 await event_gen.aclose()
201 except Exception as e:
202 traceback.print_exception(e)
203 yield create_sse_event(
204 {
205 "error": {
206 "message": str(translate_exception(e)),
207 },
208 }
209 )
210 finally:
211 await end_trace()
212
213 return StreamingResponse(
214 sse_generator(func(**kwargs)), media_type="text/event-stream"
215 )
216
217 else:
218
219 async def endpoint(**kwargs):
220 await start_trace(func.__name__)
221 try:
222 return (
223 await func(**kwargs)
224 if asyncio.iscoroutinefunction(func)
225 else func(**kwargs)
226 )
227 except Exception as e:
228 traceback.print_exception(e)
229 raise translate_exception(e) from e
230 finally:
231 await end_trace()
232
233 sig = inspect.signature(func)
234 if method == "post":
235 # make sure every parameter is annotated with Body() so FASTAPI doesn't
236 # do anything too intelligent and ask for some parameters in the query
237 # and some in the body
238 endpoint.__signature__ = sig.replace(
239 parameters=[
240 param.replace(
241 annotation=Annotated[param.annotation, Body(..., embed=True)]
242 )
243 for param in sig.parameters.values()
244 ]
245 )
246 else:
247 endpoint.__signature__ = sig
248
249 return endpoint
250
251
252def topological_sort(providers: List[ProviderSpec]) -> List[ProviderSpec]:
253 by_id = {x.api: x for x in providers}
254
255 def dfs(a: ProviderSpec, visited: Set[Api], stack: List[Api]):
256 visited.add(a.api)
257
258 for api in a.api_dependencies:
259 if api not in visited:
260 dfs(by_id[api], visited, stack)
261
262 stack.append(a.api)
263
264 visited = set()
265 stack = []
266
267 for a in providers:
268 if a.api not in visited:
269 dfs(a, visited, stack)
270
271 return [by_id[x] for x in stack]
272
273
274def resolve_impls(
275 provider_specs: Dict[str, ProviderSpec], config: Dict[str, Any]
276) -> Dict[Api, Any]:
277 provider_configs = config["providers"]
278 provider_specs = topological_sort(provider_specs.values())
279
280 impls = {}
281 for provider_spec in provider_specs:
282 api = provider_spec.api
283 if api.value not in provider_configs:
284 raise ValueError(
285 f"Could not find provider_spec config for {api}. Please add it to the config"
286 )
287
288 if isinstance(provider_spec, InlineProviderSpec):
289 deps = {api: impls[api] for api in provider_spec.api_dependencies}
290 else:
291 deps = {}
292 provider_config = provider_configs[api.value]
293 impl = instantiate_provider(provider_spec, provider_config, deps)
294 impls[api] = impl
295
296 return impls
297
298
299def main(yaml_config: str, port: int = 5000, disable_ipv6: bool = False):
300 with open(yaml_config, "r") as fp:
301 config = yaml.safe_load(fp)
302
303 app = FastAPI()
304
305 all_endpoints = api_endpoints()
306 all_providers = api_providers()
307
308 provider_specs = {}
309 for api_str, provider_config in config["providers"].items():
310 api = Api(api_str)
311 providers = all_providers[api]
312 provider_type = provider_config["provider_type"]
313 if provider_type not in providers:
314 raise ValueError(
315 f"Unknown provider `{provider_type}` is not available for API `{api}`"
316 )
317
318 provider_specs[api] = providers[provider_type]
319
320 impls = resolve_impls(provider_specs, config)
321 if Api.telemetry in impls:
322 setup_logger(impls[Api.telemetry])
323
324 for provider_spec in provider_specs.values():
325 api = provider_spec.api
326 endpoints = all_endpoints[api]
327 impl = impls[api]
328
329 if (
330 isinstance(provider_spec, RemoteProviderSpec)
331 and provider_spec.adapter is None
332 ):
333 for endpoint in endpoints:
334 url = impl.__provider_config__.url.rstrip("/") + endpoint.route
335 getattr(app, endpoint.method)(endpoint.route)(
336 create_dynamic_passthrough(url)
337 )
338 else:
339 for endpoint in endpoints:
340 if not hasattr(impl, endpoint.name):
341 # ideally this should be a typing violation already
342 raise ValueError(
343 f"Could not find method {endpoint.name} on {impl}!!"
344 )
345
346 impl_method = getattr(impl, endpoint.name)
347 getattr(app, endpoint.method)(endpoint.route, response_model=None)(
348 create_dynamic_typed_route(impl_method, endpoint.method)
349 )
350
351 for route in app.routes:
352 if isinstance(route, APIRoute):
353 cprint(
354 f"Serving {next(iter(route.methods))} {route.path}",
355 "white",
356 attrs=["bold"],
357 )
358
359 app.exception_handler(RequestValidationError)(global_exception_handler)
360 app.exception_handler(Exception)(global_exception_handler)
361 signal.signal(signal.SIGINT, handle_sigint)
362
363 import uvicorn
364
365 # FYI this does not do hot-reloads
366 listen_host = "::" if not disable_ipv6 else "0.0.0.0"
367 print(f"Listening on {listen_host}:{port}")
368 uvicorn.run(app, host=listen_host, port=port)
369
370
371if __name__ == "__main__":
372 fire.Fire(main)