-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy patheval_utils.py
368 lines (329 loc) · 12.2 KB
/
eval_utils.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
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
import requests
import msgpack
import os.path as osp
import os
import re
import json
import openai
from tenacity import (
retry,
stop_after_attempt,
stop_never,
wait_random_exponential,
) # for exponential backoff
from api_call_util import decoder_for_openai, decoder_for_local_completion, decoder_for_local_chat, set_proxy, unset_proxy
import apikeys
API_KEY = apikeys.apikey_list[0]
seed_data_dir = './data/seed_data/'
def get_character_names():
return [
'Caesar',
'Spartacus',
'Voldemort',
'Newton',
'Socrates',
'Beethoven',
'Cleopatra',
'Hermione',
'Martin'
]
def read_profile(path):
with open(path, 'r', encoding='utf-8') as fp:
text = fp.read().strip()
parts = text.split('\n\n')
assert parts[0].startswith('# '), parts[0]
agent_name = parts[0].replace('#', '').strip()
agent_profile = []
for p in parts[1:]:
agent_profile.append(p.strip())
return agent_name, agent_profile
def read_gen_data(path):
with open(path, 'r', encoding='utf-8') as fp:
raw = fp.read().split('}{\n')
data = []
for s in raw:
s = s.strip()
if not s.startswith('{'):
s = '{' + s
if not s.endswith('}'):
s = s + '}'
ex = json.loads(s)
data.append(ex)
return data
def read_json(path):
with open(path, 'rb') as fp:
return json.load(fp)
def read_jsonl(path):
results = []
with open(path, 'rb') as fp:
for line in fp:
if line.strip():
results.append(json.loads(line))
return results
def get_output(res):
out = res['message']['content']
if res['finish_reason'] != 'stop':
out += '<|NONSTOP|>'
return out
class Character:
def __init__(self, seed_data_dir, name, location=None, status=None) -> None:
self.seed_data_dir = seed_data_dir,
self.character_short_name = name
self.model_name = 'pjeval'
self.location = location
self.status = status
self.backend = 'sft'
with open(osp.join(seed_data_dir, 'prompts', 'agent_meta_prompt_sft.txt'), 'r', encoding='utf-8') as fp:
self.meta_instruction = fp.read().strip()
self.character_name, _ = read_profile(osp.join(seed_data_dir, 'profiles', f'wiki_{name}.txt'))
self.dialogue_history = []
def set_scene(self, location, status):
self.location = location.strip()
self.status = status.strip()
def start_conversation(self):
self.dialogue_history.clear()
def add_dialogue_history(self, dialogue):
self.dialogue_history.extend(dialogue)
def get_prompt(self):
prompt = self.meta_instruction.format(
character=self.character_name, loc_time=self.location, status=self.status
)
prompt += '\n\n'
text = ''
for d in self.dialogue_history[-8:]:
role = d['role']
action = d['action']
content = d['content']
if role == self.character_short_name or action == '(speaking)':
text += f'{role} {action}: {content}<|eot|>\n'
text += f'{self.character_short_name} ('
return prompt + text
def post_process(self, text: str):
text = f'{self.character_short_name} (' + text
# print('output:', text)
sp_pos = text.find(f'(speaking):')
if sp_pos != -1:
pos = text.find('<|eot|>', sp_pos)
if pos != -1:
text = text[:pos]
dialogue = []
for line in text.split('<|eot|>'):
line = line.strip()
if not line:
continue
if ': ' not in line:
part = ''
content = line
else:
part = line.split(': ')[0]
content = '\n\n'.join(line.split(': ')[1:])
action = re.findall(r'\(.*?\)', part)[0]
role = part.replace(action, '').strip()
if len(role) == 0:
role = self.character_short_name
dialogue.append({
'role': role,
'action': action,
'content': content
})
# print('dialogue:', dialogue)
return dialogue
@retry(stop=stop_after_attempt(3))
def get_reply(self):
payload = {
'prompt': self.get_prompt(),
'max_new_tokens': 256,
'temperature': 0.2,
}
response = requests.post(self.url, data=msgpack.packb(payload))
# print(payload['prompt'])
# print(response.status_code)
dialogue = self.post_process(response.text)
return dialogue
class LocalCharacter(Character):
def __init__(self, model_name, seed_data_dir, name, location=None, status=None) -> None:
super().__init__(seed_data_dir, name, location, status)
self.model_name = model_name
@retry(stop=stop_after_attempt(3))
def get_reply(self):
max_length = 256
temperature = 0.2
unset_proxy()
response = openai.Completion.create(
api_key="EMPTY",
api_base="http://localhost:8000/v1",
model=self.model_name,
prompt=self.get_prompt(),
max_tokens=max_length,
temperature=temperature,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
n=1,
stop='<|eot|>',
)
# print(payload['prompt'])
def _get_output(res):
out = res['text']
if res['finish_reason'] != 'stop':
out += '<|NONSTOP|>'
return out
content = _get_output(response["choices"][0])
dialogue = self.post_process(content)
return dialogue
class PromptCharacter(Character):
def __init__(self, seed_data_dir, name, location=None, status=None) -> None:
self.seed_data_dir = seed_data_dir,
self.character_short_name = name
self.location = location
self.status = status
self.backend = 'chatgpt'
self.model_name = 'gpt-3.5-turbo'
with open(osp.join(seed_data_dir, 'prompts', 'agent_meta_prompt_chatgpt.txt'), 'r', encoding='utf-8') as fp:
self.meta_instruction = fp.read().strip()
self.character_name, _ = read_profile(osp.join(seed_data_dir, 'profiles', f'wiki_{name}.txt'))
self.dialogue_history = []
def get_prompt(self):
prompt = self.meta_instruction.format(
character=self.character_name, loc_time=self.location, status=self.status
)
prompt += '\n\n'
text = ''
for d in self.dialogue_history[-8:]:
role = d['role']
action = d['action']
content = d['content']
if role == self.character_short_name or action == '(speaking)':
text += f'{role} {action}: {content}\n\n'
text += f'{self.character_short_name} ('
return prompt + text
def post_process(self, text: str):
text = f'{self.character_short_name} ' + text
# print('output:', text)
sp_pos = text.find(f'(speaking):')
if sp_pos != -1:
pos = text.find('\n\n', sp_pos)
if pos != -1:
text = text[:pos]
dialogue = []
for line in text.split('\n\n'):
line = line.strip()
if not line:
continue
if ': ' not in line:
part = ''
content = line
else:
part = line.split(': ')[0]
content = '\n\n'.join(line.split(': ')[1:])
action = re.findall(r'\(.*?\)', part)
if len(action) == 0:
action = '(speaking)'
role = self.character_short_name
else:
action = action[0]
role = part.replace(action, '').strip()
if len(role) == 0:
role = self.character_short_name
dialogue.append({
'role': role,
'action': action,
'content': content
})
# print('dialogue:', dialogue)
return dialogue
@retry(stop=stop_after_attempt(3))
def get_reply(self):
max_length = 256
temperature = 0.2
prompt = self.get_prompt()
response = decoder_for_openai('gpt-3.5-turbo', prompt, max_length, temperature, apikey=API_KEY, stop='\n\n')
# print('[START]\n' + prompt + '\n[END]')
dialogue = self.post_process(response)
return dialogue
class PromptInterviewer(PromptCharacter):
def __init__(self, seed_data_dir, name, location=None, status=None) -> None:
self.seed_data_dir = seed_data_dir,
self.character_short_name = name
self.location = location
self.status = status
self.backend = 'chatgpt_interviewer'
self.role = 'Man'
with open(osp.join(seed_data_dir, 'prompts', 'agent_meta_prompt_interviewer_chatgpt.txt'), 'r', encoding='utf-8') as fp:
self.meta_instruction = fp.read().strip()
self.character_name, profiles = read_profile(osp.join(seed_data_dir, 'profiles', f'wiki_{name}.txt'))
self.dialogue_history = []
self.current_topic = None
self.current_profile = None
def set_topic_and_profile(self, topic: str, profile: str):
self.current_topic = topic
self.current_profile = profile
def get_prompt(self):
assert self.current_topic, self.current_topic
assert self.current_profile, self.current_profile
prompt = self.meta_instruction.format(
character=self.character_name, loc_time=self.location, status=self.status,
topic=self.current_topic, profile=self.current_profile,
)
prompt += '\n\n'
text = ''
for d in self.dialogue_history:
role = d['role']
action = d['action']
content = d['content']
if role == self.character_short_name or action == '(speaking)':
text += f'{role} {action}: {content}\n\n'
text += f'{self.role} (speaking):'
return prompt + text
def post_process(self, text: str):
# print('output:', text)
re.sub(r'\(.*?\)', '', text)
content = text.split('\n\n')[0]
dialogue = []
dialogue.append({
'role': self.role,
'action': '(speaking)',
'content': content.strip()
})
return dialogue
def get_reply(self):
max_length = 128
temperature = 0.2
prompt = self.get_prompt()
response = decoder_for_openai('gpt-3.5-turbo', prompt, max_length, temperature, apikey=API_KEY)
dialogue = self.post_process(response)
return dialogue
class PromptLocalCharacter(PromptCharacter):
def __init__(self, model_name, seed_data_dir, name, location=None, status=None) -> None:
super().__init__(seed_data_dir, name, location, status)
self.model_name = model_name
self.backend = model_name
def get_prompt(self):
prompt = self.meta_instruction.format(
character=self.character_name, loc_time=self.location, status=self.status
)
prompt += '\n\n'
text = ''
for d in self.dialogue_history[-8:]:
role = d['role']
action = d['action']
content = d['content']
if role == self.character_short_name or action == '(speaking)':
text += f'{role} {action}: {content}\n\n'
text += f'{self.character_short_name} (speaking): '
return prompt + text
def get_reply(self):
max_length = 256
temperature = 0.2
prompt = self.get_prompt()
response = decoder_for_local_chat(self.model_name, prompt, max_length, temperature)
# print('[START]\n' + prompt + '\n[END]')
# print(response)
# dialogue = self.post_process(response)
# print(dialogue)
dialogue = {
'role': self.character_short_name,
'action': '(speaking)',
'content': response,
}
return dialogue