-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add direct client implementation #15
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
import inspect | ||
from typing import Any, cast, get_args, get_origin, Type | ||
|
||
from llama_stack.distribution.datatypes import StackRunConfig | ||
from llama_stack.distribution.distribution import get_provider_registry | ||
from llama_stack.distribution.resolver import resolve_impls | ||
from llama_stack.distribution.server.endpoints import get_all_api_endpoints | ||
from llama_stack.distribution.server.server import is_streaming_request | ||
|
||
from llama_stack.distribution.store.registry import create_dist_registry | ||
from pydantic import BaseModel | ||
|
||
from ..._base_client import ResponseT | ||
from ..._client import LlamaStackClient | ||
from ..._streaming import Stream | ||
from ..._types import Body, NOT_GIVEN, RequestFiles, RequestOptions | ||
|
||
|
||
class LlamaStackDirectClient(LlamaStackClient): | ||
def __init__(self, config: StackRunConfig, **kwargs): | ||
super().__init__(**kwargs) | ||
self.endpoints = get_all_api_endpoints() | ||
self.config = config | ||
self.dist_registry = None | ||
self.impls = None | ||
|
||
async def initialize(self) -> None: | ||
self.dist_registry, _ = await create_dist_registry(self.config) | ||
self.impls = await resolve_impls(self.config, get_provider_registry(), self.dist_registry) | ||
|
||
def _convert_param(self, param_type: Any, value: Any) -> Any: | ||
dltn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
origin = get_origin(param_type) | ||
if origin == list: | ||
item_type = get_args(param_type)[0] | ||
if isinstance(item_type, type) and issubclass(item_type, BaseModel): | ||
return [item_type(**item) for item in value] | ||
return value | ||
|
||
elif origin == dict: | ||
_, val_type = get_args(param_type) | ||
if isinstance(val_type, type) and issubclass(val_type, BaseModel): | ||
return {k: val_type(**v) for k, v in value.items()} | ||
return value | ||
|
||
elif isinstance(param_type, type) and issubclass(param_type, BaseModel): | ||
return param_type(**value) | ||
|
||
# Return as-is for primitive types | ||
return value | ||
|
||
async def _call_endpoint(self, path: str, method: str, body: dict = None) -> Any: | ||
for api, endpoints in self.endpoints.items(): | ||
for endpoint in endpoints: | ||
if endpoint.route == path: | ||
impl = self.impls[api] | ||
func = getattr(impl, endpoint.name) | ||
sig = inspect.signature(func) # | ||
|
||
if body: | ||
# Strip NOT_GIVENs to use the defaults in signature | ||
body = {k: v for k, v in body.items() if v is not NOT_GIVEN} | ||
|
||
# Convert parameters to Pydantic models where needed | ||
converted_body = {} | ||
for param_name, param in sig.parameters.items(): | ||
if param_name in body: | ||
value = body.get(param_name) | ||
converted_body[param_name] = self._convert_param(param.annotation, value) | ||
body = converted_body | ||
|
||
if is_streaming_request(endpoint.name, body): | ||
async for chunk in func(**(body or {})): | ||
yield chunk | ||
else: | ||
yield await func(**(body or {})) | ||
|
||
raise ValueError(f"No endpoint found for {path}") | ||
|
||
async def get( | ||
self, | ||
path: str, | ||
*, | ||
cast_to: Type[ResponseT], | ||
options: RequestOptions = None, | ||
stream: bool = False, | ||
stream_cls: type[Stream[Any]] | None = None, | ||
) -> ResponseT: | ||
options = options or {} | ||
async for response in self._call_endpoint(path, "GET"): | ||
return cast(ResponseT, response) | ||
|
||
async def post( | ||
self, | ||
path: str, | ||
*, | ||
cast_to: Type[ResponseT], | ||
body: Body | None = None, | ||
options: RequestOptions = None, | ||
files: RequestFiles | None = None, | ||
stream: bool = False, | ||
stream_cls: type[Stream[Any]] | None = None, | ||
) -> ResponseT: | ||
options = options or {} | ||
async for response in self._call_endpoint(path, "POST", body): | ||
return cast(ResponseT, response) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import argparse | ||
|
||
import yaml | ||
from llama_stack.distribution.configure import parse_and_maybe_upgrade_config | ||
from llama_stack_client.lib.direct.direct import LlamaStackDirectClient | ||
from llama_stack_client.types import UserMessage | ||
|
||
|
||
async def main(config_path: str): | ||
with open(config_path, "r") as f: | ||
config_dict = yaml.safe_load(f) | ||
|
||
run_config = parse_and_maybe_upgrade_config(config_dict) | ||
|
||
client = LlamaStackDirectClient(config=run_config) | ||
await client.initialize() | ||
|
||
response = await client.models.list() | ||
print(response) | ||
|
||
response = await client.inference.chat_completion( | ||
messages=[UserMessage(content="What is the capital of France?", role="user")], | ||
model="Llama3.1-8B-Instruct", | ||
stream=False, | ||
) | ||
print("\nChat completion response:") | ||
print(response) | ||
|
||
|
||
if __name__ == "__main__": | ||
import asyncio | ||
|
||
parser = argparse.ArgumentParser() | ||
parser.add_argument("config_path", help="Path to the config YAML file") | ||
args = parser.parse_args() | ||
asyncio.run(main(args.config_path)) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we add
llama-stack
as a dependency for thellama-stack-client
package?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nope it should be the reverse as we talked about. this code should always be exercised when the person already has llama-stack in their environment (as a library or as pip)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, should this
class LlamaStackDirectClient
be inside thellama-stack
repo instead of thellama-stack-client-python
repo?User who want to use llama-stack as a library. Install
llama-stack
package (dependent onllama-stack-client
package). Is able to useLlamaStackDirectClient
.User who just installs
llama-stack-client
package. They cannot useLlamaStackDirectClient
without installingllama-stack
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@yanxi0830 yeah I think that makes sense to me actually.