Spaces:
Sleeping
Sleeping
import os | |
import requests | |
import gradio as gr | |
# Load API Key | |
GROQ_API_KEY = os.getenv("GROQ_API_KEY") | |
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
HEADERS = { | |
"Authorization": f"Bearer {GROQ_API_KEY}", | |
"Content-Type": "application/json" | |
} | |
# Core logic | |
def groq_chatbot(message, history): | |
system_prompt = ( | |
"You are a helpful assistant. Always answer clearly and provide 3 follow-up suggestions at the end.\n\n" | |
"Structure your response like:\n\n" | |
"Answer:\n<response>\n\nSuggestions:\n1. <...>\n2. <...>\n3. <...>" | |
) | |
# Start with system prompt | |
messages = [{"role": "system", "content": system_prompt}] | |
# Add chat history | |
for user_msg, bot_msg in history: | |
messages.append({"role": "user", "content": user_msg}) | |
messages.append({"role": "assistant", "content": bot_msg}) | |
# Add the new user message | |
messages.append({"role": "user", "content": message}) | |
# Prepare payload | |
payload = { | |
"model": "llama3-8b-8192", | |
"messages": messages, | |
"temperature": 0.7 | |
} | |
# Send request | |
response = requests.post(GROQ_API_URL, headers=HEADERS, json=payload) | |
# Return result | |
if response.status_code == 200: | |
return response.json()["choices"][0]["message"]["content"] | |
else: | |
return "❌ Failed to get response from Groq API." | |
# Gradio ChatInterface | |
chatbot = gr.ChatInterface( | |
fn=groq_chatbot, | |
title="🧠 Groq ChatGPT Clone", | |
description="Ask anything! Get a helpful answer and 3 smart follow-up suggestions.", | |
theme="soft", | |
examples=[ | |
"What is quantum computing?", | |
"How does e-commerce logistics work?", | |
"Explain photosynthesis" | |
] | |
) | |
if __name__ == "__main__": | |
chatbot.launch() | |