| import os |
| import gradio as gr |
| from groq import Groq |
|
|
| |
| GROQ_API_KEY = os.environ.get("Keypass") |
|
|
| if GROQ_API_KEY is None: |
| raise ValueError("GROQ_API_KEY not found. Add it in Hugging Face β Settings β Secrets.") |
|
|
| client = Groq(api_key=GROQ_API_KEY) |
|
|
| |
| def chat(message, history): |
| try: |
| messages = [] |
|
|
| |
| for user, bot in history: |
| messages.append({"role": "user", "content": user}) |
| messages.append({"role": "assistant", "content": bot}) |
|
|
| |
| messages.append({"role": "user", "content": message}) |
|
|
| response = client.chat.completions.create( |
| model="llama3-70b-8192", |
| messages=messages, |
| temperature=0.7, |
| max_tokens=512, |
| ) |
|
|
| reply = response.choices[0].message.content |
| return reply |
|
|
| except Exception as e: |
| return f"Error: {str(e)}" |
|
|
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("## π Groq AI Chatbot") |
| gr.Markdown("Simple chatbot using Groq API + Gradio") |
|
|
| chatbot = gr.Chatbot() |
| msg = gr.Textbox(label="Your Message") |
| clear = gr.Button("Clear Chat") |
|
|
| def respond(message, chat_history): |
| bot_message = chat(message, chat_history) |
| chat_history.append((message, bot_message)) |
| return "", chat_history |
|
|
| msg.submit(respond, [msg, chatbot], [msg, chatbot]) |
| clear.click(lambda: None, None, chatbot, queue=False) |
|
|
| demo.launch() |