Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from groq import Groq | |
| import os | |
| # ✅ Get API key from environment variable | |
| # (You will set it in Hugging Face “Secrets” panel, not in code) | |
| api_key = os.getenv("GROQ_API_KEY") | |
| if not api_key: | |
| raise ValueError("⚠️ Please set your GROQ_API_KEY in the Hugging Face Space secrets.") | |
| # ✅ Initialize Groq client | |
| client = Groq(api_key=api_key) | |
| # ✅ Chat function | |
| def chat_with_groq(message, history): | |
| # Build chat history | |
| 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}) | |
| # Call Groq API | |
| completion = client.chat.completions.create( | |
| model="openai/gpt-oss-20b", # You can change to "llama3-8b" etc. | |
| messages=messages, | |
| temperature=0.7, | |
| ) | |
| return completion.choices[0].message.content | |
| # ✅ Build Gradio UI | |
| chatbot = gr.ChatInterface( | |
| fn=chat_with_groq, | |
| title="Demo ChatBot by Ahmad", | |
| description="A simple chatbot powered by Groq API and Gradio, deployed on Hugging Face Spaces.", | |
| theme="soft" | |
| ) | |
| # ✅ Launch app | |
| if __name__ == "__main__": | |
| chatbot.launch() | |