Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import os
|
|
@@ -7,143 +8,154 @@ from datetime import datetime
|
|
| 7 |
|
| 8 |
# Groq API Configuration
|
| 9 |
API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 10 |
-
API_KEY = os.getenv("GROQ_API_KEY")
|
| 11 |
|
| 12 |
-
|
| 13 |
-
if not API_KEY or API_KEY == "your-api-key-here":
|
| 14 |
-
print("β No valid API key found")
|
| 15 |
-
print("Please set GROQ_API_KEY environment variable")
|
| 16 |
-
return False
|
| 17 |
-
return True
|
| 18 |
|
| 19 |
# In-memory chat history storage
|
| 20 |
chat_history: List[Dict[str, str]] = []
|
| 21 |
|
| 22 |
-
def groq_with_memory(message: str, topic: str = "general", summarize: bool = False) -> str:
|
| 23 |
-
"""Groq API call with chat history"""
|
| 24 |
-
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
if not message.strip():
|
| 28 |
-
return "β
|
| 29 |
|
| 30 |
try:
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
chat_history.append({
|
| 33 |
"role": "user",
|
| 34 |
-
"content": message,
|
| 35 |
"topic": topic,
|
| 36 |
"timestamp": datetime.now().isoformat()
|
| 37 |
})
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
|
| 43 |
if summarize:
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
})
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
"messages": messages,
|
| 58 |
-
"temperature": 0.7
|
| 59 |
-
},
|
| 60 |
-
timeout=30
|
| 61 |
-
)
|
| 62 |
|
| 63 |
if response.status_code == 200:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
"
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
| 74 |
except Exception as e:
|
| 75 |
-
return f"β
|
| 76 |
|
| 77 |
-
def
|
| 78 |
-
"""
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
reply = groq_with_memory(message, topic)
|
| 82 |
-
return "", chat_ui + [(message, reply)]
|
| 83 |
|
| 84 |
-
def view_history(topic: str = None)
|
| 85 |
-
"""View
|
| 86 |
if not chat_history:
|
| 87 |
-
return "No history
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
def
|
| 92 |
-
"""
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
# Gradio Interface
|
| 97 |
-
with gr.Blocks(title="Groq Chat"
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
with gr.
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
gr.Markdown(f"""
|
| 124 |
-
**API Status:** {'β
Ready' if verify_api_key() else 'β Not Configured'}
|
| 125 |
-
**Endpoint:** `{API_URL}`
|
| 126 |
-
**Models Available:**
|
| 127 |
-
- `llama3-8b-8192`
|
| 128 |
-
- `llama3-70b-8192`
|
| 129 |
-
- `mixtral-8x7b-32768`
|
| 130 |
-
|
| 131 |
-
**How to set up:**
|
| 132 |
-
1. Get API key from [Groq Cloud](https://console.groq.com/)
|
| 133 |
-
2. Set environment variable:
|
| 134 |
-
```bash
|
| 135 |
-
export GROQ_API_KEY="your-api-key-here"
|
| 136 |
-
```
|
| 137 |
-
""")
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
if __name__ == "__main__":
|
| 146 |
-
|
| 147 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 148 |
-
else:
|
| 149 |
-
print("Cannot start app - no valid API key found")
|
|
|
|
| 1 |
+
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import os
|
|
|
|
| 8 |
|
| 9 |
# Groq API Configuration
|
| 10 |
API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 11 |
+
API_KEY = os.getenv("GROQ_API_KEY")
|
| 12 |
|
| 13 |
+
print(f"π API Key Found: {'Yes' if API_KEY else 'No'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# In-memory chat history storage
|
| 16 |
chat_history: List[Dict[str, str]] = []
|
| 17 |
|
| 18 |
+
def groq_with_memory(message: str, topic: str = "general", summarize: bool = False, max_history: int = 10) -> str:
|
| 19 |
+
"""Groq API call with chat history and optional summarization"""
|
| 20 |
+
|
| 21 |
+
if not API_KEY:
|
| 22 |
+
return "β No API Key found"
|
| 23 |
|
| 24 |
if not message.strip():
|
| 25 |
+
return "β Empty message"
|
| 26 |
|
| 27 |
try:
|
| 28 |
+
headers = {
|
| 29 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 30 |
+
"Content-Type": "application/json"
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# Add current message to history with timestamp and topic
|
| 34 |
chat_history.append({
|
| 35 |
"role": "user",
|
| 36 |
+
"content": message.strip(),
|
| 37 |
"topic": topic,
|
| 38 |
"timestamp": datetime.now().isoformat()
|
| 39 |
})
|
| 40 |
|
| 41 |
+
# Limit history to max_history messages
|
| 42 |
+
recent_history = chat_history[-max_history:]
|
| 43 |
+
|
| 44 |
+
# Prepare messages for API call
|
| 45 |
+
messages = [{"role": msg["role"], "content": msg["content"]} for msg in recent_history]
|
| 46 |
|
| 47 |
if summarize:
|
| 48 |
+
summary_prompt = f"Summarize this conversation about '{topic}':\n\n"
|
| 49 |
+
summary_prompt += "\n".join([f"{msg['role']}: {msg['content']}" for msg in recent_history])
|
| 50 |
+
messages.append({"role": "user", "content": summary_prompt})
|
|
|
|
| 51 |
|
| 52 |
+
payload = {
|
| 53 |
+
"model": "deepseek-r1-distill-llama-70b",
|
| 54 |
+
"messages": messages,
|
| 55 |
+
"max_tokens": 512,
|
| 56 |
+
"temperature": 0.7
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
if response.status_code == 200:
|
| 62 |
+
result = response.json()
|
| 63 |
+
if "choices" in result and result["choices"]:
|
| 64 |
+
response_content = result["choices"][0]["message"]["content"]
|
| 65 |
+
chat_history.append({
|
| 66 |
+
"role": "assistant",
|
| 67 |
+
"content": response_content,
|
| 68 |
+
"topic": topic,
|
| 69 |
+
"timestamp": datetime.now().isoformat()
|
| 70 |
+
})
|
| 71 |
+
return response_content
|
| 72 |
+
return f"β No choices in response: {result}"
|
| 73 |
+
return f"β HTTP {response.status_code}: {response.text}"
|
| 74 |
+
|
| 75 |
except Exception as e:
|
| 76 |
+
return f"β Error: {str(e)}"
|
| 77 |
|
| 78 |
+
def clear_history():
|
| 79 |
+
"""Clear the chat history"""
|
| 80 |
+
chat_history.clear()
|
| 81 |
+
return "β
Chat history cleared"
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
def view_history(topic: str = None):
|
| 84 |
+
"""View chat history with optional topic filter"""
|
| 85 |
if not chat_history:
|
| 86 |
+
return "β No chat history available"
|
| 87 |
+
|
| 88 |
+
filtered = [msg for msg in chat_history if topic is None or msg["topic"] == topic]
|
| 89 |
+
return "\n".join(
|
| 90 |
+
f"[{msg['timestamp']}] {msg['role'].capitalize()}: {msg['content']}"
|
| 91 |
+
for msg in filtered
|
| 92 |
+
)
|
| 93 |
|
| 94 |
+
def manual_curl_example():
|
| 95 |
+
"""Generate example curl command"""
|
| 96 |
+
if not API_KEY:
|
| 97 |
+
return "β No API key available"
|
| 98 |
+
return f"""curl -X POST "{API_URL}" \\
|
| 99 |
+
-H "Authorization: Bearer {API_KEY}" \\
|
| 100 |
+
-H "Content-Type: application/json" \\
|
| 101 |
+
-d '{{"model": "llama3-8b-8192", "messages": [{{"role": "user", "content": "Hello"}}]}}'
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def process_message(message: str, topic: str, summarize: bool):
|
| 105 |
+
"""Process message and clear input"""
|
| 106 |
+
response = groq_with_memory(message, topic, summarize)
|
| 107 |
+
return response, ""
|
| 108 |
|
| 109 |
# Gradio Interface
|
| 110 |
+
with gr.Blocks(title="Groq Chat Debugger") as demo:
|
| 111 |
+
gr.Markdown("## π¬ Groq API Chat Interface")
|
| 112 |
+
|
| 113 |
+
with gr.Tab("Chat"):
|
| 114 |
+
with gr.Row():
|
| 115 |
+
with gr.Column():
|
| 116 |
+
msg_input = gr.Textbox(
|
| 117 |
+
label="Your Message",
|
| 118 |
+
value="Hello, how can you help me today?"
|
| 119 |
+
)
|
| 120 |
+
topic_input = gr.Textbox(
|
| 121 |
+
label="Topic",
|
| 122 |
+
value="general"
|
| 123 |
+
)
|
| 124 |
+
summarize_cb = gr.Checkbox(label="Summarize conversation")
|
| 125 |
+
send_btn = gr.Button("Send", variant="primary")
|
| 126 |
+
|
| 127 |
+
with gr.Column():
|
| 128 |
+
response_output = gr.Textbox(
|
| 129 |
+
label="Response",
|
| 130 |
+
lines=10,
|
| 131 |
+
interactive=False
|
| 132 |
+
)
|
| 133 |
|
| 134 |
+
send_btn.click(
|
| 135 |
+
process_message,
|
| 136 |
+
inputs=[msg_input, topic_input, summarize_cb],
|
| 137 |
+
outputs=[response_output, msg_input]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
with gr.Tab("History"):
|
| 141 |
+
history_topic = gr.Textbox(label="Filter by Topic")
|
| 142 |
+
view_btn = gr.Button("View History")
|
| 143 |
+
clear_btn = gr.Button("Clear History", variant="stop")
|
| 144 |
+
history_output = gr.Textbox(label="Chat History", lines=10)
|
| 145 |
|
| 146 |
+
view_btn.click(view_history, inputs=[history_topic], outputs=[history_output])
|
| 147 |
+
clear_btn.click(clear_history, outputs=[history_output])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
with gr.Tab("API Tools"):
|
| 150 |
+
gr.Markdown(f"""
|
| 151 |
+
**API Status:** {'β
Ready' if API_KEY else 'β No API Key'}
|
| 152 |
+
**Endpoint:** `{API_URL}`
|
| 153 |
+
**Models:** `llama3-8b-8192`, `llama3-70b-8192`, `mixtral-8x7b-32768`
|
| 154 |
+
""")
|
| 155 |
+
|
| 156 |
+
curl_btn = gr.Button("Generate cURL Example")
|
| 157 |
+
curl_output = gr.Code(label="cURL Command", language="shell")
|
| 158 |
+
curl_btn.click(manual_curl_example, outputs=[curl_output])
|
| 159 |
|
| 160 |
if __name__ == "__main__":
|
| 161 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|