Elffuss BraidHub

kikocis/llama-stack public

main · 1.5 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
7from llama_stack.apis.inference import (
8 ChatCompletionResponseEventType,
9 ChatCompletionResponseStreamChunk,
10)
11from termcolor import cprint
12
13
14class LogEvent:
15 def __init__(
16 self,
17 content: str = "",
18 end: str = "\n",
19 color="white",
20 ):
21 self.content = content
22 self.color = color
23 self.end = "\n" if end is None else end
24
25 def print(self, flush=True):
26 cprint(f"{self.content}", color=self.color, end=self.end, flush=flush)
27
28
29class EventLogger:
30 async def log(self, event_generator):
31 async for chunk in event_generator:
32 if isinstance(chunk, ChatCompletionResponseStreamChunk):
33 event = chunk.event
34 if event.event_type == ChatCompletionResponseEventType.start:
35 yield LogEvent("Assistant> ", color="cyan", end="")
36 elif event.event_type == ChatCompletionResponseEventType.progress:
37 yield LogEvent(event.delta, color="yellow", end="")
38 elif event.event_type == ChatCompletionResponseEventType.complete:
39 yield LogEvent("")
40 else:
41 yield LogEvent("Assistant> ", color="cyan", end="")
42 yield LogEvent(chunk.completion_message.content, color="yellow")