Spaces:
Sleeping
Sleeping
| 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() | |