jeevitha-app commited on
Commit
c1937b1
Β·
verified Β·
1 Parent(s): 32b5c78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -213
app.py CHANGED
@@ -15,8 +15,7 @@ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
15
  # ============================================
16
 
17
  conversation_store = {
18
- "histories": {}, # stores per-personality chat history
19
- "current_personality": "default",
20
  "total_messages": 0,
21
  "session_start": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
22
  }
@@ -39,14 +38,13 @@ You are friendly, direct, and never say you cannot help unless absolutely necess
39
  "πŸ‘¨β€πŸ’» Code Expert": {
40
  "id": "coder",
41
  "system": """You are an elite software engineer and coding expert with 20 years of experience.
42
- You are fluent in Python, JavaScript, TypeScript, Java, C++, SQL, React, Node.js, and all major frameworks.
43
  When answering coding questions:
44
  - Always provide complete, working code
45
  - Add clear comments explaining each part
46
  - Suggest best practices and optimizations
47
  - Point out potential bugs or edge cases
48
- - Format all code in proper markdown code blocks with language specified
49
- You are patient, thorough, and love helping people learn to code.""",
50
  "welcome": "Hey! I'm your Code Expert. Share any coding problem β€” I'll help you solve it! πŸ‘¨β€πŸ’»"
51
  },
52
 
@@ -55,9 +53,7 @@ You are patient, thorough, and love helping people learn to code.""",
55
  "system": """You are a profound philosophical thinker and intellectual powerhouse.
56
  You approach every question with depth, nuance, and multi-dimensional analysis.
57
  You draw connections across philosophy, science, psychology, history, and culture.
58
- You challenge assumptions, explore paradoxes, and offer perspectives most people never consider.
59
  You think like a combination of Socrates, Einstein, and Richard Feynman.
60
- You make complex ideas accessible without dumbing them down.
61
  Always end with a thought-provoking follow-up question to deepen the conversation.""",
62
  "welcome": "Greetings, curious mind. Ask me anything worth thinking deeply about. 🧠"
63
  },
@@ -66,77 +62,34 @@ Always end with a thought-provoking follow-up question to deepen the conversatio
66
  "id": "tutor",
67
  "system": """You are the world's best study tutor β€” patient, clear, and brilliant at explaining.
68
  You can teach any subject from basics to advanced level.
69
- Your teaching style:
70
  - Start with the big picture, then zoom into details
71
  - Use real-world analogies and examples
72
  - Break complex topics into digestible steps
73
- - Check for understanding with questions
74
- - Create summaries, flashcards, and quizzes when helpful
75
- - Adapt your explanation level to the student
76
- You make learning feel exciting and achievable for everyone.""",
77
  "welcome": "Hi! I'm your personal Study Tutor. What would you like to learn today? πŸŽ“"
78
  },
79
 
80
  "✍️ Creative Writer": {
81
  "id": "writer",
82
  "system": """You are a masterful creative writer, storyteller, and wordsmith.
83
- You excel at:
84
- - Writing compelling stories, scripts, and narratives
85
- - Poetry in any style β€” haiku, sonnet, free verse, spoken word
86
- - Copywriting and persuasive content
87
- - Character development and world-building
88
- - Blog posts, essays, and articles
89
- - Email templates and professional writing
90
- Your writing is vivid, emotionally resonant, and always tailored to the tone requested.
91
- You have the imagination of a novelist and the precision of a journalist.""",
92
  "welcome": "Hello, wordsmith! Tell me what you'd like me to write for you. ✍️"
93
  },
94
 
95
  "πŸ’Ό Business Advisor": {
96
  "id": "business",
97
- "system": """You are a seasoned business advisor, entrepreneur, and strategist with decades of experience.
98
- You advise on:
99
- - Business strategy and planning
100
- - Marketing and growth hacking
101
- - Financial planning and analysis
102
- - Leadership and team building
103
- - Startup advice and fundraising
104
- - Career advancement and negotiation
105
- - Product development and go-to-market strategy
106
- You think like a combination of a McKinsey consultant, a Silicon Valley founder, and a Fortune 500 CEO.
107
  You give bold, actionable, no-nonsense advice backed by real business frameworks.""",
108
  "welcome": "Hello! I'm your Business Advisor. What business challenge can I help you solve? πŸ’Ό"
109
  },
110
 
111
- "πŸ₯ Health & Wellness Guide": {
112
- "id": "health",
113
- "system": """You are a knowledgeable health and wellness guide.
114
- You provide evidence-based information on:
115
- - Nutrition and diet
116
- - Exercise and fitness
117
- - Mental wellness and stress management
118
- - Sleep optimization
119
- - Preventive health habits
120
- - Understanding medical concepts in plain language
121
- IMPORTANT: You always remind users that you provide general wellness information only,
122
- and they should consult a qualified doctor for medical advice and diagnosis.
123
- You are warm, encouraging, and help people build sustainable healthy habits.""",
124
- "welcome": "Hi! I'm your Health & Wellness Guide. How can I support your wellbeing today? πŸ₯"
125
- },
126
-
127
  "πŸ˜„ Fun & Humor": {
128
  "id": "humor",
129
  "system": """You are a witty, hilarious, and entertaining AI with a great sense of humor.
