Phaneendrabayi commited on
Commit
31956ab
·
verified ·
1 Parent(s): ca4f92d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -132
app.py CHANGED
@@ -1,150 +1,64 @@
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
- # Initialize session state for unique user
11
- if "user_id" not in st.session_state:
12
- st.session_state["user_id"] = str(uuid.uuid4()) # Unique user session
 
13
 
14
- # Set up SQLite database for chat history
15
- conn = sqlite3.connect("chat_history.db", check_same_thread=False)
16
- cursor = conn.cursor()
17
- cursor.execute("""
18
- CREATE TABLE IF NOT EXISTS chat_history (
19
- id INTEGER PRIMARY KEY AUTOINCREMENT,
20
- user_id TEXT,
21
- message TEXT,
22
- response TEXT
23
- )
24
- """)
25
- conn.commit()
26
 
27
- # Initialize conversation memory with SQLite chat history
28
- chat_history = SQLChatMessageHistory(session_id=st.session_state["user_id"], connection_string="sqlite:///chat_history.db")
29
- memory = ConversationBufferMemory(chat_memory=chat_history, return_messages=True)
30
 
31
- # Function to handle chatbot conversation
32
- def conversational_tutor(user_input):
33
- """Function to interact with the conversational AI tutor."""
34
- memory.save_context({"human": user_input}, {"ai": "Processing..."}) # Temporary response
35
-
36
- conversation_history = memory.load_memory_variables({})
37
-
38
- prompt = f"""
39
- You are a data science tutor. Answer ONLY data science-related questions.
40
- If the user asks something unrelated, politely decline.
41
- Keep the conversation aware using memory.
42
-
43
- Conversation history: {conversation_history}
44
-
45
- User: {user_input}
46
- """
47
-
48
- chat_model = ChatGoogleGenerativeAI(model="gemini-1.5-pro", temperature=0.7, google_api_key="AIzaSyBItvysBggCo5T2iE61M209b24e36FmiBo")
49
- response = chat_model.invoke(prompt)
50
-
51
- # Extract content properly
52
- if isinstance(response, dict):
53
- response_text = response.get("content", "I'm sorry, I couldn't generate a response.")
54
- elif hasattr(response, 'content'):
55
- response_text = response.content
56
- else:
57
- response_text = str(response)
58
 
59
- return response_text
 
 
 
60
 
61
  # Streamlit UI
62
- st.set_page_config(page_title="Data Science AI Tutor", layout="wide")
63
- st.markdown("""
64
- <style>
65
- .chat-container {
66
- max-width: 700px;
67
- margin: auto;
68
- }
69
- .user-bubble {
70
- background-color: #DCF8C6;
71
- padding: 10px;
72
- border-radius: 10px;
73
- margin: 5px;
74
- text-align: right;
75
- max-width: 60%;
76
- float: right;
77
- clear: both;
78
- }
79
- .bot-bubble {
80
- background-color: #E6E6E6;
81
- padding: 10px;
82
- border-radius: 10px;
83
- margin: 5px;
84
- text-align: left;
85
- max-width: 60%;
86
- float: left;
87
- clear: both;
88
- }
89
- .chatbox {
90
- height: 500px;
91
- overflow-y: auto;
92
- padding: 10px;
93
- border: 1px solid #ccc;
94
- border-radius: 10px;
95
- background: #f9f9f9;
96
- }
97
- .input-container {
98
- position: fixed;
99
- bottom: 10px;
100
- width: 100%;
101
- text-align: center;
102
- background: white;
103
- padding: 10px;
104
- }
105
- </style>
106
- """, unsafe_allow_html=True)
107
-
108
- st.title("📱 Data Science AI Tutor - WhatsApp Style Chat")
109
- st.write("Ask me anything about Data Science!")
110
 
111
- # Layout with a single chat interface
112
- chat_container = st.container()
113
- st.markdown('<div class="chatbox">', unsafe_allow_html=True)
 
 
114
 
