Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -179,21 +179,32 @@ def create_deepseek_interface():
|
|
179 |
|
180 |
# Function to call DeepSeek API with streaming
|
181 |
def query_deepseek_streaming(message, history, use_deep_research):
|
|
|
|
|
|
|
|
|
|
|
182 |
if not api_key:
|
183 |
-
|
|
|
184 |
return
|
185 |
|
186 |
search_context = ""
|
187 |
search_info = ""
|
|
|
|
|
|
|
|
|
188 |
if use_deep_research:
|
189 |
try:
|
190 |
-
#
|
191 |
-
|
|
|
192 |
|
193 |
-
# Execute search
|
194 |
print(f"Deep Research activated: Starting search for '{message}'")
|
195 |
search_results = search_with_serphouse(message)
|
196 |
-
print(f"Search results received: {search_results[:100]}...")
|
197 |
|
198 |
if not search_results.startswith("Error during search") and not search_results.startswith("SERPHOUSE_API_KEY"):
|
199 |
search_context = f"""
|
@@ -202,22 +213,27 @@ Here are recent search results related to the user's question. Use this informat
|
|
202 |
Based on the above search results, answer the user's question. If you cannot find a clear answer in the search results, use your knowledge to provide the best answer.
|
203 |
When citing search results, mention the source, and ensure your answer reflects the latest information.
|
204 |
"""
|
205 |
-
search_info =
|
206 |
else:
|
207 |
print(f"Search failed or no results: {search_results}")
|
|
|
208 |
except Exception as e:
|
209 |
print(f"Exception occurred during Deep Research: {str(e)}")
|
210 |
-
search_info = f"🔍 Deep Research feature error: {str(e)}"
|
|
|
|
|
|
|
|
|
211 |
|
212 |
# Prepare conversation history for API request
|
213 |
messages = []
|
214 |
for user, assistant in history:
|
215 |
-
|
216 |
-
|
|
|
217 |
|
218 |
# Add system message with search context if available
|
219 |
if search_context:
|
220 |
-
# DeepSeek model supports system messages
|
221 |
messages.insert(0, {"role": "system", "content": search_context})
|
222 |
|
223 |
# Add new user message
|
@@ -234,7 +250,7 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
234 |
"frequency_penalty": 0,
|
235 |
"temperature": 0.6,
|
236 |
"messages": messages,
|
237 |
-
"stream": True
|
238 |
}
|
239 |
headers = {
|
240 |
"Accept": "application/json",
|
@@ -242,20 +258,18 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
242 |
"Authorization": f"Bearer {api_key}"
|
243 |
}
|
244 |
|
|
|
|
|
|
|
245 |
try:
|
246 |
-
|
247 |
-
response
|
248 |
-
response.raise_for_status() # Raise exception for HTTP errors
|
249 |
-
|
250 |
-
# Add message and start with initial response
|
251 |
-
new_history = history.copy()
|
252 |
|
253 |
-
|
254 |
-
start_msg = search_info if search_info else ""
|
255 |
-
new_history.append((message, start_msg))
|
256 |
|
257 |
# Full response text
|
258 |
-
full_response =
|
|
|
259 |
|
260 |
# Process streaming response
|
261 |
for line in response.iter_lines():
|
@@ -268,29 +282,61 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
268 |
|
269 |
# Check for stream end message
|
270 |
if line_text == "[DONE]":
|
|
|
271 |
break
|
272 |
|
273 |
try:
|
274 |
# Parse JSON
|
275 |
chunk = json.loads(line_text)
|
276 |
-
chunk_content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
|
277 |
|
278 |
-
if
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
284 |
continue
|
285 |
|
286 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
287 |
yield new_history, ""
|
288 |
|
289 |
except requests.exceptions.RequestException as e:
|
290 |
error_msg = f"API error: {str(e)}"
|
291 |
if hasattr(e, 'response') and e.response and e.response.status_code == 401:
|
292 |
error_msg = "Authentication failed. Please check your FW_API_KEY environment variable."
|
293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
294 |
|
295 |
# Create Gradio interface
|
296 |
with gr.Blocks(theme="soft", fill_height=True) as demo:
|
@@ -310,7 +356,8 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
310 |
chatbot = gr.Chatbot(
|
311 |
height=500,
|
312 |
show_label=False,
|
313 |
-
container=True
|
|
|
314 |
)
|
315 |
|
316 |
# Add Deep Research toggle and status display
|
@@ -325,12 +372,14 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
325 |
api_status = gr.Markdown("API Status: Ready")
|
326 |
|
327 |
# Check and display API key status
|
|
|
328 |
if not serphouse_api_key:
|
329 |
-
|
330 |
if not api_key:
|
331 |
-
|
332 |
if api_key and serphouse_api_key:
|
333 |
-
|
|
|
334 |
|
335 |
# Input area
|
336 |
with gr.Row():
|
@@ -338,7 +387,8 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
338 |
label="Message",
|
339 |
placeholder="Enter your prompt here...",
|
340 |
show_label=False,
|
341 |
-
scale=9
|
|
|
342 |
)
|
343 |
submit = gr.Button("Send", variant="primary", scale=1)
|
344 |
|
@@ -363,7 +413,8 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
363 |
submit.click(
|
364 |
query_deepseek_streaming,
|
365 |
inputs=[msg, chatbot, use_deep_research],
|
366 |
-
outputs=[chatbot, error_box]
|
|
|
367 |
).then(
|
368 |
lambda: "",
|
369 |
None,
|
@@ -374,7 +425,8 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
374 |
msg.submit(
|
375 |
query_deepseek_streaming,
|
376 |
inputs=[msg, chatbot, use_deep_research],
|
377 |
-
outputs=[chatbot, error_box]
|
|
|
378 |
).then(
|
379 |
lambda: "",
|
380 |
None,
|
@@ -386,4 +438,4 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
386 |
# Run interface
|
387 |
if __name__ == "__main__":
|
388 |
demo = create_deepseek_interface()
|
389 |
-
demo.launch(debug=True)
|
|
|
179 |
|
180 |
# Function to call DeepSeek API with streaming
|
181 |
def query_deepseek_streaming(message, history, use_deep_research):
|
182 |
+
print(f"\n=== Starting query_deepseek_streaming ===")
|
183 |
+
print(f"Message: {message}")
|
184 |
+
print(f"History length: {len(history)}")
|
185 |
+
print(f"Deep Research: {use_deep_research}")
|
186 |
+
|
187 |
if not api_key:
|
188 |
+
error_msg = "Environment variable FW_API_KEY is not set. Please check the environment variables on the server."
|
189 |
+
yield history + [(message, error_msg)], error_msg
|
190 |
return
|
191 |
|
192 |
search_context = ""
|
193 |
search_info = ""
|
194 |
+
|
195 |
+
# Create new history with the user message
|
196 |
+
new_history = history + [(message, "")]
|
197 |
+
|
198 |
if use_deep_research:
|
199 |
try:
|
200 |
+
# Update with search status
|
201 |
+
new_history[-1] = (message, "🔍 Extracting optimal keywords and searching the web...")
|
202 |
+
yield new_history, ""
|
203 |
|
204 |
+
# Execute search
|
205 |
print(f"Deep Research activated: Starting search for '{message}'")
|
206 |
search_results = search_with_serphouse(message)
|
207 |
+
print(f"Search results received: {search_results[:100]}...")
|
208 |
|
209 |
if not search_results.startswith("Error during search") and not search_results.startswith("SERPHOUSE_API_KEY"):
|
210 |
search_context = f"""
|
|
|
213 |
Based on the above search results, answer the user's question. If you cannot find a clear answer in the search results, use your knowledge to provide the best answer.
|
214 |
When citing search results, mention the source, and ensure your answer reflects the latest information.
|
215 |
"""
|
216 |
+
search_info = "🔍 Deep Research feature activated: Generating response based on relevant web search results...\n\n"
|
217 |
else:
|
218 |
print(f"Search failed or no results: {search_results}")
|
219 |
+
search_info = f"🔍 Search error: {search_results}\n\n"
|
220 |
except Exception as e:
|
221 |
print(f"Exception occurred during Deep Research: {str(e)}")
|
222 |
+
search_info = f"🔍 Deep Research feature error: {str(e)}\n\n"
|
223 |
+
|
224 |
+
# Update history with search info
|
225 |
+
new_history[-1] = (message, search_info)
|
226 |
+
yield new_history, ""
|
227 |
|
228 |
# Prepare conversation history for API request
|
229 |
messages = []
|
230 |
for user, assistant in history:
|
231 |
+
if user and assistant: # Only add non-empty messages
|
232 |
+
messages.append({"role": "user", "content": user})
|
233 |
+
messages.append({"role": "assistant", "content": assistant})
|
234 |
|
235 |
# Add system message with search context if available
|
236 |
if search_context:
|
|
|
237 |
messages.insert(0, {"role": "system", "content": search_context})
|
238 |
|
239 |
# Add new user message
|
|
|
250 |
"frequency_penalty": 0,
|
251 |
"temperature": 0.6,
|
252 |
"messages": messages,
|
253 |
+
"stream": True
|
254 |
}
|
255 |
headers = {
|
256 |
"Accept": "application/json",
|
|
|
258 |
"Authorization": f"Bearer {api_key}"
|
259 |
}
|
260 |
|
261 |
+
print(f"Calling DeepSeek API...")
|
262 |
+
print(f"Number of messages in conversation: {len(messages)}")
|
263 |
+
|
264 |
try:
|
265 |
+
response = requests.post(url, headers=headers, json=payload, stream=True)
|
266 |
+
response.raise_for_status()
|
|
|
|
|
|
|
|
|
267 |
|
268 |
+
print(f"API Response Status: {response.status_code}")
|
|
|
|
|
269 |
|
270 |
# Full response text
|
271 |
+
full_response = search_info
|
272 |
+
chunk_count = 0
|
273 |
|
274 |
# Process streaming response
|
275 |
for line in response.iter_lines():
|
|
|
282 |
|
283 |
# Check for stream end message
|
284 |
if line_text == "[DONE]":
|
285 |
+
print(f"Stream completed. Total chunks: {chunk_count}")
|
286 |
break
|
287 |
|
288 |
try:
|
289 |
# Parse JSON
|
290 |
chunk = json.loads(line_text)
|
|
|
291 |
|
292 |
+
# Check if there's content in the chunk
|
293 |
+
if "choices" in chunk and len(chunk["choices"]) > 0:
|
294 |
+
delta = chunk["choices"][0].get("delta", {})
|
295 |
+
chunk_content = delta.get("content", "")
|
296 |
+
|
297 |
+
if chunk_content:
|
298 |
+
chunk_count += 1
|
299 |
+
full_response += chunk_content
|
300 |
+
|
301 |
+
# Update chat history
|
302 |
+
new_history[-1] = (message, full_response)
|
303 |
+
|
304 |
+
# Debug: Print first few chunks
|
305 |
+
if chunk_count <= 5:
|
306 |
+
print(f"Chunk {chunk_count}: {repr(chunk_content[:50])}")
|
307 |
+
|
308 |
+
# Yield updated history
|
309 |
+
yield new_history, ""
|
310 |
+
|
311 |
+
except json.JSONDecodeError as e:
|
312 |
+
print(f"JSON decode error: {e}")
|
313 |
+
print(f"Line content: {repr(line_text[:100])}")
|
314 |
continue
|
315 |
|
316 |
+
# Final update
|
317 |
+
if not full_response or full_response == search_info:
|
318 |
+
# If no response was generated, add an error message
|
319 |
+
full_response = search_info + "Error: No response generated from the model. Please try again."
|
320 |
+
new_history[-1] = (message, full_response)
|
321 |
+
|
322 |
+
print(f"Final response length: {len(full_response)}")
|
323 |
yield new_history, ""
|
324 |
|
325 |
except requests.exceptions.RequestException as e:
|
326 |
error_msg = f"API error: {str(e)}"
|
327 |
if hasattr(e, 'response') and e.response and e.response.status_code == 401:
|
328 |
error_msg = "Authentication failed. Please check your FW_API_KEY environment variable."
|
329 |
+
|
330 |
+
print(f"Request error: {error_msg}")
|
331 |
+
new_history[-1] = (message, search_info + error_msg)
|
332 |
+
yield new_history, error_msg
|
333 |
+
except Exception as e:
|
334 |
+
error_msg = f"Unexpected error: {str(e)}"
|
335 |
+
print(f"Unexpected error: {error_msg}")
|
336 |
+
import traceback
|
337 |
+
traceback.print_exc()
|
338 |
+
new_history[-1] = (message, search_info + error_msg)
|
339 |
+
yield new_history, error_msg
|
340 |
|
341 |
# Create Gradio interface
|
342 |
with gr.Blocks(theme="soft", fill_height=True) as demo:
|
|
|
356 |
chatbot = gr.Chatbot(
|
357 |
height=500,
|
358 |
show_label=False,
|
359 |
+
container=True,
|
360 |
+
type="tuples" # Explicitly set type
|
361 |
)
|
362 |
|
363 |
# Add Deep Research toggle and status display
|
|
|
372 |
api_status = gr.Markdown("API Status: Ready")
|
373 |
|
374 |
# Check and display API key status
|
375 |
+
status_text = ""
|
376 |
if not serphouse_api_key:
|
377 |
+
status_text = "⚠️ SERPHOUSE_API_KEY is not set"
|
378 |
if not api_key:
|
379 |
+
status_text = "⚠️ FW_API_KEY is not set"
|
380 |
if api_key and serphouse_api_key:
|
381 |
+
status_text = "✅ API keys configured"
|
382 |
+
api_status.value = status_text
|
383 |
|
384 |
# Input area
|
385 |
with gr.Row():
|
|
|
387 |
label="Message",
|
388 |
placeholder="Enter your prompt here...",
|
389 |
show_label=False,
|
390 |
+
scale=9,
|
391 |
+
lines=2
|
392 |
)
|
393 |
submit = gr.Button("Send", variant="primary", scale=1)
|
394 |
|
|
|
413 |
submit.click(
|
414 |
query_deepseek_streaming,
|
415 |
inputs=[msg, chatbot, use_deep_research],
|
416 |
+
outputs=[chatbot, error_box],
|
417 |
+
queue=True # Enable queue for streaming
|
418 |
).then(
|
419 |
lambda: "",
|
420 |
None,
|
|
|
425 |
msg.submit(
|
426 |
query_deepseek_streaming,
|
427 |
inputs=[msg, chatbot, use_deep_research],
|
428 |
+
outputs=[chatbot, error_box],
|
429 |
+
queue=True # Enable queue for streaming
|
430 |
).then(
|
431 |
lambda: "",
|
432 |
None,
|
|
|
438 |
# Run interface
|
439 |
if __name__ == "__main__":
|
440 |
demo = create_deepseek_interface()
|
441 |
+
demo.launch(debug=True, share=False, server_name="0.0.0.0", server_port=7860)
|