| 1 | import os |
| 2 | import sys |
| 3 | import threading |
| 4 | from abc import ABC, abstractmethod |
| 5 | from typing import Literal |
| 6 | |
| 7 | import litellm |
| 8 | from litellm import cost_per_token |
| 9 | from litellm.utils import Choices, Message, ModelResponse |
| 10 | from openai import BadRequestError |
| 11 | from tenacity import retry, stop_after_attempt, wait_random_exponential |
| 12 | |
| 13 | from app.log import log_and_cprint, log_and_print |
| 14 | |
| 15 | # Variables for each process. Since models are singleton objects, their references are copied |
| 16 | # to each process, but they all point to the same objects. For safe updating costs per process, |
| 17 | # we define the accumulators here. |
| 18 | |
| 19 | thread_cost = threading.local() |
| 20 | thread_cost.process_cost = 0.0 |
| 21 | thread_cost.process_input_tokens = 0 |
| 22 | thread_cost.process_output_tokens = 0 |
| 23 | |
| 24 | |
| 25 | class Model(ABC): |
| 26 | def __init__( |
| 27 | self, |
| 28 | name: str, |
| 29 | cost_per_input: float, |
| 30 | cost_per_output: float, |
| 31 | parallel_tool_call: bool = False, |
| 32 | ): |
| 33 | self.name: str = name |
| 34 | # cost stats - zero for local models |
| 35 | self.cost_per_input: float = cost_per_input |
| 36 | self.cost_per_output: float = cost_per_output |
| 37 | # whether the model supports parallel tool call |
| 38 | self.parallel_tool_call: bool = parallel_tool_call |
| 39 | |
| 40 | @abstractmethod |
| 41 | def check_api_key(self) -> str: |
| 42 | raise NotImplementedError("abstract base class") |
| 43 | |
| 44 | @abstractmethod |
| 45 | def setup(self) -> None: |
| 46 | raise NotImplementedError("abstract base class") |
| 47 | |
| 48 | @abstractmethod |
| 49 | def call(self, messages: list[dict], **kwargs): |
| 50 | raise NotImplementedError("abstract base class") |
| 51 | |
| 52 | def calc_cost(self, input_tokens: int, output_tokens: int) -> float: |
| 53 | """ |
| 54 | Calculates the cost of a request based on the number of input/output tokens. |
| 55 | """ |
| 56 | input_cost = self.cost_per_input * input_tokens |
| 57 | output_cost = self.cost_per_output * output_tokens |
| 58 | cost = input_cost + output_cost |
| 59 | log_and_cprint( |
| 60 | f"Model API request cost info: " |
| 61 | f"input_tokens={input_tokens}, output_tokens={output_tokens}, cost={cost:.6f}", |
| 62 | style="yellow", |
| 63 | ) |
| 64 | return cost |
| 65 | |
| 66 | def get_overall_exec_stats(self): |
| 67 | return { |
| 68 | "model": self.name, |
| 69 | "input_cost_per_token": self.cost_per_input, |
| 70 | "output_cost_per_token": self.cost_per_output, |
| 71 | "total_input_tokens": thread_cost.process_input_tokens, |
| 72 | "total_output_tokens": thread_cost.process_output_tokens, |
| 73 | "total_tokens": thread_cost.process_input_tokens |
| 74 | + thread_cost.process_output_tokens, |
| 75 | "total_cost": thread_cost.process_cost, |
| 76 | } |
| 77 | |
| 78 | |
| 79 | class LiteLLMGeneric(Model): |
| 80 | """ |
| 81 | Base class for creating instances of LiteLLM-supported models. |
| 82 | """ |
| 83 | |
| 84 | _instances = {} |
| 85 | |
| 86 | def __new__(cls, model_name: str, cost_per_input: float, cost_per_output: float): |
| 87 | if model_name not in cls._instances: |
| 88 | cls._instances[model_name] = super().__new__(cls) |
| 89 | cls._instances[model_name]._initialized = False |
| 90 | return cls._instances[model_name] |
| 91 | |
| 92 | def __init__( |
| 93 | self, |
| 94 | name: str, |
| 95 | cost_per_input: float, |
| 96 | cost_per_output: float, |
| 97 | parallel_tool_call: bool = False, |
| 98 | ): |
| 99 | if self._initialized: |
| 100 | return |
| 101 | super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call) |
| 102 | self._initialized = True |
| 103 | |
| 104 | def setup(self) -> None: |
| 105 | """ |
| 106 | Check API key. |
| 107 | """ |
| 108 | pass |
| 109 | |
| 110 | def check_api_key(self) -> str: |
| 111 | return "" |
| 112 | |
| 113 | def extract_resp_content(self, chat_message: Message) -> str: |
| 114 | """ |
| 115 | Given a chat completion message, extract the content from it. |
| 116 | """ |
| 117 | content = chat_message.content |
| 118 | if content is None: |
| 119 | return "" |
| 120 | else: |
| 121 | return content |
| 122 | |
| 123 | @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3)) |
| 124 | def call( |
| 125 | self, |
| 126 | messages: list[dict], |
| 127 | top_p=1, |
| 128 | tools=None, |
| 129 | response_format: Literal["text", "json_object"] = "text", |
| 130 | **kwargs, |
| 131 | ): |
| 132 | # FIXME: ignore tools field since we don't use tools now |
| 133 | try: |
| 134 | prefill_content = "{" |
| 135 | if response_format == "json_object": # prefill |
| 136 | messages.append({"role": "assistant", "content": prefill_content}) |
| 137 | |
| 138 | response = litellm.completion( |
| 139 | model=self.name, |
| 140 | messages=messages, |
| 141 | temperature=MODEL_TEMP, |
| 142 | max_tokens=os.getenv("ACR_TOKEN_LIMIT", 1024), |
| 143 | response_format=( |
| 144 | {"type": response_format} if "gpt" in self.name else None |
| 145 | ), |
| 146 | top_p=top_p, |
| 147 | stream=False, |
| 148 | ) |
| 149 | assert isinstance(response, ModelResponse) |
| 150 | resp_usage = response.usage |
| 151 | assert resp_usage is not None |
| 152 | input_tokens = int(resp_usage.prompt_tokens) |
| 153 | output_tokens = int(resp_usage.completion_tokens) |
| 154 | cost = self.calc_cost(input_tokens, output_tokens) |
| 155 | |
| 156 | thread_cost.process_cost += cost |
| 157 | thread_cost.process_input_tokens += input_tokens |
| 158 | thread_cost.process_output_tokens += output_tokens |
| 159 | |
| 160 | first_resp_choice = response.choices[0] |
| 161 | assert isinstance(first_resp_choice, Choices) |
| 162 | resp_msg: Message = first_resp_choice.message |
| 163 | content = self.extract_resp_content(resp_msg) |
| 164 | if response_format == "json_object": |
| 165 | # prepend the prefilled character |
| 166 | if not content.startswith(prefill_content): |
| 167 | content = prefill_content + content |
| 168 | |
| 169 | return content, cost, input_tokens, output_tokens |
| 170 | |
| 171 | except BadRequestError as e: |
| 172 | if e.code == "context_length_exceeded": |
| 173 | log_and_print("Context length exceeded") |
| 174 | raise e |
| 175 | |
| 176 | |
| 177 | MODEL_HUB = {} |
| 178 | |
| 179 | |
| 180 | def register_model(model: Model): |
| 181 | global MODEL_HUB |
| 182 | MODEL_HUB[model.name] = model |
| 183 | |
| 184 | |
| 185 | def get_all_model_names(): |
| 186 | return list(MODEL_HUB.keys()) |
| 187 | |
| 188 | |
| 189 | # To be set at runtime - the selected model for a run |
| 190 | SELECTED_MODEL: Model |
| 191 | |
| 192 | |
| 193 | def set_model(model_name: str): |
| 194 | global SELECTED_MODEL |
| 195 | if model_name not in MODEL_HUB and not model_name.startswith("litellm-generic-"): |
| 196 | print(f"Invalid model name: {model_name}") |
| 197 | sys.exit(1) |
| 198 | if model_name.startswith("litellm-generic-"): |
| 199 | real_model_name = model_name.removeprefix("litellm-generic-") |
| 200 | prompt_tokens = 5 |
| 201 | completion_tokens = 10 |
| 202 | prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar = ( |
| 203 | cost_per_token( |
| 204 | model=real_model_name, |
| 205 | prompt_tokens=prompt_tokens, |
| 206 | completion_tokens=completion_tokens, |
| 207 | ) |
| 208 | ) |
| 209 | # litellm.set_verbose = True |
| 210 | SELECTED_MODEL = LiteLLMGeneric( |
| 211 | real_model_name, |
| 212 | prompt_tokens_cost_usd_dollar, |
| 213 | completion_tokens_cost_usd_dollar, |
| 214 | ) |
| 215 | else: |
| 216 | SELECTED_MODEL = MODEL_HUB[model_name] |
| 217 | SELECTED_MODEL.setup() |
| 218 | |
| 219 | |
| 220 | # the model temperature to use |
| 221 | # For OpenAI models: this value should be from 0 to 2 |
| 222 | MODEL_TEMP: float = 0.0 |