Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,68 +1,39 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import sqlite3
|
| 3 |
-
|
| 4 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 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 |
-
chat_history = cursor.fetchall()
|
| 37 |
-
conn.close()
|
| 38 |
-
return chat_history
|
| 39 |
-
|
| 40 |
-
def delete_message(msg_id):
|
| 41 |
-
"""Delete a specific chat message by ID."""
|
| 42 |
-
conn = sqlite3.connect(DB_PATH)
|
| 43 |
-
cursor = conn.cursor()
|
| 44 |
-
cursor.execute("DELETE FROM chat WHERE id = ?", (msg_id,))
|
| 45 |
-
conn.commit()
|
| 46 |
-
conn.close()
|
| 47 |
-
|
| 48 |
-
def clear_chat_history():
|
| 49 |
-
"""Delete all chat messages from the database."""
|
| 50 |
-
conn = sqlite3.connect(DB_PATH)
|
| 51 |
-
cursor = conn.cursor()
|
| 52 |
-
cursor.execute("DELETE FROM chat")
|
| 53 |
-
conn.commit()
|
| 54 |
-
conn.close()
|
| 55 |
-
|
| 56 |
-
# Initialize memory
|
| 57 |
-
memory = ConversationBufferMemory()
|
| 58 |
-
|
| 59 |
-
# Initialize Gemini AI Model (Replace with actual API key)
|
| 60 |
-
chat_model = ChatGoogleGenerativeAI(
|
| 61 |
-
model="gemini-1.5-pro",
|
| 62 |
-
temperature=0.7,
|
| 63 |
-
google_api_key="AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo"
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
def conversational_tutor(user_input):
|
| 67 |
"""Function to interact with the conversational AI tutor."""
|
| 68 |
memory.save_context({"human": user_input}, {"ai": "Processing..."}) # Temporary response
|
|
@@ -79,58 +50,60 @@ def conversational_tutor(user_input):
|
|
| 79 |
User: {user_input}
|
| 80 |
"""
|
| 81 |
|
|
|
|
| 82 |
response = chat_model.invoke(prompt)
|
| 83 |
|
| 84 |
# Extract content properly
|
| 85 |
if isinstance(response, dict):
|
| 86 |
response_text = response.get("content", "I'm sorry, I couldn't generate a response.")
|
| 87 |
-
elif hasattr(response, 'content'):
|
| 88 |
response_text = response.content
|
| 89 |
else:
|
| 90 |
-
response_text = str(response)
|
| 91 |
-
|
| 92 |
-
# Store cleaned response in memory
|
| 93 |
-
memory.save_context({"human": user_input}, {"ai": response_text})
|
| 94 |
-
|
| 95 |
-
# Store in database
|
| 96 |
-
add_message("user", user_input)
|
| 97 |
-
add_message("assistant", response_text)
|
| 98 |
-
|
| 99 |
return response_text
|
| 100 |
|
| 101 |
# Streamlit UI
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
init_db() # Initialize the database
|
| 109 |
-
|
| 110 |
-
if "messages" not in st.session_state:
|
| 111 |
-
st.session_state["messages"] = get_chat_history() # Load history from DB
|
| 112 |
-
|
| 113 |
-
# Display chat history
|
| 114 |
-
for msg_id, role, content in st.session_state["messages"]:
|
| 115 |
-
with st.chat_message(role):
|
| 116 |
-
st.write(content)
|
| 117 |
-
if role == "user":
|
| 118 |
-
if st.button(f"🗑️ Delete", key=f"del_{msg_id}"):
|
| 119 |
-
delete_message(msg_id)
|
| 120 |
-
st.session_state["messages"] = get_chat_history()
|
| 121 |
-
st.experimental_rerun() # Refresh chat UI
|
| 122 |
-
|
| 123 |
-
user_input = st.chat_input("Type your question here...")
|
| 124 |
if user_input:
|
| 125 |
response = conversational_tutor(user_input)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import uuid
|
| 3 |
import sqlite3
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 6 |
+
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
| 7 |
+
from langchain.memory import ConversationBufferMemory
|
| 8 |
+
from langchain.memory.chat_message_histories import SQLChatMessageHistory
|
| 9 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 10 |
+
|
| 11 |
+
# Set up the Gemini API key
|
| 12 |
+
GEMINI_API_KEY = "AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo"
|
| 13 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 14 |
+
|
| 15 |
+
# Initialize session state for unique user
|
| 16 |
+
if "user_id" not in st.session_state:
|
| 17 |
+
st.session_state["user_id"] = str(uuid.uuid4()) # Unique user session
|
| 18 |
+
|
| 19 |
+
# Set up SQLite database for chat history
|
| 20 |
+
conn = sqlite3.connect("chat_history.db")
|
| 21 |
+
cursor = conn.cursor()
|
| 22 |
+
cursor.execute("""
|
| 23 |
+
CREATE TABLE IF NOT EXISTS chat_history (
|
| 24 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 25 |
+
user_id TEXT,
|
| 26 |
+
message TEXT,
|
| 27 |
+
response TEXT
|
| 28 |
+
)
|
| 29 |
+
""")
|
| 30 |
+
conn.commit()
|
| 31 |
+
|
| 32 |
+
# Initialize conversation memory with SQLite chat history
|
| 33 |
+
chat_history = SQLChatMessageHistory(session_id=st.session_state["user_id"], connection_string="sqlite:///chat_history.db")
|
| 34 |
+
memory = ConversationBufferMemory(chat_memory=chat_history, return_messages=True)
|
| 35 |
+
|
| 36 |
+
# Function to handle chatbot conversation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def conversational_tutor(user_input):
|
| 38 |
"""Function to interact with the conversational AI tutor."""
|
| 39 |
memory.save_context({"human": user_input}, {"ai": "Processing..."}) # Temporary response
|
|
|
|
| 50 |
User: {user_input}
|
| 51 |
"""
|
| 52 |
|
| 53 |
+
chat_model = ChatGoogleGenerativeAI(model="gemini-pro")
|
| 54 |
response = chat_model.invoke(prompt)
|
| 55 |
|
| 56 |
# Extract content properly
|
| 57 |
if isinstance(response, dict):
|
| 58 |
response_text = response.get("content", "I'm sorry, I couldn't generate a response.")
|
| 59 |
+
elif hasattr(response, 'content'):
|
| 60 |
response_text = response.content
|
| 61 |
else:
|
| 62 |
+
response_text = str(response)
|
| 63 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
return response_text
|
| 65 |
|
| 66 |
# Streamlit UI
|
| 67 |
+
st.title("Data Science AI Tutor")
|
| 68 |
+
st.write("Ask me anything about Data Science!")
|
| 69 |
+
|
| 70 |
+
# Layout with two columns
|
| 71 |
+
col1, col2 = st.columns([1, 2])
|
| 72 |
+
|
| 73 |
+
with col1:
|
| 74 |
+
st.write("### Chat History")
|
| 75 |
+
cursor.execute("SELECT id, message FROM chat_history WHERE user_id = ?", (st.session_state["user_id"],))
|
| 76 |
+
rows = cursor.fetchall()
|
| 77 |
+
messages_to_delete = []
|
| 78 |
+
for row in rows:
|
| 79 |
+
msg_id, user_msg = row
|
| 80 |
+
if st.button(f"Delete {user_msg[:30]}...", key=f"delete_{msg_id}"):
|
| 81 |
+
messages_to_delete.append(msg_id)
|
| 82 |
+
|
| 83 |
+
# Delete selected messages
|
| 84 |
+
for msg_id in messages_to_delete:
|
| 85 |
+
cursor.execute("DELETE FROM chat_history WHERE id = ?", (msg_id,))
|
| 86 |
+
conn.commit()
|
| 87 |
+
|
| 88 |
+
with col2:
|
| 89 |
+
st.write("### Chatbot")
|
| 90 |
+
user_input = st.text_input("Enter your question:")
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
if user_input:
|
| 93 |
response = conversational_tutor(user_input)
|
| 94 |
+
|
| 95 |
+
# Display response
|
| 96 |
+
st.write(response)
|
| 97 |
+
|
| 98 |
+
# Store conversation in database
|
| 99 |
+
cursor.execute("INSERT INTO chat_history (user_id, message, response) VALUES (?, ?, ?)", (st.session_state["user_id"], user_input, response))
|
| 100 |
+
conn.commit()
|
| 101 |
+
|
| 102 |
+
# Store bot response in memory
|
| 103 |
+
memory.save_context({}, {"output": response})
|
| 104 |
+
|
| 105 |
+
# Button to clear entire chat history
|
| 106 |
+
if st.button("Clear Chat History"):
|
| 107 |
+
cursor.execute("DELETE FROM chat_history WHERE user_id = ?", (st.session_state["user_id"],))
|
| 108 |
+
conn.commit()
|
| 109 |
+
memory.clear()
|