130
- You love:
131
- - Telling jokes (clean, clever, and actually funny)
132
- - Playful banter and witty comebacks
133
- - Fun facts that blow people's minds
134
- - Riddles and brain teasers
135
- - Roasting ideas (never people) in a fun way
136
- - Making any topic entertaining
137
- You have the humor of a stand-up comedian, the wit of Oscar Wilde,
138
- and the energy of someone who had the perfect amount of coffee.
139
- But you also answer questions accurately β€” just with more fun!""",
140
  "welcome": "Heyyy! πŸ˜„ Ready to have some fun? Ask me anything β€” I'll make it entertaining!"
141
  },
142
  }
@@ -145,34 +98,23 @@ But you also answer questions accurately β€” just with more fun!""",
145
  # CORE CHAT FUNCTION
146
  # ============================================
147
 
148
- def chat(
149
- message,
150
- history,
151
- personality_name,
152
- temperature,
153
- max_tokens,
154
- system_override
155
- ):
156
  if not message.strip():
157
  return "", history
158
 
159
- # Get personality
160
  personality = PERSONALITIES.get(personality_name, PERSONALITIES["πŸ€– Default Assistant"])
161
  pid = personality["id"]
162
-
163
- # System prompt
164
  system_prompt = system_override.strip() if system_override.strip() else personality["system"]
165
 
166
- # Build messages from gradio history
167
  messages = [{"role": "system", "content": system_prompt}]
168
- for human, assistant in history:
169
- if human:
170
- messages.append({"role": "user", "content": human})
171
- if assistant:
172
- messages.append({"role": "assistant", "content": assistant})
173
  messages.append({"role": "user", "content": message})
174
 
175
- # Call Groq API
176
  try:
