Spaces:
Sleeping
Sleeping
import streamlit as st | |
import openai | |
import pandas as pd | |
from sqlalchemy import create_engine | |
from langchain.chat_models import ChatOpenAI | |
from langchain.utilities.sql_database import SQLDatabase | |
from langchain.chains import SQLDatabaseChain | |
# Set OpenAI API Key | |
openai.api_key = "sk-O7esHSo2XAWm-GXUGXp7_P9l4qXrQMn0CIGzs34ojLT3BlbkFJeXGSSvywppRTAvyT0zZkmZLZsj5cg7XkAkBTh8ZxoA" | |
# Database connection | |
DATABASE_URL = "sqlite:///Sakila.db" # Replace with your DB path or connection string | |
engine = create_engine(DATABASE_URL) | |
# Set up LangChain components | |
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5) # OpenAI's Chat model for LLM | |
db = SQLDatabase(engine) # Connect LangChain to the database | |
sql_chain = SQLDatabaseChain.from_llm(llm, database=db) # Create the SQL chain | |
# Streamlit UI setup | |
st.title("SQL Data Chatbot with LangChain") | |
st.write("Ask questions about the data, and I will answer them with both a response and an SQL query.") | |
# Input field for the user question | |
user_question = st.text_input("Your question:") | |
# Process the question if provided | |
if user_question: | |
# Generate the SQL query and answer using the SQL chain | |
try: | |
# Execute the question through the SQL chain | |
response = sql_chain.run(user_question) | |
# Display the generated SQL query and answer | |
st.subheader("Generated SQL Query and Answer") | |
st.write(response) | |
# Execute the SQL query to get results | |
with engine.connect() as conn: | |
result_df = pd.read_sql_query(response.query, conn) | |
# Show query results if any | |
if not result_df.empty: | |
st.write("Query Results:") | |
st.write(result_df) | |
else: | |
st.write("No results found for this query.") | |
except Exception as e: | |
st.write(f"Error processing the query: {e}") | |