ginipick commited on
Commit
b1da780
·
verified ·
1 Parent(s): c6faacf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +389 -0
app.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import requests
4
+ import json
5
+ import time
6
+ from dotenv import load_dotenv
7
+
8
+ # Load .env file (if it exists)
9
+ load_dotenv()
10
+
11
+ def create_deepseek_interface():
12
+ # Get API keys from environment variables
13
+ api_key = os.getenv("FW_API_KEY")
14
+ serphouse_api_key = os.getenv("SERPHOUSE_API_KEY")
15
+
16
+ if not api_key:
17
+ print("Warning: FW_API_KEY environment variable is not set.")
18
+ if not serphouse_api_key:
19
+ print("Warning: SERPHOUSE_API_KEY environment variable is not set.")
20
+
21
+ # Keyword extraction function (LLM-based)
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 = {
29
+ "model": "accounts/fireworks/models/llama4-maverick-instruct-basic",
30
+ "max_tokens": 200,
31
+ "temperature": 0.1, # Low temperature for consistent results
32
+ "messages": [
33
+ {
34
+ "role": "system",
35
+ "content": "You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside tags, and then provide your solution or response to the problem. 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'"
36
+ },
37
+ {
38
+ "role": "user",
39
+ "content": query
40
+ }
41
+ ]
42
+ }
43
+ headers = {
44
+ "Accept": "application/json",
45
+ "Content-Type": "application/json",
46
+ "Authorization": f"Bearer {api_key}"
47
+ }
48
+
49
+ try:
50
+ response = requests.post(url, headers=headers, json=payload)
51
+ response.raise_for_status()
52
+ result = response.json()
53
+
54
+ # Extract keywords from response
55
+ keywords = result["choices"][0]["message"]["content"].strip()
56
+
57
+ # Use original query if keywords are too long or improperly formatted
58
+ if len(keywords) > 100:
59
+ return f"Extracted keywords: {keywords}", query
60
+
61
+ return f"Extracted keywords: {keywords}", keywords
62
+
63
+ except Exception as e:
64
+ print(f"Error during keyword extraction: {str(e)}")
65
+ return f"Error during keyword extraction: {str(e)}", query
66
+
67
+ # Search function using SerpHouse API
68
+ def search_with_serphouse(query):
69
+ if not serphouse_api_key:
70
+ return "SERPHOUSE_API_KEY is not set."
71
+
72
+ try:
73
+ # Extract keywords
74
+ extraction_result, search_query = extract_keywords_with_llm(query)
75
+ print(f"Original query: {query}")
76
+ print(extraction_result)
77
+
78
+ # Basic GET method seems best after analyzing documentation
79
+ url = "https://api.serphouse.com/serp/live"
80
+
81
+ # Check if query is in Korean
82
+ is_korean = any('\uAC00' <= c <= '\uD7A3' for c in search_query)
83
+
84
+ # Simplified parameters
85
+ params = {
86
+ "q": search_query,
87
+ "domain": "google.com",
88
+ "serp_type": "web", # Changed to basic web search
89
+ "device": "desktop",
90
+ "lang": "ko" if is_korean else "en"
91
+ }
92
+
93
+ headers = {
94
+ "Authorization": f"Bearer {serphouse_api_key}"
95
+ }
96
+
97
+ print(f"Calling SerpHouse API with basic GET method...")
98
+ print(f"Search term: {search_query}")
99
+ print(f"Request URL: {url} - Parameters: {params}")
100
+
101
+ # Execute GET request
102
+ response = requests.get(url, headers=headers, params=params)
103
+ response.raise_for_status()
104
+
105
+ print(f"SerpHouse API response status code: {response.status_code}")
106
+ search_results = response.json()
107
+
108
+ # Check response structure
109
+ print(f"Response structure: {list(search_results.keys()) if isinstance(search_results, dict) else 'Not a dictionary'}")
110
+
111
+ # Parse and format search results (in Markdown)
112
+ formatted_results = []
113
+ formatted_results.append(f"## Search term: {search_query}\n\n")
114
+
115
+ # Handle various possible response structures
116
+ organic_results = None
117
+
118
+ # Possible response structure 1
119
+ if "results" in search_results and "organic" in search_results["results"]:
120
+ organic_results = search_results["results"]["organic"]
121
+
122
+ # Possible response structure 2
123
+ elif "organic" in search_results:
124
+ organic_results = search_results["organic"]
125
+
126
+ # Possible response structure 3 (nested results)
127
+ elif "results" in search_results and "results" in search_results["results"]:
128
+ if "organic" in search_results["results"]["results"]:
129
+ organic_results = search_results["results"]["results"]["organic"]
130
+
131
+ # Process organic results if available
132
+ if organic_results and len(organic_results) > 0:
133
+ # Output response structure
134
+ print(f"First organic result structure: {organic_results[0].keys() if len(organic_results) > 0 else 'empty'}")
135
+
136
+ for i, result in enumerate(organic_results[:5], 1): # Show only top 5 results
137
+ title = result.get("title", "No title")
138
+ snippet = result.get("snippet", "No content")
139
+ link = result.get("link", "#")
140
+ displayed_link = result.get("displayed_link", link)
141
+
142
+ # Format in Markdown (including number and link)
143
+ formatted_results.append(
144
+ f"### {i}. [{title}]({link})\n\n"
145
+ f"{snippet}\n\n"
146
+ f"**Source**: [{displayed_link}]({link})\n\n"
147
+ f"---\n\n"
148
+ )
149
+
150
+ print(f"Found {len(organic_results)} search results")
151
+ return "".join(formatted_results)
152
+
153
+ # Handle case with no results or unexpected structure
154
+ print("No search results or unexpected response structure")
155
+ print(f"Detailed response structure: {search_results.keys() if hasattr(search_results, 'keys') else 'Unclear structure'}")
156
+
157
+ # Find error messages in response
158
+ error_msg = "No search results found or response format is different than expected"
159
+ if "error" in search_results:
160
+ error_msg = search_results["error"]
161
+ elif "message" in search_results:
162
+ error_msg = search_results["message"]
163
+
164
+ return f"## Results for '{search_query}'\n\n{error_msg}"
165
+
166
+ except Exception as e:
167
+ error_msg = f"Error during search: {str(e)}"
168
+ print(error_msg)
169
+ import traceback
170
+ print(traceback.format_exc())
171
+
172
+ # Add API request details for debugging (in Markdown)
173
+ return f"## Error Occurred\n\n" + \
174
+ f"An error occurred during search: **{str(e)}**\n\n" + \
175
+ f"### API Request Details:\n" + \
176
+ f"- **URL**: {url}\n" + \
177
+ f"- **Search Term**: {search_query}\n" + \
178
+ f"- **Parameters**: {params}\n"
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
+ yield history, "Environment variable FW_API_KEY is not set. Please check the environment variables on the server."
184
+ return
185
+
186
+ search_context = ""
187
+ search_info = ""
188
+ if use_deep_research:
189
+ try:
190
+ # Start search (first message)
191
+ yield history + [(message, "🔍 Extracting optimal keywords and searching the web...")], ""
192
+
193
+ # Execute search - add logs for debugging
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]}...") # Output first part of results
197
+
198
+ if not search_results.startswith("Error during search") and not search_results.startswith("SERPHOUSE_API_KEY"):
199
+ search_context = f"""
200
+ Here are recent search results related to the user's question. Use this information to provide an accurate response with the latest information:
201
+ {search_results}
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 = f"🔍 Deep Research feature activated: Generating response based on relevant web search results..."
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
+ messages.append({"role": "user", "content": user})
216
+ messages.append({"role": "assistant", "content": assistant})
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
224
+ messages.append({"role": "user", "content": message})
225
+
226
+ # Prepare API request
227
+ url = "https://api.fireworks.ai/inference/v1/chat/completions"
228
+ payload = {
229
+ "model": "accounts/fireworks/models/llama4-maverick-instruct-basic",
230
+ "max_tokens": 20480,
231
+ "top_p": 1,
232
+ "top_k": 40,
233
+ "presence_penalty": 0,
234
+ "frequency_penalty": 0,
235
+ "temperature": 0.6,
236
+ "messages": messages,
237
+ "stream": True # Enable streaming
238
+ }
239
+ headers = {
240
+ "Accept": "application/json",
241
+ "Content-Type": "application/json",
242
+ "Authorization": f"Bearer {api_key}"
243
+ }
244
+
245
+ try:
246
+ # Request streaming response
247
+ response = requests.request("POST", url, headers=headers, data=json.dumps(payload), stream=True)
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
+ # Include search_info in starting message if available
254
+ start_msg = search_info if search_info else ""
255
+ new_history.append((message, start_msg))
256
+
257
+ # Full response text
258
+ full_response = start_msg
259
+
260
+ # Process streaming response
261
+ for line in response.iter_lines():
262
+ if line:
263
+ line_text = line.decode('utf-8')
264
+
265
+ # Remove 'data: ' prefix
266
+ if line_text.startswith("data: "):
267
+ line_text = line_text[6:]
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 chunk_content:
279
+ full_response += chunk_content
280
+ # Update chat history
281
+ new_history[-1] = (message, full_response)
282
+ yield new_history, ""
283
+ except json.JSONDecodeError:
284
+ continue
285
+
286
+ # Return final response
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
+ yield history, error_msg
294
+
295
+ # Create Gradio interface
296
+ with gr.Blocks(theme="soft", fill_height=True) as demo:
297
+ # Header section
298
+ gr.Markdown(
299
+ """
300
+ # 🤖 Llama-4-Maverick-17B + Research
301
+ ### Llama-4-Maverick-17B Model + Real-time 'Deep Research' Agentic AI System @ https://discord.gg/openfreeai
302
+ """
303
+ )
304
+
305
+ # Main layout
306
+ with gr.Row():
307
+ # Main content area
308
+ with gr.Column():
309
+ # Chat interface
310
+ chatbot = gr.Chatbot(
311
+ height=500,
312
+ show_label=False,
313
+ container=True
314
+ )
315
+
316
+ # Add Deep Research toggle and status display
317
+ with gr.Row():
318
+ with gr.Column(scale=3):
319
+ use_deep_research = gr.Checkbox(
320
+ label="Enable Deep Research",
321
+ info="Utilize optimal keyword extraction and web search for latest information",
322
+ value=False
323
+ )
324
+ with gr.Column(scale=1):
325
+ api_status = gr.Markdown("API Status: Ready")
326
+
327
+ # Check and display API key status
328
+ if not serphouse_api_key:
329
+ api_status.value = "⚠️ SERPHOUSE_API_KEY is not set"
330
+ if not api_key:
331
+ api_status.value = "⚠️ FW_API_KEY is not set"
332
+ if api_key and serphouse_api_key:
333
+ api_status.value = "✅ API keys configured"
334
+
335
+ # Input area
336
+ with gr.Row():
337
+ msg = gr.Textbox(
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
+
345
+ # Clear conversation button
346
+ with gr.Row():
347
+ clear = gr.ClearButton([msg, chatbot], value="🧹 Clear Conversation")
348
+
349
+ # Example queries
350
+ gr.Examples(
351
+ examples=[
352
+ "Explain the difference between Transformers and RNNs in deep learning.",
353
+ "Write a Python function to find prime numbers within a specific range.",
354
+ "Summarize the key concepts of reinforcement learning."
355
+ ],
356
+ inputs=msg
357
+ )
358
+
359
+ # Error message display
360
+ error_box = gr.Markdown("")
361
+
362
+ # Connect buttons to functions
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,
370
+ [msg]
371
+ )
372
+
373
+ # Allow Enter key submission
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,
381
+ [msg]
382
+ )
383
+
384
+ return demo
385
+
386
+ # Run interface
387
+ if __name__ == "__main__":
388
+ demo = create_deepseek_interface()
389
+ demo.launch(debug=True)