Kubratech3's picture
Update app.py
947ce07 verified
# =====================================
# πŸ’ŒπŸ’—πŸŒ» Kubra's AI Chatbot (FINAL FIX)
# Gradio 6 + Groq + HF Ready
# =====================================
import os
import gradio as gr
from groq import Groq
# -------------------------------------
# Load API Key
# -------------------------------------
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("❌ GROQ_API_KEY is missing.")
# -------------------------------------
# Init Groq Client
# -------------------------------------
client = Groq(api_key=GROQ_API_KEY)
# -------------------------------------
# Universal History Converter
# -------------------------------------
def build_messages(history, user_msg):
messages = []
if not history:
history = []
for item in history:
# Case 1: New Gradio format (dict)
if isinstance(item, dict):
if "role" in item and "content" in item:
messages.append({
"role": item["role"],
"content": str(item["content"])
})
# Case 2: Old format (tuple/list)
elif isinstance(item, (list, tuple)) and len(item) == 2:
human, ai = item
if isinstance(human, str):
messages.append({
"role": "user",
"content": human
})
if isinstance(ai, str):
messages.append({
"role": "assistant",
"content": ai
})
# Add current user message
messages.append({
"role": "user",
"content": user_msg
})
return messages
# -------------------------------------
# Chat Function
# -------------------------------------
def chat_with_ai(user_message, history):
try:
messages = build_messages(history, user_message)
response = client.chat.completions.create(
messages=messages,
model="llama-3.3-70b-versatile"
)
return response.choices[0].message.content
except Exception as e:
return f"⚠️ System Error:\n{str(e)}"
# -------------------------------------
# CSS
# -------------------------------------
custom_css = """
body {
background: linear-gradient(135deg, #ffd6ec, #e7ddff);
font-family: system-ui;
}
.gradio-container {
max-width: 1000px !important;
margin: auto;
padding: 20px;
}
div[data-testid="chatbot"] {
background: white;
border-radius: 18px;
border: 2px solid #d7c7ff;
min-height: 500px;
}
textarea {
min-height: 90px !important;
font-size: 17px !important;
padding: 14px !important;
border-radius: 14px !important;
}
button {
background: #7a4cff !important;
color: white !important;
border-radius: 14px !important;
font-weight: bold;
}
button:hover {
background: #9c73ff !important;
}
"""
# -------------------------------------
# App
# -------------------------------------
with gr.Blocks(
title="πŸ’ŒπŸ’—πŸŒ» Kubra's AI Chatbot"
) as demo:
gr.Markdown("# πŸ’ŒπŸ’—πŸŒ» Kubra's AI Chatbot")
gr.Markdown("### Your Friendly AI Assistant 🌷🀍")
chatbot = gr.Chatbot(
height=520
)
with gr.Row():
user_input = gr.Textbox(
placeholder="Type your message here...",
lines=4,
show_label=False
)
send_btn = gr.Button("Send πŸ’Œ")
clear_btn = gr.Button("Clear 🧹")
# Response handler
def respond(msg, history):
if not msg.strip():
return "", history
if history is None:
history = []
reply = chat_with_ai(msg, history)
# Gradio 6 expects dict format
history.append({
"role": "user",
"content": msg
})
history.append({
"role": "assistant",
"content": reply
})
return "", history
send_btn.click(
respond,
[user_input, chatbot],
[user_input, chatbot]
)
user_input.submit(
respond,
[user_input, chatbot],
[user_input, chatbot]
)
clear_btn.click(
lambda: [],
None,
chatbot
)
# -------------------------------------
# Launch
# -------------------------------------
demo.launch(css=custom_css)