177
  response = client.chat.completions.create(
178
  model="llama-3.3-70b-versatile",
@@ -181,191 +123,146 @@ def chat(
181
  max_tokens=int(max_tokens),
182
  )
183
  reply = response.choices[0].message.content
184
-
185
- # Update stats
186
  conversation_store["total_messages"] += 1
187
 
188
- # Store history per personality
189
  if pid not in conversation_store["histories"]:
190
  conversation_store["histories"][pid] = []
191
- conversation_store["histories"][pid].append({
192
- "role": "user",
193
- "content": message,
194
- "time": datetime.datetime.now().strftime("%H:%M")
195
- })
196
- conversation_store["histories"][pid].append({
197
- "role": "assistant",
198
- "content": reply[:100] + "...",
199
- "time": datetime.datetime.now().strftime("%H:%M")
200
- })
201
-
202
- history.append((message, reply))
203
  return "", history
204
 
205
  except Exception as e:
206
- error_msg = f"⚠️ Error: {str(e)}"
207
- history.append((message, error_msg))
208
  return "", history
209
 
210
 
211
- # ============================================
212
- # HELPER FUNCTIONS
213
- # ============================================
214
-
215
  def clear_chat():
216
  return []
217
 
 
218
  def get_welcome(personality_name):
219
  personality = PERSONALITIES.get(personality_name, PERSONALITIES["πŸ€– Default Assistant"])
220
- return [(None, personality["welcome"])]
 
221
 
222
  def get_stats():
223
  total = conversation_store["total_messages"]
224
  session = conversation_store["session_start"]
225
  histories = conversation_store["histories"]
226
- total_saved = sum(len(v) for v in histories.values())
227
-
228
- stats = f"""
229
- πŸ“Š **Session Statistics**
230
 
231
  πŸ• Session Started: {session}
232
  πŸ’¬ Total Messages: {total}
233
- πŸ’Ύ Messages in Memory: {total_saved}
234
  οΏ½οΏ½οΏ½οΏ½ Personalities Used: {len(histories)}
235
 
236
- **Conversations by Personality:**
237
  """
238
  for pid, msgs in histories.items():
239
- stats += f"\n- {pid}: {len(msgs)//2} exchanges"
240
-
241
  return stats
242
 
 
243
  def export_chat(history, personality_name):
244
  if not history:
245
  return "No conversation to export."
246
-
247
- export = f"# PSYCHE Chat Export\n"
248
- export += f"Personality: {personality_name}\n"
249
- export += f"Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}\n"
250
- export += "=" * 50 + "\n\n"
251
-
252
- for i, (human, assistant) in enumerate(history):
253
- if human:
254
- export += f"**You:** {human}\n\n"
255
- if assistant:
256
- export += f"**AI:** {assistant}\n\n"
257
- export += "---\n\n"
258
-
259
  return export
260
 
 
261
  def summarize_chat(history, personality_name):
262
  if len(history) < 2:
263
  return "Not enough conversation to summarize."
264
-
265
  conversation_text = ""
266
- for human, assistant in history[-10:]:
267
- if human:
268
- conversation_text += f"User: {human}\n"
269
- if assistant:
270
- conversation_text += f"AI: {assistant[:300]}...\n"
271
-
272
  try:
273
  response = client.chat.completions.create(
274
  model="llama-3.3-70b-versatile",
275
  messages=[
276
- {"role": "system", "content": "Summarize this conversation concisely in 5 bullet points."},
277
  {"role": "user", "content": conversation_text}
278
  ],
279
  temperature=0.3,
280
  max_tokens=500,
281
  )
282
- return f"πŸ“‹ **Conversation Summary:**\n\n{response.choices[0].message.content}"
283
  except Exception as e:
284
  return f"Error: {str(e)}"
285
 
286
 
287
  # ============================================
288
- # GRADIO UI
289
  # ============================================
290
 
291
- with gr.Blocks(
292
- title="πŸ€– AI Chat β€” Full ChatGPT-like App",
293
- theme=gr.themes.Soft(),
294
- css="""
295
- .contain { max-width: 900px; margin: auto; }
296
- .chatbot { height: 500px; }
297
- footer { display: none !important; }
298
- .personality-radio label { cursor: pointer; }
299
- """
300
- ) as demo:
301
-
302
- # Header
303
- gr.Markdown("""
304
- # πŸ€– AI Chat Assistant
305
- ### A full-featured ChatGPT-like experience powered by LLaMA 3.3
306
- """)
307
 
308
  with gr.Row():
309
 
310
  # LEFT SIDEBAR
311
  with gr.Column(scale=1):
312
- gr.Markdown("### 🎭 Choose Personality")
 
313
  personality = gr.Radio(
314
  choices=list(PERSONALITIES.keys()),
315
  value="πŸ€– Default Assistant",
316
- label="AI Personality",
317
  interactive=True
318
  )
319
 
320
  gr.Markdown("### βš™οΈ Settings")
321
  temperature = gr.Slider(
322
- minimum=0.0,
323
- maximum=1.5,
324
- value=0.7,
325
- step=0.1,
326
- label="🌑️ Creativity (Temperature)",
327
- info="Low = focused, High = creative"
328
  )
329
  max_tokens = gr.Slider(
330
- minimum=256,
331
- maximum=4096,
332
- value=1024,
333
- step=256,
334
- label="πŸ“ Max Response Length",
335
- info="Tokens in response"
336
  )
337
 
338
- gr.Markdown("### πŸ› οΈ Custom System Prompt")
339
  system_override = gr.Textbox(
340
- placeholder="Override AI personality with custom instructions...",
341
- label="Custom Instructions (optional)",
342
  lines=3
343
  )
344
 
345
  gr.Markdown("### πŸ”§ Actions")
346
  clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
347
- summarize_btn = gr.Button("πŸ“‹ Summarize Chat", variant="secondary")
348
  export_btn = gr.Button("πŸ’Ύ Export Chat", variant="secondary")
349
- stats_btn = gr.Button("πŸ“Š Session Stats", variant="secondary")
350
 
351
- # RIGHT MAIN CHAT
 
 
 
 
 
 
352
  with gr.Column(scale=3):
 
353
  chatbot = gr.Chatbot(
354
  label="Chat",
355
  height=500,
356
  show_label=False,
357
- avatar_images=(
358
- None,
359
- "https://api.dicebear.com/7.x/bottts/svg?seed=psyche"
360
- ),
361
  render_markdown=True,
362
- bubble_full_width=False,
363
  )
364
 
365
  with gr.Row():
366
  msg_input = gr.Textbox(
367
  placeholder="Message AI Assistant... (Press Enter to send)",
368
- label="",
369
  lines=2,
370
  scale=5,
371
  show_label=False,
@@ -373,27 +270,17 @@ with gr.Blocks(
373
  )
374
  send_btn = gr.Button("Send ➀", variant="primary", scale=1)
375
 
376
- # Quick prompts
377
  gr.Markdown("**⚑ Quick Prompts:**")
378
  with gr.Row():
379
  q1 = gr.Button("Explain quantum computing", size="sm")
380
- q2 = gr.Button("Write Python code for...", size="sm")
381
- q3 = gr.Button("Give me a study plan", size="sm")
382
- q4 = gr.Button("Tell me a joke", size="sm")
383
-
384
- # Output area for summaries/exports/stats
385
- output_box = gr.Textbox(
386
- label="πŸ“„ Output",
387
- lines=8,
388
- visible=False,
389
- interactive=False
390
- )
391
 
392
  # ============================================
393
  # EVENT HANDLERS
394
  # ============================================
395
 
396
- # Send message
397
  send_btn.click(
398
  fn=chat,
399
  inputs=[msg_input, chatbot, personality, temperature, max_tokens, system_override],
@@ -404,48 +291,30 @@ with gr.Blocks(
404
  inputs=[msg_input, chatbot, personality, temperature, max_tokens, system_override],
405
  outputs=[msg_input, chatbot]
406
  )
407
-
408
- # Change personality β†’ show welcome message
409
- personality.change(
410
- fn=get_welcome,
411
- inputs=[personality],
412
- outputs=[chatbot]
413
- )
414
-
415
- # Clear chat
416
- clear_btn.click(
417
- fn=clear_chat,
418
- outputs=[chatbot]
419
- )
420
-
421
- # Summarize
422
  summarize_btn.click(
423
- fn=lambda h, p: (summarize_chat(h, p), gr.update(visible=True)),
424
  inputs=[chatbot, personality],
425
- outputs=[output_box, output_box]
426
  )
427
-
428
- # Export
429
  export_btn.click(
430
- fn=lambda h, p: (export_chat(h, p), gr.update(visible=True)),
431
  inputs=[chatbot, personality],
432
- outputs=[output_box, output_box]
433
- )
434
-
435
- # Stats
436
- stats_btn.click(
437
- fn=lambda: (get_stats(), gr.update(visible=True)),
438
- outputs=[output_box, output_box]
439
  )
 
440
 
441
- # Quick prompts
442
  q1.click(fn=lambda: "Explain quantum computing in simple terms", outputs=[msg_input])
443
  q2.click(fn=lambda: "Write Python code to build a REST API with FastAPI", outputs=[msg_input])
444
  q3.click(fn=lambda: "Give me a 30-day study plan to learn Machine Learning", outputs=[msg_input])
445
  q4.click(fn=lambda: "Tell me the funniest joke you know", outputs=[msg_input])
446
 
447
- # Load welcome on start
448
  demo.load(fn=get_welcome, inputs=[personality], outputs=[chatbot])
449
 
450
 
451
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
15
  # ============================================
16
 
17
  conversation_store = {
18
+ "histories": {},
 
19
  "total_messages": 0,
20
  "session_start": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
21
  }
 
38
  "πŸ‘¨β€πŸ’» Code Expert": {
39
  "id": "coder",
40
  "system": """You are an elite software engineer and coding expert with 20 years of experience.
41
+ You are fluent in Python, JavaScript, Java, C++, SQL, React, Node.js, and all major frameworks.
42
  When answering coding questions:
43
  - Always provide complete, working code
44
  - Add clear comments explaining each part
45
  - Suggest best practices and optimizations
46
  - Point out potential bugs or edge cases
47
+ - Format all code in proper markdown code blocks with language specified""",
 
48
  "welcome": "Hey! I'm your Code Expert. Share any coding problem β€” I'll help you solve it! πŸ‘¨β€πŸ’»"
49
  },
50
 
 
53
  "system": """You are a profound philosophical thinker and intellectual powerhouse.
54
  You approach every question with depth, nuance, and multi-dimensional analysis.
55
  You draw connections across philosophy, science, psychology, history, and culture.
 
56
  You think like a combination of Socrates, Einstein, and Richard Feynman.
 
57
  Always end with a thought-provoking follow-up question to deepen the conversation.""",
58
  "welcome": "Greetings, curious mind. Ask me anything worth thinking deeply about. 🧠"
59
  },
 
62
  "id": "tutor",
63
  "system": """You are the world's best study tutor β€” patient, clear, and brilliant at explaining.
64
  You can teach any subject from basics to advanced level.
 
65
  - Start with the big picture, then zoom into details
66
  - Use real-world analogies and examples
67
  - Break complex topics into digestible steps
68
+ - Create summaries and quizzes when helpful""",
 
 
 
69
  "welcome": "Hi! I'm your personal Study Tutor. What would you like to learn today? πŸŽ“"
70
  },
71
 
72
  "✍️ Creative Writer": {
73
  "id": "writer",
74
  "system": """You are a masterful creative writer, storyteller, and wordsmith.
75
+ You excel at stories, poetry, copywriting, blog posts, essays, and all forms of writing.
76
+ Your writing is vivid, emotionally resonant, and always tailored to the tone requested.""",
 
 
 
 
 
 
 
77
  "welcome": "Hello, wordsmith! Tell me what you'd like me to write for you. ✍️"
78
  },
79
 
80
  "πŸ’Ό Business Advisor": {
81
  "id": "business",
82
+ "system": """You are a seasoned business advisor and strategist with decades of experience.
83
+ You advise on strategy, marketing, finance, leadership, startups, and career growth.
 
 
 
 
 
 
 
 
84
  You give bold, actionable, no-nonsense advice backed by real business frameworks.""",
85
  "welcome": "Hello! I'm your Business Advisor. What business challenge can I help you solve? πŸ’Ό"
86
  },
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  "πŸ˜„ Fun & Humor": {
89
  "id": "humor",
90
  "system": """You are a witty, hilarious, and entertaining AI with a great sense of humor.
91
+ You love jokes, banter, riddles, and making any topic fun.
92
+ You have the humor of a stand-up comedian but still answer questions accurately β€” just with more fun!""",
 
 
 
 
 
 
 
 
93
  "welcome": "Heyyy! πŸ˜„ Ready to have some fun? Ask me anything β€” I'll make it entertaining!"
94
  },
95
  }
 
