Phaneendrabayi commited on
Commit
3167d6d
Β·
verified Β·
1 Parent(s): 51cefa5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -98
app.py CHANGED
@@ -1,104 +1,99 @@
1
  import streamlit as st
 
 
2
  import uuid
3
- from langchain_google_genai import ChatGoogleGenerativeAI
4
  from langchain.schema import SystemMessage, HumanMessage, AIMessage
5
- from langchain.memory.chat_message_histories import SQLChatMessageHistory
6
- from langchain_core.output_parsers import StrOutputParser
7
 
8
- # Configure Gemini API
9
- GEMINI_API_KEY = "AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo"
10
- model = ChatGoogleGenerativeAI(model="gemini-2.0-pro", google_api_key=GEMINI_API_KEY)
11
- output_parser = StrOutputParser()
12
-
13
- # Function to create a chat history store for each user
14
- def get_history_store(user):
15
- return SQLChatMessageHistory(connection_string="sqlite:///chat_history.db", session_id=user)
16
-
17
- # Retrieve past chat history
18
- def get_chat_history(history_store):
19
- return history_store.messages
20
-
21
- # Save chat history
22
- def save_chat(history_store, message, response):
23
- history_store.add_message(HumanMessage(content=message))
24
- history_store.add_message(AIMessage(content=response))
25
-
26
- # Delete specific message from chat history
27
- def delete_selected_message(user, message_content):
28
- history_store = get_history_store(user)
29
- new_messages = [msg for msg in history_store.messages if msg.content != message_content]
30
- history_store.clear()
31
- for msg in new_messages:
32
- history_store.add_message(msg)
33
-
34
- # Delete entire chat history
35
- def delete_chat_history(user):
36
- history_store = get_history_store(user)
37
- history_store.clear()
38
-
39
- # Conversational AI function (Only Answers Data Science Topics)
40
- def chat_with_ai(user, message):
41
- # Check if the question is related to Data Science
42
- topic_check_prompt = f"Does this question relate to Data Science? Respond with 'Yes' or 'No' only:\n\n{message}"
43
- topic_check_response = model.invoke([SystemMessage(content=topic_check_prompt)])
44
-
45
- if "yes" not in topic_check_response.content.lower():
46
- response = "Sorry, I don't know about that topic."
47
- else:
48
- # Proceed with normal chatbot response for Data Science queries
49
- history_store = get_history_store(user)
50
- history = get_chat_history(history_store)
51
-
52
- response = model.invoke([
53
- SystemMessage(content="You are a Data Science AI assistant. Answer only questions related to Data Science."),
54
- *history
55
- ])
56
-
57
- response = output_parser.parse(response.content.strip())
58
- save_chat(history_store, message, response)
59
-
60
- return response
61
 
62
  # Streamlit UI
63
- st.set_page_config(page_title="AI Data Science Chatbot", layout="wide")
64
-
65
- st.title("πŸ€– AI Chatbot (Data Science Only)")
66
-
67
- # User input for session
68
- user = st.text_input("Enter your username:", value="User1")
69
-
70
- # Retrieve chat history
71
- history_store = get_history_store(user)
72
- chat_history = get_chat_history(history_store)
73
-
74
- # Chat UI
75
- st.write("### Chat History")
76
- if chat_history:
77
- for msg in chat_history:
78
- if isinstance(msg, HumanMessage):
79
- st.text_area("πŸ§‘β€πŸ’¬ You:", value=msg.content, height=50, key=uuid.uuid4().hex)
80
- elif isinstance(msg, AIMessage):
81
- st.text_area("πŸ€– AI:", value=msg.content, height=50, key=uuid.uuid4().hex, disabled=True)
82
- else:
83
- st.write("No conversation yet. Start chatting below!")
84
-
85
- # User message input
86
- message = st.text_input("Type your message here:")
87
-
88
- # Chat interaction
89
- if st.button("Send Message"):
90
- if message:
91
- response = chat_with_ai(user, message)
92
- st.experimental_rerun()
93
-
94
- # Delete selected message
95
- if chat_history:
96
- delete_msg = st.selectbox("Select a message to delete:", [msg.content for msg in chat_history if isinstance(msg, HumanMessage)])
97
- if st.button("Delete Selected Message"):
98
- delete_selected_message(user, delete_msg)
99
- st.experimental_rerun()
100
-
101
- # Clear all chat history
102
- if st.button("Clear Chat History"):
103
- delete_chat_history(user)
104
- st.experimental_rerun()
 
