DnyaneshHF/TextToSQLGenerativeAI
0
1from dotenv import load_dotenv2 3load_dotenv() ## load all the environment variables4 5import streamlit as st6import os7import sqlite38 9import google.generativeai as genai10## Configure GenAI Key11 12genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))13 14## function to load Google Gemini Model and provide queries as response15 16def get_gemini_response(question, prompt):17 model = genai.GenerativeModel('gemini-pro') ## gemini-pro --> text, gemini-pro-vision --> images/videos18 response = model.generate_content([prompt[0], question])19 return response.text20 21## function to retrieve the query from the database22 23def read_sql_query(sql, db):24 conn = sqlite3.connect(db)25 cur = conn.cursor()26 cur.execute(sql)27 rows = cur.fetchall()28 conn.commit()29 conn.close()30 for row in rows:31 print(row)32 return rows33 34## define our prompt35prompt = [36 """37 You are an expert in converting English quetions to SQL query!38 The SQL database name is STUDENT and has the following columns - NAME, CLASS, 39 SECTION \n\nFor Example, \nExample 1- How many entries of record are present?,40 the SQL command will be something like this SELECT COUNT(*) FROM STUDENT ;41 \nExample 2 - Tell me all the students studying in DS class?,42 the SQL command will be something like this SELECT * FROM STUDENT WHERE CLASS='DS' ;43 also the sql code should not have ``` in the beginning or end and sql word in output44 """45]46 47st.set_page_config(page_title='I can Retrieve Any SQL query')48st.header('Gemini Pro App To Retrieve SQL Data')49 50question = st.text_input('Inpit', key='input')51 52submit = st.button('Ask the quetion')53 54## if submit is clicked55if submit:56 response = get_gemini_response(question, prompt)57 print("SQL query is ", response)58 response = read_sql_query(response, 'student.db')59 st.subheader('The response is:')60 for row in response:61 print(row)62 st.header(row)63 