98
  # CORE CHAT FUNCTION
99
  # ============================================
100
 
101
+ def chat(message, history, personality_name, temperature, max_tokens, system_override):
 
 
 
 
 
 
 
102
  if not message.strip():
103
  return "", history
104
 
 
105
  personality = PERSONALITIES.get(personality_name, PERSONALITIES["πŸ€– Default Assistant"])
106
  pid = personality["id"]
 
 
107
  system_prompt = system_override.strip() if system_override.strip() else personality["system"]
108
 
109
+ # Build messages
110
  messages = [{"role": "system", "content": system_prompt}]
111
+ for item in history:
112
+ if item["role"] == "user":
113
+ messages.append({"role": "user", "content": item["content"]})
114
+ elif item["role"] == "assistant":
115
+ messages.append({"role": "assistant", "content": item["content"]})
116
  messages.append({"role": "user", "content": message})
117
 
 
118
  try:
119
  response = client.chat.completions.create(
120
  model="llama-3.3-70b-versatile",
 
123
  max_tokens=int(max_tokens),
124
  )
125
  reply = response.choices[0].message.content
 
 
126
  conversation_store["total_messages"] += 1
127
 
 
128
  if pid not in conversation_store["histories"]:
129
  conversation_store["histories"][pid] = []
130
+ conversation_store["histories"][pid].append({"role": "user", "content": message})
131
+ conversation_store["histories"][pid].append({"role": "assistant", "content": reply})
132
+
133
+ history.append({"role": "user", "content": message})
134
+ history.append({"role": "assistant", "content": reply})
 
 
 
 
 
 
 
