ncuxomun commited on
Commit
32f51ff
·
verified ·
1 Parent(s): ce08efd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +259 -14
app.py CHANGED
@@ -29,38 +29,283 @@ class AgentState(TypedDict):
29
  intermediate_steps: List[Dict[str, Any]]
30
 
31
  # --------------------- IMPROVED TOOLS ---------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  @tool
34
  def web_search(query: str, max_results: int = 10) -> str:
35
  """
36
- Search the web for information about a given query using DuckDuckGo.
37
- Provides more comprehensive results than a standard search.
38
-
39
  Args:
40
  query: The search query string.
41
  max_results: Maximum number of search results to return (default: 10)
42
-
43
  Returns:
44
- Formatted search results as a string.
45
  """
46
  try:
47
  print(f"Searching the web for: {query}")
48
 
 
 
 
 
 
49
  results = []
50
- with DDGS() as ddgs:
51
- search_results = list(ddgs.text(query, max_results=max_results))
52
 
53
- for i, result in enumerate(search_results, 1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  title = result.get('title', 'No title')
55
  body = result.get('body', 'No content')
56
  url = result.get('href', 'No URL')
57
- results.append(f"{i}. {title}\n {body}\n URL: {url}\n")
58
-
59
- if not results:
60
- return "No search results found."
61
 
62
- formatted_results = "\n".join(results)
63
- print(f"Web search found {len(results)} results")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  return formatted_results
65
  except Exception as e:
66
  print(f"Error during web search: {e}")
 
29
  intermediate_steps: List[Dict[str, Any]]
30
 
31
  # --------------------- IMPROVED TOOLS ---------------------
32
+ # Helper functions for the enhanced web search
33
+
34
+ def refine_search_query(query: str) -> str:
35
+ """
36
+ Refine the search query by adding strategic terms or removing noise.
37
+
38
+ Args:
39
+ query: Original search query
40
+
41
+ Returns:
42
+ Refined search query
43
+ """
44
+ # Simple refinements
45
+ # 1. Convert questions to keyword format
46
+ question_words = ['what', 'when', 'where', 'who', 'why', 'how']
47
+ query_lower = query.lower()
48
+
49
+ for word in question_words:
50
+ if query_lower.startswith(word):
51
+ # Remove the question word and question mark
52
+ query = re.sub(r'^' + word + r'\s+is\s+', '', query, flags=re.IGNORECASE)
53
+ query = re.sub(r'^' + word + r'\s+are\s+', '', query, flags=re.IGNORECASE)
54
+ query = re.sub(r'^' + word + r'\s+', '', query, flags=re.IGNORECASE)
55
+ query = query.rstrip('?')
56
+ break
57
+
58
+ # 2. Add specific qualifiers for more accurate results
59
+ if re.search(r'\d{4}', query): # Contains a year
60
+ # Don't add "latest" for historical queries
61
+ pass
62
+ elif any(word in query_lower for word in ['history', 'historical', 'ancient', 'past']):
63
+ # Don't add "latest" for historical queries
64
+ pass
65
+ else:
66
+ # For current topics, prefer recent information
67
+ current_year = datetime.now().year
68
+ query += f" {current_year}"
69
+
70
+ return query
71
+
72
+ def get_ddg_results(query: str, max_results: int) -> list:
73
+ """Get search results from DuckDuckGo"""
74
+ results = []
75
+ try:
76
+ with DDGS() as ddgs:
77
+ search_results = list(ddgs.text(query, max_results=max_results))
78
+ results.extend(search_results)
79
+ except Exception as e:
80
+ print(f"DuckDuckGo search error: {e}")
81
+ return results
82
+
83
+ def get_bing_results(query: str, max_results: int) -> list:
84
+ """Get search results from Bing (example - would need API key in practice)"""
85
+ # This is a placeholder for an actual Bing API implementation
86
+ # In a real implementation, you would use the Bing Web Search API
87
+ return []
88
+
89
+ def deduplicate_results(results: list) -> list:
90
+ """Remove duplicate search results based on URL or content similarity"""
91
+ seen_urls = set()
92
+ unique_results = []
93
+
94
+ for result in results:
95
+ url = result.get('href', '')
96
+ # Simple URL normalization
97
+ normalized_url = url.rstrip('/').lower()
98
+
99
+ if normalized_url and normalized_url not in seen_urls:
100
+ seen_urls.add(normalized_url)
101
+ unique_results.append(result)
102
+
103
+ return unique_results
104
+
105
+ def extract_metadata(content: str, url: str) -> dict:
106
+ """Extract additional metadata from content and URL"""
107
+ metadata = {}
108
+
109
+ # Extract date (simple regex for date patterns)
110
+ date_patterns = [
111
+ r'(\d{1,2}\s+(?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4})',
112
+ r'(\d{1,2}/\d{1,2}/\d{4})',
113
+ r'(\d{4}-\d{2}-\d{2})'
114
+ ]
115
+
116
+ for pattern in date_patterns:
117
+ date_match = re.search(pattern, content, re.IGNORECASE)
118
+ if date_match:
119
+ metadata['date'] = date_match.group(1)
120
+ break
121
+
122
+ # Extract author if present
123
+ author_patterns = [
124
+ r'By\s+([A-Z][a-z]+\s+[A-Z][a-z]+)',
125
+ r'Author[:\s]+([A-Z][a-z]+\s+[A-Z][a-z]+)'
126
+ ]
127
+
128
+ for pattern in author_patterns:
129
+ author_match = re.search(pattern, content)
130
+ if author_match:
131
+ metadata['author'] = author_match.group(1)
132
+ break
133
+
134
+ return metadata
135
+
136
+ def clean_content(content: str) -> str:
137
+ """Clean and normalize content"""
138
+ # Remove extra whitespace
139
+ cleaned = re.sub(r'\s+', ' ', content).strip()
140
+ # Truncate if too long
141
+ if len(cleaned) > 300:
142
+ cleaned = cleaned[:297] + "..."
143
+ return cleaned
144
+
145
+ def highlight_key_info(content: str, query: str) -> str:
146
+ """Highlight key information in the content related to the query"""
147
+ # Extract important keywords from the query
148
+ keywords = [w for w in query.lower().split() if w not in ['the', 'a', 'an', 'is', 'are', 'was', 'were', 'to', 'of', 'in', 'on', 'at', 'by', 'for']]
149
+
150
+ # Simple highlighting by adding context around keyword matches
151
+ highlighted = content
152
+ for keyword in keywords:
153
+ # Find position of keyword in content
154
+ keyword_pos = highlighted.lower().find(keyword)
155
+ if keyword_pos >= 0:
156
+ # Extract sentence containing the keyword
157
+ sentence_start = max(0, highlighted.rfind('.', 0, keyword_pos) + 1)
158
+ sentence_end = highlighted.find('.', keyword_pos)
159
+ if sentence_end < 0:
160
+ sentence_end = len(highlighted)
161
+
162
+ # If the sentence is too long, take a window around the keyword
163
+ if sentence_end - sentence_start > 200:
164
+ start_pos = max(0, keyword_pos - 100)
165
+ end_pos = min(len(highlighted), keyword_pos + 100)
166
+ highlighted = highlighted[start_pos:end_pos]
167
+ if start_pos > 0:
168
+ highlighted = "..." + highlighted
169
+ if end_pos < len(content):
170
+ highlighted = highlighted + "..."
171
+
172
+ return highlighted
173
+
174
+ def extract_domain(url: str) -> str:
175
+ """Extract readable domain name from URL"""
176
+ try:
177
+ domain = urlparse(url).netloc
178
+ # Remove www. prefix if present
179
+ if domain.startswith('www.'):
180
+ domain = domain[4:]
181
+ return domain
182
+ except:
183
+ return "Unknown source"
184
+
185
+ def organize_results(results: list, query: str) -> list:
186
+ """Organize results by relevance and cluster similar information"""
187
+ # This is a simplified implementation
188
+ # A more advanced version could use NLP to cluster results
189
+
190
+ # For now, just return the results as is
191
+ return results
192
+
193
+ def generate_search_summary(results: list, query: str) -> str:
194
+ """Generate a brief summary of search results"""
195
+ # Count sources by domain
196
+ domains = {}
197
+ for result in results:
198
+ url = result.get('href', '')
199
+ domain = extract_domain(url)
200
+ domains[domain] = domains.get(domain, 0) + 1
201
+
202
+ # Find most common domains
203
+ top_domains = sorted(domains.items(), key=lambda x: x[1], reverse=True)[:3]
204
+
205
+ # Create summary
206
+ summary_lines = [
207
+ f"Found {len(results)} results for '{query}'",
208
+ f"Top sources: {', '.join(f'{domain} ({count})' for domain, count in top_domains)}"
209
+ ]
210
+
211
+ # Add a note about result freshness if we have dates
212
+ dates = []
213
+ for result in results:
214
+ body = result.get('body', '')
215
+ metadata = extract_metadata(body, result.get('href', ''))
216
+ if 'date' in metadata:
217
+ dates.append(metadata['date'])
218
+
219
+ if dates:
220
+ summary_lines.append(f"Results include information from {min(dates)} to {max(dates)}")
221
+
222
+ return "\n".join(summary_lines)
223
 
224
  @tool
225
  def web_search(query: str, max_results: int = 10) -> str:
226
  """
227
+ Search the web for information about a given query using multiple search engines
228
+ and process the results for better comprehension.
229
+
230
  Args:
231
  query: The search query string.
232
  max_results: Maximum number of search results to return (default: 10)
233
+
234
  Returns:
235
+ Formatted search results as a string with enhanced metadata and summaries.
236
  """
237
  try:
238
  print(f"Searching the web for: {query}")
239
 
240
+ # Step 1: Query refinement - add strategic terms if needed
241
+ refined_query = refine_search_query(query)
242
+ print(f"Refined query: {refined_query}")
243
+
244
+ # Step 2: Get results from multiple sources
245
  results = []
246
+ metadata = {"sources": [], "query": refined_query}
 
247
 
248
+ # First try DuckDuckGo
249
+ ddg_results = get_ddg_results(refined_query, max_results)
250
+ results.extend(ddg_results)
251
+ metadata["sources"].append("DuckDuckGo")
252
+
253
+ # Try Bing if we need more results
254
+ if len(results) < max_results:
255
+ try:
256
+ remaining = max_results - len(results)
257
+ bing_results = get_bing_results(refined_query, remaining)
258
+ results.extend(bing_results)
259
+ metadata["sources"].append("Bing")
260
+ except Exception as e:
261
+ print(f"Bing search error (non-critical): {e}")
262
+
263
+ # Step 3: Deduplicate results
264
+ results = deduplicate_results(results)
265
+
266
+ # Step 4: Enhanced metadata extraction
267
+ enhanced_results = []
268
+ for i, result in enumerate(results[:max_results], 1):
269
  title = result.get('title', 'No title')
270
  body = result.get('body', 'No content')
271
  url = result.get('href', 'No URL')
 
 
 
 
272
 
273
+ # Extract additional metadata
274
+ additional_metadata = extract_metadata(body, url)
275
+
276
+ # Clean and format content
277
+ clean_body = clean_content(body)
278
+
279
+ # Highlight key information
280
+ highlighted_body = highlight_key_info(clean_body, query)
281
+
282
+ # Structure the result
283
+ formatted_result = f"{i}. {title}\n"
284
+
285
+ # Add date if available
286
+ if additional_metadata.get('date'):
287
+ formatted_result += f" Date: {additional_metadata['date']}\n"
288
+
289
+ # Add summary and source
290
+ formatted_result += f" Summary: {highlighted_body}\n"
291
+ formatted_result += f" Source: {extract_domain(url)}\n"
292
+ formatted_result += f" URL: {url}\n"
293
+
294
+ enhanced_results.append(formatted_result)
295
+
296
+ if not enhanced_results:
297
+ return "No search results found."
298
+
299
+ # Step 5: Results clustering and organization by relevance
300
+ organized_results = organize_results(enhanced_results, query)
301
+
302
+ # Add search summary
303
+ summary = generate_search_summary(results, query)
304
+
305
+ # Final formatting
306
+ formatted_results = f"SEARCH SUMMARY:\n{summary}\n\nDETAILED RESULTS:\n" + "\n".join(organized_results)
307
+ print(f"Web search found {len(organized_results)} results")
308
+
309
  return formatted_results
310
  except Exception as e:
311
  print(f"Error during web search: {e}")