Elffuss BraidHub

kikocis/auto-code-rover public

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