Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import openai
|
3 |
+
import pandas as pd
|
4 |
+
from sqlalchemy import create_engine
|
5 |
+
from langchain.chat_models import ChatOpenAI
|
6 |
+
from langchain.utilities.sql_database import SQLDatabase
|
7 |
+
from langchain.tools.sql.toolkit import SQLDatabaseToolkit
|
8 |
+
|
9 |
+
# Set OpenAI API Key
|
10 |
+
openai.api_key = "sk-O7esHSo2XAWm-GXUGXp7_P9l4qXrQMn0CIGzs34ojLT3BlbkFJeXGSSvywppRTAvyT0zZkmZLZsj5cg7XkAkBTh8ZxoA"
|
11 |
+
|
12 |
+
# Database connection
|
13 |
+
DATABASE_URL = "sqlite:///Sakila.db" # Replace with your DB path or connection string
|
14 |
+
engine = create_engine(DATABASE_URL)
|
15 |
+
|
16 |
+
# Set up LangChain components
|
17 |
+
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5) # OpenAI's Chat model for LLM
|
18 |
+
db = SQLDatabase(engine) # Connect LangChain to the database
|
19 |
+
toolkit = SQLDatabaseToolkit(llm=llm, db=db) # Create the SQL toolkit
|
20 |
+
|
21 |
+
# Streamlit UI setup
|
22 |
+
st.title("SQL Data Chatbot with LangChain")
|
23 |
+
st.write("Ask questions about the data, and I will answer them with both a response and an SQL query.")
|
24 |
+
|
25 |
+
# Input field for the user question
|
26 |
+
user_question = st.text_input("Your question:")
|
27 |
+
|
28 |
+
# Process the question if provided
|
29 |
+
if user_question:
|
30 |
+
# Generate the SQL query and answer using the toolkit
|
31 |
+
try:
|
32 |
+
# Execute the question through the SQL toolkit
|
33 |
+
answer = toolkit.query(user_question)
|
34 |
+
|
35 |
+
# Display the generated SQL query and answer
|
36 |
+
st.subheader("Generated SQL Query")
|
37 |
+
st.code(answer.query, language="sql")
|
38 |
+
|
39 |
+
# Display the generated answer
|
40 |
+
st.subheader("Answer")
|
41 |
+
st.write(answer.result)
|
42 |
+
|
43 |
+
# Execute the SQL query to get results
|
44 |
+
with engine.connect() as conn:
|
45 |
+
result_df = pd.read_sql_query(answer.query, conn)
|
46 |
+
|
47 |
+
# Show query results if any
|
48 |
+
if not result_df.empty:
|
49 |
+
st.write("Query Results:")
|
50 |
+
st.write(result_df)
|
51 |
+
else:
|
52 |
+
st.write("No results found for this query.")
|
53 |
+
|
54 |
+
except Exception as e:
|
55 |
+
st.write(f"Error processing the query: {e}")
|