Gowthamvemula commited on
Commit
e499b4e
·
verified ·
1 Parent(s): 83d0baf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -60
app.py CHANGED
@@ -7,6 +7,7 @@ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
7
  from langchain_core.output_parsers import StrOutputParser
8
  from langchain_community.chat_message_histories import SQLChatMessageHistory
9
  from langchain_core.runnables.history import RunnableWithMessageHistory
 
10
 
11
  # Load API key
12
  GOOGLE_API_KEY = st.secrets.get("GOOGLE_API_KEY")
@@ -22,19 +23,22 @@ CREATE TABLE IF NOT EXISTS chat (
22
  id INTEGER PRIMARY KEY AUTOINCREMENT,
23
  session_id TEXT,
24
  role TEXT,
25
- content TEXT
 
26
  )
27
  """)
28
  conn.commit()
29
 
30
  # Function to save messages
31
  def save_message(session_id, role, content):
32
- cursor.execute("INSERT INTO chat (session_id, role, content) VALUES (?, ?, ?)", (session_id, role, content))
 
33
  conn.commit()
34
 
35
  # Function to load chat history
36
  def load_chat_history(session_id):
37
- cursor.execute("SELECT role, content FROM chat WHERE session_id = ?", (session_id,))
 
38
  return cursor.fetchall()
39
 
40
  # Chat history instance
@@ -47,19 +51,89 @@ def chat_history(session_id):
47
  # Generate unique session ID
48
  if "session_id" not in st.session_state:
49
  st.session_state.session_id = str(uuid.uuid4())
50
- st.session_state.messages = []
51
 
52
- # Sidebar for session management
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  with st.sidebar:
54
- st.title("💬 AI Data Science Tutor")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if st.button("🆕 New Chat"):
56
  st.session_state.session_id = str(uuid.uuid4())
57
  st.session_state.messages = []
58
  st.rerun()
59
- st.write("### Chat Sessions")
60
- st.write("Session ID: ", st.session_state.session_id)
61
-
62
- # Get session ID
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  session_id = st.session_state.session_id
64
  chat_history_instance = chat_history(session_id)
65
 
@@ -68,6 +142,7 @@ chat_prompt = ChatPromptTemplate(
68
  messages=[
69
  ('system', """You are an AI assistant specialized in Data Science tutoring.
70
  You will only answer questions related to Data Science.
 
71
  If asked anything outside this topic, politely decline and request a Data Science-related question.
72
  """),
73
  MessagesPlaceholder(variable_name="history", optional=True),
@@ -75,13 +150,9 @@ chat_prompt = ChatPromptTemplate(
75
  ]
76
  )
77
 
78
- # Define output parser
79
  out_parser = StrOutputParser()
80
-
81
- # Create a chain
82
  chain = chat_prompt | llm | out_parser
83
-
84
- # Define Runnable with message history
85
  chat = RunnableWithMessageHistory(
86
  chain,
87
  lambda session: SQLChatMessageHistory(session, "sqlite:///chat_history.db"),
@@ -89,59 +160,53 @@ chat = RunnableWithMessageHistory(
89
  history_messages_key="history"
90
  )
91
 
92
- # Chat UI Styling
93
- st.markdown("""
94
- <style>
95
- .chat-container {
96
- max-width: 700px;
97
- margin: auto;
98
- padding: 20px;
99
- background-color: #FAFAFA;
100
- border-radius: 10px;
101
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
102
- }
103
- .chat-message {
104
- padding: 10px;
105
- margin: 5px 0;
106
- border-radius: 10px;
107
- font-size: 16px;
108
- }
109
- .user-message {
110
- background-color: #0078FF;
111
- color: white;
112
- text-align: right;
113
- }
114
- .assistant-message {
115
- background-color: #E0E0E0;
116
- }
117
- </style>
118
- """, unsafe_allow_html=True)
119
 
120
- # Load chat history
121
  if "messages" not in st.session_state:
122
  st.session_state.messages = load_chat_history(session_id)
123
- else:
124
- st.session_state.messages = [(role, content) for role, content in load_chat_history(session_id)]
125
 
126
- # Display Chat Messages
127
- st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
128
- for role, content in st.session_state.messages:
129
- role_class = "user-message" if role == "user" else "assistant-message"
130
- st.markdown(f"<div class='chat-message {role_class}'><b>{role.capitalize()}:</b> {content}</div>", unsafe_allow_html=True)
131
- st.markdown("</div>", unsafe_allow_html=True)
132
-
133
- # User Input Box
134
- user_input = st.text_area("Type your message here:", key="user_message", help="Ask a Data Science-related question")
135
-
136
- # Process User Input
137
- if user_input:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  save_message(session_id, "user", user_input)
139
- st.session_state.messages.append(("user", user_input))
140
 
141
  config = {'configurable': {'session_id': session_id}}
142
  response = chat.invoke({'prompt': user_input}, config)
143
 
144
  save_message(session_id, "assistant", response)
145
- st.session_state.messages.append(("assistant", response))
 
146
 
147
- st.rerun()
 
 
 
 
 
 
7
  from langchain_core.output_parsers import StrOutputParser
8
  from langchain_community.chat_message_histories import SQLChatMessageHistory
9
  from langchain_core.runnables.history import RunnableWithMessageHistory
10
+ import io
11
 
12
  # Load API key
13
  GOOGLE_API_KEY = st.secrets.get("GOOGLE_API_KEY")
 
23
  id INTEGER PRIMARY KEY AUTOINCREMENT,
24
  session_id TEXT,
25
  role TEXT,
26
+ content TEXT,
27
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
28
  )
29
  """)
