forked from neulab/prompt2model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai_tools.py
221 lines (195 loc) · 8.18 KB
/
openai_tools.py
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
"""Tools for accessing OpenAI's API."""
from __future__ import annotations # noqa FI58
import asyncio
import json
import logging
import time
import aiolimiter
import openai
import openai.error
import tiktoken
from aiohttp import ClientSession
from litellm import acompletion, completion
from tqdm.asyncio import tqdm_asyncio
OPENAI_ERRORS = (
openai.error.APIError,
openai.error.Timeout,
openai.error.RateLimitError,
openai.error.ServiceUnavailableError,
openai.error.InvalidRequestError,
json.decoder.JSONDecodeError,
AssertionError,
)
ERROR_ERRORS_TO_MESSAGES = {
openai.error.InvalidRequestError: "OpenAI API Invalid Request: Prompt was filtered", # noqa E501
openai.error.RateLimitError: "OpenAI API rate limit exceeded. Sleeping for 10 seconds.", # noqa E501
openai.error.APIConnectionError: "OpenAI API Connection Error: Error Communicating with OpenAI", # noqa E501
openai.error.Timeout: "OpenAI APITimeout Error: OpenAI Timeout",
openai.error.ServiceUnavailableError: "OpenAI service unavailable error: {e}",
openai.error.APIError: "OpenAI API error: {e}",
}
class ChatGPTAgent:
"""A class for accessing OpenAI's ChatCompletion API."""
def __init__(self, api_key: str | None, model_name: str = "gpt-3.5-turbo"):
"""Initialize ChatGPTAgent with an API key.
Args:
api_key: A valid OpenAI API key. Alternatively, set as None and set
the environment variable with `export OPENAI_API_KEY=<your key>`.
model_name: Name fo the OpenAI model to use (by default, gpt-3.5-turbo).
"""
self.api_key = api_key
if self.api_key is None or self.api_key == "":
raise ValueError(
"API key must be provided or set the environment variable "
"with `export OPENAI_API_KEY=<your key>`."
)
self.model_name = model_name
def generate_one_openai_chat_completion(
self,
prompt: str,
temperature: float = 0,
presence_penalty: float = 0,
frequency_penalty: float = 0,
) -> openai.Completion:
"""Generate a chat completion using OpenAI's gpt-3.5-turbo.
Args:
prompt: A prompt asking for a response.
temperature: What sampling temperature to use, between 0 and 2. Higher
values like 0.8 will make the output more random, while lower values
like 0.2 will make it more focused and deterministic.
presence_penalty: Float between -2.0 and 2.0. Positive values penalize new
tokens based on whether they appear in the text so far, increasing the
model's likelihood to talk about new topics.
frequency_penalty: Float between -2.0 and 2.0. Positive values penalize new
tokens based on their existing frequency in the text so far, decreasing
the model's likelihood of repeating the same line verbatim.
Returns:
A response object.
"""
response = completion( # completion gets the key from os.getenv
model=self.model_name,
messages=[
{"role": "user", "content": f"{prompt}"},
],
temperature=temperature,
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty,
)
return response
async def generate_batch_openai_chat_completion(
self,
prompts: list[str],
temperature: float = 1,
responses_per_request: int = 5,
requests_per_minute: int = 80,
) -> list[openai.Completion]:
"""Generate a batch responses from OpenAI Chat Completion API.
Args:
prompts: List of prompts to generate from.
model_config: Model configuration.
temperature: Temperature to use.
responses_per_request: Number of responses for each request.
i.e. the parameter n of OpenAI API call.
requests_per_minute: Number of requests per minute to allow.
Returns:
List of generated responses.
"""
openai.aiosession.set(ClientSession())
limiter = aiolimiter.AsyncLimiter(requests_per_minute)
async def _throttled_openai_chat_completion_acreate(
model: str,
messages: list[dict[str, str]],
temperature: float,
max_tokens: int,
n: int,
top_p: float,
limiter: aiolimiter.AsyncLimiter,
):
async with limiter:
for _ in range(3):
try:
return await acompletion(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
n=n,
top_p=top_p,
)
except tuple(ERROR_ERRORS_TO_MESSAGES.keys()) as e:
if isinstance(
e,
(
openai.error.ServiceUnavailableError,
openai.error.APIError,
),
):
logging.warning(
ERROR_ERRORS_TO_MESSAGES[type(e)].format(e=e)
)
elif isinstance(e, openai.error.InvalidRequestError):
logging.warning(ERROR_ERRORS_TO_MESSAGES[type(e)])
return {
"choices": [
{
"message": {
"content": "Invalid Request: Prompt was filtered" # noqa E501
}
}
]
}
else:
logging.warning(ERROR_ERRORS_TO_MESSAGES[type(e)])
await asyncio.sleep(10)
return {"choices": [{"message": {"content": ""}}]}
async_responses = [
_throttled_openai_chat_completion_acreate(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": f"{prompt}"},
],
temperature=temperature,
max_tokens=500,
n=responses_per_request,
top_p=1,
limiter=limiter,
)
for prompt in prompts
]
responses = await tqdm_asyncio.gather(*async_responses)
# Note: will never be none because it's set, but mypy doesn't know that.
await openai.aiosession.get().close()
return responses
def handle_openai_error(e, api_call_counter):
"""Handle OpenAI errors or related errors that the OpenAI API may raise.
Args:
e: The error to handle. This could be an OpenAI error or a related
non-fatal error, such as JSONDecodeError or AssertionError.
api_call_counter: The number of API calls made so far.
Returns:
The api_call_counter (if no error was raised), else raise the error.
"""
logging.error(e)
if isinstance(
e,
(openai.error.APIError, openai.error.Timeout, openai.error.RateLimitError),
):
# For these errors, OpenAI recommends waiting before retrying.
time.sleep(1)
if isinstance(e, OPENAI_ERRORS):
# For these errors, we can increment a counter and retry the API call.
return api_call_counter
else:
# For all other errors, immediately throw an exception.
raise e
def count_tokens_from_string(string: str, encoding_name: str = "cl100k_base") -> int:
"""Handle count the tokens in a string with OpenAI's tokenizer.
Args:
string: The string to count.
encoding_name: The name of the tokenizer to use.
Returns:
The number of tokens in the string.
"""
encoding = tiktoken.get_encoding(encoding_name)
num_tokens = len(encoding.encode(string))
return num_tokens