|
| 1 | +from __future__ import annotations as _annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from collections.abc import AsyncGenerator, AsyncIterator |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import httpx |
| 8 | +from llama_stack.core.library_client import AsyncLlamaStackAsLibraryClient, convert_pydantic_to_json_value |
| 9 | +from llama_stack.core.request_headers import PROVIDER_DATA_VAR, request_provider_data_context |
| 10 | +from llama_stack.core.server.routes import find_matching_route |
| 11 | +from llama_stack.core.utils.context import preserve_contexts_async_generator |
| 12 | + |
| 13 | + |
| 14 | +class _AsyncByteStream(httpx.AsyncByteStream): |
| 15 | + """Wraps an async byte generator as an httpx AsyncByteStream.""" |
| 16 | + |
| 17 | + def __init__(self, gen: AsyncGenerator[bytes, None]) -> None: |
| 18 | + self._gen = gen |
| 19 | + |
| 20 | + async def __aiter__(self) -> AsyncIterator[bytes]: |
| 21 | + async for chunk in self._gen: |
| 22 | + yield chunk |
| 23 | + |
| 24 | + |
| 25 | +class LlamaStackLibraryTransport(httpx.AsyncBaseTransport): |
| 26 | + """Custom httpx transport that dispatches requests through a Llama Stack library client. |
| 27 | +
|
| 28 | + Instead of making real HTTP calls, this transport routes requests directly |
| 29 | + to the Llama Stack's in-process route handlers via the library client's |
| 30 | + route matching and body conversion logic. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, client: AsyncLlamaStackAsLibraryClient) -> None: |
| 34 | + self._client = client |
| 35 | + |
| 36 | + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: |
| 37 | + if self._client.route_impls is None: |
| 38 | + raise RuntimeError('Llama Stack library client not initialized. Call initialize() first.') |
| 39 | + |
| 40 | + method = request.method |
| 41 | + path = request.url.raw_path.decode('utf-8') |
| 42 | + |
| 43 | + body = json.loads(request.content) if request.content else {} |
| 44 | + |
| 45 | + headers: dict[str, str] = { |
| 46 | + k.decode('utf-8') if isinstance(k, bytes) else k: v.decode('utf-8') |
| 47 | + if isinstance(v, bytes) |
| 48 | + else v |
| 49 | + for k, v in request.headers.raw |
| 50 | + } |
| 51 | + |
| 52 | + if self._client.provider_data: |
| 53 | + keys = ['X-LlamaStack-Provider-Data', 'x-llamastack-provider-data'] |
| 54 | + if all(key not in headers for key in keys): |
| 55 | + headers['X-LlamaStack-Provider-Data'] = json.dumps(self._client.provider_data) |
| 56 | + |
| 57 | + with request_provider_data_context(headers): |
| 58 | + is_stream = body.get('stream', False) |
| 59 | + |
| 60 | + if is_stream: |
| 61 | + return await self._handle_streaming(request, method, path, body) |
| 62 | + else: |
| 63 | + return await self._handle_non_streaming(request, method, path, body) |
| 64 | + |
| 65 | + async def _handle_non_streaming( |
| 66 | + self, |
| 67 | + request: httpx.Request, |
| 68 | + method: str, |
| 69 | + path: str, |
| 70 | + body: dict[str, Any], |
| 71 | + ) -> httpx.Response: |
| 72 | + assert self._client.route_impls is not None |
| 73 | + |
| 74 | + matched_func, path_params, _, _ = find_matching_route( |
| 75 | + method, path, self._client.route_impls |
| 76 | + ) |
| 77 | + body |= path_params |
| 78 | + body = self._client._convert_body(matched_func, body) |
| 79 | + |
| 80 | + result = await matched_func(**body) |
| 81 | + |
| 82 | + json_content = json.dumps(convert_pydantic_to_json_value(result)) |
| 83 | + status_code = httpx.codes.OK |
| 84 | + |
| 85 | + if method.upper() == 'DELETE' and result is None: |
| 86 | + status_code = httpx.codes.NO_CONTENT |
| 87 | + json_content = '' |
| 88 | + |
| 89 | + return httpx.Response( |
| 90 | + status_code=status_code, |
| 91 | + content=json_content.encode('utf-8'), |
| 92 | + headers={'Content-Type': 'application/json'}, |
| 93 | + request=request, |
| 94 | + ) |
| 95 | + |
| 96 | + async def _handle_streaming( |
| 97 | + self, |
| 98 | + request: httpx.Request, |
| 99 | + method: str, |
| 100 | + path: str, |
| 101 | + body: dict[str, Any], |
| 102 | + ) -> httpx.Response: |
| 103 | + assert self._client.route_impls is not None |
| 104 | + |
| 105 | + func, path_params, _, _ = find_matching_route(method, path, self._client.route_impls) |
| 106 | + body |= path_params |
| 107 | + body = self._client._convert_body(func, body) |
| 108 | + |
| 109 | + result = await func(**body) |
| 110 | + |
| 111 | + async def gen() -> AsyncGenerator[bytes, None]: |
| 112 | + async for chunk in result: |
| 113 | + data = json.dumps(convert_pydantic_to_json_value(chunk)) |
| 114 | + yield f'data: {data}\n\n'.encode('utf-8') |
| 115 | + |
| 116 | + wrapped_gen = preserve_contexts_async_generator(gen(), [PROVIDER_DATA_VAR]) |
| 117 | + |
| 118 | + return httpx.Response( |
| 119 | + status_code=httpx.codes.OK, |
| 120 | + stream=_AsyncByteStream(wrapped_gen), |
| 121 | + headers={'Content-Type': 'text/event-stream'}, |
| 122 | + request=request, |
| 123 | + ) |
0 commit comments