115
- # Display chat messages with delete option
116
- cursor.execute("SELECT id, message, response FROM chat_history WHERE user_id = ?", (st.session_state["user_id"],))
117
- chat_data = cursor.fetchall()
118
-
119
- delete_message_id = None
120
-
121
- for chat_id, user_msg, bot_response in chat_data:
122
- col1, col2 = st.columns([0.9, 0.1])
123
- with col1:
124
- st.markdown(f'<div class="user-bubble">{user_msg}</div>', unsafe_allow_html=True)
125
- st.markdown(f'<div class="bot-bubble">{bot_response}</div>', unsafe_allow_html=True)
126
- with col2:
127
- if st.button("❌", key=f"del_{chat_id}"):
128
- delete_message_id = chat_id
129
-
130
- st.markdown('</div>', unsafe_allow_html=True)
131
-
132
- # Delete selected message
133
- if delete_message_id:
134
- cursor.execute("DELETE FROM chat_history WHERE id = ?", (delete_message_id,))
135
- conn.commit()
136
-
137
- # Input field for new messages
138
- st.markdown('<div class="input-container">', unsafe_allow_html=True)
139
- user_input = st.text_input("Type your message...", placeholder="Ask me a data science question")
140
- st.markdown('</div>', unsafe_allow_html=True)
141
 
 
 
142
  if user_input:
143
- response = conversational_tutor(user_input)
144
-
145
- # Store conversation in database
146
- cursor.execute("INSERT INTO chat_history (user_id, message, response) VALUES (?, ?, ?)", (st.session_state["user_id"], user_input, response))
147
- conn.commit()
148
-
149
- # Store bot response in memory
150
- memory.save_context({"human": user_input}, {"ai": response})
 
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 import ConversationBufferMemory
6
  from langchain.memory.chat_message_histories import SQLChatMessageHistory
7
  from langchain_core.output_parsers import StrOutputParser
8
 
9
+ # Configure Gemini API
10
+ GEMINI_API_KEY = "AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo"
11
+ model = ChatGoogleGenerativeAI(model="gemini-2.0-pro-exp", google_api_key=GEMINI_API_KEY)
12
+ output_parser = StrOutputParser()
13
 
14
+ # Function to create a chat history store for each user
15
+ def get_history_store(user):
16
+ return SQLChatMessageHistory(connection_string="sqlite:///chat_history.db", session_id=user)
 
 
 
 
 
 
 
 
 
17
 
18
+ # Retrieve past chat history
19
+ def get_chat_history(history_store):
20
+ return history_store.messages
21
 
22
+ # Save chat history
23
+ def save_chat(history_store, message, response):
24
+ history_store.add_message(HumanMessage(content=message))
25
+ history_store.add_message(AIMessage(content=response))
26
+
27
+ # AI Agent function using LangChain
28
+ def chat_with_ai(user, message):
29
+ history_store = get_history_store(user)
30
+ history = get_chat_history(history_store)
31
+ memory = ConversationBufferMemory()
32
+ for msg in history:
33
+ memory.chat_memory.add_message(msg)
34
+ memory.chat_memory.add_message(HumanMessage(content=message))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ response = model.invoke([SystemMessage(content="You are a helpful AI agent.")] + memory.chat_memory.messages)
37
+ parsed_response = output_parser.parse(response.content.strip())
38
+ save_chat(history_store, message, parsed_response)
39
+ return parsed_response
40
 
41
  # Streamlit UI
42
+ st.title("Chat with AI (Gemini + LangChain)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # User session management
45
+ if "user" not in st.session_state:
46
+ st.session_state.user = str(uuid.uuid4())
47
+ if "messages" not in st.session_state:
48
+ st.session_state.messages = []
49
 
50
+ # Display chat history
51
+ history_store = get_history_store(st.session_state.user)
52
+ past_chats = get_chat_history(history_store)
53
+ for chat in past_chats:
54
+ if isinstance(chat, HumanMessage):
55
+ st.chat_message("user").write(chat.content)
56
+ elif isinstance(chat, AIMessage):
57
+ st.chat_message("assistant").write(chat.content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # Chat input
60
+ user_input = st.chat_input("Type your message...")
61
  if user_input:
62
+ st.chat_message("user").write(user_input)
63
+ ai_response = chat_with_ai(st.session_state.user, user_input)
64
+ st.chat_message("assistant").write(ai_response)