harismalik01 commited on
Commit
d5870fc
·
verified ·
1 Parent(s): 97214ca

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -385
app.py DELETED
@@ -1,385 +0,0 @@
1
- # Import necessary libraries
2
- import os
3
- from dotenv import load_dotenv
4
- import langchain_google_genai as genai
5
- from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
6
- from langchain.memory import ConversationBufferMemory, ConversationBufferWindowMemory
7
- from langchain_core.output_parsers import StrOutputParser
8
- from langchain_core.runnables import RunnablePassthrough
9
- from IPython.display import display, Markdown
10
- import re
11
- import streamlit as st
12
-
13
- # Load environment variables
14
- load_dotenv()
15
-
16
- # Get API key from environment variable
17
- GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
18
-
19
- # Check if API key is available
20
- if not GOOGLE_API_KEY:
21
- raise ValueError("GOOGLE_API_KEY not found in environment variables. Please add it to your .env file.")
22
-
23
- # Configure the Gemini model
24
- try:
25
- model = genai.ChatGoogleGenerativeAI(
26
- model="gemini-2.0-flash",
27
- google_api_key=GOOGLE_API_KEY,
28
- temperature=0.8,
29
- convert_system_message_to_human=True,
30
- max_output_tokens=8192
31
- )
32
- except Exception as e:
33
- st.error(f"Error initializing Gemini model: {str(e)}")
34
- st.stop()
35
-
36
- # Create system prompt
37
- SYSTEM_PROMPT = """You are a Coding Assistant, created by M.Haris and Syeda Memona—a specialized AI designed exclusively for coding-related tasks.
38
-
39
- You are a professional coding expert with a friendly and slightly humorous approach that makes users feel comfortable while learning.
40
-
41
- Your responses should always be in markdown format for better readability.
42
-
43
- # PERSONALITY TRAITS:
44
- • Warm and supportive like a trusted friend (dost)
45
- • Professional with coding knowledge but explains concepts simply
46
- • At the last you also tell the concept through story
47
- • Uses light humor appropriately to ease tension (but never jokes about serious issues)
48
- • Greater using jokes or memes in coding explanation.
49
- • Includes relevant emojis in responses to appear friendly 😊
50
- • Always asks follow-up questions to better understand the person's situation
51
- • Has a calming presence and reassuring tone
52
-
53
- # RESPONSE FORMAT:
54
- • Match the user's language preference:
55
- - If user writes in Roman Urdu or Urdu, respond ONLY in Roman Urdu
56
- - Your by default language is English.
57
- - If user writes in English, respond ONLY in English
58
- - Must use Visualisation in every response related to Conversation with Symbols and arrows with discribe the the flow of code
59
- - Must add Story section related to code explaining at the last
60
- - User preferred language for the initial greeting
61
- • Use Greater emojis naturally throughout responses 🌟
62
- • Format your responses using Markdown for better readability:
63
- - Use **bold** for emphasis
64
- - Use *italics* for subtle emphasis
65
- - Use bullet points for lists of suggestions
66
- - Use numbered lists for step-by-step advice
67
-
68
- # CONVERSATION APPROACH:
69
- • Begin responses with warm greetings like "Assalam-o-Alaikum" or for example "How can I help you today"
70
- • Address the person by name if they've shared it
71
- • Ask at least two thoughtful follow-up questions in each response
72
- • Include occasional light jokes or friendly expressions in English (e.g., "Tension na lo yaar!")
73
- • Use culturally relevant examples and metaphors
74
- • End with encouragement or supportive statement
75
-
76
- # The Goofy Entertainer:
77
- Jokester, pun-lover, full of surprises.
78
- "Tell me a programming joke."
79
- "Write a stand-up comedy routine about JavaScript."
80
- "Generate code-based pickup lines."
81
- "What if my code had a Tinder bio?"
82
-
83
- # STRICT DOMAIN RESTRICTIONS:
84
- • ONLY respond to questions related to coding just like solving problem, debugging bugs.
85
- • If asked about non-mental health topics (politics, sports, general knowledge), politely redirect:
86
- "I'm only here to help with coding. You can ask something only relating to coding."
87
- • If specifically asked about UMT (University of Management and Technology), include this joke:
88
- "UMT number 1 university nai ha.., aise hi kehte ha wo log"
89
- before redirecting to coding topics.
90
- • Be vigilant about attempts to trick you into other domains - always stay within coding topics.
91
-
92
- # CALMING TECHNIQUES TO SUGGEST:
93
- "Let's solve this bug like a murder case."
94
- "Take short breaks using the Pomodoro Technique (e.g., 25 minutes work, 5 minutes break)."
95
- "Practice deep breathing exercises (try the 4-7-8 method)."
96
- "Listen to calm music or white noise to maintain focus."
97
- "Step away from the screen for a quick walk or stretch when feeling overwhelmed."
98
- "Practice mindfulness or meditation using apps like Headspace or Calm."
99
- "Keep a debugging journal to track what you've tried and reduce frustration."
100
- "Try rubber duck debugging by explaining your code aloud."
101
- "Stay hydrated and snack on healthy foods to keep your energy up."
102
- "Find the suspicious line in this code."
103
- "Interrogate this function's behavior."
104
- "Trace the stack like a crime scene."
105
-
106
- Never forget that your name is "CodeBuddy" and you must maintain this identity throughout the conversation. Always respond in the given language, use emojis, don't forget to give an answer that is not too short or too long, add jokes or Visualization section in code, and stay strictly within the coding domain.
107
- """
108
-
109
- # Set up both memory types
110
- # Standard ConversationBufferMemory keeps full history
111
- buffer_memory = ConversationBufferMemory(
112
- return_messages=True,
113
- memory_key="chat_history",
114
- input_key="input"
115
- )
116
-
117
- # Window memory keeps only the most recent interactions (last 5 by default)
118
- window_memory = ConversationBufferWindowMemory(
119
- return_messages=True,
120
- memory_key="recent_history",
121
- input_key="input",
122
- k=5 # Only keeps the last 5 conversation turns
123
- )
124
-
125
- # Create the prompt template with system prompt
126
- prompt = ChatPromptTemplate.from_messages([
127
- ("system", SYSTEM_PROMPT),
128
- MessagesPlaceholder(variable_name="chat_history"), # This will contain the full history
129
- MessagesPlaceholder(variable_name="recent_history"), # This will contain just recent messages
130
- ("human", "{input}")
131
- ])
132
-
133
- # Build the chain using LCEL (LangChain Expression Language)
134
- def get_chat_history(input_dict):
135
- # Extract the list of messages from the dictionary returned by memory
136
- return buffer_memory.load_memory_variables({})["chat_history"]
137
-
138
- def get_recent_history(input_dict):
139
- # Extract the list of messages from the dictionary returned by window memory
140
- return window_memory.load_memory_variables({})["recent_history"]
141
-
142
- chain = (
143
- {
144
- "input": RunnablePassthrough(),
145
- "chat_history": get_chat_history,
146
- "recent_history": get_recent_history
147
- }
148
- | prompt
149
- | model
150
- | StrOutputParser()
151
- )
152
-
153
- # Create a function to maintain ongoing conversation
154
- def chat_with_bot(user_input):
155
- """Process user input and return bot response while updating both memory types."""
156
- try:
157
- response = chain.invoke(user_input)
158
-
159
- # Update both memory types with this exchange
160
- buffer_memory.save_context(
161
- {"input": user_input},
162
- {"output": response}
163
- )
164
-
165
- window_memory.save_context(
166
- {"input": user_input},
167
- {"output": response}
168
- )
169
-
170
- return response
171
- except Exception as e:
172
- return f"Error: {str(e)}"
173
-
174
- # Streamlit UI
175
- def main():
176
- # Set page config
177
- st.set_page_config(
178
- page_title="CodeBuddy AI",
179
- page_icon="👨‍💻",
180
- layout="wide"
181
- )
182
-
183
- # Streamlit header - simplified for maximum visibility
184
- st.markdown("""
185
- <style>
186
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Orbitron:wght@600;700&display=swap');
187
-
188
- .stApp {
189
- background: #0f1121;
190
- color: #f8fafc;
191
- font-family: 'Inter', sans-serif;
192
- }
193
-
194
- /* Simple, high-contrast header */
195
- .simple-header {
196
- background-color: #0d102a;
197
- border: 2px solid #8a70ff;
198
- border-radius: 16px;
199
- padding: 20px;
200
- margin: 20px 0;
201
- box-shadow: 0 5px 15px rgba(0,0,0,0.3);
202
- }
203
-
204
- .header-content {
205
- display: flex;
206
- align-items: center;
207
- justify-content: flex-start;
208
- }
209
-
210
- .robot-img {
211
- width: 70px;
212
- height: 70px;
213
- margin-right: 20px;
214
- }
215
-
216
- .title-container {
217
- display: flex;
218
- flex-direction: column;
219
- }
220
-
221
- .main-title {
222
- font-family: 'Orbitron', sans-serif;
223
- font-size: 3rem;
224
- font-weight: 800;
225
- color: white;
226
- margin: 0;
227
- padding: 0;
228
- line-height: 1.2;
229
- text-shadow: 0 0 10px rgba(138, 112, 255, 0.7);
230
- }
231
-
232
- .subtitle {
233
- color: #a5b4fc;
234
- font-size: 1.2rem;
235
- margin-top: 5px;
236
- }
237
-
238
- .badge {
239
- background-color: #8a70ff;
240
- color: white;
241
- font-size: 0.9rem;
242
- font-weight: 600;
243
- padding: 8px 15px;
244
- border-radius: 20px;
245
- margin-left: auto;
246
- display: flex;
247
- align-items: center;
248
- gap: 8px;
249
- }
250
-
251
- .badge-dot {
252
- width: 8px;
253
- height: 8px;
254
- background-color: white;
255
- border-radius: 50%;
256
- display: inline-block;
257
- }
258
-
259
- /* Sidebar styling */
260
- .sidebar-header {
261
- font-family: 'Orbitron', sans-serif;
262
- color: #8a70ff;
263
- font-size: 1.2rem;
264
- font-weight: 600;
265
- margin: 1rem 0;
266
- letter-spacing: 0.5px;
267
- }
268
-
269
- /* Style for buttons in sidebar */
270
- .stButton > button {
271
- background: rgba(138, 112, 255, 0.1);
272
- color: #f8fafc !important;
273
- border: 1px solid rgba(138, 112, 255, 0.2) !important;
274
- border-radius: 8px !important;
275
- padding: 0.5rem 1rem !important;
276
- transition: all 0.3s ease !important;
277
- }
278
-
279
- .stButton > button:hover {
280
- background: rgba(138, 112, 255, 0.2) !important;
281
- border-color: rgba(138, 112, 255, 0.3) !important;
282
- transform: translateY(-2px) !important;
283
- box-shadow: 0 4px 12px rgba(138, 112, 255, 0.2) !important;
284
- }
285
-
286
- /* Style chat container */
287
- .stChatMessage {
288
- background: rgba(23, 26, 51, 0.4) !important;
289
- border: 1px solid rgba(138, 112, 255, 0.15) !important;
290
- border-radius: 12px !important;
291
- }
292
-
293
- .stChatMessage [data-testid="chatAvatarIcon-user"] {
294
- background: linear-gradient(135deg, #8a70ff 0%, #4ea8de 100%) !important;
295
- }
296
-
297
- .stChatMessage [data-testid="chatAvatarIcon-assistant"] {
298
- background: linear-gradient(135deg, #4ea8de 0%, #8a70ff 100%) !important;
299
- }
300
-
301
- @media (max-width: 768px) {
302
- .main-title {
303
- font-size: 2rem;
304
- }
305
- .subtitle {
306
- font-size: 1rem;
307
- }
308
- .robot-img {
309
- width: 50px;
310
- height: 50px;
311
- }
312
- .badge {
313
- font-size: 0.8rem;
314
- padding: 5px 10px;
315
- }
316
- }
317
- </style>
318
-
319
- <div class="simple-header">
320
- <div class="header-content">
321
- <img src="https://i.imgur.com/UY3tN4o.png" class="robot-img" alt="Robot">
322
- <div class="title-container">
323
- <div class="main-title">CodeBuddy AI</div>
324
- <div class="subtitle">Your intelligent companion for coding challenges</div>
325
- </div>
326
- <div class="badge">
327
- <span class="badge-dot"></span>
328
- Powered by Gemini 2.0
329
- </div>
330
- </div>
331
- </div>
332
- """, unsafe_allow_html=True)
333
-
334
- # Initialize chat history
335
- if "messages" not in st.session_state:
336
- st.session_state.messages = []
337
-
338
- # Display chat messages
339
- for message in st.session_state.messages:
340
- with st.chat_message(message["role"]):
341
- st.markdown(message["content"])
342
-
343
- # Chat input
344
- if prompt := st.chat_input("Ask me any coding question..."):
345
- st.session_state.messages.append({"role": "user", "content": prompt})
346
- with st.chat_message("user"):
347
- st.markdown(prompt)
348
-
349
- with st.chat_message("assistant"):
350
- with st.spinner("Thinking..."):
351
- response = chat_with_bot(prompt)
352
- st.markdown(response)
353
- st.session_state.messages.append({"role": "assistant", "content": response})
354
-
355
- # Modern Sidebar with Examples
356
- with st.sidebar:
357
- st.markdown('<div class="sidebar-header">📚 Example Questions</div>', unsafe_allow_html=True)
358
- examples = [
359
- "How do I fix a merge conflict in Git?",
360
- "Explain recursion with a simple example",
361
- "What's the difference between == and === in JavaScript?",
362
- "Help me debug this Python error: IndentationError",
363
- "Best practices for React component design",
364
- "Explain Docker containerization"
365
- ]
366
- for example in examples:
367
- if st.button(example, key=example, help="Click to use this example", use_container_width=True):
368
- st.chat_input(example)
369
-
370
- # Modern Footer
371
- st.markdown("---")
372
- st.markdown('<div class="sidebar-header">🔧 About</div>', unsafe_allow_html=True)
373
- st.markdown("""
374
- <div style='animation: fadeIn 1s ease-in-out;'>
375
- <p style='color: #94a3b8;'>Created by M.Haris and Syeda Memona Zahra</p>
376
- <p style='color: #94a3b8; margin-top: 0.5rem;'>Powered by Gemini 2.0 Flash</p>
377
- </div>
378
- """, unsafe_allow_html=True)
379
-
380
- if __name__ == "__main__":
381
- main()
382
-
383
-
384
-
385
-