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