Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -22,7 +22,8 @@ def create_deepseek_interface():
|
|
22 |
def extract_keywords_with_llm(query):
|
23 |
if not api_key:
|
24 |
return "FW_API_KEY not set for LLM keyword extraction.", query
|
25 |
-
|
|
|
26 |
# Extract keywords using LLM (DeepSeek model)
|
27 |
url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
28 |
payload = {
|
@@ -32,7 +33,7 @@ def create_deepseek_interface():
|
|
32 |
"messages": [
|
33 |
{
|
34 |
"role": "system",
|
35 |
-
"content": "
|
36 |
},
|
37 |
{
|
38 |
"role": "user",
|
@@ -177,51 +178,49 @@ def create_deepseek_interface():
|
|
177 |
f"- **Search Term**: {search_query}\n" + \
|
178 |
f"- **Parameters**: {params}\n"
|
179 |
|
180 |
-
#
|
181 |
-
def
|
182 |
-
"""Non-streaming version that returns complete response"""
|
183 |
-
print(f"\n=== Starting query_deepseek_no_stream ===")
|
184 |
-
print(f"Message: {message}")
|
185 |
-
print(f"History length: {len(history)}")
|
186 |
-
print(f"Deep Research: {use_deep_research}")
|
187 |
-
|
188 |
if not api_key:
|
189 |
-
|
190 |
-
return
|
191 |
|
192 |
search_context = ""
|
193 |
search_info = ""
|
194 |
-
|
195 |
if use_deep_research:
|
196 |
try:
|
|
|
|
|
|
|
|
|
197 |
print(f"Deep Research activated: Starting search for '{message}'")
|
198 |
search_results = search_with_serphouse(message)
|
199 |
-
print(f"Search results received: {search_results[:100]}...")
|
200 |
|
201 |
if not search_results.startswith("Error during search") and not search_results.startswith("SERPHOUSE_API_KEY"):
|
202 |
search_context = f"""
|
203 |
Here are recent search results related to the user's question. Use this information to provide an accurate response with the latest information:
|
|
|
204 |
{search_results}
|
|
|
205 |
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.
|
206 |
When citing search results, mention the source, and ensure your answer reflects the latest information.
|
207 |
"""
|
208 |
-
search_info = "🔍 Deep Research feature activated: Generating response based on relevant web search results
|
209 |
else:
|
210 |
print(f"Search failed or no results: {search_results}")
|
211 |
-
search_info = f"🔍 Search error: {search_results}\n\n"
|
212 |
except Exception as e:
|
213 |
print(f"Exception occurred during Deep Research: {str(e)}")
|
214 |
-
search_info = f"🔍 Deep Research feature error: {str(e)}
|
215 |
|
216 |
# Prepare conversation history for API request
|
217 |
messages = []
|
218 |
-
for
|
219 |
-
|
220 |
-
|
221 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
222 |
|
223 |
# Add system message with search context if available
|
224 |
if search_context:
|
|
|
225 |
messages.insert(0, {"role": "system", "content": search_context})
|
226 |
|
227 |
# Add new user message
|
@@ -230,7 +229,7 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
230 |
# Prepare API request
|
231 |
url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
232 |
payload = {
|
233 |
-
"model": "accounts/fireworks/models/deepseek-
|
234 |
"max_tokens": 20480,
|
235 |
"top_p": 1,
|
236 |
"top_k": 40,
|
@@ -238,7 +237,7 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
238 |
"frequency_penalty": 0,
|
239 |
"temperature": 0.6,
|
240 |
"messages": messages,
|
241 |
-
"stream":
|
242 |
}
|
243 |
headers = {
|
244 |
"Accept": "application/json",
|
@@ -246,58 +245,63 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
246 |
"Authorization": f"Bearer {api_key}"
|
247 |
}
|
248 |
|
249 |
-
print(f"Calling DeepSeek API (no streaming)...")
|
250 |
-
print(f"Number of messages in conversation: {len(messages)}")
|
251 |
-
|
252 |
try:
|
253 |
-
#
|
254 |
-
|
|
|
255 |
|
256 |
-
|
257 |
-
|
258 |
|
259 |
-
|
|
|
|
|
260 |
|
261 |
-
|
262 |
-
full_response =
|
263 |
|
264 |
-
|
265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
266 |
|
267 |
-
# Return
|
268 |
-
|
269 |
|
270 |
except requests.exceptions.RequestException as e:
|
271 |
error_msg = f"API error: {str(e)}"
|
272 |
if hasattr(e, 'response') and e.response and e.response.status_code == 401:
|
273 |
error_msg = "Authentication failed. Please check your FW_API_KEY environment variable."
|
274 |
-
|
275 |
-
print(f"Request error: {error_msg}")
|
276 |
-
return history + [(message, search_info + error_msg)], ""
|
277 |
-
except Exception as e:
|
278 |
-
error_msg = f"Unexpected error: {str(e)}"
|
279 |
-
print(f"Unexpected error: {error_msg}")
|
280 |
-
import traceback
|
281 |
-
traceback.print_exc()
|
282 |
-
return history + [(message, search_info + error_msg)], ""
|
283 |
-
|
284 |
-
# Function to call DeepSeek API with streaming
|
285 |
-
def query_deepseek_streaming(message, history, use_deep_research):
|
286 |
-
print(f"\n=== Starting query_deepseek_streaming ===")
|
287 |
-
print(f"Message: {message}")
|
288 |
-
print(f"History length: {len(history)}")
|
289 |
-
print(f"Deep Research: {use_deep_research}")
|
290 |
-
|
291 |
-
# For now, use non-streaming version
|
292 |
-
return query_deepseek_no_stream(message, history, use_deep_research)
|
293 |
|
294 |
# Create Gradio interface
|
295 |
with gr.Blocks(theme="soft", fill_height=True) as demo:
|
296 |
# Header section
|
297 |
gr.Markdown(
|
298 |
"""
|
299 |
-
# 🤖
|
300 |
-
###
|
301 |
"""
|
302 |
)
|
303 |
|
@@ -310,7 +314,6 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
310 |
height=500,
|
311 |
show_label=False,
|
312 |
container=True
|
313 |
-
# Use default format
|
314 |
)
|
315 |
|
316 |
# Add Deep Research toggle and status display
|
@@ -325,14 +328,12 @@ 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 |
-
status_text = ""
|
329 |
if not serphouse_api_key:
|
330 |
-
|
331 |
if not api_key:
|
332 |
-
|
333 |
if api_key and serphouse_api_key:
|
334 |
-
|
335 |
-
api_status.value = status_text
|
336 |
|
337 |
# Input area
|
338 |
with gr.Row():
|
@@ -340,8 +341,7 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
340 |
label="Message",
|
341 |
placeholder="Enter your prompt here...",
|
342 |
show_label=False,
|
343 |
-
scale=9
|
344 |
-
lines=2
|
345 |
)
|
346 |
submit = gr.Button("Send", variant="primary", scale=1)
|
347 |
|
@@ -362,15 +362,9 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
362 |
# Error message display
|
363 |
error_box = gr.Markdown("")
|
364 |
|
365 |
-
# Function to handle submission
|
366 |
-
def handle_submit(message, history, use_deep_research):
|
367 |
-
if not message.strip():
|
368 |
-
return history, ""
|
369 |
-
return query_deepseek_no_stream(message, history, use_deep_research)
|
370 |
-
|
371 |
# Connect buttons to functions
|
372 |
submit.click(
|
373 |
-
|
374 |
inputs=[msg, chatbot, use_deep_research],
|
375 |
outputs=[chatbot, error_box]
|
376 |
).then(
|
@@ -381,7 +375,7 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
381 |
|
382 |
# Allow Enter key submission
|
383 |
msg.submit(
|
384 |
-
|
385 |
inputs=[msg, chatbot, use_deep_research],
|
386 |
outputs=[chatbot, error_box]
|
387 |
).then(
|
@@ -394,13 +388,5 @@ When citing search results, mention the source, and ensure your answer reflects
|
|
394 |
|
395 |
# Run interface
|
396 |
if __name__ == "__main__":
|
397 |
-
print("Starting Deepseek Interface...")
|
398 |
demo = create_deepseek_interface()
|
399 |
-
|
400 |
-
demo.launch(
|
401 |
-
debug=True,
|
402 |
-
share=False,
|
403 |
-
server_name="0.0.0.0",
|
404 |
-
server_port=7860,
|
405 |
-
show_error=True
|
406 |
-
)
|
|
|
22 |
def extract_keywords_with_llm(query):
|
23 |
if not api_key:
|
24 |
return "FW_API_KEY not set for LLM keyword extraction.", query
|
25 |
+
|
26 |
+
|
27 |
# Extract keywords using LLM (DeepSeek model)
|
28 |
url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
29 |
payload = {
|
|
|
33 |
"messages": [
|
34 |
{
|
35 |
"role": "system",
|
36 |
+
"content": "Extract key search terms from the user's question that would be effective for web searches. Provide these as a search query with words separated by spaces only, without commas. For example: 'Prime Minister Han Duck-soo impeachment results'"
|
37 |
},
|
38 |
{
|
39 |
"role": "user",
|
|
|
178 |
f"- **Search Term**: {search_query}\n" + \
|
179 |
f"- **Parameters**: {params}\n"
|
180 |
|
181 |
+
# Function to call DeepSeek API with streaming
|
182 |
+
def query_deepseek_streaming(message, history, use_deep_research):
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
if not api_key:
|
184 |
+
yield history, "Environment variable FW_API_KEY is not set. Please check the environment variables on the server."
|
185 |
+
return
|
186 |
|
187 |
search_context = ""
|
188 |
search_info = ""
|
|
|
189 |
if use_deep_research:
|
190 |
try:
|
191 |
+
# Start search (first message)
|
192 |
+
yield history + [(message, "🔍 Extracting optimal keywords and searching the web...")], ""
|
193 |
+
|
194 |
+
# Execute search - add logs for debugging
|
195 |
print(f"Deep Research activated: Starting search for '{message}'")
|
196 |
search_results = search_with_serphouse(message)
|
197 |
+
print(f"Search results received: {search_results[:100]}...") # Output first part of results
|
198 |
|
199 |
if not search_results.startswith("Error during search") and not search_results.startswith("SERPHOUSE_API_KEY"):
|
200 |
search_context = f"""
|
201 |
Here are recent search results related to the user's question. Use this information to provide an accurate response with the latest information:
|
202 |
+
|
203 |
{search_results}
|
204 |
+
|
205 |
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.
|
206 |
When citing search results, mention the source, and ensure your answer reflects the latest information.
|
207 |
"""
|
208 |
+
search_info = f"🔍 Deep Research feature activated: Generating response based on relevant web search results..."
|
209 |
else:
|
210 |
print(f"Search failed or no results: {search_results}")
|
|
|
211 |
except Exception as e:
|
212 |
print(f"Exception occurred during Deep Research: {str(e)}")
|
213 |
+
search_info = f"🔍 Deep Research feature error: {str(e)}"
|
214 |
|
215 |
# Prepare conversation history for API request
|
216 |
messages = []
|
217 |
+
for user, assistant in history:
|
218 |
+
messages.append({"role": "user", "content": user})
|
219 |
+
messages.append({"role": "assistant", "content": assistant})
|
|
|
220 |
|
221 |
# Add system message with search context if available
|
222 |
if search_context:
|
223 |
+
# DeepSeek model supports system messages
|
224 |
messages.insert(0, {"role": "system", "content": search_context})
|
225 |
|
226 |
# Add new user message
|
|
|
229 |
# Prepare API request
|
230 |
url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
231 |
payload = {
|
232 |
+
"model": "accounts/fireworks/models/deepseek-v3-0324",
|
233 |
"max_tokens": 20480,
|
234 |
"top_p": 1,
|
235 |
"top_k": 40,
|
|
|
237 |
"frequency_penalty": 0,
|
238 |
"temperature": 0.6,
|
239 |
"messages": messages,
|
240 |
+
"stream": True # Enable streaming
|
241 |
}
|
242 |
headers = {
|
243 |
"Accept": "application/json",
|
|
|
245 |
"Authorization": f"Bearer {api_key}"
|
246 |
}
|
247 |
|
|
|
|
|
|
|
248 |
try:
|
249 |
+
# Request streaming response
|
250 |
+
response = requests.request("POST", url, headers=headers, data=json.dumps(payload), stream=True)
|
251 |
+
response.raise_for_status() # Raise exception for HTTP errors
|
252 |
|
253 |
+
# Add message and start with initial response
|
254 |
+
new_history = history.copy()
|
255 |
|
256 |
+
# Include search_info in starting message if available
|
257 |
+
start_msg = search_info if search_info else ""
|
258 |
+
new_history.append((message, start_msg))
|
259 |
|
260 |
+
# Full response text
|
261 |
+
full_response = start_msg
|
262 |
|
263 |
+
# Process streaming response
|
264 |
+
for line in response.iter_lines():
|
265 |
+
if line:
|
266 |
+
line_text = line.decode('utf-8')
|
267 |
+
|
268 |
+
# Remove 'data: ' prefix
|
269 |
+
if line_text.startswith("data: "):
|
270 |
+
line_text = line_text[6:]
|
271 |
+
|
272 |
+
# Check for stream end message
|
273 |
+
if line_text == "[DONE]":
|
274 |
+
break
|
275 |
+
|
276 |
+
try:
|
277 |
+
# Parse JSON
|
278 |
+
chunk = json.loads(line_text)
|
279 |
+
chunk_content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
|
280 |
+
|
281 |
+
if chunk_content:
|
282 |
+
full_response += chunk_content
|
283 |
+
# Update chat history
|
284 |
+
new_history[-1] = (message, full_response)
|
285 |
+
yield new_history, ""
|
286 |
+
except json.JSONDecodeError:
|
287 |
+
continue
|
288 |
|
289 |
+
# Return final response
|
290 |
+
yield new_history, ""
|
291 |
|
292 |
except requests.exceptions.RequestException as e:
|
293 |
error_msg = f"API error: {str(e)}"
|
294 |
if hasattr(e, 'response') and e.response and e.response.status_code == 401:
|
295 |
error_msg = "Authentication failed. Please check your FW_API_KEY environment variable."
|
296 |
+
yield history, error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
297 |
|
298 |
# Create Gradio interface
|
299 |
with gr.Blocks(theme="soft", fill_height=True) as demo:
|
300 |
# Header section
|
301 |
gr.Markdown(
|
302 |
"""
|
303 |
+
# 🤖 DeepSeek V3-0324 + Research
|
304 |
+
### DeepSeek V3-0324 Latest Model + Real-time 'Deep Research' Agentic AI System @ https://discord.gg/openfreeai
|
305 |
"""
|
306 |
)
|
307 |
|
|
|
314 |
height=500,
|
315 |
show_label=False,
|
316 |
container=True
|
|
|
317 |
)
|
318 |
|
319 |
# Add Deep Research toggle and status display
|
|
|
328 |
api_status = gr.Markdown("API Status: Ready")
|
329 |
|
330 |
# Check and display API key status
|
|
|
331 |
if not serphouse_api_key:
|
332 |
+
api_status.value = "⚠️ SERPHOUSE_API_KEY is not set"
|
333 |
if not api_key:
|
334 |
+
api_status.value = "⚠️ FW_API_KEY is not set"
|
335 |
if api_key and serphouse_api_key:
|
336 |
+
api_status.value = "✅ API keys configured"
|
|
|
337 |
|
338 |
# Input area
|
339 |
with gr.Row():
|
|
|
341 |
label="Message",
|
342 |
placeholder="Enter your prompt here...",
|
343 |
show_label=False,
|
344 |
+
scale=9
|
|
|
345 |
)
|
346 |
submit = gr.Button("Send", variant="primary", scale=1)
|
347 |
|
|
|
362 |
# Error message display
|
363 |
error_box = gr.Markdown("")
|
364 |
|
|
|
|
|
|
|
|
|
|
|
|
|
365 |
# Connect buttons to functions
|
366 |
submit.click(
|
367 |
+
query_deepseek_streaming,
|
368 |
inputs=[msg, chatbot, use_deep_research],
|
369 |
outputs=[chatbot, error_box]
|
370 |
).then(
|
|
|
375 |
|
376 |
# Allow Enter key submission
|
377 |
msg.submit(
|
378 |
+
query_deepseek_streaming,
|
379 |
inputs=[msg, chatbot, use_deep_research],
|
380 |
outputs=[chatbot, error_box]
|
381 |
).then(
|
|
|
388 |
|
389 |
# Run interface
|
390 |
if __name__ == "__main__":
|
|
|
391 |
demo = create_deepseek_interface()
|
392 |
+
demo.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|