Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,8 +15,7 @@ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
|
| 15 |
# ============================================
|
| 16 |
|
| 17 |
conversation_store = {
|
| 18 |
-
"histories": {},
|
| 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,
|
| 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 |
-
-
|
| 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 |
-
|
| 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
|
| 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 |
-
-
|
| 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
|
| 167 |
messages = [{"role": "system", "content": system_prompt}]
|
| 168 |
-
for
|
| 169 |
-
if
|
| 170 |
-
messages.append({"role": "user", "content":
|
| 171 |
-
|
| 172 |
-
messages.append({"role": "assistant", "content":
|
| 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 |
-
|
| 193 |
-
|
| 194 |
-
|
| 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 |
-
|
| 207 |
-
history.append(
|
| 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 [
|
|
|
|
| 221 |
|
| 222 |
def get_stats():
|
| 223 |
total = conversation_store["total_messages"]
|
| 224 |
session = conversation_store["session_start"]
|
| 225 |
histories = conversation_store["histories"]
|
| 226 |
-
|
| 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 |
-
|
| 237 |
"""
|
| 238 |
for pid, msgs in histories.items():
|
| 239 |
-
stats += f"\n
|
| 240 |
-
|
| 241 |
return stats
|
| 242 |
|
|
|
|
| 243 |
def export_chat(history, personality_name):
|
| 244 |
if not history:
|
| 245 |
return "No conversation to export."
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 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
|
| 267 |
-
if
|
| 268 |
-
|
| 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
|
| 277 |
{"role": "user", "content": conversation_text}
|
| 278 |
],
|
| 279 |
temperature=0.3,
|
| 280 |
max_tokens=500,
|
| 281 |
)
|
| 282 |
-
return f"π
|
| 283 |
except Exception as e:
|
| 284 |
return f"Error: {str(e)}"
|
| 285 |
|
| 286 |
|
| 287 |
# ============================================
|
| 288 |
-
# GRADIO UI
|
| 289 |
# ============================================
|
| 290 |
|
| 291 |
-
with gr.Blocks(
|
| 292 |
-
|
| 293 |
-
|
| 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 |
-
|
|
|
|
| 313 |
personality = gr.Radio(
|
| 314 |
choices=list(PERSONALITIES.keys()),
|
| 315 |
value="π€ Default Assistant",
|
| 316 |
-
label="AI
|
| 317 |
interactive=True
|
| 318 |
)
|
| 319 |
|
| 320 |
gr.Markdown("### βοΈ Settings")
|
| 321 |
temperature = gr.Slider(
|
| 322 |
-
minimum=0.0,
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
step=0.1,
|
| 326 |
-
label="π‘οΈ Creativity (Temperature)",
|
| 327 |
-
info="Low = focused, High = creative"
|
| 328 |
)
|
| 329 |
max_tokens = gr.Slider(
|
| 330 |
-
minimum=256,
|
| 331 |
-
|
| 332 |
-
value=1024,
|
| 333 |
-
step=256,
|
| 334 |
-
label="π Max Response Length",
|
| 335 |
-
info="Tokens in response"
|
| 336 |
)
|
| 337 |
|
| 338 |
-
gr.Markdown("### π οΈ Custom
|
| 339 |
system_override = gr.Textbox(
|
| 340 |
-
placeholder="Override
|
| 341 |
-
label="
|
| 342 |
lines=3
|
| 343 |
)
|
| 344 |
|
| 345 |
gr.Markdown("### π§ Actions")
|
| 346 |
clear_btn = gr.Button("ποΈ Clear Chat", variant="secondary")
|
| 347 |
-
summarize_btn = gr.Button("π Summarize
|
| 348 |
export_btn = gr.Button("πΎ Export Chat", variant="secondary")
|
| 349 |
-
stats_btn = gr.Button("π
|
| 350 |
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
with gr.Column(scale=3):
|
|
|
|
| 353 |
chatbot = gr.Chatbot(
|
| 354 |
label="Chat",
|
| 355 |
height=500,
|
| 356 |
show_label=False,
|
| 357 |
-
|
| 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
|
| 381 |
-
q3 = gr.Button("
|
| 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 |
-
|
| 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=
|
| 424 |
inputs=[chatbot, personality],
|
| 425 |
-
outputs=[output_box
|
| 426 |
)
|
| 427 |
-
|
| 428 |
-
# Export
|
| 429 |
export_btn.click(
|
| 430 |
-
fn=
|
| 431 |
inputs=[chatbot, personality],
|
| 432 |
-
outputs=[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(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
)
|