-
Notifications
You must be signed in to change notification settings - Fork 0
/
AgentS1.py
222 lines (156 loc) · 6.99 KB
/
AgentS1.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
from pathlib import Path
import random
import json
from openai import OpenAI
import dotenv
import rich
import json
import torch
import numpy as np
import argparse
dotenv.load_dotenv('.env')
class AgentS1():
def __init__(self, prompts, question_schema, price_bin='', log_dir='./example_files', log_name='s2ex.json', city='United States', model_dial='gpt-4o', model_trans='gpt-3.5-turbo', chat_temp=0.3):
if type(question_schema) == str and question_schema.endswith('.json'):
question_schema = json.load(open(question_schema))
if type(question_schema) == str:
question_schema = json.loads(question_schema)
self.question_schema = question_schema
self.schema = {'Question': json.loads(json.dumps(question_schema))}
self.temperature = chat_temp
# make log directory, recursively
path = Path(log_dir)
path.mkdir(parents=True, exist_ok=True)
self.log_path = Path(log_dir, log_name)
if type(prompts) == str and prompts.endswith('.json'):
prompts = json.load(open(prompts))
if type(prompts) == dict:
prompts = json.dumps(prompts)
if price_bin == '':
self.pbins = "Price: $0-$50, $51-$100, $101-$200, $201-$500, $501 and above"
else:
self.pbins = price_bin
if city != 'United States':
prompts = prompts.replace('United States', city)
prompts = prompts.replace('[PRICEBINS]', self.pbins)
self.prompts = json.loads(prompts)
self.client = OpenAI()
self.model_dial = model_dial
self.model_trans = model_trans
self.city = city
self.records = {}
self.records['schema'] = json.loads(json.dumps(self.schema))
self.records['city'] = city
def log(self):
# log self.records
json.dump(self.records, open(self.log_path, 'w'), indent=2)
#print(self.log_path)
def prompt(self, name):
return [i.copy() for i in self.prompts[name]]
def get_schema(self,):
return json.loads(json.dumps(self.schema))
def set_schema(self, schema):
if type(schema) == str and schema.endswith('.json'):
schema = json.load(open(schema))
if type(schema) == str:
schema = json.loads(schema)
self.schema = json.loads(json.dumps(schema))
self.records['schema'] = json.loads(json.dumps(self.schema))
def question_text(self, js_question, add_city=True):
question_prompt = self.prompt('eval_question_text')
if type(js_question) == dict:
js_question = json.dumps(js_question)
if add_city:
js_question = json.loads(js_question)
js_question['Condition'].append({'Name': 'City', 'Value': [self.city]})
js_question = json.dumps(js_question)
js_question = json.dumps(js_question)
question_prompt.append({'role': 'user', 'content': js_question})
response = self.client.chat.completions.create(
model=self.model_trans,
response_format={ "type": "text" },
temperature=0,
messages=question_prompt
)
ques = response.choices[0].message.content
return ques
def translate_var(self, prop_assist):
var_trans = self.prompt('var_trans')
#prop_assist += "Do not forget about variable " + self.pbins
var_trans.append({'role': 'user', 'content': prop_assist})
response = self.client.chat.completions.create(
model=self.model_trans,
response_format={ "type": "json_object" },
temperature=0,
messages=var_trans
)
assistant_message = response.choices[0].message.content
var_trans.append({'role': 'assistant', 'content': assistant_message})
return var_trans, assistant_message
def translate_query(self, ):
query_trans = self.prompt('query_trans')
schema = self.get_schema()
question_text = schema['Question']['Text']
schema['Question'].pop('Text')
question_js = json.dumps(schema['Question'])
schema.pop('Question')
var_schema = json.dumps(schema)
# replace city name in the question
question_text = question_text.replace(self.city, '')
new_message = "[Question] " + question_text + "\n\n"
new_message += '[Database] ' + var_schema
query_trans.append({'role': 'user', 'content': new_message})
response = self.client.chat.completions.create(
model=self.model_dial,
response_format={ "type": "json_object" },
temperature=0,
messages=query_trans
)
assistant_message = response.choices[0].message.content
query_trans.append({'role': 'assistant', 'content': assistant_message})
return query_trans, assistant_message
def get_variable(self, question):
prop = self.prompt('var_prop')
prop[-1]['content'] += "We would focus on question like: " + question
prop[-1]['content'] += " Therefore, make sure the variable values at least cover those in the question. "
#prop[-1]['content'] += "Propose 2~3 variables in your final summary. "
response = self.client.chat.completions.create(
model=self.model_dial,
response_format={ "type": "text" },
temperature=self.temperature,
messages=prop
)
# Get the assistant's response
assistant_message = response.choices[0].message.content
# Append the assistant's response to the message list
prop.append({"role": "assistant", "content": assistant_message})
print(assistant_message)
return prop.copy(), assistant_message
def compile(self, ):
self.log()
schema = self.get_schema()
if 'Text' not in schema['Question']:
#print("Question text not found. Translating...")
schema['Question']['Text'] = self.question_text(schema['Question'])
self.set_schema(schema)
schema = self.get_schema()
#print(schema['Question']['Text'])
#print("Getting variable proposal...")
var_mess, var_assist = self.get_variable(schema['Question']['Text'])
self.records['variable proposal'] = var_mess
#print("Translating the variables...")
js_mess, js_assist = self.translate_var(var_assist)
self.records['variable translation'] = js_mess
self.log()
var_schema = json.loads(js_assist)
schema['Variables'] = var_schema['Variables']
self.set_schema(schema)
schema = self.get_schema()
#print("Translating the query...")
query_mess, query_assist = self.translate_query()
self.records['query translation'] = query_mess
schema['Queries'] = json.loads(query_assist)['Queries']
self.set_schema(schema)
self.records['schema'] = schema
self.log()
return self.get_schema()