Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,187 +3,287 @@ import requests
|
|
| 3 |
import os
|
| 4 |
from typing import List, Tuple
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
}
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
"free": True
|
| 19 |
-
},
|
| 20 |
-
"together": {
|
| 21 |
-
"url": "https://api.together.xyz/v1/chat/completions",
|
| 22 |
-
"key": os.getenv("TOGETHER_API_KEY"),
|
| 23 |
-
"model": "meta-llama/Llama-2-7b-chat-hf",
|
| 24 |
-
"free": True # $5 free credit
|
| 25 |
-
},
|
| 26 |
-
"openrouter": {
|
| 27 |
-
"url": "https://openrouter.ai/api/v1/chat/completions",
|
| 28 |
-
"key": os.getenv("OPENROUTER_API_KEY"),
|
| 29 |
-
"model": "google/gemma-7b-it:free", # Free model
|
| 30 |
-
"free": True
|
| 31 |
-
}
|
| 32 |
}
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
try:
|
| 46 |
-
# Build
|
| 47 |
-
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
|
|
|
|
|
|
| 48 |
for user_msg, bot_msg in history:
|
| 49 |
if user_msg and bot_msg:
|
| 50 |
messages.extend([
|
| 51 |
{"role": "user", "content": user_msg},
|
| 52 |
{"role": "assistant", "content": bot_msg}
|
| 53 |
])
|
|
|
|
|
|
|
| 54 |
messages.append({"role": "user", "content": message})
|
| 55 |
|
| 56 |
-
|
| 57 |
-
"Authorization": f"Bearer {config['key']}",
|
| 58 |
-
"Content-Type": "application/json"
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
# Add special headers for some APIs
|
| 62 |
-
if api_choice == "openrouter":
|
| 63 |
-
headers["HTTP-Referer"] = "https://your-app.com"
|
| 64 |
-
headers["X-Title"] = "Gradio Chat"
|
| 65 |
-
|
| 66 |
response = requests.post(
|
| 67 |
-
|
| 68 |
headers=headers,
|
| 69 |
json={
|
| 70 |
-
"model":
|
| 71 |
"messages": messages,
|
| 72 |
"temperature": 0.7,
|
| 73 |
-
"max_tokens":
|
|
|
|
|
|
|
| 74 |
},
|
| 75 |
timeout=30
|
| 76 |
)
|
| 77 |
|
| 78 |
-
# Handle
|
| 79 |
if response.status_code == 401:
|
| 80 |
-
return
|
| 81 |
-
elif response.status_code == 402:
|
| 82 |
-
return f"π³ **Payment Required ({api_choice})**\nAccount needs billing setup or credits"
|
| 83 |
elif response.status_code == 403:
|
| 84 |
-
return
|
| 85 |
elif response.status_code == 429:
|
| 86 |
-
return
|
| 87 |
-
elif response.status_code
|
| 88 |
-
return
|
|
|
|
|
|
|
| 89 |
|
| 90 |
response.raise_for_status()
|
|
|
|
|
|
|
| 91 |
result = response.json()
|
| 92 |
|
| 93 |
if "choices" in result and len(result["choices"]) > 0:
|
| 94 |
-
|
|
|
|
| 95 |
else:
|
| 96 |
-
return f"β **
|
| 97 |
|
| 98 |
except requests.exceptions.Timeout:
|
| 99 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
except Exception as e:
|
| 101 |
-
return f"β **Error
|
| 102 |
|
| 103 |
-
def
|
| 104 |
-
"""
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
def
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
with gr.Blocks(
|
| 116 |
-
|
| 117 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
|
|
|
| 119 |
with gr.Row():
|
| 120 |
-
|
| 121 |
-
choices=list(
|
| 122 |
-
value="
|
| 123 |
-
label="Select
|
| 124 |
-
info="Choose
|
| 125 |
)
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
|
|
|
| 129 |
with gr.Row():
|
| 130 |
-
|
| 131 |
-
label="Message",
|
| 132 |
-
placeholder="
|
| 133 |
-
scale=4
|
|
|
|
|
|
|
| 134 |
)
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
clear_btn = gr.Button("Clear Chat ποΈ")
|
| 138 |
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
if not message.strip():
|
| 141 |
return "", chat_history
|
| 142 |
|
|
|
|
| 143 |
history_tuples = [(h[0], h[1]) for h in chat_history if len(h) >= 2]
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
chat_history.append([message, bot_message])
|
| 146 |
return "", chat_history
|
| 147 |
|
| 148 |
# Event handlers
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
-
#
|
| 154 |
gr.Examples(
|
| 155 |
examples=[
|
| 156 |
-
["Hello!
|
| 157 |
-
["Explain
|
| 158 |
-
["Write a Python function to
|
| 159 |
-
["What's the difference between AI and
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
],
|
| 161 |
-
inputs=
|
|
|
|
| 162 |
)
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
gr.Markdown("""
|
| 165 |
---
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
**Set Environment Variables:**
|
| 177 |
-
```bash
|
| 178 |
-
export GROQ_API_KEY="your-key"
|
| 179 |
-
export TOGETHER_API_KEY="your-key"
|
| 180 |
-
export OPENROUTER_API_KEY="your-key"
|
| 181 |
-
export DEEPSEEK_API_KEY="your-key"
|
| 182 |
-
```
|
| 183 |
""")
|
| 184 |
|
| 185 |
return demo
|
| 186 |
|
|
|
|
| 187 |
if __name__ == "__main__":
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
from typing import List, Tuple
|
| 5 |
|
| 6 |
+
# Groq API Configuration
|
| 7 |
+
API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 8 |
+
API_KEY = os.getenv("GROQ_API_KEY") # This will read from HF Secrets
|
| 9 |
+
|
| 10 |
+
# Debug info (will show in HF Spaces logs)
|
| 11 |
+
print(f"π Groq API Key Status: {'β
Found' if API_KEY else 'β Missing'}")
|
| 12 |
+
if API_KEY:
|
| 13 |
+
print(f"π API Key Preview: {API_KEY[:8]}...")
|
| 14 |
+
|
| 15 |
+
headers = {
|
| 16 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 17 |
+
"Content-Type": "application/json"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
}
|
| 19 |
|
| 20 |
+
# Groq Models
|
| 21 |
+
MODELS = {
|
| 22 |
+
"llama3-8b-8192": "Llama 3 8B β‘ (Fastest)",
|
| 23 |
+
"llama3-70b-8192": "Llama 3 70B π§ (Smartest)",
|
| 24 |
+
"mixtral-8x7b-32768": "Mixtral 8x7B βοΈ (Balanced)",
|
| 25 |
+
"gemma-7b-it": "Gemma 7B π (Google)"
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
def query_groq(message: str, history: List[Tuple[str, str]], model: str) -> str:
|
| 29 |
+
"""Query Groq API with comprehensive error handling"""
|
| 30 |
|
| 31 |
+
# Check API key
|
| 32 |
+
if not API_KEY:
|
| 33 |
+
return """β **API Key Not Found**
|
| 34 |
+
|
| 35 |
+
Please set up your API key in Hugging Face Spaces:
|
| 36 |
+
|
| 37 |
+
1. Go to your Space's **Settings**
|
| 38 |
+
2. Click **Repository secrets**
|
| 39 |
+
3. Add new secret:
|
| 40 |
+
- Name: `GROQ_API_KEY`
|
| 41 |
+
- Value: Your Groq API key
|
| 42 |
+
4. Restart the Space
|
| 43 |
+
|
| 44 |
+
Get your free API key at: [console.groq.com](https://console.groq.com)"""
|
| 45 |
|
| 46 |
try:
|
| 47 |
+
# Build conversation history
|
| 48 |
+
messages = [{"role": "system", "content": "You are a helpful AI assistant powered by Groq's lightning-fast inference."}]
|
| 49 |
+
|
| 50 |
+
# Add chat history
|
| 51 |
for user_msg, bot_msg in history:
|
| 52 |
if user_msg and bot_msg:
|
| 53 |
messages.extend([
|
| 54 |
{"role": "user", "content": user_msg},
|
| 55 |
{"role": "assistant", "content": bot_msg}
|
| 56 |
])
|
| 57 |
+
|
| 58 |
+
# Add current message
|
| 59 |
messages.append({"role": "user", "content": message})
|
| 60 |
|
| 61 |
+
# Make API request
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
response = requests.post(
|
| 63 |
+
API_URL,
|
| 64 |
headers=headers,
|
| 65 |
json={
|
| 66 |
+
"model": model,
|
| 67 |
"messages": messages,
|
| 68 |
"temperature": 0.7,
|
| 69 |
+
"max_tokens": 2048,
|
| 70 |
+
"stream": False,
|
| 71 |
+
"stop": None
|
| 72 |
},
|
| 73 |
timeout=30
|
| 74 |
)
|
| 75 |
|
| 76 |
+
# Handle HTTP errors
|
| 77 |
if response.status_code == 401:
|
| 78 |
+
return "β **Authentication Failed**\nInvalid API key. Please check your GROQ_API_KEY secret."
|
|
|
|
|
|
|
| 79 |
elif response.status_code == 403:
|
| 80 |
+
return "β **Access Forbidden**\nAPI key doesn't have permission."
|
| 81 |
elif response.status_code == 429:
|
| 82 |
+
return "β **Rate Limited**\nToo many requests. Groq has generous limits, this should be rare."
|
| 83 |
+
elif response.status_code == 500:
|
| 84 |
+
return "β **Server Error**\nGroq server issue. Please try again."
|
| 85 |
+
elif response.status_code == 503:
|
| 86 |
+
return "β **Service Unavailable**\nGroq is temporarily down. Try again in a moment."
|
| 87 |
|
| 88 |
response.raise_for_status()
|
| 89 |
+
|
| 90 |
+
# Parse response
|
| 91 |
result = response.json()
|
| 92 |
|
| 93 |
if "choices" in result and len(result["choices"]) > 0:
|
| 94 |
+
content = result["choices"][0]["message"]["content"]
|
| 95 |
+
return content.strip()
|
| 96 |
else:
|
| 97 |
+
return f"β **Unexpected Response Format**\n```json\n{result}\n```"
|
| 98 |
|
| 99 |
except requests.exceptions.Timeout:
|
| 100 |
+
return "β **Timeout**\nRequest took too long (>30s). Try again."
|
| 101 |
+
except requests.exceptions.ConnectionError:
|
| 102 |
+
return "β **Connection Error**\nCannot connect to Groq API. Check internet connection."
|
| 103 |
+
except requests.exceptions.RequestException as e:
|
| 104 |
+
return f"β **Request Error**\n{str(e)}"
|
| 105 |
except Exception as e:
|
| 106 |
+
return f"β **Unexpected Error**\n{str(e)}"
|
| 107 |
|
| 108 |
+
def test_api_connection():
|
| 109 |
+
"""Test API connection and return status"""
|
| 110 |
+
if not API_KEY:
|
| 111 |
+
return "π΄ API Key Missing"
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
response = requests.post(
|
| 115 |
+
API_URL,
|
| 116 |
+
headers=headers,
|
| 117 |
+
json={
|
| 118 |
+
"model": "llama3-8b-8192",
|
| 119 |
+
"messages": [{"role": "user", "content": "test"}],
|
| 120 |
+
"max_tokens": 5
|
| 121 |
+
},
|
| 122 |
+
timeout=10
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if response.status_code == 200:
|
| 126 |
+
return "π’ Connected Successfully"
|
| 127 |
+
else:
|
| 128 |
+
return f"π΄ HTTP {response.status_code}"
|
| 129 |
+
except Exception as e:
|
| 130 |
+
return f"π΄ Connection Failed: {str(e)[:50]}"
|
| 131 |
|
| 132 |
+
def create_gradio_interface():
|
| 133 |
+
# Test connection at startup
|
| 134 |
+
connection_status = test_api_connection()
|
| 135 |
+
|
| 136 |
+
# Custom CSS for better UI
|
| 137 |
+
css = """
|
| 138 |
+
.gradio-container {
|
| 139 |
+
max-width: 800px !important;
|
| 140 |
+
margin: auto !important;
|
| 141 |
+
}
|
| 142 |
+
.chat-message {
|
| 143 |
+
padding: 10px !important;
|
| 144 |
+
}
|
| 145 |
+
"""
|
| 146 |
|
| 147 |
+
with gr.Blocks(
|
| 148 |
+
title="β‘ Groq AI Chat",
|
| 149 |
+
theme=gr.themes.Soft(primary_hue="blue"),
|
| 150 |
+
css=css
|
| 151 |
+
) as demo:
|
| 152 |
+
|
| 153 |
+
# Header
|
| 154 |
+
gr.Markdown("""
|
| 155 |
+
# β‘ Groq AI Chat
|
| 156 |
+
### Lightning-fast AI responses powered by Groq's LPUβ’
|
| 157 |
+
""")
|
| 158 |
+
|
| 159 |
+
# Status indicator
|
| 160 |
+
with gr.Row():
|
| 161 |
+
gr.Markdown(f"**Connection Status:** {connection_status}")
|
| 162 |
|
| 163 |
+
# Model selector
|
| 164 |
with gr.Row():
|
| 165 |
+
model_dropdown = gr.Dropdown(
|
| 166 |
+
choices=list(MODELS.keys()),
|
| 167 |
+
value="llama3-8b-8192",
|
| 168 |
+
label="π€ Select AI Model",
|
| 169 |
+
info="Choose the model that best fits your needs"
|
| 170 |
)
|
| 171 |
|
| 172 |
+
# Chat interface
|
| 173 |
+
chatbot = gr.Chatbot(
|
| 174 |
+
label="π¬ Chat History",
|
| 175 |
+
height=500,
|
| 176 |
+
bubble_full_width=False,
|
| 177 |
+
show_copy_button=True
|
| 178 |
+
)
|
| 179 |
|
| 180 |
+
# Input area
|
| 181 |
with gr.Row():
|
| 182 |
+
msg_textbox = gr.Textbox(
|
| 183 |
+
label="βοΈ Your Message",
|
| 184 |
+
placeholder="Ask me anything... Groq responses are incredibly fast!",
|
| 185 |
+
scale=4,
|
| 186 |
+
lines=2,
|
| 187 |
+
max_lines=5
|
| 188 |
)
|
| 189 |
+
send_button = gr.Button("Send β‘", variant="primary", scale=1)
|
|
|
|
|
|
|
| 190 |
|
| 191 |
+
# Control buttons
|
| 192 |
+
with gr.Row():
|
| 193 |
+
clear_button = gr.Button("ποΈ Clear Chat", variant="secondary")
|
| 194 |
+
|
| 195 |
+
# Chat logic
|
| 196 |
+
def respond(message: str, chat_history: List[List[str]], model: str):
|
| 197 |
if not message.strip():
|
| 198 |
return "", chat_history
|
| 199 |
|
| 200 |
+
# Convert gradio format to API format
|
| 201 |
history_tuples = [(h[0], h[1]) for h in chat_history if len(h) >= 2]
|
| 202 |
+
|
| 203 |
+
# Get AI response
|
| 204 |
+
bot_message = query_groq(message.strip(), history_tuples, model)
|
| 205 |
+
|
| 206 |
+
# Update chat history
|
| 207 |
chat_history.append([message, bot_message])
|
| 208 |
return "", chat_history
|
| 209 |
|
| 210 |
# Event handlers
|
| 211 |
+
msg_textbox.submit(
|
| 212 |
+
respond,
|
| 213 |
+
inputs=[msg_textbox, chatbot, model_dropdown],
|
| 214 |
+
outputs=[msg_textbox, chatbot]
|
| 215 |
+
)
|
| 216 |
+
send_button.click(
|
| 217 |
+
respond,
|
| 218 |
+
inputs=[msg_textbox, chatbot, model_dropdown],
|
| 219 |
+
outputs=[msg_textbox, chatbot]
|
| 220 |
+
)
|
| 221 |
+
clear_button.click(
|
| 222 |
+
lambda: [],
|
| 223 |
+
outputs=chatbot
|
| 224 |
+
)
|
| 225 |
|
| 226 |
+
# Example prompts
|
| 227 |
gr.Examples(
|
| 228 |
examples=[
|
| 229 |
+
["Hello! What makes Groq special?"],
|
| 230 |
+
["Explain quantum computing in simple terms"],
|
| 231 |
+
["Write a Python function to find prime numbers"],
|
| 232 |
+
["What's the difference between AI, ML, and Deep Learning?"],
|
| 233 |
+
["Help me debug this error: 'TypeError: 'str' object is not callable'"],
|
| 234 |
+
["Create a simple REST API with FastAPI"],
|
| 235 |
+
["Explain the concept of recursion with examples"],
|
| 236 |
+
["What are the latest trends in web development?"]
|
| 237 |
],
|
| 238 |
+
inputs=msg_textbox,
|
| 239 |
+
label="π‘ Try these examples:"
|
| 240 |
)
|
| 241 |
|
| 242 |
+
# Information accordion
|
| 243 |
+
with gr.Accordion("βΉοΈ About Groq & Models", open=False):
|
| 244 |
+
gr.Markdown(f"""
|
| 245 |
+
**π Why Groq is Amazing:**
|
| 246 |
+
- β‘ **Fastest AI inference** in the world (500+ tokens/second)
|
| 247 |
+
- π **Generous free tier** with high rate limits
|
| 248 |
+
- π **Real-time responses** feel like magic
|
| 249 |
+
- π― **Consistent quality** across all models
|
| 250 |
+
|
| 251 |
+
**π€ Available Models:**
|
| 252 |
+
{chr(10).join([f"- **{model}**: {desc}" for model, desc in MODELS.items()])}
|
| 253 |
+
|
| 254 |
+
**π§ Technical Details:**
|
| 255 |
+
- Powered by Groq's custom LPUβ’ (Language Processing Unit)
|
| 256 |
+
- Optimized for transformer model inference
|
| 257 |
+
- Supports context windows up to 32K tokens
|
| 258 |
+
- Enterprise-grade reliability and security
|
| 259 |
+
""")
|
| 260 |
+
|
| 261 |
+
# Footer
|
| 262 |
gr.Markdown("""
|
| 263 |
---
|
| 264 |
+
**π Setup Instructions:**
|
| 265 |
+
1. Get free API key: [console.groq.com](https://console.groq.com)
|
| 266 |
+
2. Add to HF Spaces: Settings β Repository secrets β `GROQ_API_KEY`
|
| 267 |
+
3. Restart your Space and enjoy lightning-fast AI!
|
| 268 |
+
|
| 269 |
+
**π‘ Tips:**
|
| 270 |
+
- Groq excels at coding, explanations, and creative tasks
|
| 271 |
+
- Try different models to see which fits your use case
|
| 272 |
+
- The speed difference is immediately noticeable!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
""")
|
| 274 |
|
| 275 |
return demo
|
| 276 |
|
| 277 |
+
# Create and launch the interface
|
| 278 |
if __name__ == "__main__":
|
| 279 |
+
print("π Initializing Groq Chat Interface...")
|
| 280 |
+
print(f"π API Key Status: {'β
Ready' if API_KEY else 'β Please add GROQ_API_KEY to secrets'}")
|
| 281 |
+
|
| 282 |
+
demo = create_gradio_interface()
|
| 283 |
+
demo.launch(
|
| 284 |
+
server_name="0.0.0.0",
|
| 285 |
+
server_port=7860,
|
| 286 |
+
show_error=True,
|
| 287 |
+
show_api=False, # Hide API docs for cleaner interface
|
| 288 |
+
favicon_path=None
|
| 289 |
+
)
|