Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,121 +1,136 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import uuid
|
| 3 |
import sqlite3
|
| 4 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 5 |
-
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
| 6 |
from langchain.memory import ConversationBufferMemory
|
| 7 |
-
from
|
| 8 |
-
from langchain_core.output_parsers import StrOutputParser
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
model = ChatGoogleGenerativeAI(model="gemini-2.0-pro-exp", google_api_key=GEMINI_API_KEY)
|
| 13 |
-
output_parser = StrOutputParser()
|
| 14 |
|
| 15 |
-
# Initialize Database
|
| 16 |
def init_db():
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
response TEXT
|
| 25 |
)
|
| 26 |
""")
|
| 27 |
conn.commit()
|
| 28 |
conn.close()
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
c.execute("SELECT id, message, response FROM chat_history WHERE user_id = ?", (user_id,))
|
| 37 |
-
data = c.fetchall()
|
| 38 |
conn.close()
|
| 39 |
-
return data
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
conn = sqlite3.connect(
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
conn.close()
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
conn = sqlite3.connect(
|
| 52 |
-
|
| 53 |
-
|
| 54 |
conn.commit()
|
| 55 |
conn.close()
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
conn = sqlite3.connect(
|
| 60 |
-
|
| 61 |
-
|
| 62 |
conn.commit()
|
| 63 |
conn.close()
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
-
st.title("π¬ Gemini AI Chat")
|
| 68 |
-
st.sidebar.header("Chat History")
|
| 69 |
-
|
| 70 |
-
# Initialize user session
|
| 71 |
-
if "user_id" not in st.session_state:
|
| 72 |
-
st.session_state.user_id = str(uuid.uuid4())
|
| 73 |
|
| 74 |
-
#
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
st.write("Ask me anything!")
|
| 82 |
-
user_input = st.text_input("Enter your query:", key="user_input")
|
| 83 |
|
| 84 |
-
if
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
st.experimental_rerun()
|
| 94 |
|
| 95 |
-
#
|
| 96 |
-
st.
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
with chat_container:
|
| 100 |
-
col1, col2 = st.columns([10, 1])
|
| 101 |
-
with col1:
|
| 102 |
-
st.markdown(f"""
|
| 103 |
-
<div style='border-radius: 15px; padding: 10px; background-color: #DCF8C6; max-width: 80%;'>
|
| 104 |
-
<b>You:</b> {message}
|
| 105 |
-
</div>
|
| 106 |
-
<div style='border-radius: 15px; padding: 10px; background-color: #EAEAEA; max-width: 80%;'>
|
| 107 |
-
<b>AI:</b> {response}
|
| 108 |
-
</div>
|
| 109 |
-
""", unsafe_allow_html=True)
|
| 110 |
-
with col2:
|
| 111 |
-
if st.button("β", key=f"del_{chat_id}"):
|
| 112 |
-
delete_message(chat_id)
|
| 113 |
-
st.experimental_rerun()
|
| 114 |
-
|
| 115 |
-
with col2:
|
| 116 |
-
# Clear Chat History Option
|
| 117 |
-
if st.sidebar.button("π Clear Chat History"):
|
| 118 |
-
delete_chat_history(st.session_state.user_id)
|
| 119 |
st.experimental_rerun()
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import sqlite3
|
|
|
|
|
|
|
| 3 |
from langchain.memory import ConversationBufferMemory
|
| 4 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
|
|
|
| 5 |
|
| 6 |
+
# Database Setup
|
| 7 |
+
DB_PATH = "chat_history.db"
|
|
|
|
|
|
|
| 8 |
|
|
|
|
| 9 |
def init_db():
|
| 10 |
+
"""Initialize database to store chat history."""
|
| 11 |
+
conn = sqlite3.connect(DB_PATH)
|
| 12 |
+
cursor = conn.cursor()
|
| 13 |
+
cursor.execute("""
|
| 14 |
+
CREATE TABLE IF NOT EXISTS chat (
|
| 15 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 16 |
+
role TEXT NOT NULL,
|
| 17 |
+
content TEXT NOT NULL
|
|
|
|
| 18 |
)
|
| 19 |
""")
|
| 20 |
conn.commit()
|
| 21 |
conn.close()
|
| 22 |
|
| 23 |
+
def add_message(role, content):
|
| 24 |
+
"""Insert chat message into database."""
|
| 25 |
+
conn = sqlite3.connect(DB_PATH)
|
| 26 |
+
cursor = conn.cursor()
|
| 27 |
+
cursor.execute("INSERT INTO chat (role, content) VALUES (?, ?)", (role, content))
|
| 28 |
+
conn.commit()
|
|
|
|
|
|
|
| 29 |
conn.close()
|
|
|
|
| 30 |
|
| 31 |
+
def get_chat_history():
|
| 32 |
+
"""Retrieve chat messages from database."""
|
| 33 |
+
conn = sqlite3.connect(DB_PATH)
|
| 34 |
+
cursor = conn.cursor()
|
| 35 |
+
cursor.execute("SELECT id, role, content FROM chat")
|
| 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="YOUR_GOOGLE_API_KEY"
|
| 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
|
| 69 |
+
|
| 70 |
+
conversation_history = memory.load_memory_variables({})
|
| 71 |
+
|
| 72 |
+
prompt = f"""
|
| 73 |
+
You are a data science tutor. Answer ONLY data science-related questions.
|
| 74 |
+
If the user asks something unrelated, politely decline.
|
| 75 |
+
Keep the conversation aware using memory.
|
| 76 |
+
|
| 77 |
+
Conversation history: {conversation_history}
|
| 78 |
+
|
| 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 |
+
def main():
|
| 103 |
+
st.image("181.jpg", use_container_width=True)
|
| 104 |
+
|
| 105 |
+
st.title("Conversational AI Data Science Tutor π€π")
|
| 106 |
+
st.write("Ask me anything about Data Science!")
|
| 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 |
+
st.session_state["messages"] = get_chat_history()
|
| 127 |
st.experimental_rerun()
|
| 128 |
|
| 129 |
+
# Clear Chat Button
|
| 130 |
+
if st.button("π§Ή Clear Chat History"):
|
| 131 |
+
clear_chat_history()
|
| 132 |
+
st.session_state["messages"] = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
st.experimental_rerun()
|
| 134 |
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
main()
|