Phaneendrabayi commited on
Commit
8e2ca88
Β·
verified Β·
1 Parent(s): f905d0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -91
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 langchain.memory.chat_message_histories import SQLChatMessageHistory
8
- from langchain_core.output_parsers import StrOutputParser
9
 
10
- # Configure Gemini API
11
- GEMINI_API_KEY = "AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo"
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
- conn = sqlite3.connect("chat_history.db")
18
- c = conn.cursor()
19
- c.execute("""
20
- CREATE TABLE IF NOT EXISTS chat_history (
 
21
  id INTEGER PRIMARY KEY AUTOINCREMENT,
22
- user_id TEXT,
23
- message TEXT,
24
- response TEXT
25
  )
26
  """)
27
  conn.commit()
28
  conn.close()
29
 
30
- init_db()
31
-
32
- # Retrieve past chat history
33
- def get_chat_history(user_id):
34
- conn = sqlite3.connect("chat_history.db")
35
- c = conn.cursor()
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
- # Save chat history
42
- def save_chat(user_id, message, response):
43
- conn = sqlite3.connect("chat_history.db")
44
- c = conn.cursor()
45
- c.execute("INSERT INTO chat_history (user_id, message, response) VALUES (?, ?, ?)", (user_id, message, response))
46
- conn.commit()
47
  conn.close()
 
48
 
49
- # Delete specific message
50
- def delete_message(message_id):
51
- conn = sqlite3.connect("chat_history.db")
52
- c = conn.cursor()
53
- c.execute("DELETE FROM chat_history WHERE id = ?", (message_id,))
54
  conn.commit()
55
  conn.close()
56
 
57
- # Delete all chat history
58
- def delete_chat_history(user_id):
59
- conn = sqlite3.connect("chat_history.db")
60
- c = conn.cursor()
61
- c.execute("DELETE FROM chat_history WHERE user_id = ?", (user_id,))
62
  conn.commit()
63
  conn.close()
64
 
65
- # Streamlit UI Setup
66
- st.set_page_config(page_title="Gemini AI Chatbot", layout="wide")
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
- # Retrieve chat history
75
- chat_history = get_chat_history(st.session_state.user_id)
 
 
 
 
76
 
77
- # Chat Interface Layout
78
- col1, col2 = st.columns([3, 1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- with col1:
81
- st.write("Ask me anything!")
82
- user_input = st.text_input("Enter your query:", key="user_input")
83
 
84
- if st.button("πŸš€ Send") and user_input:
85
- response = model.invoke([
86
- SystemMessage(content="You are a helpful AI agent."),
87
- HumanMessage(content=user_input)
88
- ]).content.strip()
89
-
90
- parsed_response = output_parser.parse(response)
91
- save_chat(st.session_state.user_id, user_input, parsed_response)
92
- chat_history = get_chat_history(st.session_state.user_id)
 
 
 
 
 
 
 
 
93
  st.experimental_rerun()
94
 
95
- # Display Chat History with Delete Option
96
- st.subheader("Chat")
97
- chat_container = st.container()
98
- for chat_id, message, response in chat_history:
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()