| 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 | import json |
| 9 | from typing import Any, AsyncGenerator, List, Optional |
| 10 | |
| 11 | import fire |
| 12 | import httpx |
| 13 | from pydantic import BaseModel |
| 14 | |
| 15 | from llama_models.llama3.api import * # noqa: F403 |
| 16 | from llama_stack.apis.inference import * # noqa: F403 |
| 17 | from termcolor import cprint |
| 18 | |
| 19 | from llama_stack.distribution.datatypes import RemoteProviderConfig |
| 20 | |
| 21 | from .event_logger import EventLogger |
| 22 | |
| 23 | |
| 24 | async def get_client_impl(config: RemoteProviderConfig, _deps: Any) -> Inference: |
| 25 | return InferenceClient(config.url) |
| 26 | |
| 27 | |
| 28 | def encodable_dict(d: BaseModel): |
| 29 | return json.loads(d.json()) |
| 30 | |
| 31 | |
| 32 | class InferenceClient(Inference): |
| 33 | def __init__(self, base_url: str): |
| 34 | self.base_url = base_url |
| 35 | |
| 36 | async def initialize(self) -> None: |
| 37 | pass |
| 38 | |
| 39 | async def shutdown(self) -> None: |
| 40 | pass |
| 41 | |
| 42 | async def completion(self, request: CompletionRequest) -> AsyncGenerator: |
| 43 | raise NotImplementedError() |
| 44 | |
| 45 | async def chat_completion( |
| 46 | self, |
| 47 | model: str, |
| 48 | messages: List[Message], |
| 49 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 50 | tools: Optional[List[ToolDefinition]] = None, |
| 51 | tool_choice: Optional[ToolChoice] = ToolChoice.auto, |
| 52 | tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json, |
| 53 | stream: Optional[bool] = False, |
| 54 | logprobs: Optional[LogProbConfig] = None, |
| 55 | ) -> AsyncGenerator: |
| 56 | request = ChatCompletionRequest( |
| 57 | model=model, |
| 58 | messages=messages, |
| 59 | sampling_params=sampling_params, |
| 60 | tools=tools or [], |
| 61 | tool_choice=tool_choice, |
| 62 | tool_prompt_format=tool_prompt_format, |
| 63 | stream=stream, |
| 64 | logprobs=logprobs, |
| 65 | ) |
| 66 | async with httpx.AsyncClient() as client: |
| 67 | async with client.stream( |
| 68 | "POST", |
| 69 | f"{self.base_url}/inference/chat_completion", |
| 70 | json=encodable_dict(request), |
| 71 | headers={"Content-Type": "application/json"}, |
| 72 | timeout=20, |
| 73 | ) as response: |
| 74 | if response.status_code != 200: |
| 75 | content = await response.aread() |
| 76 | cprint( |
| 77 | f"Error: HTTP {response.status_code} {content.decode()}", "red" |
| 78 | ) |
| 79 | return |
| 80 | |
| 81 | async for line in response.aiter_lines(): |
| 82 | if line.startswith("data:"): |
| 83 | data = line[len("data: ") :] |
| 84 | try: |
| 85 | if request.stream: |
| 86 | if "error" in data: |
| 87 | cprint(data, "red") |
| 88 | continue |
| 89 | |
| 90 | yield ChatCompletionResponseStreamChunk( |
| 91 | **json.loads(data) |
| 92 | ) |
| 93 | else: |
| 94 | yield ChatCompletionResponse(**json.loads(data)) |
| 95 | except Exception as e: |
| 96 | print(data) |
| 97 | print(f"Error with parsing or validation: {e}") |
| 98 | |
| 99 | |
| 100 | async def run_main(host: str, port: int, stream: bool): |
| 101 | client = InferenceClient(f"http://{host}:{port}") |
| 102 | |
| 103 | message = UserMessage( |
| 104 | content="hello world, write me a 2 sentence poem about the moon" |
| 105 | ) |
| 106 | cprint(f"User>{message.content}", "green") |
| 107 | iterator = client.chat_completion( |
| 108 | model="Meta-Llama3.1-8B-Instruct", |
| 109 | messages=[message], |
| 110 | stream=stream, |
| 111 | ) |
| 112 | async for log in EventLogger().log(iterator): |
| 113 | log.print() |
| 114 | |
| 115 | |
| 116 | def main(host: str, port: int, stream: bool = True): |
| 117 | asyncio.run(run_main(host, port, stream)) |
| 118 | |
| 119 | |
| 120 | if __name__ == "__main__": |
| 121 | fire.Fire(main) |