GowriHarikrishnan/Text2SQL_Basics
0
1import streamlit as st2import os3import sqlite34 5import google.generativeai as genai6 7##Configure our api key8# genai.configure(api_key = os.getenv("GOOGLE_API_KEY"))9genai.configure(api_key = st.secrets["GOOGLE_API_KEY"])10 11#Function to Load Gemini model and provide query as the response12def get_gemini_response(question, prompt):13 model = genai.GenerativeModel('gemini-pro')14 response = model.generate_content([prompt[0], question])15 return response.text16 17#Function to retrieve query from the SQL db18def read_sql_query(sql, db):19 conn = sqlite3.connect(db)20 cur = conn.cursor()21 cur.execute(sql)22 rows = cur.fetchall()23 conn.commit()24 conn.close()25 for row in rows:26 print(row)27 return rows28 29#Defining Prompt30prompt = [31 """32 You are an expert in converting English questions to SQL query!33 The SQL database has the name RETAIL and has the following columns - PR_ID, PR_SUB_CAT, 34 PR_CAT, DATE, SALES \n\nFor example,\nExample 1 - How many entries of records are present?, 35 the SQL command will be something like this SELECT COUNT(*) FROM RETAIL ;36 \nExample 2 - Tell me the number of products in VEGETABLES sub category?, 37 the SQL command will be something like this SELECT COUNT(DISTINCT PR_ID) FROM RETAIL 38 where PR_SUB_CAT="Vegetables"; 39 also the sql code should not have ``` in beginning or end and sql word in output40 41 """42]43 44#Create an streamlit app45st.set_page_config(page_title="Retrieve Any SQL query")46st.header("App To Retrieve SQL Data from Natural Language queries")47 48question=st.text_input("Input: ",key="input")49 50submit=st.button("Ask the question")51 52# if submit is clicked53if submit:54 response=get_gemini_response(question,prompt)55 print(response)56 response=read_sql_query(response,"retail.db")57 st.subheader("The Response is")58 for row in response:59 print(row)60 st.header(row)