Geministreamlit / app.py
ziyadsuper2017's picture
modification
8f02c87
import os
import streamlit as st
import google.generativeai as genai
import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('chat_history.db')
c = conn.cursor()
# Create table if it doesn't exist
c.execute('''
CREATE TABLE IF NOT EXISTS history (
role TEXT,
message TEXT
)
''')
# API key
api_key = "AIzaSyC70u1sN87IkoxOoIj4XCAPw97ae2LZwNM"
# Configure the API key
genai.configure(api_key=api_key)
# Create chatbot interface
st.title("Gemini API Chatbot")
# Get chat history from session state
chat_history = st.session_state.get("chat_history", [])
# Display previous messages
for message in chat_history:
role, text = message
st.markdown(f"**{role.title()}:** {text}")
# Get user input from text box
user_input = st.text_input("You")
# Check if user input is not empty
if user_input:
# Add user message to chat history
chat_history.append({"role": "user", "content": user_input})
# Display user message with markdown
st.markdown(f"**You:** {user_input}")
# Create model object
model = genai.GenerativeModel(model_name="gemini-pro")
# Get model response with generate_content method
with st.spinner("Thinking..."):
response = model.generate_content(chat_history)
# Get response text from response object
response_text = response.text
# Add response message to chat history
chat_history.append({"role": "assistant", "content": response_text})
# Display response message with markdown
st.markdown(f"**Gemini Bot:** {response_text}")
# Update session state with chat history
st.session_state["chat_history"] = chat_history
# Add a button to reset chat
if st.button("Reset Chat"):
st.session_state["chat_history"] = []
# Add a button to display chat history from database
if st.button("Display History"):
c.execute("SELECT * FROM history")
rows = c.fetchall()
for row in rows:
st.markdown(f"**{row[0].title()}:** {row[1]}")
# Add a button to clear chat history from database
if st.button("Clear History"):
c.execute("DELETE FROM history")
conn.commit()
# Save chat history to database
for message in chat_history:
c.execute("INSERT INTO history VALUES (?, ?)", (message["role"], message["content"]))
conn.commit()
# Close the connection
conn.close()