30
  conn.commit()
31
 
32
  # Function to save messages
33
  def save_message(session_id, role, content):
34
+ cursor.execute("INSERT INTO chat (session_id, role, content) VALUES (?, ?, ?)",
35
+ (session_id, role, content))
36
  conn.commit()
37
 
38
  # Function to load chat history
39
  def load_chat_history(session_id):
40
+ cursor.execute("SELECT role, content, timestamp FROM chat WHERE session_id = ? ORDER BY timestamp",
41
+ (session_id,))
42
  return cursor.fetchall()
43
 
44
  # Chat history instance
 
51
  # Generate unique session ID
52
  if "session_id" not in st.session_state:
53
  st.session_state.session_id = str(uuid.uuid4())
 
54
 
55
+ # Custom CSS
56
+ st.markdown("""
57
+ <style>
58
+ .title-text {
59
+ text-align: center;
60
+ font-size: 32px;
61
+ font-weight: bold;
62
+ margin-bottom: 20px;
63
+ }
64
+ .stTextInput {
65
+ position: fixed;
66
+ bottom: 60px;
67
+ width: 70%;
68
+ left: 15%;
69
+ z-index: 999;
70
+ }
71
+ .code-block {
72
+ background-color: #f0f0f0;
73
+ padding: 10px;
74
+ border-radius: 5px;
75
+ font-family: monospace;
76
+ }
77
+ .timestamp {
78
+ font-size: 12px;
79
+ color: #666;
80
+ margin-top: 5px;
81
+ }
82
+ </style>
83
+ """, unsafe_allow_html=True)
84
+
85
+ # Sidebar for additional controls
86
  with st.sidebar:
87
+ st.title("Chat Controls")
88
+ theme = st.selectbox("Theme", ["Light", "Dark"])
89
+ if theme == "Dark":
90
+ st.markdown("""
91
+ <style>
92
+ .stApp {
93
+ background-color: #1E1E1E;
94
+ color: #FFFFFF;
95
+ }
96
+ .code-block {
97
+ background-color: #2D2D2D;
98
+ color: #FFFFFF;
99
+ }
100
+ </style>
101
+ """, unsafe_allow_html=True)
102
+
103
  if st.button("🆕 New Chat"):
104
  st.session_state.session_id = str(uuid.uuid4())
105
  st.session_state.messages = []
106
  st.rerun()
