File size: 2,285 Bytes
57c5bcb
c3cd834
5b0a6ee
1d3466d
 
 
 
 
 
 
 
 
 
 
 
 
c3cd834
54385f0
 
37ac5ae
5b0a6ee
 
 
74fa8e5
 
485a5d1
74fa8e5
 
0195449
1d3466d
 
 
8f02c87
1d3466d
74fa8e5
b118f5f
37ac5ae
74fa8e5
37ac5ae
96e098a
8f02c87
 
 
 
49bb563
96e098a
5b0a6ee
57c5bcb
96e098a
 
8f02c87
49bb563
96e098a
a608f56
49bb563
96e098a
8f02c87
 
 
 
49bb563
96e098a
5b0a6ee
1d3466d
 
 
 
 
 
 
 
 
 
8f02c87
1d3466d
 
 
 
 
 
 
 
8f02c87
1d3466d
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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()