Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from groq import Groq
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# ✅ Get API key from environment variable
|
| 6 |
+
# (You will set it in Hugging Face “Secrets” panel, not in code)
|
| 7 |
+
api_key = os.getenv("GROQ_API_KEY")
|
| 8 |
+
|
| 9 |
+
if not api_key:
|
| 10 |
+
raise ValueError("⚠️ Please set your GROQ_API_KEY in the Hugging Face Space secrets.")
|
| 11 |
+
|
| 12 |
+
# ✅ Initialize Groq client
|
| 13 |
+
client = Groq(api_key=api_key)
|
| 14 |
+
|
| 15 |
+
# ✅ Chat function
|
| 16 |
+
def chat_with_groq(message, history):
|
| 17 |
+
# Build chat history
|
| 18 |
+
messages = [{"role": "system", "content": "You are a helpful AI assistant."}]
|
| 19 |
+
for user, bot in history:
|
| 20 |
+
messages.append({"role": "user", "content": user})
|
| 21 |
+
messages.append({"role": "assistant", "content": bot})
|
| 22 |
+
messages.append({"role": "user", "content": message})
|
| 23 |
+
|
| 24 |
+
# Call Groq API
|
| 25 |
+
completion = client.chat.completions.create(
|
| 26 |
+
model="mixtral-8x7b", # You can change to "llama3-8b" etc.
|
| 27 |
+
messages=messages,
|
| 28 |
+
temperature=0.7,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
return completion.choices[0].message.content
|
| 32 |
+
|
| 33 |
+
# ✅ Build Gradio UI
|
| 34 |
+
chatbot = gr.ChatInterface(
|
| 35 |
+
fn=chat_with_groq,
|
| 36 |
+
title="💬 Groq Chatbot",
|
| 37 |
+
description="A simple chatbot powered by Groq API and Gradio, deployed on Hugging Face Spaces.",
|
| 38 |
+
theme="soft"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# ✅ Launch app
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
chatbot.launch()
|