-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtext2sql.py
More file actions
357 lines (293 loc) · 11.7 KB
/
text2sql.py
File metadata and controls
357 lines (293 loc) · 11.7 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
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
import os
import io
from langchain_community.chat_models import ChatOllama
from langchain_community.utilities import SQLDatabase
from langchain_community.chat_models import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_community.llms import Replicate
from contextlib import redirect_stdout
# Chain to query with memory
from langchain.memory import ConversationBufferMemory
from langchain.memory import ConversationBufferWindowMemory #use sliding window memory to store the k latest
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_core.runnables import RunnableLambda
from langchain.agents import create_sql_agent
from langchain.agents.agent_types import AgentType
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from langchain_community.llms.openai import OpenAI
SQL_FAIL_MESSAGE = "SQL_ERROR"
def read_api_key(file_path):
'''read the api key from the file
:param file_path: the path of the file
'''
with open(file_path, 'r') as file:
return file.read().strip()
REPLICATE_API_TOKE = read_api_key('API_Key/REPLICATE_API_TOKEN.txt')
OPENAI_API_KEY = read_api_key('API_Key/OPENAI_API_KEY.txt')
os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKE
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
def model_select(model_name):
if model_name == "llama2_chat":
return ChatOllama(model="llama2:13b-chat")
elif model_name == "llama2_code":
return ChatOllama(model="codellama:7b-instruct")
elif model_name == "gpt4":
return ChatOpenAI(model='gpt-4-0613')
elif model_name == "gpt3":
return ChatOpenAI(model='gpt-3.5-turbo-1106')
else:
return ChatOpenAI(model='gpt-3.5-turbo-1106')
def init(model_name,db_name):
REPLICATE_API_TOKE = read_api_key('API_Key/REPLICATE_API_TOKEN.txt')
OPENAI_API_KEY = read_api_key('API_Key/OPENAI_API_KEY.txt')
os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKE
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
model = model_select(model_name)
# Replicate API
replicate_id = "meta/llama-2-13b-chat:f4e2de70d66816a838a89eeeb621910adffb0dd0baba3976c96980970978018d"
llama2_chat_replicate = Replicate(
model=replicate_id, model_kwargs={"temperature": 0.00, "max_length": 500, "top_p": 1}
)
# Database
db = SQLDatabase.from_uri(f"sqlite:///./{db_name}.db", sample_rows_in_table_info=0)
return model,db
def text2sql(model_name,db_name,question):
model,db = init(model_name,db_name)
# Using Closure desgin pattern to pass the db to the model
def get_schema(_):
return db.get_table_info()
template = """Based on the table schema below, write a SQLite query that would answer the user's question.Only output the SQL query:
{schema}
Question: {question}
SQL Query:"""
prompt = ChatPromptTemplate.from_template(template)
sql_response = (
RunnablePassthrough.assign(schema=get_schema)
| prompt
| model.bind(stop=["\nSQLResult:"])
| StrOutputParser()
)
return sql_response.invoke({"question": question})
def execute_sql(query,db_name):
db = SQLDatabase.from_uri(f"sqlite:///./{db_name}.db", sample_rows_in_table_info=0)
update_action_list = ['UPDATE','ADD','DELETE','DROP','MODIFY','INSERT']
try:
if any(item in query for item in update_action_list)==False:# no update actions
result = db.run(query)
if result:
return result
else:
return "No results found."
else: return 'Finished' #update actions return no result but "Finished"
except Exception as e:
error_message = str(e)
print(SQL_FAIL_MESSAGE,error_message)
return SQL_FAIL_MESSAGE
def sqlresult2text(model_name,db_name,question,sql_query,sql_result):
# Using Closure desgin pattern to pass the db to the model
model,db = init(model_name,db_name)
def get_schema(_):
return db.get_table_info()
## To natural language
template = """Based on the table schema below, question, sql query, and sql response, write a natural language response:
{schema}
Question: {question}
SQL Query: {query}
SQL Response: {response}"""
prompt_response = ChatPromptTemplate.from_template(template)
text_response = (
RunnablePassthrough.assign(schema=get_schema)
| prompt_response
| model
)
# execute the model
return text_response.invoke({"question": question,"query":sql_query,"response":sql_result})
def text2sql_end2end(model_name,db_name,question):
model,db = init(model_name,db_name)
# Prompts
#
def get_schema(_):
return db.get_table_info()
def run_query(query):
print("running query\n", query)
try:
result = db.run(query)
if result:
print("successfully run query")
return result
else:
return "No results found."
except Exception as e:
error_message = str(e)
print(SQL_FAIL_MESSAGE)
return SQL_FAIL_MESSAGE
template = """Based on the table schema below, write a SQLite query that would answer the user's question. Only output the SQL query:
{schema}
Question: {question}
SQL Query:"""
prompt = ChatPromptTemplate.from_template(template)
sql_response = (
RunnablePassthrough.assign(schema=get_schema)
| prompt
| model.bind(stop=["\nSQLResult:"])
| StrOutputParser()
)
## To natural language
template = """Based on the table schema below, question, sql query, and sql response, write a natural language response:
{schema}
Question: {question}
SQL Query: {query}
SQL Response: {response}"""
prompt_response = ChatPromptTemplate.from_template(template)
full_chain = (
RunnablePassthrough.assign(query=sql_response).assign(
schema=get_schema,
response=lambda x: run_query(x["query"]),
)
| prompt_response
| model
)
# execute the model
return full_chain.invoke({"question": question})
def sql_agent(question,db_name="Chinook"):
db=SQLDatabase.from_uri(f"sqlite:///./{db_name}.db")
toolkit = SQLDatabaseToolkit(db=db, llm=ChatOpenAI(model='gpt-3.5-turbo-1106',temperature=0))
agent_executor = create_sql_agent(
llm=ChatOpenAI(model='gpt-3.5-turbo-1106',temperature=0),
toolkit=toolkit,
verbose=True,
agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
)
buffer = io.StringIO()
# Redirect stdout to the buffer
with redirect_stdout(buffer):
agent_executor.run(question)
output = buffer.getvalue()
return output
def sql_explaination(model_name,db_name,question,sql_query,sql_result):
# Using Closure desgin pattern to pass the db to the model
model,db = init(model_name,db_name)
def get_schema(_):
return db.get_table_info()
## To natural language
template = """Based on the table schema below, question, sql query, and sql response, explain the sql query step by step:
{schema}
Question: {question}
SQL Query: {query}
SQL Response: {response}"""
prompt_response = ChatPromptTemplate.from_template(template)
text_response = (
RunnablePassthrough.assign(schema=get_schema)
| prompt_response
| model
)
# execute the model
return text_response.invoke({"question": question,"query":sql_query,"response":sql_result})
def text2sql_memory(memory,model_name,db_name,question):
model,db = init(model_name,db_name)
# Using Closure desgin pattern to pass the db to the model and response to memory
def save(input_output):
output = {"output": input_output.pop("output")}
memory.save_context(input_output, output)
return output["output"]
def get_schema(_):
return db.get_table_info()
template = """Based on the table schema below, write a SQLite query that would answer the user's question. Only output the SQL query:
{schema}
Question: {question}
SQL Query:"""
prompt = ChatPromptTemplate.from_template(template)
sql_response = (
RunnablePassthrough.assign(schema=get_schema,
history=RunnableLambda(lambda x: memory.load_memory_variables(x)["history"]))
| prompt
| model.bind(stop=["\nSQLResult:"])
| StrOutputParser()
)
sql_response_memory = RunnablePassthrough.assign(output=sql_response) | save
return sql_response_memory.invoke({"question": question})
def execute_sql_memory(query,db_name,memory):
db = SQLDatabase.from_uri(f"sqlite:///./{db_name}.db", sample_rows_in_table_info=0)
try:
result = db.run(query)
if result:
output = f"sql result is: {result}"
memory.chat_memory.add_ai_message(output)
return result
else:
return "No results found."
except Exception as e:
error_message = str(e)
print(SQL_FAIL_MESSAGE,error_message)
return SQL_FAIL_MESSAGE
def freechat_memory(memory,model_name,user_input):
model = model_select(model_name)
template = """Your name is EduSmartQuery Bot. You are a chatbot mentor which is good at sql and willing to educate others. You are chatting with a student who is learning sql.
Previous conversation:
{history}
New human question: {question}
Response:"""
prompt = PromptTemplate.from_template(template)
# Notice that we need to align the `memory_key`
conversation = LLMChain(
llm=model,
prompt=prompt,
verbose=False,
memory=memory
)
return conversation({"question": user_input})['text']
def sql_agent_memory(memory,question,db_name="Chinook"):
db=SQLDatabase.from_uri(f"sqlite:///./{db_name}.db")
toolkit = SQLDatabaseToolkit(db=db, llm=ChatOpenAI(model='gpt-3.5-turbo-1106',temperature=0))
agent_executor = create_sql_agent(
llm=ChatOpenAI(model='gpt-3.5-turbo-1106',temperature=0),
toolkit=toolkit,
verbose=True,
agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
memory=memory
)
buffer = io.StringIO()
# Redirect stdout to the buffer
with redirect_stdout(buffer):
agent_executor.run(question)
output = buffer.getvalue()
return output
'''
examples
'''
question = "What are the top 3 best-selling artists from the database?"
#example of using the model
# example 1: auto agent
# print(sql_agent(question))
# example 2: end 2 end
# print(text2sql_end2end("gpt3","Chinook",question))
# example 3: step by step
# sql= text2sql("gpt3","Chinook",question)
# print('sql:',sql)
# result = execute_sql(sql,"Chinook")
# print('result:',result)
# text = sqlresult2text("gpt3","Chinook",question,sql,result)
# print(text)
# explain=sql_explaination("llama2_chat","Chinook",question,sql,result)
# print(explain)
# example 4: step by step usage using memory
# memory = ConversationBufferMemory(return_messages=True) # reset memory
# while True:
# question = input("Enter your question:>> ")
# if question == "exit":
# break
# elif question.startswith("@"):
# question=question[1:]
# sqlfromtext = text2sql_memory(memory, "gpt3", "Chinook", question)
# print("AI response:", sqlfromtext)
# sql_result = execute_sql_memory(sqlfromtext, "Chinook", memory)
# print("SQL result:", sql_result)
# result_description = sqlresult2text("gpt3", "Chinook", question, sqlfromtext, sql_result)
# print("AI response:", result_description)
# elif question.startswith("#"):
# print("AI response:",sql_agent(question))
# else:
# print("AI response:",freechat_memory(memory,"gpt3",question))