Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,23 +7,66 @@ from typing import List, Tuple, Any
|
|
| 7 |
API_URL = "https://api.deepseek.com/v1/chat/completions"
|
| 8 |
API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
headers = {
|
| 11 |
"Authorization": f"Bearer {API_KEY}",
|
| 12 |
"Content-Type": "application/json"
|
| 13 |
}
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
def query_deepseek(message: str, history: List[Tuple[str, str]]) -> str:
|
| 16 |
"""Query DeepSeek API with robust error handling"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
try:
|
| 18 |
# Build conversation history
|
| 19 |
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
|
|
|
|
|
|
| 20 |
for user_msg, bot_msg in history:
|
| 21 |
-
messages
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
messages.append({"role": "user", "content": message})
|
| 26 |
|
|
|
|
| 27 |
response = requests.post(
|
| 28 |
API_URL,
|
| 29 |
headers=headers,
|
|
@@ -31,62 +74,122 @@ def query_deepseek(message: str, history: List[Tuple[str, str]]) -> str:
|
|
| 31 |
"model": "deepseek-chat",
|
| 32 |
"messages": messages,
|
| 33 |
"temperature": 0.7,
|
| 34 |
-
"max_tokens": 1024
|
|
|
|
| 35 |
},
|
| 36 |
timeout=30
|
| 37 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
response.raise_for_status()
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
-
return f"
|
| 43 |
|
| 44 |
-
# Gradio interface with explicit component definitions
|
| 45 |
def create_interface():
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
chatbot = gr.Chatbot(
|
| 50 |
label="Conversation",
|
| 51 |
-
bubble_full_width=False
|
| 52 |
-
|
| 53 |
-
msg = gr.Textbox(
|
| 54 |
-
label="Your Message",
|
| 55 |
-
placeholder="Type here...",
|
| 56 |
-
scale=7
|
| 57 |
)
|
| 58 |
|
| 59 |
with gr.Row():
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
#
|
| 64 |
-
def respond(message: str, chat_history: List[
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
return "", chat_history
|
| 68 |
|
|
|
|
| 69 |
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 70 |
submit.click(respond, [msg, chatbot], [msg, chatbot])
|
| 71 |
-
clear.click(lambda:
|
| 72 |
|
|
|
|
| 73 |
gr.Examples(
|
| 74 |
examples=[
|
| 75 |
-
["
|
| 76 |
-
["
|
| 77 |
-
["
|
|
|
|
|
|
|
| 78 |
],
|
| 79 |
inputs=msg
|
| 80 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
return demo
|
| 83 |
|
| 84 |
-
# Launch
|
| 85 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 86 |
app = create_interface()
|
| 87 |
app.launch(
|
| 88 |
server_name="0.0.0.0",
|
| 89 |
server_port=7860,
|
| 90 |
-
show_error=True
|
| 91 |
-
|
|
|
|
| 92 |
)
|
|
|
|
| 7 |
API_URL = "https://api.deepseek.com/v1/chat/completions"
|
| 8 |
API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 9 |
|
| 10 |
+
# Debug API key loading
|
| 11 |
+
print(f"π API Key Status: {'β
Loaded' if API_KEY else 'β Missing'}")
|
| 12 |
+
if API_KEY:
|
| 13 |
+
print(f"π API Key Preview: {API_KEY[:10]}...")
|
| 14 |
+
|
| 15 |
+
# Validate API key at startup
|
| 16 |
+
if not API_KEY:
|
| 17 |
+
print("β ERROR: DEEPSEEK_API_KEY environment variable not found!")
|
| 18 |
+
print("π‘ Please set your API key:")
|
| 19 |
+
print(" - Local: export DEEPSEEK_API_KEY='your-key'")
|
| 20 |
+
print(" - HF Spaces: Add to Repository Secrets")
|
| 21 |
+
|
| 22 |
headers = {
|
| 23 |
"Authorization": f"Bearer {API_KEY}",
|
| 24 |
"Content-Type": "application/json"
|
| 25 |
}
|
| 26 |
|
| 27 |
+
def test_api_connection():
|
| 28 |
+
"""Test if API is accessible"""
|
| 29 |
+
if not API_KEY:
|
| 30 |
+
return False, "API key not found"
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
response = requests.post(
|
| 34 |
+
API_URL,
|
| 35 |
+
headers=headers,
|
| 36 |
+
json={
|
| 37 |
+
"model": "deepseek-chat",
|
| 38 |
+
"messages": [{"role": "user", "content": "test"}],
|
| 39 |
+
"max_tokens": 10
|
| 40 |
+
},
|
| 41 |
+
timeout=10
|
| 42 |
+
)
|
| 43 |
+
return response.status_code == 200, f"Status: {response.status_code}"
|
| 44 |
+
except Exception as e:
|
| 45 |
+
return False, str(e)
|
| 46 |
+
|
| 47 |
def query_deepseek(message: str, history: List[Tuple[str, str]]) -> str:
|
| 48 |
"""Query DeepSeek API with robust error handling"""
|
| 49 |
+
|
| 50 |
+
# Check API key first
|
| 51 |
+
if not API_KEY:
|
| 52 |
+
return "β **API Key Missing**\n\nPlease set DEEPSEEK_API_KEY environment variable:\n- Local: `export DEEPSEEK_API_KEY='your-key'`\n- HF Spaces: Add to Repository Secrets"
|
| 53 |
+
|
| 54 |
try:
|
| 55 |
# Build conversation history
|
| 56 |
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 57 |
+
|
| 58 |
+
# Add chat history
|
| 59 |
for user_msg, bot_msg in history:
|
| 60 |
+
if user_msg and bot_msg: # Skip empty messages
|
| 61 |
+
messages.extend([
|
| 62 |
+
{"role": "user", "content": user_msg},
|
| 63 |
+
{"role": "assistant", "content": bot_msg}
|
| 64 |
+
])
|
| 65 |
+
|
| 66 |
+
# Add current message
|
| 67 |
messages.append({"role": "user", "content": message})
|
| 68 |
|
| 69 |
+
# API request
|
| 70 |
response = requests.post(
|
| 71 |
API_URL,
|
| 72 |
headers=headers,
|
|
|
|
| 74 |
"model": "deepseek-chat",
|
| 75 |
"messages": messages,
|
| 76 |
"temperature": 0.7,
|
| 77 |
+
"max_tokens": 1024,
|
| 78 |
+
"stream": False
|
| 79 |
},
|
| 80 |
timeout=30
|
| 81 |
)
|
| 82 |
+
|
| 83 |
+
# Detailed error handling
|
| 84 |
+
if response.status_code == 401:
|
| 85 |
+
return "β **Authentication Error**\nInvalid API key. Please check your DEEPSEEK_API_KEY."
|
| 86 |
+
elif response.status_code == 403:
|
| 87 |
+
return "β **Access Denied**\nAPI key doesn't have permission or quota exceeded."
|
| 88 |
+
elif response.status_code == 404:
|
| 89 |
+
return "β **API Not Found**\nCheck if the API URL is correct: https://api.deepseek.com/v1/chat/completions"
|
| 90 |
+
elif response.status_code == 429:
|
| 91 |
+
return "β **Rate Limited**\nToo many requests. Please wait and try again."
|
| 92 |
+
elif response.status_code >= 500:
|
| 93 |
+
return f"β **Server Error**\nDeepSeek server error (HTTP {response.status_code}). Try again later."
|
| 94 |
+
|
| 95 |
response.raise_for_status()
|
| 96 |
+
|
| 97 |
+
# Parse response
|
| 98 |
+
result = response.json()
|
| 99 |
+
if "choices" in result and len(result["choices"]) > 0:
|
| 100 |
+
return result["choices"][0]["message"]["content"]
|
| 101 |
+
else:
|
| 102 |
+
return f"β **Unexpected Response**\n```json\n{result}\n```"
|
| 103 |
|
| 104 |
+
except requests.exceptions.Timeout:
|
| 105 |
+
return "β **Timeout Error**\nRequest took too long. Please try again."
|
| 106 |
+
except requests.exceptions.ConnectionError:
|
| 107 |
+
return "β **Connection Error**\nCannot connect to DeepSeek API. Check your internet connection."
|
| 108 |
+
except requests.exceptions.RequestException as e:
|
| 109 |
+
return f"β **Request Error**\n{str(e)}"
|
| 110 |
except Exception as e:
|
| 111 |
+
return f"β **Unexpected Error**\n{str(e)}"
|
| 112 |
|
|
|
|
| 113 |
def create_interface():
|
| 114 |
+
# Test API connection at startup
|
| 115 |
+
api_ok, api_msg = test_api_connection()
|
| 116 |
+
status_msg = f"π’ API Connected: {api_msg}" if api_ok else f"π΄ API Issue: {api_msg}"
|
| 117 |
+
|
| 118 |
+
with gr.Blocks(
|
| 119 |
+
title="DeepSeek Chat",
|
| 120 |
+
theme=gr.themes.Soft(),
|
| 121 |
+
analytics_enabled=False
|
| 122 |
+
) as demo:
|
| 123 |
+
|
| 124 |
+
gr.Markdown("# π€ DeepSeek API Chat")
|
| 125 |
+
gr.Markdown(f"**Status:** {status_msg}")
|
| 126 |
|
| 127 |
chatbot = gr.Chatbot(
|
| 128 |
label="Conversation",
|
| 129 |
+
bubble_full_width=False,
|
| 130 |
+
height=500
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
)
|
| 132 |
|
| 133 |
with gr.Row():
|
| 134 |
+
msg = gr.Textbox(
|
| 135 |
+
label="Your Message",
|
| 136 |
+
placeholder="Type your message here...",
|
| 137 |
+
scale=4,
|
| 138 |
+
lines=2
|
| 139 |
+
)
|
| 140 |
+
with gr.Column(scale=1):
|
| 141 |
+
submit = gr.Button("Send π€", variant="primary")
|
| 142 |
+
clear = gr.Button("Clear ποΈ")
|
| 143 |
|
| 144 |
+
# Chat handler
|
| 145 |
+
def respond(message: str, chat_history: List[List[str]]) -> Tuple[str, List[List[str]]]:
|
| 146 |
+
if not message.strip():
|
| 147 |
+
return "", chat_history
|
| 148 |
+
|
| 149 |
+
# Convert to tuple format for API
|
| 150 |
+
history_tuples = [(h[0], h[1]) for h in chat_history if len(h) >= 2]
|
| 151 |
+
bot_message = query_deepseek(message.strip(), history_tuples)
|
| 152 |
+
chat_history.append([message, bot_message])
|
| 153 |
return "", chat_history
|
| 154 |
|
| 155 |
+
# Event handlers
|
| 156 |
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 157 |
submit.click(respond, [msg, chatbot], [msg, chatbot])
|
| 158 |
+
clear.click(lambda: [], None, chatbot, queue=False)
|
| 159 |
|
| 160 |
+
# Examples
|
| 161 |
gr.Examples(
|
| 162 |
examples=[
|
| 163 |
+
["Hello! Can you introduce yourself?"],
|
| 164 |
+
["Explain quantum computing in simple terms"],
|
| 165 |
+
["Write a Python function to calculate Fibonacci numbers"],
|
| 166 |
+
["What are the key features of DeepSeek?"],
|
| 167 |
+
["Help me debug this error: 'list index out of range'"]
|
| 168 |
],
|
| 169 |
inputs=msg
|
| 170 |
)
|
| 171 |
+
|
| 172 |
+
# Footer
|
| 173 |
+
gr.Markdown("""
|
| 174 |
+
---
|
| 175 |
+
**Troubleshooting:**
|
| 176 |
+
- β API Key Missing β Set `DEEPSEEK_API_KEY` environment variable
|
| 177 |
+
- β 401 Error β Invalid API key
|
| 178 |
+
- β 403 Error β No permission or quota exceeded
|
| 179 |
+
- β 404 Error β Wrong API URL
|
| 180 |
+
""")
|
| 181 |
|
| 182 |
return demo
|
| 183 |
|
| 184 |
+
# Launch configuration
|
| 185 |
if __name__ == "__main__":
|
| 186 |
+
print("π Starting DeepSeek Gradio App...")
|
| 187 |
+
|
| 188 |
app = create_interface()
|
| 189 |
app.launch(
|
| 190 |
server_name="0.0.0.0",
|
| 191 |
server_port=7860,
|
| 192 |
+
show_error=True,
|
| 193 |
+
share=False, # Set to True if you want public link
|
| 194 |
+
quiet=False
|
| 195 |
)
|