135
  return "", history
136
 
137
  except Exception as e:
138
+ history.append({"role": "user", "content": message})
139
+ history.append({"role": "assistant", "content": f"⚠️ Error: {str(e)}"})
140
  return "", history
141
 
142
 
 
 
 
 
143
  def clear_chat():
144
  return []
145
 
146
+
147
  def get_welcome(personality_name):
148
  personality = PERSONALITIES.get(personality_name, PERSONALITIES["πŸ€– Default Assistant"])
149
+ return [{"role": "assistant", "content": personality["welcome"]}]
150
+
151
 
152
  def get_stats():
153
  total = conversation_store["total_messages"]
154
  session = conversation_store["session_start"]
155
  histories = conversation_store["histories"]
156
+ stats = f"""πŸ“Š Session Statistics
 
 
 
157
 
158
  πŸ• Session Started: {session}
159
  πŸ’¬ Total Messages: {total}
 
160
  οΏ½οΏ½οΏ½οΏ½ Personalities Used: {len(histories)}
161
 
162
+ Conversations by Personality:
163
  """
164
  for pid, msgs in histories.items():
165
+ stats += f"\nβ€’ {pid}: {len(msgs)//2} exchanges"
 
166
  return stats
167
 
168
+
169
  def export_chat(history, personality_name):
