Spaces:
Sleeping
Sleeping
File size: 2,626 Bytes
aacb8f7 12387b6 a3e9a25 d5cde89 a3e9a25 43e923a a3e9a25 b27d388 8d46f3f 72dd052 6b471e6 d3562a0 a3e9a25 6b471e6 8d46f3f 83d78fc 8d46f3f 83d78fc 8d46f3f a3e9a25 672c29b a3e9a25 f02b085 8d46f3f f02b085 299ee1b f02b085 8d46f3f f02b085 a3e9a25 f02b085 a3e9a25 6b471e6 f02b085 a3e9a25 f02b085 672c29b f02b085 a3e9a25 f02b085 299ee1b f02b085 299ee1b a3e9a25 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
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()
|