1
  import streamlit as st
2
+ import google.generativeai as genai
3
+ import sqlite3
4
  import uuid
5
+ from langchain_community.chat_message_histories import SQLChatMessageHistory
6
  from langchain.schema import SystemMessage, HumanMessage, AIMessage
 
 
7
 
8
+ # Configure API Key
9
+ genai.configure(api_key="YOUR_GOOGLE_API_KEY")
10
+
11
+ # System Prompt
12
+ sys_prompt = """You are a helpful data science tutor. You can only resolve data science-related queries. \
13
+ If someone asks unrelated queries, politely ask them to stay on topic."""
14
+
15
+ # Load Model
16
+ model = genai.GenerativeModel(model_name='gemini-1.5-flash', system_instruction=sys_prompt)
17
+
18
+ # Initialize Database
19
+ def init_db():
20
+ conn = sqlite3.connect("chat_history.db")
21
+ c = conn.cursor()
22
+ c.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
+ conn.close()
32
+
33
+ # Save Chat History
34
+ def save_chat(user_id, message, response):
35
+ conn = sqlite3.connect("chat_history.db")
36
+ c = conn.cursor()
37
+ c.execute("INSERT INTO chat_history (user_id, message, response) VALUES (?, ?, ?)", (user_id, message, response))
38
+ conn.commit()
39
+ conn.close()
40
+
41
+ # Retrieve Chat History
42
+ def get_chat_history(user_id):
43
+ conn = sqlite3.connect("chat_history.db")
44
+ c = conn.cursor()
45
+ c.execute("SELECT id, message, response FROM chat_history WHERE user_id = ?", (user_id,))
46
+ data = c.fetchall()
47
+ conn.close()
48
+ return data
49
+
50
+ # Delete Selected Chat
51
+ def delete_chat(chat_id):
52
+ conn = sqlite3.connect("chat_history.db")
53
+ c = conn.cursor()
54
+ c.execute("DELETE FROM chat_history WHERE id = ?", (chat_id,))
55
+ conn.commit()
56
+ conn.close()
 
 
 
 
57
 
58
  # Streamlit UI
59
+ st.set_page_config(page_title="Data Science Tutor AI", layout="wide")
60
+ st.title("πŸ€– Data Science Tutor (AI)")
61
+ st.sidebar.header("Chat History")
62
+
63
+ # User Session
64
+ if "user_id" not in st.session_state:
65
+ st.session_state.user_id = str(uuid.uuid4())
66
+
67
+ # Layout with Chat Interface
68
+ col1, col2 = st.columns([3, 1])
69
+
70
+ with col1:
71
+ st.write("Ask me any data science-related question!")
72
+ user_prompt = st.text_input("Enter your query:", key="user_input")
73
+ if st.button("πŸš€ Send", key="send_button") and user_prompt:
74
+ response = model.generate_content(user_prompt).text
75
+ save_chat(st.session_state.user_id, user_prompt, response)
76
+ st.session_state.messages.append((user_prompt, response))
77
+
78
+ # Display Chat History in Chat Format
79
+ chat_history = get_chat_history(st.session_state.user_id)
80
+ st.subheader("Chat")
81
+ chat_container = st.container()
82
+ for chat in chat_history:
83
+ chat_id, message, response = chat
84
+ with chat_container:
85
+ st.markdown(f"<div style='border-radius: 10px; padding: 10px; background-color: #DCF8C6; margin: 5px;'><b>You:</b> {message}</div>", unsafe_allow_html=True)
86
+ st.markdown(f"<div style='border-radius: 10px; padding: 10px; background-color: #ECECEC; margin: 5px;'><b>AI:</b> {response}</div>", unsafe_allow_html=True)
87
+
88
+ with col2:
89
+ # Display Chat History in Sidebar with Delete Option
90
+ chat_history = get_chat_history(st.session_state.user_id)
91
+ for chat in chat_history:
92
+ chat_id, message, _ = chat
93
+ with st.sidebar.expander(message):
94
+ if st.button("πŸ—‘ Delete", key=f"delete_{chat_id}"):
95
+ delete_chat(chat_id)
96
+ st.experimental_rerun()
97
+
98
+ # Initialize Database
99
+ init_db()