170
  if not history:
171
  return "No conversation to export."
172
+ export = f"# AI Chat Export\nPersonality: {personality_name}\nDate: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}\n{'='*50}\n\n"
173
+ for item in history:
174
+ role = "You" if item["role"] == "user" else "AI"
175
+ export += f"**{role}:** {item['content']}\n\n---\n\n"
 
 
 
 
 
 
 
 
 
176
  return export
177
 
178
+
179
  def summarize_chat(history, personality_name):
180
  if len(history) < 2:
181
  return "Not enough conversation to summarize."
 
182
  conversation_text = ""
183
+ for item in history[-10:]:
184
+ role = "User" if item["role"] == "user" else "AI"
185
+ conversation_text += f"{role}: {item['content'][:300]}\n"
 
 
 
186
  try:
187
  response = client.chat.completions.create(
188
  model="llama-3.3-70b-versatile",
189
  messages=[
190
+ {"role": "system", "content": "Summarize this conversation in 5 bullet points."},
191
  {"role": "user", "content": conversation_text}
192
  ],
193
  temperature=0.3,
194
  max_tokens=500,
195
  )
196
+ return f"πŸ“‹ Conversation Summary:\n\n{response.choices[0].message.content}"
197
  except Exception as e:
198
  return f"Error: {str(e)}"
199
 
200
 
201
  # ============================================
202
+ # GRADIO UI β€” Gradio 6.0 compatible
203
  # ============================================
204
 
205
+ with gr.Blocks(title="πŸ€– AI Chat Assistant") as demo:
206
+
207
+ gr.Markdown("# πŸ€– AI Chat Assistant\n### Full ChatGPT-like experience powered by LLaMA 3.3")
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
  with gr.Row():
210
 
211
  # LEFT SIDEBAR
212
  with gr.Column(scale=1):
213
+
214
+ gr.Markdown("### 🎭 Personality")
215
  personality = gr.Radio(
216
  choices=list(PERSONALITIES.keys()),
217
  value="πŸ€– Default Assistant",
218
+ label="Choose AI Mode",
219
  interactive=True
220
  )
