| 1 | """ |
| 2 | For models other than those from OpenAI, use LiteLLM if possible. |
| 3 | """ |
| 4 | |
| 5 | import os |
| 6 | import sys |
| 7 | from typing import Literal |
| 8 | |
| 9 | import litellm |
| 10 | from litellm.utils import Choices, Message, ModelResponse |
| 11 | from openai import BadRequestError |
| 12 | from tenacity import retry, stop_after_attempt, wait_random_exponential |
| 13 | |
| 14 | from app.log import log_and_print |
| 15 | from app.model import common |
| 16 | from app.model.common import Model |
| 17 | |
| 18 | |
| 19 | class OpenaiLiteLLMModel(Model): |
| 20 | """ |
| 21 | Base class for creating Singleton instances of Openai models. |
| 22 | """ |
| 23 | |
| 24 | _instances = {} |
| 25 | |
| 26 | def __new__(cls): |
| 27 | if cls not in cls._instances: |
| 28 | cls._instances[cls] = super().__new__(cls) |
| 29 | cls._instances[cls]._initialized = False |
| 30 | return cls._instances[cls] |
| 31 | |
| 32 | def __init__( |
| 33 | self, |
| 34 | name: str, |
| 35 | cost_per_input: float, |
| 36 | cost_per_output: float, |
| 37 | parallel_tool_call: bool = False, |
| 38 | ): |
| 39 | if self._initialized: |
| 40 | return |
| 41 | super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call) |
| 42 | self._initialized = True |
| 43 | |
| 44 | def setup(self) -> None: |
| 45 | """ |
| 46 | Check API key. |
| 47 | """ |
| 48 | self.check_api_key() |
| 49 | |
| 50 | def check_api_key(self) -> str: |
| 51 | key_name = "OPENAI_KEY" |
| 52 | key = os.getenv(key_name) |
| 53 | if not key: |
| 54 | print(f"Please set the {key_name} env var") |
| 55 | sys.exit(1) |
| 56 | os.environ["OPENAI_API_KEY"] = key |
| 57 | return key |
| 58 | |
| 59 | def extract_resp_content(self, chat_message: Message) -> str: |
| 60 | """ |
| 61 | Given a chat completion message, extract the content from it. |
| 62 | """ |
| 63 | content = chat_message.content |
| 64 | if content is None: |
| 65 | return "" |
| 66 | else: |
| 67 | return content |
| 68 | |
| 69 | @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3)) |
| 70 | def call( |
| 71 | self, |
| 72 | messages: list[dict], |
| 73 | top_p=1, |
| 74 | tools=None, |
| 75 | response_format: Literal["text", "json_object"] = "text", |
| 76 | **kwargs, |
| 77 | ): |
| 78 | # FIXME: ignore tools field since we don't use tools now |
| 79 | try: |
| 80 | prefill_content = "{" |
| 81 | if response_format == "json_object": # prefill |
| 82 | messages.append({"role": "assistant", "content": prefill_content}) |
| 83 | |
| 84 | response = litellm.completion( |
| 85 | model=( |
| 86 | self.name |
| 87 | if not self.name.startswith("litellm-") |
| 88 | else self.name[len("litellm-") :] |
| 89 | ), |
| 90 | messages=messages, |
| 91 | temperature=common.MODEL_TEMP, |
| 92 | max_tokens=1024, |
| 93 | response_format={"type": response_format}, |
| 94 | top_p=top_p, |
| 95 | base_url=os.getenv("OPENAI_API_BASE_URL", None), |
| 96 | stream=False, |
| 97 | ) |
| 98 | assert isinstance(response, ModelResponse) |
| 99 | resp_usage = response.usage |
| 100 | assert resp_usage is not None |
| 101 | input_tokens = int(resp_usage.prompt_tokens) |
| 102 | output_tokens = int(resp_usage.completion_tokens) |
| 103 | cost = self.calc_cost(input_tokens, output_tokens) |
| 104 | |
| 105 | common.thread_cost.process_cost += cost |
| 106 | common.thread_cost.process_input_tokens += input_tokens |
| 107 | common.thread_cost.process_output_tokens += output_tokens |
| 108 | |
| 109 | first_resp_choice = response.choices[0] |
| 110 | assert isinstance(first_resp_choice, Choices) |
| 111 | resp_msg: Message = first_resp_choice.message |
| 112 | content = self.extract_resp_content(resp_msg) |
| 113 | if response_format == "json_object": |
| 114 | # prepend the prefilled character |
| 115 | if not content.startswith(prefill_content): |
| 116 | content = prefill_content + content |
| 117 | |
| 118 | return content, cost, input_tokens, output_tokens |
| 119 | |
| 120 | except BadRequestError as e: |
| 121 | if e.code == "context_length_exceeded": |
| 122 | log_and_print("Context length exceeded") |
| 123 | raise e |
| 124 | |
| 125 | |
| 126 | class Gpt4o_20240513LiteLLM(OpenaiLiteLLMModel): |
| 127 | def __init__(self): |
| 128 | super().__init__( |
| 129 | "litellm-gpt-4o-2024-05-13", 0.000005, 0.000015, parallel_tool_call=True |
| 130 | ) |
| 131 | self.note = "Multimodal model. Up to Oct 2023." |
| 132 | |
| 133 | |
| 134 | class Gpt4_Turbo20240409LiteLLM(OpenaiLiteLLMModel): |
| 135 | def __init__(self): |
| 136 | super().__init__( |
| 137 | "litellm-gpt-4-turbo-2024-04-09", 0.00001, 0.00003, parallel_tool_call=True |
| 138 | ) |
| 139 | self.note = "Turbo with vision. Up to Dec 2023." |
| 140 | |
| 141 | |
| 142 | class Gpt4_0125PreviewLiteLLM(OpenaiLiteLLMModel): |
| 143 | def __init__(self): |
| 144 | super().__init__( |
| 145 | "litellm-gpt-4-0125-preview", 0.00001, 0.00003, parallel_tool_call=True |
| 146 | ) |
| 147 | self.note = "Turbo. Up to Dec 2023." |
| 148 | |
| 149 | |
| 150 | class Gpt4_1106PreviewLiteLLM(OpenaiLiteLLMModel): |
| 151 | def __init__(self): |
| 152 | super().__init__( |
| 153 | "litellm-gpt-4-1106-preview", 0.00001, 0.00003, parallel_tool_call=True |
| 154 | ) |
| 155 | self.note = "Turbo. Up to Apr 2023." |
| 156 | |
| 157 | |
| 158 | class Gpt35_Turbo0125LiteLLM(OpenaiLiteLLMModel): |
| 159 | # cheapest gpt model |
| 160 | def __init__(self): |
| 161 | super().__init__( |
| 162 | "litellm-gpt-3.5-turbo-0125", 0.0000005, 0.0000015, parallel_tool_call=True |
| 163 | ) |
| 164 | self.note = "Turbo. Up to Sep 2021." |
| 165 | |
| 166 | |
| 167 | class Gpt35_Turbo1106LiteLLM(OpenaiLiteLLMModel): |
| 168 | def __init__(self): |
| 169 | super().__init__( |
| 170 | "litellm-gpt-3.5-turbo-1106", 0.000001, 0.000002, parallel_tool_call=True |
| 171 | ) |
| 172 | self.note = "Turbo. Up to Sep 2021." |
| 173 | |
| 174 | |
| 175 | class Gpt35_Turbo16k_0613LiteLLM(OpenaiLiteLLMModel): |
| 176 | def __init__(self): |
| 177 | super().__init__("litellm-gpt-3.5-turbo-16k-0613", 0.000003, 0.000004) |
| 178 | self.note = "Turbo. Deprecated. Up to Sep 2021." |
| 179 | |
| 180 | |
| 181 | class Gpt35_Turbo0613LiteLLM(OpenaiLiteLLMModel): |
| 182 | def __init__(self): |
| 183 | super().__init__("litellm-gpt-3.5-turbo-0613", 0.0000015, 0.000002) |
| 184 | self.note = "Turbo. Deprecated. Only 4k window. Up to Sep 2021." |
| 185 | |
| 186 | |
| 187 | class Gpt4_0613LiteLLM(OpenaiLiteLLMModel): |
| 188 | def __init__(self): |
| 189 | super().__init__("litellm-gpt-4-0613", 0.00003, 0.00006) |
| 190 | self.note = "Not turbo. Up to Sep 2021." |