import os
import tkinter as tk
import tkinter.ttk as ttk
from langchain.sql_database import SQLDatabase
from langchain.llms.openai import OpenAI
from langchain import SQLDatabaseChain
from langchain.prompts.prompt import PromptTemplate
from langchain.chains import SQLDatabaseSequentialChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
#Define llm variables
os.environ[‘OPENAI_API_KEY’] = “Your API Key”
llm = ChatOpenAI(model_name=“gpt-4”, model=“gpt-4”, temperature=0)
#Connect to my local database
db = SQLDatabase.from_uri(“mysql://login:Password@127.0.0.1/DB_Name”)
#Prompt template
_DEFAULT_TEMPLATE = “”" Let’s think step by step.
Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.
Use the following format:
Question: “Question here”
SQLQuery: “SQL Query to run”
SQLResult: “Result of the SQLQuery”
Answer: “Final answer here”
Only use the following tables:
{table_info}
Question: {input}“”"
PROMPT = PromptTemplate(
input_variables=[“input”, “table_info”, “dialect”], template=_DEFAULT_TEMPLATE
)
#Create the chain with the database and the prompt
db_chain = SQLDatabaseSequentialChain.from_llm(llm, db, verbose=True)
Create the UI window
root = tk.Tk()
root.title(“Chat with your Tabular Data”)
Create the text entry widget
entry = ttk.Entry(root, font=(“Arial”, 14))
entry.pack(padx=20, pady=20, fill=tk.X)
Create the button callback
def on_click():
# Get the query text from the entry widget
query = entry.get()
# Run the query using the agent executor
print(db_chain.sql_chain)
result = db_chain.run(query)
# Display the result in the text widget
text.delete("1.0", tk.END)
text.insert(tk.END, result)
Create the button widget
button = ttk.Button(root, text=“Chat”, command= on_click)
button.pack(padx=20, pady=20)
Create the text widget to display the result
text = tk.Text(root, height=10, width=60, font=(“Arial”, 14))
text.pack(padx=20, pady=20)
Start the UI event loop
root.mainloop()