GroqChatBot / app.py
junaidshafique's picture
Update app.py
62cd898 verified
import gradio as gr
import os
from groq import Groq
# === Load API Key from environment ===
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("Missing GROQ_API_KEY. Please set it in the Hugging Face Space 'Secrets'.")
# === Initialize Groq client ===
client = Groq(api_key=GROQ_API_KEY)
# === Chat function ===
def chat_with_groq(message, history):
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
messages.append({"role": "user", "content": message})
try:
response = client.chat.completions.create(
model="llama3-8b-8192", # ✅ currently supported
messages=messages,
temperature=0.7,
)
reply = response.choices[0].message.content
except Exception as e:
reply = f"Error: {e}"
return reply
# === Gradio UI ===
chatbot = gr.ChatInterface(fn=chat_with_groq, title="Groq Chatbot")
# === Run app ===
if __name__ == "__main__":
chatbot.launch()