Elffuss BraidHub

kikocis/auto-code-rover public

main · 10.0 KiBRawPermalink
1"""
2Interfacing with OpenAI models.
3"""
4
5import json
6import os
7import sys
8from typing import Literal, cast
9
10from loguru import logger
11from openai import BadRequestError, OpenAI
12from openai.types.chat import (
13 ChatCompletion,
14 ChatCompletionMessage,
15 ChatCompletionMessageToolCall,
16)
17from openai.types.chat.chat_completion_message_tool_call import (
18 Function as OpenaiFunction,
19)
20from openai.types.chat.chat_completion_tool_choice_option_param import (
21 ChatCompletionToolChoiceOptionParam,
22)
23from openai.types.chat.completion_create_params import ResponseFormat
24from tenacity import retry, stop_after_attempt, wait_random_exponential
25
26from app.data_structures import FunctionCallIntent
27from app.log import log_and_print
28from app.model import common
29from app.model.common import Model
30
31
32class OpenaiModel(Model):
33 """
34 Base class for creating Singleton instances of OpenAI models.
35 We use native API from OpenAI instead of LiteLLM.
36 """
37
38 _instances = {}
39
40 def __new__(cls):
41 if cls not in cls._instances:
42 cls._instances[cls] = super().__new__(cls)
43 cls._instances[cls]._initialized = False
44 return cls._instances[cls]
45
46 def __init__(
47 self,
48 name: str,
49 max_output_token: int,
50 cost_per_input: float,
51 cost_per_output: float,
52 parallel_tool_call: bool = False,
53 ):
54 if self._initialized:
55 return
56 super().__init__(name, cost_per_input, cost_per_output, parallel_tool_call)
57 # max number of output tokens allowed in model response
58 # sometimes we want to set a lower number for models with smaller context window,
59 # because output token limit consumes part of the context window
60 self.max_output_token = max_output_token
61 # client for making request
62 self.client: OpenAI | None = None
63 self._initialized = True
64
65 def setup(self) -> None:
66 """
67 Check API key, and initialize OpenAI client.
68 """
69 if self.client is None:
70 key = self.check_api_key()
71 self.client = OpenAI(api_key=key)
72
73 def check_api_key(self) -> str:
74 key = os.getenv("OPENAI_KEY")
75 if not key:
76 print("Please set the OPENAI_KEY env var")
77 sys.exit(1)
78 return key
79
80 def extract_resp_content(
81 self, chat_completion_message: ChatCompletionMessage
82 ) -> str:
83 """
84 Given a chat completion message, extract the content from it.
85 """
86 content = chat_completion_message.content
87 if content is None:
88 return ""
89 else:
90 return content
91
92 def extract_resp_func_calls(
93 self,
94 chat_completion_message: ChatCompletionMessage,
95 ) -> list[FunctionCallIntent]:
96 """
97 Given a chat completion message, extract the function calls from it.
98 Args:
99 chat_completion_message (ChatCompletionMessage): The chat completion message.
100 Returns:
101 List[FunctionCallIntent]: A list of function calls.
102 """
103 result = []
104 tool_calls = chat_completion_message.tool_calls
105 if tool_calls is None:
106 return result
107
108 call: ChatCompletionMessageToolCall
109 for call in tool_calls:
110 called_func: OpenaiFunction = call.function
111 func_name = called_func.name
112 func_args_str = called_func.arguments
113 # maps from arg name to arg value
114 if func_args_str == "":
115 args_dict = {}
116 else:
117 try:
118 args_dict = json.loads(func_args_str, strict=False)
119 except json.decoder.JSONDecodeError:
120 args_dict = {}
121 func_call_intent = FunctionCallIntent(func_name, args_dict, called_func)
122 result.append(func_call_intent)
123
124 return result
125
126 # FIXME: the returned type contains OpenAI specific Types, which should be avoided
127 @retry(wait=wait_random_exponential(min=30, max=600), stop=stop_after_attempt(3))
128 def call(
129 self,
130 messages: list[dict],
131 top_p: float = 1,
132 tools: list[dict] | None = None,
133 response_format: Literal["text", "json_object"] = "text",
134 temperature: float | None = None,
135 **kwargs,
136 ) -> tuple[
137 str,
138 list[ChatCompletionMessageToolCall] | None,
139 list[FunctionCallIntent],
140 float,
141 int,
142 int,
143 ]:
144 """
145 Calls the openai API to generate completions for the given inputs.
146 Assumption: we only retrieve one choice from the API response.
147
148 Args:
149 messages (List): A list of messages.
150 Each item is a dict (e.g. {"role": "user", "content": "Hello, world!"})
151 top_p (float): The top_p to use. We usually do not vary this, so not setting it as a cmd-line argument. (from 0 to 1)
152 tools (List, optional): A list of tools.
153
154 Returns:
155 Raw response and parsed components.
156 The raw response is to be sent back as part of the message history.
157 """
158 if temperature is None:
159 temperature = common.MODEL_TEMP
160
161 assert self.client is not None
162 try:
163 if tools is not None and len(tools) == 1:
164 # there is only one tool => force the model to use it
165 tool_name = tools[0]["function"]["name"]
166 tool_choice = {"type": "function", "function": {"name": tool_name}}
167 response: ChatCompletion = self.client.chat.completions.create(
168 model=self.name,
169 messages=messages, # type: ignore
170 tools=tools, # type: ignore
171 tool_choice=cast(ChatCompletionToolChoiceOptionParam, tool_choice),
172 temperature=temperature,
173 response_format=ResponseFormat(type=response_format),
174 max_tokens=self.max_output_token,
175 top_p=top_p,
176 stream=False,
177 )
178 else:
179 response: ChatCompletion = self.client.chat.completions.create(
180 model=self.name,
181 messages=messages, # type: ignore
182 tools=tools, # type: ignore
183 temperature=temperature,
184 response_format=ResponseFormat(type=response_format),
185 max_tokens=self.max_output_token,
186 top_p=top_p,
187 stream=False,
188 )
189
190 usage_stats = response.usage
191 assert usage_stats is not None
192
193 input_tokens = int(usage_stats.prompt_tokens)
194 output_tokens = int(usage_stats.completion_tokens)
195 cost = self.calc_cost(input_tokens, output_tokens)
196
197 common.thread_cost.process_cost += cost
198 common.thread_cost.process_input_tokens += input_tokens
199 common.thread_cost.process_output_tokens += output_tokens
200
201 raw_response = response.choices[0].message
202 # log_and_print(f"Raw model response: {raw_response}")
203 content = self.extract_resp_content(raw_response)
204 raw_tool_calls = raw_response.tool_calls
205 func_call_intents = self.extract_resp_func_calls(raw_response)
206 return (
207 content,
208 raw_tool_calls,
209 func_call_intents,
210 cost,
211 input_tokens,
212 output_tokens,
213 )
214 except BadRequestError as e:
215 logger.debug("BadRequestError ({}): messages={}", e.code, messages)
216 if e.code == "context_length_exceeded":
217 log_and_print("Context length exceeded")
218 raise e
219
220
221class Gpt4o_20240806(OpenaiModel):
222 def __init__(self):
223 super().__init__(
224 "gpt-4o-2024-08-06", 16384, 0.0000025, 0.000010, parallel_tool_call=True
225 )
226 self.note = "Multimodal model. Up to Apr 2023."
227
228
229class Gpt4o_20240513(OpenaiModel):
230 def __init__(self):
231 super().__init__(
232 "gpt-4o-2024-05-13", 4096, 0.000005, 0.000015, parallel_tool_call=True
233 )
234 self.note = "Multimodal model. Up to Oct 2023."
235
236
237class Gpt4_Turbo20240409(OpenaiModel):
238 def __init__(self):
239 super().__init__(
240 "gpt-4-turbo-2024-04-09", 4096, 0.00001, 0.00003, parallel_tool_call=True
241 )
242 self.note = "Turbo with vision. Up to Dec 2023."
243
244
245class Gpt4_0125Preview(OpenaiModel):
246 def __init__(self):
247 super().__init__(
248 "gpt-4-0125-preview", 4096, 0.00001, 0.00003, parallel_tool_call=True
249 )
250 self.note = "Turbo. Up to Dec 2023."
251
252
253class Gpt4_1106Preview(OpenaiModel):
254 def __init__(self):
255 super().__init__(
256 "gpt-4-1106-preview", 4096, 0.00001, 0.00003, parallel_tool_call=True
257 )
258 self.note = "Turbo. Up to Apr 2023."
259
260
261class Gpt35_Turbo0125(OpenaiModel):
262 # cheapest gpt model
263 def __init__(self):
264 super().__init__(
265 "gpt-3.5-turbo-0125", 1024, 0.0000005, 0.0000015, parallel_tool_call=True
266 )
267 self.note = "Turbo. Up to Sep 2021."
268
269
270class Gpt35_Turbo1106(OpenaiModel):
271 def __init__(self):
272 super().__init__(
273 "gpt-3.5-turbo-1106", 1024, 0.000001, 0.000002, parallel_tool_call=True
274 )
275 self.note = "Turbo. Up to Sep 2021."
276
277
278class Gpt35_Turbo16k_0613(OpenaiModel):
279 def __init__(self):
280 super().__init__("gpt-3.5-turbo-16k-0613", 1024, 0.000003, 0.000004)
281 self.note = "Turbo. Deprecated. Up to Sep 2021."
282
283
284class Gpt35_Turbo0613(OpenaiModel):
285 def __init__(self):
286 super().__init__("gpt-3.5-turbo-0613", 512, 0.0000015, 0.000002)
287 self.note = "Turbo. Deprecated. Only 4k window. Up to Sep 2021."
288
289
290class Gpt4_0613(OpenaiModel):
291 def __init__(self):
292 super().__init__("gpt-4-0613", 512, 0.00003, 0.00006)
293 self.note = "Not turbo. Up to Sep 2021."
294
295
296class Gpt4o_mini_20240718(OpenaiModel):
297 def __init__(self):
298 super().__init__("gpt-4o-mini-2024-07-18", 4096, 0.00000015, 0.0000006)