221
 
222
  gr.Markdown("### βš™οΈ Settings")
223
  temperature = gr.Slider(
224
+ minimum=0.0, maximum=1.5, value=0.7, step=0.1,
225
+ label="🌑️ Creativity",
226
+ info="Low = focused | High = creative"
 
 
 
227
  )
228
  max_tokens = gr.Slider(
229
+ minimum=256, maximum=4096, value=1024, step=256,
230
+ label="πŸ“ Response Length"
 
 
 
 
231
  )
232
 
233
+ gr.Markdown("### πŸ› οΈ Custom Instructions")
234
  system_override = gr.Textbox(
235
+ placeholder="Override personality with custom instructions...",
236
+ label="System Prompt (optional)",
237
  lines=3
238
  )
239
 
240
  gr.Markdown("### πŸ”§ Actions")
241
  clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
242
+ summarize_btn = gr.Button("πŸ“‹ Summarize", variant="secondary")
243
  export_btn = gr.Button("πŸ’Ύ Export Chat", variant="secondary")
244
+ stats_btn = gr.Button("πŸ“Š Stats", variant="secondary")
245
 
246
+ output_box = gr.Textbox(
247
+ label="πŸ“„ Output",
248
+ lines=8,
249
+ interactive=False
250
+ )
251
+
252
+ # RIGHT CHAT AREA
253
  with gr.Column(scale=3):
254
+
255
  chatbot = gr.Chatbot(
256
  label="Chat",
257
  height=500,
258
  show_label=False,
259
+ type="messages",
 
 
 
260
  render_markdown=True,
 
261
  )
262
 
263
  with gr.Row():
264
  msg_input = gr.Textbox(
265
  placeholder="Message AI Assistant... (Press Enter to send)",
 
266
  lines=2,
267
  scale=5,
268
  show_label=False,
 
270
  )
271
  send_btn = gr.Button("Send ➀", variant="primary", scale=1)
272
 
 
273
  gr.Markdown("**⚑ Quick Prompts:**")
274
  with gr.Row():
275
  q1 = gr.Button("Explain quantum computing", size="sm")
276
+ q2 = gr.Button("Write Python REST API", size="sm")
277
+ q3 = gr.Button("30-day ML study plan", size="sm")
278
+ q4 = gr.Button("Tell me a joke πŸ˜„", size="sm")
 
 
 
 
 
 
 
 
279
 
280
  # ============================================
281
  # EVENT HANDLERS
282
  # ============================================
283
 
 
284
  send_btn.click(
285
  fn=chat,
286
  inputs=[msg_input, chatbot, personality, temperature, max_tokens, system_override],
 
291
  inputs=[msg_input, chatbot, personality, temperature, max_tokens, system_override],
292
  outputs=[msg_input, chatbot]
293
  )
294
+ personality.change(fn=get_welcome, inputs=[personality], outputs=[chatbot])
295
+ clear_btn.click(fn=clear_chat, outputs=[chatbot])
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  summarize_btn.click(
297
+ fn=summarize_chat,
298
  inputs=[chatbot, personality],
299
+ outputs=[output_box]
300
  )
 
 
301
  export_btn.click(
302
+ fn=export_chat,
303
  inputs=[chatbot, personality],
304
+ outputs=[output_box]
 
 
 
 
 
 
305
  )
306
+ stats_btn.click(fn=get_stats, outputs=[output_box])
307
 
 
308
  q1.click(fn=lambda: "Explain quantum computing in simple terms", outputs=[msg_input])
309
  q2.click(fn=lambda: "Write Python code to build a REST API with FastAPI", outputs=[msg_input])
310
  q3.click(fn=lambda: "Give me a 30-day study plan to learn Machine Learning", outputs=[msg_input])
311
  q4.click(fn=lambda: "Tell me the funniest joke you know", outputs=[msg_input])
312
 
 
313
  demo.load(fn=get_welcome, inputs=[personality], outputs=[chatbot])
314
 
315
 
316
+ demo.launch(
317
+ server_name="0.0.0.0",
318
+ server_port=7860,
319
+ theme=gr.themes.Soft()
320
+ )