Elffuss BraidHub

kikocis/llama-stack public

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