File size: 1,849 Bytes
089fc67
 
 
 
 
 
a8627c5
089fc67
 
 
 
 
 
 
 
 
 
 
a8627c5
089fc67
 
 
 
 
 
 
 
 
 
a8627c5
089fc67
a8627c5
 
089fc67
 
a8627c5
 
089fc67
 
 
a8627c5
089fc67
 
 
 
 
 
 
 
 
 
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
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}")