Spaces:
Sleeping
Sleeping
File size: 1,842 Bytes
6a28378 0698a9b 6a28378 0698a9b 6a28378 0698a9b 6a28378 0698a9b 6a28378 0698a9b 6a28378 0698a9b 6a28378 0698a9b 6a28378 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import gradio as gr
from groq import Groq
import os
# -----------------------------
# GROQ CLIENT SETUP
# -----------------------------
api_key = os.environ.get("GROQ_API_KEY")
if api_key:
client = Groq(api_key=api_key)
else:
client = None
# -----------------------------
# CHAT FUNCTION
# -----------------------------
def chat_with_ai(message, history):
if history is None:
history = []
if client is None:
reply = "β Groq API key not found. Please add it in Settings β Secrets β GROQ_API_KEY."
history.append((message, reply))
return history, history, ""
# Prepare messages for Groq
messages = [{"role": "system", "content": "You are a helpful AI assistant."}]
for user, bot in history:
messages.append({"role": "user", "content": user})
messages.append({"role": "assistant", "content": bot})
messages.append({"role": "user", "content": message})
try:
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
temperature=0.7,
max_tokens=1024
)
reply = response.choices[0].message.content
except Exception as e:
reply = f"β Error from Groq API: {str(e)}"
history.append((message, reply))
return history, history, ""
# -----------------------------
# GRADIO UI
# -----------------------------
with gr.Blocks(title="Simple Groq Chatbot") as app:
gr.Markdown("# π€ Simple Groq Chatbot")
chatbot = gr.Chatbot(height=400)
msg = gr.Textbox(placeholder="Type your message...")
clear = gr.Button("Clear")
state = gr.State([])
# Submit message
msg.submit(chat_with_ai, [msg, state], [chatbot, state, msg])
clear.click(lambda: ([], [], ""), None, [chatbot, state, msg])
app.launch()
|