Elffuss BraidHub

kikocis/llama-stack public

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