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