-
Notifications
You must be signed in to change notification settings - Fork 870
/
Copy pathChatGPT.py
176 lines (143 loc) · 5.42 KB
/
ChatGPT.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
import argparse
import copy
import json
import os
import re
import random
import time
import typing
import warnings
import tiktoken
from tqdm import tqdm
import openai
import nltk
from loguru import logger
from thefuzz import fuzz
from tenacity import Retrying, retry_if_not_exception_type, _utils
from tenacity.stop import stop_base
from tenacity.wait import wait_base
import sys
sys.path.append("..")
import logging
warnings.filterwarnings('ignore')
def get_exist_set(output_path):
with open(output_path, "r") as f:
all_data = f.readlines()
all_data = [json.loads(line) for line in all_data]
exist_id_set = [d['ID'] for d in all_data]
return set(exist_id_set)
def my_before_sleep(retry_state):
logger.debug(
f'Retrying: attempt {retry_state.attempt_number} ended with: {retry_state.outcome}, spend {retry_state.seconds_since_start} in total')
class my_wait_exponential(wait_base):
def __init__(
self,
multiplier: typing.Union[int, float] = 1,
max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa
exp_base: typing.Union[int, float] = 2,
min: _utils.time_unit_type = 0, # noqa
) -> None:
self.multiplier = multiplier
self.min = _utils.to_seconds(min)
self.max = _utils.to_seconds(max)
self.exp_base = exp_base
def __call__(self, retry_state: "RetryCallState") -> float:
if retry_state.outcome == openai.error.Timeout:
return 0
try:
exp = self.exp_base ** (retry_state.attempt_number - 1)
result = self.multiplier * exp
except OverflowError:
return self.max
return max(max(0, self.min), min(result, self.max))
class my_stop_after_attempt(stop_base):
"""Stop when the previous attempt >= max_attempt."""
def __init__(self, max_attempt_number: int) -> None:
self.max_attempt_number = max_attempt_number
def __call__(self, retry_state: "RetryCallState") -> bool:
if retry_state.outcome == openai.error.Timeout:
retry_state.attempt_number -= 1
return retry_state.attempt_number >= self.max_attempt_number
def annotate(prompt, logit_bias=None):
if logit_bias is None:
logit_bias = {}
request_timeout = 20
while True:
# with attempt:
try:
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo', messages=prompt, temperature=0, max_tokens=128,
logit_bias=logit_bias,
request_timeout=request_timeout,
)['choices'][0]['message']['content']
print(f"response={response}")
break
# except openai.error.RateLimitError as e:
# print("Retrying...", e)
# time.sleep(max(i + 1, 3))
# except openai.InvalidRequestError as e:
# print("Retrying...", e)
# break
except Exception as e:
print("Retrying...", e)
time.sleep(3)
request_timeout = min(300, request_timeout * 2)
return response
if __name__ == '__main__':
local_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser()
parser.add_argument('--api_key')
parser.add_argument('--input')
parser.add_argument('--output')
args = parser.parse_args()
openai.api_key = args.api_key
input = args.input
output = args.output
data_id2data = {}
with open(input, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
each_data = json.loads(line)
data_id2data[each_data['ID']] = each_data
# TODO: add dataset
if os.path.exists(output):
data_id_set = set(data_id2data.keys()) - get_exist_set(output)
mode = "a+"
else:
data_id_set = set(data_id2data.keys())
mode = "w"
with open(output, 'w') as w:
for data_id in tqdm(data_id_set, total=len(data_id_set)):
data = data_id2data[data_id]
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
logit_bias = {encoding.encode(option)[0]: 10 for option in ['A', 'B', 'C', 'D']}
if 'openbook' in input:
prompt_list = [{
'role': 'system',
'content': "You need to choose an answer to the question. You must only output A, B, C, or D."
}]
elif 'socialiqa' in input:
prompt_list = [{
'role': 'system',
'content': "You need to choose an answer to the question. You must only output A, B, or C."
}]
elif 'hellaswag' in input:
prompt_list = [{
'role': 'system',
'content': "You need to choose an answer to the question. You must only output A, B, C, or D."
}]
input = data['input']
prompt_list = []
prompt_list.append({
'role': 'user',
'content': input
})
ans = annotate(prompt_list, logit_bias).strip()
gen = {
"id": data['ID'],
"input": input,
"reference": data['ref'],
"generation": ans,
}
w.write(json.dumps(gen) + "\n")