Elffuss BraidHub

kikocis/auto-code-rover public

831d2a8f2ea0 · 5.9 KiBRawPermalink
1"""
2For models other than those from OpenAI, use LiteLLM if possible.
3"""
4
5import os
6import sys
7from typing import Literal
8
9import litellm
10from litellm.utils import Choices, Message, ModelResponse
11from openai import BadRequestError
12from tenacity import retry, stop_after_attempt, wait_random_exponential
13
14from app.log import log_and_print
15from app.model import common
16from app.model.common import Model
17
18
19class 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 stream=False,
96 )
97 assert isinstance(response, ModelResponse)
98 resp_usage = response.usage
99 assert resp_usage is not None
100 input_tokens = int(resp_usage.prompt_tokens)
101 output_tokens = int(resp_usage.completion_tokens)
102 cost = self.calc_cost(input_tokens, output_tokens)
103
104 common.thread_cost.process_cost += cost
105 common.thread_cost.process_input_tokens += input_tokens
106 common.thread_cost.process_output_tokens += output_tokens
107
108 first_resp_choice = response.choices[0]
109 assert isinstance(first_resp_choice, Choices)
110 resp_msg: Message = first_resp_choice.message
111 content = self.extract_resp_content(resp_msg)
112 if response_format == "json_object":
113 # prepend the prefilled character
114 if not content.startswith(prefill_content):
115 content = prefill_content + content
116
117 return content, cost, input_tokens, output_tokens
118
119 except BadRequestError as e:
120 if e.code == "context_length_exceeded":
121 log_and_print("Context length exceeded")
122 raise e
123
124
125class Gpt4o_20240513LiteLLM(OpenaiLiteLLMModel):
126 def __init__(self):
127 super().__init__(
128 "litellm-gpt-4o-2024-05-13", 0.000005, 0.000015, parallel_tool_call=True
129 )
130 self.note = "Multimodal model. Up to Oct 2023."
131
132
133class Gpt4_Turbo20240409LiteLLM(OpenaiLiteLLMModel):
134 def __init__(self):
135 super().__init__(
136 "litellm-gpt-4-turbo-2024-04-09", 0.00001, 0.00003, parallel_tool_call=True
137 )
138 self.note = "Turbo with vision. Up to Dec 2023."
139
140
141class Gpt4_0125PreviewLiteLLM(OpenaiLiteLLMModel):
142 def __init__(self):
143 super().__init__(
144 "litellm-gpt-4-0125-preview", 0.00001, 0.00003, parallel_tool_call=True
145 )
146 self.note = "Turbo. Up to Dec 2023."
147
148
149class Gpt4_1106PreviewLiteLLM(OpenaiLiteLLMModel):
150 def __init__(self):
151 super().__init__(
152 "litellm-gpt-4-1106-preview", 0.00001, 0.00003, parallel_tool_call=True
153 )
154 self.note = "Turbo. Up to Apr 2023."
155
156
157class Gpt35_Turbo0125LiteLLM(OpenaiLiteLLMModel):
158 # cheapest gpt model
159 def __init__(self):
160 super().__init__(
161 "litellm-gpt-3.5-turbo-0125", 0.0000005, 0.0000015, parallel_tool_call=True
162 )
163 self.note = "Turbo. Up to Sep 2021."
164
165
166class Gpt35_Turbo1106LiteLLM(OpenaiLiteLLMModel):
167 def __init__(self):
168 super().__init__(
169 "litellm-gpt-3.5-turbo-1106", 0.000001, 0.000002, parallel_tool_call=True
170 )
171 self.note = "Turbo. Up to Sep 2021."
172
173
174class Gpt35_Turbo16k_0613LiteLLM(OpenaiLiteLLMModel):
175 def __init__(self):
176 super().__init__("litellm-gpt-3.5-turbo-16k-0613", 0.000003, 0.000004)
177 self.note = "Turbo. Deprecated. Up to Sep 2021."
178
179
180class Gpt35_Turbo0613LiteLLM(OpenaiLiteLLMModel):
181 def __init__(self):
182 super().__init__("litellm-gpt-3.5-turbo-0613", 0.0000015, 0.000002)
183 self.note = "Turbo. Deprecated. Only 4k window. Up to Sep 2021."
184
185
186class Gpt4_0613LiteLLM(OpenaiLiteLLMModel):
187 def __init__(self):
188 super().__init__("litellm-gpt-4-0613", 0.00003, 0.00006)
189 self.note = "Not turbo. Up to Sep 2021."