| 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 | |
| 7 | import asyncio |
| 8 | |
| 9 | from typing import List, Optional |
| 10 | |
| 11 | import fire |
| 12 | import httpx |
| 13 | from termcolor import cprint |
| 14 | |
| 15 | from .models import * # noqa: F403 |
| 16 | |
| 17 | |
| 18 | class ModelsClient(Models): |
| 19 | def __init__(self, base_url: str): |
| 20 | self.base_url = base_url |
| 21 | |
| 22 | async def initialize(self) -> None: |
| 23 | pass |
| 24 | |
| 25 | async def shutdown(self) -> None: |
| 26 | pass |
| 27 | |
| 28 | async def list_models(self) -> List[ModelServingSpec]: |
| 29 | async with httpx.AsyncClient() as client: |
| 30 | response = await client.get( |
| 31 | f"{self.base_url}/models/list", |
| 32 | headers={"Content-Type": "application/json"}, |
| 33 | ) |
| 34 | response.raise_for_status() |
| 35 | return [ModelServingSpec(**x) for x in response.json()] |
| 36 | |
| 37 | async def get_model(self, core_model_id: str) -> Optional[ModelServingSpec]: |
| 38 | async with httpx.AsyncClient() as client: |
| 39 | response = await client.get( |
| 40 | f"{self.base_url}/models/get", |
| 41 | params={ |
| 42 | "core_model_id": core_model_id, |
| 43 | }, |
| 44 | headers={"Content-Type": "application/json"}, |
| 45 | ) |
| 46 | response.raise_for_status() |
| 47 | j = response.json() |
| 48 | if j is None: |
| 49 | return None |
| 50 | return ModelServingSpec(**j) |
| 51 | |
| 52 | |
| 53 | async def run_main(host: str, port: int, stream: bool): |
| 54 | client = ModelsClient(f"http://{host}:{port}") |
| 55 | |
| 56 | response = await client.list_models() |
| 57 | cprint(f"list_models response={response}", "green") |
| 58 | |
| 59 | response = await client.get_model("Meta-Llama3.1-8B-Instruct") |
| 60 | cprint(f"get_model response={response}", "blue") |
| 61 | |
| 62 | response = await client.get_model("Llama-Guard-3-8B") |
| 63 | cprint(f"get_model response={response}", "red") |
| 64 | |
| 65 | |
| 66 | def main(host: str, port: int, stream: bool = True): |
| 67 | asyncio.run(run_main(host, port, stream)) |
| 68 | |
| 69 | |
| 70 | if __name__ == "__main__": |
| 71 | fire.Fire(main) |