Search

Wednesday 15 November 2023

Streamlit app to talk to relational data in Postgres Database with Graphs, Chart and Tabular functionality

Streamlit app for a SQL Query Chatbot that interacts with an OpenAI GPT-3.5 model

  11_streamlit_postgres_sql_generation_comments
1. Importing Libraries:
streamlit: A Python library for creating web applications with minimal effort.
openai: A library for interacting with the OpenAI GPT-3.5 model.
psycopg2: A PostgreSQL adapter for Python, used for connecting to a PostgreSQL database.
pandas: A data manipulation and analysis library.
matplotlib.pyplot: A library for creating static, animated, and interactive visualizations in Python.

2. Set OpenAI API Key:
openai.api_key: The API key for accessing the OpenAI GPT-3.5 model.

3. Database Connection:
Connects to a PostgreSQL database named "adventureworks" on a local server using the psycopg2 library.

4. Define Functions:

get_schema():
Fetches the schema of tables in the 'humanresources' schema of the PostgreSQL database.
get_query_from_ai(input_question, schema):
Sends a chat-based message to the OpenAI GPT-3.5 model, incorporating the schema.
Extracts and modifies the suggested SQL query from the OpenAI response.

execute_query(query):
Executes a SQL query using the PostgreSQL connection and returns the result.
Handles exceptions and returns error messages if there's an issue.

chatbot(input_question):
Integrates the above functions to provide a conversational interface.
Gets the schema, generates a SQL query using OpenAI, executes the query, and returns the result.

on_input_change():
Handles input changes, triggers the chatbot function, and updates the conversation history.

5. Streamlit App:
Set Title:

Sets the title of the Streamlit app to "SQL Query Chatbot."
Initialize Conversation History:

Initializes and maintains a conversation history in the session state.
Display Conversation History:

For each chat in the conversation history, displays the question and answer.
If the answer is a figure, it displays the chart. If it's a DataFrame, it displays the table.
Text Input Field:
Creates a text input field for the user to enter their SQL-related question.
Calls the on_input_change function on input change.

6. Run the Streamlit App:
The code ends with the Streamlit app running and waiting for user input.
This code combines Streamlit for the web interface, OpenAI GPT-3.5 for generating SQL queries based on user input, and PostgreSQL for executing those queries against a specific database schema. The app provides a conversational interface for users to interact with the SQL Query Chatbot.