forked from confident-ai/deepeval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai_model.py
More file actions
396 lines (365 loc) · 13.1 KB
/
openai_model.py
File metadata and controls
396 lines (365 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
from openai.types.chat.chat_completion import ChatCompletion
from typing import Optional, Tuple, Union, Dict
from openai import OpenAI, AsyncOpenAI
from pydantic import BaseModel
import logging
import openai
from tenacity import (
retry,
retry_if_exception_type,
wait_exponential_jitter,
RetryCallState,
)
from deepeval.models import DeepEvalBaseLLM
from deepeval.models.llms.utils import trim_and_load_json
def log_retry_error(retry_state: RetryCallState):
exception = retry_state.outcome.exception()
logging.error(
f"OpenAI Error: {exception} Retrying: {retry_state.attempt_number} time(s)..."
)
valid_gpt_models = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-0125",
"gpt-3.5-turbo-1106",
"gpt-4-0125-preview",
"gpt-4-1106-preview",
"gpt-4-turbo",
"gpt-4-turbo-2024-04-09",
"gpt-4-turbo-preview",
"gpt-4o",
"gpt-4o-2024-05-13",
"gpt-4o-2024-08-06",
"gpt-4o-2024-11-20",
"gpt-4o-mini",
"gpt-4o-mini-2024-07-18",
"gpt-4-32k",
"gpt-4-32k-0613",
"gpt-4.1",
"gpt-4.1-mini",
"gpt-4.1-nano",
"gpt-4.5-preview",
"o1",
"o1-preview",
"o1-2024-12-17",
"o1-preview-2024-09-12",
"o1-mini",
"o1-mini-2024-09-12",
"o3-mini",
"o3-mini-2025-01-31",
"o4-mini",
"gpt-4.5-preview-2025-02-27",
]
unsupported_log_probs_gpt_models = [
"o1",
"o1-preview",
"o1-2024-12-17",
"o1-preview-2024-09-12",
"o1-mini",
"o1-mini-2024-09-12",
"o3-mini",
"o3-mini-2025-01-31",
"gpt-4.5-preview-2025-02-27",
]
structured_outputs_models = [
"gpt-4o",
"gpt-4o-2024-05-13",
"gpt-4o-2024-08-06",
"gpt-4o-2024-11-20",
"gpt-4o-mini",
"gpt-4o-mini-2024-07-18",
"gpt-4.1",
"gpt-4.1-mini",
"gpt-4.1-nano",
"o1",
"o1-preview",
"o1-2024-12-17",
"o3-mini",
"o3-mini-2025-01-31",
"gpt-4.5-preview-2025-02-27",
]
json_mode_models = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-0125",
"gpt-3.5-turbo-1106",
"gpt-4-0125-preview",
"gpt-4-1106-preview",
"gpt-4-turbo",
"gpt-4-turbo-2024-04-09",
"gpt-4-turbo-preview",
"gpt-4-32k",
"gpt-4-32k-0613",
]
model_pricing = {
"gpt-4o-mini": {"input": 0.150 / 1e6, "output": 0.600 / 1e6},
"gpt-4o": {"input": 2.50 / 1e6, "output": 10.00 / 1e6},
"gpt-4-turbo": {"input": 10.00 / 1e6, "output": 30.00 / 1e6},
"gpt-4-turbo-preview": {"input": 10.00 / 1e6, "output": 30.00 / 1e6},
"gpt-4-0125-preview": {"input": 10.00 / 1e6, "output": 30.00 / 1e6},
"gpt-4-1106-preview": {"input": 10.00 / 1e6, "output": 30.00 / 1e6},
"gpt-4": {"input": 30.00 / 1e6, "output": 60.00 / 1e6},
"gpt-4-32k": {"input": 60.00 / 1e6, "output": 120.00 / 1e6},
"gpt-3.5-turbo-1106": {"input": 1.00 / 1e6, "output": 2.00 / 1e6},
"gpt-3.5-turbo": {"input": 0.50 / 1e6, "output": 1.50 / 1e6},
"gpt-3.5-turbo-16k": {"input": 3.00 / 1e6, "output": 4.00 / 1e6},
"gpt-3.5-turbo-0125": {"input": 0.50 / 1e6, "output": 1.50 / 1e6},
"gpt-3.5-turbo-instruct": {"input": 1.50 / 1e6, "output": 2.00 / 1e6},
"o1": {"input": 15.00 / 1e6, "output": 60.00 / 1e6},
"o1-preview": {"input": 15.00 / 1e6, "output": 60.00 / 1e6},
"o1-2024-12-17": {"input": 15.00 / 1e6, "output": 60.00 / 1e6},
"o3-mini": {"input": 1.10 / 1e6, "output": 4.40 / 1e6},
"o3-mini-2025-01-31": {"input": 1.10 / 1e6, "output": 4.40 / 1e6},
"o4-mini": {"input": 1.10 / 1e6, "output": 4.40 / 1e6},
"gpt-4.1": {
"input": 2.00 / 1e6,
"output": 8.00 / 1e6,
},
"gpt-4.1-mini": {
"input": 0.4 / 1e6,
"output": 1.60 / 1e6,
},
"gpt-4.1-nano": {
"input": 0.1 / 1e6,
"output": 0.4 / 1e6,
},
"gpt-4.5-preview": {
"input": 75.00 / 1e6,
"output": 150.00 / 1e6,
},
}
default_gpt_model = "gpt-4o"
retryable_exceptions = (
openai.RateLimitError,
openai.APIConnectionError,
openai.APITimeoutError,
openai.LengthFinishReasonError,
)
class GPTModel(DeepEvalBaseLLM):
def __init__(
self,
model: Optional[str] = None,
_openai_api_key: Optional[str] = None,
base_url: Optional[str] = None,
temperature: float = 0,
*args,
**kwargs,
):
model_name = None
if isinstance(model, str):
model_name = model
if model_name not in valid_gpt_models:
raise ValueError(
f"Invalid model. Available GPT models: {', '.join(model for model in valid_gpt_models)}"
)
elif model is None:
model_name = default_gpt_model
self._openai_api_key = _openai_api_key
self.base_url = base_url
# args and kwargs will be passed to the underlying model, in load_model function
if temperature < 0:
raise ValueError("Temperature must be >= 0.")
self.temperature = temperature
self.args = args
self.kwargs = kwargs
super().__init__(model_name)
###############################################
# Other generate functions
###############################################
@retry(
wait=wait_exponential_jitter(initial=1, exp_base=2, jitter=2, max=10),
retry=retry_if_exception_type(retryable_exceptions),
after=log_retry_error,
)
def generate(
self, prompt: str, schema: Optional[BaseModel] = None
) -> Tuple[Union[str, Dict], float]:
client = self.load_model(async_mode=False)
if schema:
if self.model_name in structured_outputs_models:
completion = client.beta.chat.completions.parse(
model=self.model_name,
messages=[
{"role": "user", "content": prompt},
],
response_format=schema,
temperature=self.temperature,
)
structured_output: BaseModel = completion.choices[
0
].message.parsed
cost = self.calculate_cost(
completion.usage.prompt_tokens,
completion.usage.completion_tokens,
)
return structured_output, cost
if self.model_name in json_mode_models:
completion = client.beta.chat.completions.parse(
model=self.model_name,
messages=[
{"role": "user", "content": prompt},
],
response_format={"type": "json_object"},
temperature=self.temperature,
)
json_output = trim_and_load_json(
completion.choices[0].message.content
)
cost = self.calculate_cost(
completion.usage.prompt_tokens,
completion.usage.completion_tokens,
)
return schema.model_validate(json_output), cost
completion = client.chat.completions.create(
model=self.model_name,
messages=[{"role": "user", "content": prompt}],
)
output = completion.choices[0].message.content
cost = self.calculate_cost(
completion.usage.prompt_tokens, completion.usage.completion_tokens
)
if schema:
json_output = trim_and_load_json(output)
return schema.model_validate(json_output), cost
else:
return output, cost
@retry(
wait=wait_exponential_jitter(initial=1, exp_base=2, jitter=2, max=10),
retry=retry_if_exception_type(retryable_exceptions),
after=log_retry_error,
)
async def a_generate(
self, prompt: str, schema: Optional[BaseModel] = None
) -> Tuple[Union[str, BaseModel], float]:
client = self.load_model(async_mode=True)
if schema:
if self.model_name in structured_outputs_models:
completion = await client.beta.chat.completions.parse(
model=self.model_name,
messages=[
{"role": "user", "content": prompt},
],
response_format=schema,
temperature=self.temperature,
)
structured_output: BaseModel = completion.choices[
0
].message.parsed
cost = self.calculate_cost(
completion.usage.prompt_tokens,
completion.usage.completion_tokens,
)
return structured_output, cost
if self.model_name in json_mode_models:
completion = await client.beta.chat.completions.parse(
model=self.model_name,
messages=[
{"role": "user", "content": prompt},
],
response_format={"type": "json_object"},
temperature=self.temperature,
)
json_output = trim_and_load_json(
completion.choices[0].message.content
)
cost = self.calculate_cost(
completion.usage.prompt_tokens,
completion.usage.completion_tokens,
)
return schema.model_validate(json_output), cost
completion = await client.chat.completions.create(
model=self.model_name,
messages=[{"role": "user", "content": prompt}],
)
output = completion.choices[0].message.content
cost = self.calculate_cost(
completion.usage.prompt_tokens, completion.usage.completion_tokens
)
if schema:
json_output = trim_and_load_json(output)
return schema.model_validate(json_output), cost
else:
return output, cost
###############################################
# Other generate functions
###############################################
@retry(
wait=wait_exponential_jitter(initial=1, exp_base=2, jitter=2, max=10),
retry=retry_if_exception_type(retryable_exceptions),
after=log_retry_error,
)
def generate_raw_response(
self,
prompt: str,
top_logprobs: int = 5,
) -> Tuple[ChatCompletion, float]:
# Generate completion
client = self.load_model(async_mode=False)
completion = client.chat.completions.create(
model=self.model_name,
messages=[{"role": "user", "content": prompt}],
temperature=self.temperature,
logprobs=True,
top_logprobs=top_logprobs,
)
# Cost calculation
input_tokens = completion.usage.prompt_tokens
output_tokens = completion.usage.completion_tokens
cost = self.calculate_cost(input_tokens, output_tokens)
return completion, cost
@retry(
wait=wait_exponential_jitter(initial=1, exp_base=2, jitter=2, max=10),
retry=retry_if_exception_type(retryable_exceptions),
after=log_retry_error,
)
async def a_generate_raw_response(
self,
prompt: str,
top_logprobs: int = 5,
) -> Tuple[ChatCompletion, float]:
# Generate completion
client = self.load_model(async_mode=True)
completion = await client.chat.completions.create(
model=self.model_name,
messages=[{"role": "user", "content": prompt}],
temperature=self.temperature,
logprobs=True,
top_logprobs=top_logprobs,
)
# Cost calculation
input_tokens = completion.usage.prompt_tokens
output_tokens = completion.usage.completion_tokens
cost = self.calculate_cost(input_tokens, output_tokens)
return completion, cost
@retry(
wait=wait_exponential_jitter(initial=1, exp_base=2, jitter=2, max=10),
retry=retry_if_exception_type(retryable_exceptions),
after=log_retry_error,
)
def generate_samples(
self, prompt: str, n: int, temperature: float
) -> Tuple[list[str], float]:
client = self.load_model(async_mode=False)
response = client.chat.completions.create(
model=self.model_name,
messages=[{"role": "user", "content": prompt}],
n=n,
temperature=temperature,
)
completions = [choice.message.content for choice in response.choices]
return completions
###############################################
# Utilities
###############################################
def calculate_cost(self, input_tokens: int, output_tokens: int) -> float:
pricing = model_pricing.get(self.model_name, model_pricing)
input_cost = input_tokens * pricing["input"]
output_cost = output_tokens * pricing["output"]
return input_cost + output_cost
###############################################
# Model
###############################################
def get_model_name(self):
return self.model_name
def load_model(self, async_mode: bool = False):
if not async_mode:
return OpenAI(api_key=self._openai_api_key)
return AsyncOpenAI(api_key=self._openai_api_key)