107
+
108
+ # Export chat feature
109
+ if st.button("📥 Export Chat"):
110
+ chat_data = load_chat_history(st.session_state.session_id)
111
+ export_text = "\n\n".join([f"{row[0].upper()}[{row[2]}]: {row[1]}"
112
+ for row in chat_data])
113
+ st.download_button(
114
+ label="Download Chat",
115
+ data=export_text,
116
+ file_name=f"chat_{st.session_state.session_id}.txt",
117
+ mime="text/plain"
118
+ )
119
+
120
+ # Animated Title Function
121
+ def animated_text(text, speed=0.03):
122
+ placeholder = st.empty()
123
+ displayed_text = ""
124
+ for letter in text:
125
+ displayed_text += letter
126
+ placeholder.markdown(f"""
127
+ <h1 class="title-text" style="color: {'#00D1FF' if theme == 'Light' else '#FFD700'}">
128
+ {displayed_text} 🚀
129
+ </h1>
130
+ """, unsafe_allow_html=True)
131
+ time.sleep(speed)
132
+
133
+ # Display Animated Welcome Message
134
+ animated_text('Data Science Tutor AI')
135
+
136
+ # Get session ID and chat history
137
  session_id = st.session_state.session_id
138
  chat_history_instance = chat_history(session_id)
139
 
 
142
  messages=[
143
  ('system', """You are an AI assistant specialized in Data Science tutoring.
144
  You will only answer questions related to Data Science.
145
+ Provide code examples with proper syntax highlighting when relevant.
146
  If asked anything outside this topic, politely decline and request a Data Science-related question.
147
  """),
148
  MessagesPlaceholder(variable_name="history", optional=True),
 
150
  ]
151
  )
152
 
153
+ # Create chain
154
  out_parser = StrOutputParser()
 
 
155
  chain = chat_prompt | llm | out_parser
 
 
156
  chat = RunnableWithMessageHistory(
157
  chain,
158
  lambda session: SQLChatMessageHistory(session, "sqlite:///chat_history.db"),
 
160
  history_messages_key="history"
161
  )
162
 
163
+ # Chat History Container
164
+ chat_container = st.container()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
+ # Load and display chat history
167
  if "messages" not in st.session_state:
168
  st.session_state.messages = load_chat_history(session_id)
 
 
169
 
170
+ with chat_container:
171
+ for role, content, timestamp in st.session_state.messages:
172
+ with st.chat_message(role):
173
+ # Handle code blocks in content
174
+ if "```" in content:
175
+ parts = content.split("```")
176
+ for i, part in enumerate(parts):
177
+ if i % 2 == 0:
178
+ st.markdown(part)
179
+ else:
180
+ st.markdown(f'<div class="code-block">{part}</div>',
181
+ unsafe_allow_html=True)
182
+ else:
183
+ st.markdown(content)
184
+ st.markdown(f'<div class="timestamp">{timestamp}</div>',
185
+ unsafe_allow_html=True)
186
+
187
+ # User input with additional features
188
+ with st.form(key='chat_form', clear_on_submit=True):
189
+ col1, col2 = st.columns([5, 1])
190
+ with col1:
191
+ user_input = st.text_input("Ask a Data Science question:", key="user_message")
192
+ with col2:
193
+ submit_button = st.form_submit_button("Send")
194
+
195
+ # Process user input
196
+ if submit_button and user_input:
197
  save_message(session_id, "user", user_input)
198
+ st.session_state.messages.append(("user", user_input, time.strftime('%Y-%m-%d %H:%M:%S')))
199
 
200
  config = {'configurable': {'session_id': session_id}}
201
  response = chat.invoke({'prompt': user_input}, config)
202
 
203
  save_message(session_id, "assistant", response)
204
+ st.session_state.messages.append(("assistant", response, time.strftime('%Y-%m-%d %H:%M:%S')))
205
+ st.rerun()
206
 
207
+ # Help button in bottom right
208
+ st.markdown("""
209
+ <div style="position: fixed; bottom: 10px; right: 10px;">
210
+ <button onclick="alert('Ask me anything about Data Science! Examples: Python, SQL, Machine Learning, Statistics')">ℹ️ Help</button>
211
+ </div>
212
+ """, unsafe_allow_html=True)