Professional Documents
Culture Documents
Snowchat - Leveraging OpenAI's GPT For SQL Queries
Snowchat - Leveraging OpenAI's GPT For SQL Queries
By kaarthik Andavar
Do you struggle with complex SQL queries? Are you lost in a sea of tables while trying to locate a single piece of data?
Fear not, for I have created snowChat to solve these problems!
❄️ Ready to leap right in? Check out the app and the full code.
snowChat is a powerful and user-friendly application that enables users to interact with their Snowflake DataBase using
snowChat leverages OpenAI's GPT model to convert natural language into SQL queries, making it ideal for users who
may not have a firm grasp of SQL syntax. And it has a transformative impact on data interaction by expediting and
streamlining data-driven decision-making.
Get the Data Definition Language (DDL) for all tables from snowflake.account_usage.tables :
OPENAI_API_KEY=
#snowflake
ACCOUNT=
USER_NAME=
PASSWORD=
ROLE=
DATABASE=
SCHEMA=
WAREHOUSE=
SUPABASE_URL=
SUPABASE_SERVICE_KEY=
Store the schema files for each table in the docs/ folder.
Create an account with Supabase, set up a free database, and configure environment variables for the
.streamlit folder in secrets.toml (remember to include your Snowflake credentials).
[streamlit]
SUPABASE_URL = "<https://yourapp.supabase.co>"
SUPABASE_KEY = "yourkey"
[snowflake]
SNOWFLAKE_ACCOUNT = "youraccount"
SNOWFLAKE_USER = "youruser"
SNOWFLAKE_PASSWORD = "yourpassword"
SNOWFLAKE_DATABASE = "yourdatabase"
SNOWFLAKE_SCHEMA = "yourschema"
SNOWFLAKE_WAREHOUSE = "yourwarehouse"
Run the Supabase scripts found under supabase/scripts.sql in the Supabase SQL editor to activate the
'documents.'
| id | vector | contents |
|----|----------|------------------|
| 1 | [1,2,3] | This is document |
| 2 | [4,5,6] | This is another |
| 3 | [7,8,9] | This is a third |
•••
The core of snowChat is the "chain" function, which manages OpenAI's GPT model, the embedding model, the vector
The chain function takes user input, applies a prompt template to format it, and then passes the formatted response to
def get_chain(vectorstore):
"""
Get a chain for chatting with a vector database.
"""
q_llm = OpenAI(
temperature=0,
openai_api_key=st.secrets["OPENAI_API_KEY"],
model_name="gpt-3.5-turbo-16k",
)
llm = ChatOpenAI(
temperature=0,
openai_api_key=st.secrets["OPENAI_API_KEY"],
model_name="gpt-3.5-turbo",
)
Your get_chain function is now ready to use. Simply run chain = get_chain(SupabaseVectorStore) and start
your fun with chain({"question": "Did you understand the chain?", "chat_history": chat_history}) .
After creating the chain, use this code to destructure the response from the answer key:
response = result['answer']
The response variable contains both SQL and an explanation. A helper function called get_sql extracts only the
SQL code from the response. Once the SQL is obtained, it's sent to Snowflake (Snowpark) to fetch the data and create a
DataFrame object.
1. The model generates the SQL correctly: Display the output directly in Streamlit.
2. The model generates the SQL incorrectly: Send it back to the GPT model along with the error message and the SQL
it generated (self-healing). This way, the model can correct its mistake and return the corrected response.
•••
The input will be designed using the st.chat_input() container from Streamlit's chat element:
if prompt := st.chat_input():
st.session_state.messages.append({"role": "user", "content": prompt})
A helper function called message_func takes care of the styling for each message, including avatars on the side.
Following the steps outlined, you should have a fully functional chat app ready!
if prompt := st.chat_input():
st.session_state.messages.append({"role": "user", "content": prompt})
Let's bring snowChat to the world! To get started, head to Community Cloud, click "Create a new app," select your
GitHub repo, and deploy. Don't forget to add the necessary secrets to the settings.
Wrapping up
That's a wrap, folks! In this post, we've discussed building snowChat, an intuitive tool that leverages the power of
OpenAI's GPT to convert natural language into SQL queries. By breaking down the intimidating walls of SQL syntax,
snowChat fosters swift and effective data-driven decisions, even for those not well-versed in SQL.
I hope snowChat will increase your productivity and impress you with its cool functionalities (see what we did there? 😜 ).
If you have any questions or doubts, please post them in the comments below or contact me on GitHub, LinkedIn, or
Twitter.
Comments
1 reply
justinmulli 29 Sep
Cool! This reminds me of https://www.blazesql.com, although that’s a more full-service AI Data Analytics tool, from which you can then add the graphs to
dashboards etc. Love that you managed to pull it all together in streamlit though!
Continue Discussion
Last name
Email*
You may unsubscribe from Streamlit communications at anytime. Check out our Privacy Policy.
protected by reCAPTCHA
Privacy - Terms
Submit