Gowdham/Text-SQL-Bot
0
1import os2from dotenv import load_dotenv3load_dotenv()4 5import streamlit as st6import sqlite37import google.generativeai as genai8 9 10genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))11model = genai.GenerativeModel('gemini-pro')12chat = model.start_chat(history=[])13 14# Sending the question and getting response from gemini 15def get_response(question,prompt):16 response = chat.send_message([prompt,question])17 return response.text18 19# Initialize session state for chat history if it doesn't exist20if 'chat_history' not in st.session_state:21 st.session_state['chat_history'] = []22 23# To retreive query from db24def read_sql_query(sql_query,db):25 connect = sqlite3.connect(db)26 curs = connect.cursor()27 curs.execute(sql_query)28 rows = curs.fetchall()29 connect.commit()30 connect.close()31 for row in rows:32 print(row)33 return rows34 35# Defining the prompt36prompt=[37 """38 You are an expert in converting English questions to SQL query!39 The SQL database has the name STUDENT and has the following columns - NAME, CLASS, 40 SECTION \n\nFor example,\nExample 1 - How many entries of records are present?, 41 the SQL command will be something like this SELECT COUNT(*) FROM STUDENT ;42 \nExample 2 - Tell me all the students studying in Data Science class?, 43 the SQL command will be something like this SELECT * FROM STUDENT 44 where CLASS="Data Science"; 45 also the sql code should not have ``` in beginning or end and sql word in output46 """47]48 49# Streamlit50st.set_page_config(page_title='Text2SQL')51st.title('Text2SQL')52st.sidebar.title("Chat History")53st.header('Bot to Retrive SQL Data')54 55question = st.text_input("A",key='input_question',label_visibility='hidden')56submit = st.button('Retrieve SQL')57 58if submit:59 response = get_response(question,prompt[0])60 61 st.session_state['chat_history'].append(("You", question))62 63 st.subheader('Your SQL Query is ...')64 print(response)65 st.write(response)66 67 db_records = read_sql_query(response, "student.db")68 print(db_records)69 70 st.session_state['chat_history'].append(("Bot", db_records))71 72 st.subheader('The Records are ...')73 for row in db_records:74 print(row)75 st.write(row)76 77for role, text in st.session_state['chat_history']:78 # Limit display to a maximum of 100 words with an ellipsis for longer messages79 truncated_text = ''.join(str(item) for item in text[:30]) + ('...' if len(text) > 30 else '')80 st.sidebar.text(f"{role}: {truncated_text}")81 82 