|
| 1 | +import threading |
| 2 | +from queue import Empty, Queue |
| 3 | +import json |
| 4 | +import time |
| 5 | +import traceback |
| 6 | +from typing import Dict, List, Callable |
| 7 | +from openvino_interface import LLMInterface |
| 8 | +from openvino_params import LLMParams |
| 9 | + |
| 10 | +RAG_PROMPT_FORMAT = "Answer the questions based on the information below. \n{context}\n\nQuestion: {prompt}" |
| 11 | + |
| 12 | +class LLM_SSE_Adapter: |
| 13 | + msg_queue: Queue |
| 14 | + finish: bool |
| 15 | + singal: threading.Event |
| 16 | + llm_interface: LLMInterface |
| 17 | + should_stop: bool |
| 18 | + |
| 19 | + def __init__(self, llm_interface: LLMInterface): |
| 20 | + self.msg_queue = Queue(-1) |
| 21 | + self.finish = False |
| 22 | + self.singal = threading.Event() |
| 23 | + self.llm_interface = llm_interface |
| 24 | + self.should_stop = False |
| 25 | + self.num_tokens = 0 |
| 26 | + self.start_time = 0 |
| 27 | + self.first_token_time = 0 |
| 28 | + self.last_token_time = 0 |
| 29 | + self.is_first_token = True |
| 30 | + |
| 31 | + def put_msg(self, data): |
| 32 | + self.msg_queue.put_nowait(data) |
| 33 | + self.singal.set() |
| 34 | + |
| 35 | + def load_model_callback(self, event: str): |
| 36 | + data = {"type": "load_model", "event": event} |
| 37 | + self.put_msg(data) |
| 38 | + |
| 39 | + def text_in_callback(self, msg: str): |
| 40 | + data = {"type": "text_in", "value": msg} |
| 41 | + self.put_msg(data) |
| 42 | + |
| 43 | + def text_out_callback(self, msg: str, type=1): |
| 44 | + data = {"type": "text_out", "value": msg, "dtype": type} |
| 45 | + self.put_msg(data) |
| 46 | + |
| 47 | + def first_latency_callback(self, first_latency: str): |
| 48 | + data = {"type": "first_token_latency", "value": first_latency} |
| 49 | + self.put_msg(data) |
| 50 | + |
| 51 | + def after_latency_callback(self, after_latency: str): |
| 52 | + data = {"type": "after_token_latency", "value": after_latency} |
| 53 | + self.put_msg(data) |
| 54 | + |
| 55 | + def sr_latency_callback(self, sr_latency: str): |
| 56 | + data = {"type": "sr_latency", "value": sr_latency} |
| 57 | + self.put_msg(data) |
| 58 | + |
| 59 | + def error_callback(self, ex: Exception): |
| 60 | + if ( |
| 61 | + isinstance(ex, NotImplementedError) |
| 62 | + and ex.__str__() == "Access to repositories lists is not implemented." |
| 63 | + ): |
| 64 | + self.put_msg( |
| 65 | + { |
| 66 | + "type": "error", |
| 67 | + "err_type": "repositories_not_found", |
| 68 | + } |
| 69 | + ) |
| 70 | + # elif isinstance(ex, NotEnoughDiskSpaceException): |
| 71 | + # self.put_msg( |
| 72 | + # { |
| 73 | + # "type": "error", |
| 74 | + # "err_type": "not_enough_disk_space", |
| 75 | + # "need": bytes2human(ex.requires_space), |
| 76 | + # "free": bytes2human(ex.free_space), |
| 77 | + # } |
| 78 | + # ) |
| 79 | + # elif isinstance(ex, DownloadException): |
| 80 | + # self.put_msg({"type": "error", "err_type": "download_exception"}) |
| 81 | + # # elif isinstance(ex, llm_biz.StopGenerateException): |
| 82 | + # # pass |
| 83 | + elif isinstance(ex, RuntimeError): |
| 84 | + self.put_msg({"type": "error", "err_type": "runtime_error"}) |
| 85 | + else: |
| 86 | + self.put_msg({"type": "error", "err_type": "unknown_exception"}) |
| 87 | + self.put_msg(f"exception:{str(ex)}") |
| 88 | + |
| 89 | + def text_conversation(self, params: LLMParams): |
| 90 | + thread = threading.Thread( |
| 91 | + target=self.text_conversation_run, |
| 92 | + args=[params], |
| 93 | + ) |
| 94 | + thread.start() |
| 95 | + return self.generator() |
| 96 | + |
| 97 | + |
| 98 | + def stream_function(self, output): |
| 99 | + if self.is_first_token: |
| 100 | + self.first_token_time = time.time() |
| 101 | + self.is_first_token = False |
| 102 | + |
| 103 | + self.text_out_callback(output) |
| 104 | + self.num_tokens += 1 |
| 105 | + |
| 106 | + if self.llm_interface.stop_generate: |
| 107 | + self.put_msg("Stopping generation.") |
| 108 | + return True # Stop generation |
| 109 | + |
| 110 | + return False |
| 111 | + |
| 112 | + |
| 113 | + def text_conversation_run( |
| 114 | + self, |
| 115 | + params: LLMParams, |
| 116 | + ): |
| 117 | + try: |
| 118 | + self.llm_interface.load_model(params, callback=self.load_model_callback) |
| 119 | + |
| 120 | + # Reset metrics tracking |
| 121 | + self.num_tokens = 0 |
| 122 | + self.start_time = time.time() |
| 123 | + self.first_token_time = 0 |
| 124 | + self.last_token_time = 0 |
| 125 | + self.is_first_token = True |
| 126 | + |
| 127 | + prompt = params.prompt |
| 128 | + full_prompt = convert_prompt(prompt) |
| 129 | + self.llm_interface.create_chat_completion(full_prompt, self.stream_function, params.max_tokens) |
| 130 | + |
| 131 | + # Calculate and send metrics |
| 132 | + self.last_token_time = time.time() |
| 133 | + metrics_data = { |
| 134 | + "type": "metrics", |
| 135 | + "num_tokens": self.num_tokens, |
| 136 | + "total_time": self.last_token_time - self.start_time, |
| 137 | + "overall_tokens_per_second": self.num_tokens / (self.last_token_time - self.start_time) if self.num_tokens > 0 else 0, |
| 138 | + "second_plus_tokens_per_second": (self.num_tokens - 1) / (self.last_token_time - self.first_token_time) if self.num_tokens > 1 else None, |
| 139 | + "first_token_latency": self.first_token_time - self.start_time if self.num_tokens > 0 else None, |
| 140 | + "after_token_latency": (self.last_token_time - self.first_token_time) / (self.num_tokens - 1) if self.num_tokens > 1 else None |
| 141 | + } |
| 142 | + self.put_msg(metrics_data) |
| 143 | + self.put_msg({"type": "finish"}) |
| 144 | + |
| 145 | + except Exception as ex: |
| 146 | + traceback.print_exc() |
| 147 | + self.error_callback(ex) |
| 148 | + finally: |
| 149 | + self.llm_interface.stop_generate = False |
| 150 | + self.finish = True |
| 151 | + self.singal.set() |
| 152 | + |
| 153 | + def generator(self): |
| 154 | + while True: |
| 155 | + while not self.msg_queue.empty(): |
| 156 | + try: |
| 157 | + data = self.msg_queue.get_nowait() |
| 158 | + msg = f"data:{json.dumps(data)}\0" |
| 159 | + print(msg) |
| 160 | + yield msg |
| 161 | + except Empty(Exception): |
| 162 | + break |
| 163 | + if not self.finish: |
| 164 | + self.singal.clear() |
| 165 | + self.singal.wait() |
| 166 | + else: |
| 167 | + break |
| 168 | + |
| 169 | + |
| 170 | +_default_prompt = { |
| 171 | + "role": "system", |
| 172 | + "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user. Please keep the output text language the same as the user input.", |
| 173 | + } |
| 174 | + |
| 175 | +def convert_prompt(prompt: List[Dict[str, str]]): |
| 176 | + chat_history = [_default_prompt] |
| 177 | + prompt_len = prompt.__len__() |
| 178 | + i = 0 |
| 179 | + while i < prompt_len: |
| 180 | + chat_history.append({"role": "user", "content": prompt[i].get("question")}) |
| 181 | + if i < prompt_len - 1: |
| 182 | + chat_history.append( |
| 183 | + {"role": "assistant", "content": prompt[i].get("answer")} |
| 184 | + ) |
| 185 | + i = i + 1 |
| 186 | + return chat_history |
| 187 | + |
| 188 | + |
| 189 | +def process_rag( |
| 190 | + prompt: str, |
| 191 | + device: str, |
| 192 | + text_out_callback: Callable[[str, int], None] = None, |
| 193 | + ): |
| 194 | + import rag |
| 195 | + rag.to(device) |
| 196 | + query_success, context, rag_source = rag.query(prompt) |
| 197 | + if query_success: |
| 198 | + print("rag query input\r\n{}output:\r\n{}".format(prompt, context)) |
| 199 | + prompt = RAG_PROMPT_FORMAT.format(prompt=prompt, context=context) |
| 200 | + if text_out_callback is not None: |
| 201 | + text_out_callback(rag_source, 2) |
| 202 | + return prompt |
0 commit comments