Elffuss BraidHub

kikocis/llama-stack public

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