-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_maxim.py
More file actions
197 lines (168 loc) · 7.77 KB
/
Copy pathapi_maxim.py
File metadata and controls
197 lines (168 loc) · 7.77 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
# maxim classification
import os
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import openai
from datasets import load_dataset
import pandas as pd
import pickle
import pdb
from all_prompts import *
from load_all_data import *
# GPT-4o
openai.api_key='fill-here'
# Claude-3-5-Sonnet
import anthropic
client = anthropic.Anthropic(
api_key="fill-here",
)
def main():
# load dataset
data_dict = get_data("nectar", "train", op_name="", prompt=maxim_prompt_final)
print("Now running gpt-4o..")
gpt4_model_name = "gpt-4o-2024-08-06"
# iterating through gpt-4o
save_dict = {"No.": [], "Dialog": []}
save_pickle = {}
for maxim in ["Quantity-1", "Quantity-2", "Quality", "Relevance-1", "Relevance-2", "Manner-1", "Manner-2", "Benevolence-1", "Benevolence-2", "Transparency-1", "Transparency-2", "Transparency-3"]:
save_dict[maxim] = []
conv_ind = 0
acc = []
token_count = {"ip": 0, "op": 0}
for i in tqdm(range(len(data_dict["Number"]))):
model_input1 = data_dict["Input1"][i]
model_input2 = data_dict["Input2"][i]
dialog_ = data_dict["Dialog"][i]
try:
maxims_dict = {}
explanations = []
model_inputs = [model_input1, model_input2]
for ii, model_input in enumerate(model_inputs):
output_maxims = openai.chat.completions.create(
model=gpt4_model_name,
messages=model_input,
temperature=0.0,
n=1)
token_count["ip"] += output_maxims.usage.prompt_tokens
token_count["op"] += output_maxims.usage.completion_tokens
output_maxims = output_maxims.choices[0].message.content
ind1 = output_maxims.index("{")
ind2 = output_maxims.index("}")
maxims_dict_temp = eval(output_maxims[ind1:ind2+1])
assert maxims_dict_temp["Final Answer"] in ["1", "2", 1, 2]
assert "Explanation" in maxims_dict_temp
for maxim in ["Quantity-1", "Quantity-2", "Quality", "Relevance-1", "Relevance-2", "Manner-1", "Manner-2", "Benevolence-1", "Benevolence-2", "Transparency-1", "Transparency-2", "Transparency-3"]:
assert maxim in maxims_dict_temp
assert maxims_dict_temp[maxim].lower() in ["1", "2", "both", "neither", 1, 2]
maxims_dict[ii] = maxims_dict_temp
maxim_pred_1 = maxims_dict[0]
maxim_pred_2_swapped = maxims_dict[1] # the naming convention here is different than the others
maxim_pred_2 = {}
for maxim in maxim_pred_2_swapped:
if maxim=="Explanation":
maxim_pred_2["Explanation"] = "SWAPPED!!!! " + maxim_pred_2_swapped["Explanation"]
continue
tmp =maxim_pred_2_swapped[maxim]
if tmp in ["both", "neither"]:
tmp1 = tmp
elif tmp == "1":
tmp1 = "2"
elif tmp == "2":
tmp1 = "1"
maxim_pred_2[maxim] = tmp1
dialog_key = dialog_#"\n".join(dialog_).lstrip().rstrip()
save_pickle[dialog_key] = {}
save_pickle[dialog_key]["maxim_pred_1"] = maxim_pred_1
save_pickle[dialog_key]["maxim_pred_2"] = maxim_pred_2
# pdb.set_trace()
if maxim_pred_1["Final Answer"]=="1" and maxim_pred_2["Final Answer"]=="1":
acc.append(1)
else:
acc.append(0)
if conv_ind%10==0:
print(token_count)
print(len(acc), "--", np.mean(acc)*100, "%")
pickle.dump(save_pickle, open("outputs_final/nectar-train-ge4_" + gpt4_model_name + "_maxims_with_result_100k.pkl", "wb"))
conv_ind += 1
except Exception as e:
print(e)
chosen_1 = "api call failed"
rejected_1 = "api call failed"
print("api call failed")
print(token_count)
print(print(len(acc), "--", np.mean(acc)*100, "%"))
pickle.dump(save_pickle, open("outputs_final/nectar-train-ge4_" + gpt4_model_name + "_maxims_with_result_100k.pkl", "wb"))
print("Now running claude..")
claude_model_name = "claude-3-5-sonnet-20241022"
save_dict = {"No.": [], "Dialog": []}
save_pickle = {}
for maxim in ["Quantity-1", "Quantity-2", "Quality", "Relevance-1", "Relevance-2", "Manner-1", "Manner-2", "Benevolence-1", "Benevolence-2", "Transparency-1", "Transparency-2", "Transparency-3"]:
save_dict[maxim] = []
conv_ind = 0
acc = []
for i in tqdm(range(len(data_dict["Number"]))):
model_input1 = data_dict["Input1"][i]
model_input2 = data_dict["Input2"][i]
dialog_ = data_dict["Dialog"][i]
try:
maxims_dict = {}
explanations = []
model_inputs = [model_input1, model_input2]
for ii, model_input in enumerate(model_inputs):
system_prompt = "You are a helpful assistant."
user_content = model_input[1]["content"]
input_message = {"role": "user", "content": [{"type": "text", "text": user_content}]}
message = client.messages.create(
model=claude_model_name,
max_tokens=4096,
temperature=0,
system=system_prompt,
messages=[input_message]
)
output_maxims = message.content[0].text
ind1 = output_maxims.index("{")
ind2 = output_maxims.index("}")
maxims_dict_temp = eval(output_maxims[ind1:ind2+1])
assert maxims_dict_temp["Final Answer"] in ["1", "2", 1, 2]#, "both"]
assert "Explanation" in maxims_dict_temp
for maxim in ["Quantity-1", "Quantity-2", "Quality", "Relevance-1", "Relevance-2", "Manner-1", "Manner-2", "Benevolence-1", "Benevolence-2", "Transparency-1", "Transparency-2", "Transparency-3"]:
assert maxim in maxims_dict_temp
assert maxims_dict_temp[maxim].lower() in ["1", "2", "both", "neither", 1, 2]
maxims_dict[ii] = maxims_dict_temp
maxim_pred_1 = maxims_dict[0]
maxim_pred_2_swapped = maxims_dict[1]
maxim_pred_2 = {}
for maxim in maxim_pred_2_swapped:
if maxim=="Explanation":
maxim_pred_2["Explanation"] = "SWAPPED!!!! " + maxim_pred_2_swapped["Explanation"]
continue
tmp =maxim_pred_2_swapped[maxim]
if tmp in ["both", "neither"]:
tmp1 = tmp
elif tmp == "1":
tmp1 = "2"
elif tmp == "2":
tmp1 = "1"
maxim_pred_2[maxim] = tmp1
dialog_key = "\n".join(dialog_).lstrip().rstrip()
save_pickle[dialog_key] = {}
save_pickle[dialog_key]["maxim_pred_1"] = maxim_pred_1
save_pickle[dialog_key]["maxim_pred_2"] = maxim_pred_2
if maxim_pred_1["Final Answer"]=="1" and maxim_pred_2["Final Answer"]=="1":
acc.append(1)
else:
acc.append(0)
if conv_ind%100==0:
print(len(acc), "--", np.mean(acc)*100, "%")
conv_ind += 1
except Exception as e:
print(e)
chosen_1 = "api call failed"
rejected_1 = "api call failed"
print("api call failed")
print(len(acc), "--", np.mean(acc)*100, "%")
pickle.dump(save_pickle, open("outputs_final/nectar-train-ge4_" + claude_model_name + "_maxims_with_result_full.pkl", "wb"))
if __name__=="__main__":
main()