-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperiment.py
332 lines (277 loc) · 11.7 KB
/
experiment.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
import time
from typing import List, Dict
from pydantic import BaseModel
from requests import HTTPError
from bigquery import (
fetch_current_progress,
fetch_current_seller_progress,
save_single_experiment_result_to_bigquery,
save_single_seller_experiment_result_to_bigquery,
)
from llm_utils import CognitiveModel, OpenAILanguageModel, OpenRouterProxyLanguageModel
def run_llm_experiment(
price_tags: List[str],
characters: Dict,
iterations: int,
llm_model: CognitiveModel,
prompts: Dict,
experiment_id: str,
project_id: str,
dataset_name: str,
table_name: str,
debug: bool = False,
):
"""
This function runs an experiment using the OpenRouter API.
It will retry even if a 504 HTTP error is encountered from the model.
"""
# Initialize the language model
llm = OpenRouterProxyLanguageModel(model_id=llm_model)
# Fetch current progress from the database
current_progress = fetch_current_progress(
experiment_id=experiment_id,
model_id=llm_model.value,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
)
# Loop over the price tags and character IDs
for price_tag in price_tags:
for character_id in characters.keys():
price_tag_int = int(price_tag.replace("$", "").replace(",", ""))
# Determine the last completed iteration for this character and price tag
last_completed_iteration = current_progress.get(
(character_id, price_tag_int), -1
)
if debug:
print(
f"Last completed iteration for character {character_id} and price tag {price_tag}: {last_completed_iteration}"
)
# If no progress was found, start from 0; otherwise, continue from the next iteration.
start_iteration = (
0 if last_completed_iteration == -1 else last_completed_iteration + 1
)
# Continue data collection from the last completed iteration or start anew if none found
for iteration in range(start_iteration, iterations):
character_desc = characters[character_id]
prompt = f"{prompts['default']} {character_desc} {prompts['experiment'].format(price_tag=price_tag)}"
response = None
while response is None:
try:
# Generate response (assuming llm.ask() is a method to get responses)
response = llm.ask(prompt)
except HTTPError as e:
if e.response.status_code == 504:
# Log the error and retry
if debug:
print(
f"HTTP 504 Error encountered. Retrying: {character_id}, {price_tag}, {iteration}"
)
time.sleep(5) # Wait a bit before retrying
else:
# If it's not a 504 error, raise the exception
raise
if debug:
print(
f"Debug: {character_id}, {price_tag}, {iteration}, {response}"
)
answer = response.strip()
llm_response = 1 if "yes" in answer.lower() else 0
# Save results
save_single_experiment_result_to_bigquery(
character_id=character_id,
price_tag=price_tag,
iteration_number=iteration,
llm_response=llm_response,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
experiment_id=experiment_id,
model_id=llm_model.value,
)
time.sleep(5) # Sleep between iterations
def run_llm_seller_experiment(
price_tags: List[str],
iterations: int,
llm_model: CognitiveModel,
prompts: Dict,
experiment_id: str,
project_id: str,
dataset_name: str,
table_name: str,
debug: bool = False,
):
"""
This function runs an experiment using the OpenAI API.
"""
# Initialize the language model
llm = OpenRouterProxyLanguageModel(model_id=llm_model)
# Fetch current progress from the database
current_progress = fetch_current_seller_progress(
experiment_id=experiment_id,
model_id=llm_model.value,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
)
# Loop over the price tags and character IDs
for price_tag in price_tags:
price_tag_int = int(price_tag.replace("$", "").replace(",", ""))
# Determine the last completed iteration for this character and price tag
last_completed_iteration = current_progress.get((price_tag_int), -1)
if debug:
print(
f"Last completed iteration for price tag {price_tag}: {last_completed_iteration}"
)
# If no progress was found, start from 0; otherwise, continue from the next iteration.
start_iteration = (
0 if last_completed_iteration == -1 else last_completed_iteration + 1
)
# Continue data collection from the last completed iteration or start anew if none found
for iteration in range(start_iteration, iterations):
prompt = f"{prompts['default']} {prompts['experiment'].format(price_tag=price_tag)}"
# Generate response (assuming llm.ask() is a method to get responses)
# TODO: use functions for opensource models
response = llm.ask(prompt)
if debug:
print(f"Debug: {price_tag}, {iteration}, {response}")
answer = response.strip()
llm_response = 1 if "yes" in answer.lower() else 0
# Save results
save_single_seller_experiment_result_to_bigquery(
price_tag=price_tag,
iteration_number=iteration,
llm_response=llm_response,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
experiment_id=experiment_id,
model_id=llm_model.value,
)
time.sleep(0.5) # Sleep between iterations
def run_openai_llm_experiment(
price_tags: List[str],
characters: Dict,
iterations: int,
llm_model: CognitiveModel,
prompts: Dict,
experiment_id: str,
project_id: str,
dataset_name: str,
table_name: str,
debug: bool = False,
):
"""
This function runs an experiment using the OpenAI API.
"""
# Initialize the language model
llm = OpenAILanguageModel(model_id=llm_model)
# Fetch current progress from the database
current_progress = fetch_current_progress(
experiment_id=experiment_id,
model_id=llm_model.value,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
)
class CharacterResponse(BaseModel):
would_buy: bool
# Loop over the price tags and character IDs
for price_tag in price_tags:
for character_id in characters.keys():
price_tag_int = int(price_tag.replace("$", "").replace(",", ""))
# Determine the last completed iteration for this character and price tag
last_completed_iteration = current_progress.get(
(character_id, price_tag_int), -1
)
if debug:
print(
f"Last completed iteration for character {character_id} and price tag {price_tag}: {last_completed_iteration}"
)
# If no progress was found, start from 0; otherwise, continue from the next iteration.
start_iteration = (
0 if last_completed_iteration == -1 else last_completed_iteration + 1
)
# Continue data collection from the last completed iteration or start anew if none found
for iteration in range(start_iteration, iterations):
character_desc = characters[character_id]
prompt = f"{prompts['default']} {character_desc} {prompts['experiment'].format(price_tag=price_tag)}"
# Generate response (assuming llm.ask() is a method to get responses)
response = llm.generate_structured_output(prompt, CharacterResponse)
if debug:
print(
f"Debug: {character_id}, {price_tag}, {iteration}, {response}"
)
llm_response = 1 if response.would_buy else 0
# Save results
save_single_experiment_result_to_bigquery(
character_id=character_id,
price_tag=price_tag,
iteration_number=iteration,
llm_response=llm_response,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
experiment_id=experiment_id,
model_id=llm_model.value,
)
time.sleep(0.5) # Sleep between iterations
def run_openai_llm_seller_experiment(
price_tags: List[str],
iterations: int,
llm_model: CognitiveModel,
prompts: Dict,
experiment_id: str,
project_id: str,
dataset_name: str,
table_name: str,
debug: bool = False,
):
"""
This function runs an experiment using the OpenAI API.
"""
# Initialize the language model
llm = OpenAILanguageModel(model_id=llm_model)
# Fetch current progress from the database
current_progress = fetch_current_seller_progress(
experiment_id=experiment_id,
model_id=llm_model.value,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
)
class CharacterResponse(BaseModel):
would_buy: bool
# Loop over the price tags and character IDs
for price_tag in price_tags:
price_tag_int = int(price_tag.replace("$", "").replace(",", ""))
# Determine the last completed iteration for this character and price tag
last_completed_iteration = current_progress.get((price_tag_int), -1)
if debug:
print(
f"Last completed iteration for price tag {price_tag}: {last_completed_iteration}"
)
# If no progress was found, start from 0; otherwise, continue from the next iteration.
start_iteration = (
0 if last_completed_iteration == -1 else last_completed_iteration + 1
)
# Continue data collection from the last completed iteration or start anew if none found
for iteration in range(start_iteration, iterations):
prompt = f"{prompts['default']} {prompts['experiment'].format(price_tag=price_tag)}"
# Generate response (assuming llm.ask() is a method to get responses)
response = llm.generate_structured_output(prompt, CharacterResponse)
if debug:
print(f"Debug: {price_tag}, {iteration}, {response}")
llm_response = 1 if response.would_buy else 0
# Save results
save_single_seller_experiment_result_to_bigquery(
price_tag=price_tag,
iteration_number=iteration,
llm_response=llm_response,
project_id=project_id,
dataset_name=dataset_name,
table_name=table_name,
experiment_id=experiment_id,
model_id=llm_model.value,
)
time.sleep(0.5) # Sleep between iterations