Faraz-Chatbot / app.py
mfraz's picture
Update app.py
a3e9a25 verified
import gradio as gr
import requests
import os # Import os to access environment variables
# Retrieve the API key securely from Hugging Face Secrets
GROQ_API_KEY = os.getenv("myapi")
# Ensure API key is set
if not GROQ_API_KEY:
raise ValueError("Error: GROQ_API_KEY is missing! Check your Hugging Face secret settings.")
# Groq API URL
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
# Function to interact with Groq API
def chat_with_groq(prompt, history):
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
# System role for chatbot identity
messages = [{"role": "system", "content": "You are Faraz-Chatbot, an AI assistant created by Muhammad Faraz."}]
# Ensure history is in the correct format
for entry in history:
if isinstance(entry, list) and len(entry) == 2:
user_msg, bot_msg = entry
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
# Add the latest user query
messages.append({"role": "user", "content": prompt})
# Custom response when asked about the owner
if "who is your owner" in prompt.lower() or "who created you" in prompt.lower():
return "I was created by Muhammad Faraz, a passionate developer!"
payload = {"model": "llama3-8b-8192", "messages": messages}
try:
response = requests.post(GROQ_API_URL, headers=headers, json=payload)
response_data = response.json()
if response.status_code == 200:
return response_data["choices"][0]["message"]["content"]
else:
return f"API Error: {response_data.get('error', {}).get('message', 'Unknown error')}"
except Exception as e:
return f"Exception Error: {str(e)}"
# Function to handle chatbot responses
def chatbot(query, history):
if not query.strip():
return history, ""
response = chat_with_groq(query, history)
history = history + [[query, response]]
return history, ""
# Gradio Interface
with gr.Blocks() as demo:
gr.HTML("<h1 style='text-align: center; color: #00FF00; font-family: monospace;'>☠️ FARAZ-CHATBOT ☠️</h1>")
gr.HTML("<p style='text-align: center; font-size: 18px;'>🤖 How can I help you?</p>")
chatbot_interface = gr.Chatbot()
user_input = gr.Textbox(placeholder="Ask me anything...", show_label=False)
history = gr.State([])
user_input.submit(fn=chatbot, inputs=[user_input, history], outputs=[chatbot_interface, user_input])
# Launch the chatbot
demo.launch()