-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathresearch_web.py
More file actions
448 lines (352 loc) · 13.3 KB
/
research_web.py
File metadata and controls
448 lines (352 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
"""
research_web module for web searching across different search engines with improved
error handling, validation, and security features.
"""
import random
import re
import time
from functools import wraps
from typing import Dict, List, Optional, Union
import requests
from bs4 import BeautifulSoup
from langchain_community.tools import DuckDuckGoSearchResults
from pydantic import BaseModel, Field, validator
class ResearchWebError(Exception):
"""Base exception for research web errors."""
pass
class SearchConfigError(ResearchWebError):
"""Exception raised when search configuration is invalid."""
pass
class SearchRequestError(ResearchWebError):
"""Exception raised when search request fails."""
pass
class ProxyConfig(BaseModel):
"""Model for proxy configuration validation."""
server: str = Field(..., description="Proxy server address including port")
username: Optional[str] = Field(
None, description="Username for proxy authentication"
)
password: Optional[str] = Field(
None, description="Password for proxy authentication"
)
class SearchConfig(BaseModel):
"""Model for search configuration validation."""
query: str = Field(..., description="Search query")
search_engine: str = Field("duckduckgo", description="Search engine to use")
max_results: int = Field(10, description="Maximum number of results to return")
port: Optional[int] = Field(8080, description="Port for SearXNG")
timeout: int = Field(10, description="Request timeout in seconds")
proxy: Optional[Union[str, Dict, ProxyConfig]] = Field(
None, description="Proxy configuration"
)
serper_api_key: Optional[str] = Field(None, description="API key for Serper")
region: Optional[str] = Field(None, description="Country/region code")
language: str = Field("en", description="Language code")
@validator("search_engine")
def validate_search_engine(cls, v):
"""Validate search engine."""
valid_engines = {"duckduckgo", "bing", "searxng", "serper"}
if v.lower() not in valid_engines:
raise ValueError(
f"Search engine must be one of: {', '.join(valid_engines)}"
)
return v.lower()
@validator("query")
def validate_query(cls, v):
"""Validate search query."""
if not v or not isinstance(v, str):
raise ValueError("Query must be a non-empty string")
return v
@validator("max_results")
def validate_max_results(cls, v):
"""Validate max results."""
if v < 1 or v > 100:
raise ValueError("max_results must be between 1 and 100")
return v
# Define advanced PDF detection regex
PDF_REGEX = re.compile(r"\.pdf(#.*)?(\?.*)?$", re.IGNORECASE)
# Rate limiting decorator
def rate_limited(calls: int, period: int = 60):
"""
Decorator to limit the rate of function calls.
Args:
calls (int): Maximum number of calls allowed in the period.
period (int): Time period in seconds.
Returns:
Callable: Decorated function with rate limiting.
"""
min_interval = period / float(calls)
last_called = [0.0]
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
wait_time = min_interval - elapsed
if wait_time > 0:
time.sleep(wait_time)
result = func(*args, **kwargs)
last_called[0] = time.time()
return result
return wrapper
return decorator
def sanitize_search_query(query: str) -> str:
"""
Sanitizes search query to prevent injection attacks.
Args:
query (str): The search query.
Returns:
str: Sanitized query.
"""
# Remove potential command injection characters
sanitized = re.sub(r"[;&|`$()\[\]{}<>]", "", query)
# Trim whitespace
sanitized = sanitized.strip()
return sanitized
# List of user agents for rotation
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
]
def get_random_user_agent() -> str:
"""
Returns a random user agent from the list.
Returns:
str: Random user agent string.
"""
return random.choice(USER_AGENTS)
@rate_limited(calls=10, period=60)
def search_on_web(
query: str,
search_engine: str = "duckduckgo",
max_results: int = 10,
port: int = 8080,
timeout: int = 10,
proxy: Optional[Union[str, Dict, ProxyConfig]] = None,
serper_api_key: Optional[str] = None,
region: Optional[str] = None,
language: str = "en",
) -> List[str]:
"""
Search web function with improved error handling, validation, and security features.
Args:
query (str): Search query
search_engine (str): Search engine to use
max_results (int): Maximum number of results to return
port (int): Port for SearXNG
timeout (int): Request timeout in seconds
proxy (str | dict | ProxyConfig): Proxy configuration
serper_api_key (str): API key for Serper
region (str): Country/region code (e.g., 'mx' for Mexico)
language (str): Language code (e.g., 'es' for Spanish)
Returns:
List[str]: List of URLs from search results
Raises:
SearchConfigError: If search configuration is invalid
SearchRequestError: If search request fails
TimeoutError: If search request times out
"""
try:
# Sanitize query for security
sanitized_query = sanitize_search_query(query)
# Validate search configuration
config = SearchConfig(
query=sanitized_query,
search_engine=search_engine,
max_results=max_results,
port=port,
timeout=timeout,
proxy=proxy,
serper_api_key=serper_api_key,
region=region,
language=language,
)
# Format proxy once
formatted_proxy = None
if config.proxy:
formatted_proxy = format_proxy(config.proxy)
results = []
if config.search_engine == "duckduckgo":
# Create a DuckDuckGo search object with max_results
research = DuckDuckGoSearchResults(max_results=config.max_results)
# Run the search
res = research.run(config.query)
# Extract URLs using regex
results = re.findall(r"https?://[^\s,\]]+", res)
elif config.search_engine == "bing":
results = _search_bing(
config.query, config.max_results, config.timeout, formatted_proxy
)
elif config.search_engine == "searxng":
results = _search_searxng(
config.query, config.max_results, config.port, config.timeout
)
elif config.search_engine == "serper":
results = _search_serper(
config.query, config.max_results, config.serper_api_key, config.timeout
)
return filter_pdf_links(results)
except requests.Timeout:
raise TimeoutError(f"Search request timed out after {timeout} seconds")
except requests.RequestException as e:
raise SearchRequestError(f"Search request failed: {str(e)}")
except ValueError as e:
raise SearchConfigError(f"Invalid search configuration: {str(e)}")
def _search_bing(
query: str, max_results: int, timeout: int, proxy: Optional[str] = None
) -> List[str]:
"""
Helper function for Bing search with improved error handling.
Args:
query (str): Search query
max_results (int): Maximum number of results to return
timeout (int): Request timeout in seconds
proxy (str, optional): Proxy configuration
Returns:
List[str]: List of URLs from search results
"""
headers = {"User-Agent": get_random_user_agent()}
params = {"q": query, "count": max_results}
proxies = {"http": proxy, "https": proxy} if proxy else None
try:
response = requests.get(
"https://www.bing.com/search",
params=params,
headers=headers,
proxies=proxies,
timeout=timeout,
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
results = []
# Extract URLs from Bing search results
for link in soup.select("li.b_algo h2 a"):
url = link.get("href")
if url and url.startswith("http"):
results.append(url)
if len(results) >= max_results:
break
return results
except Exception as e:
raise SearchRequestError(f"Bing search failed: {str(e)}")
def _search_searxng(query: str, max_results: int, port: int, timeout: int) -> List[str]:
"""
Helper function for SearXNG search.
Args:
query (str): Search query
max_results (int): Maximum number of results to return
port (int): Port for SearXNG
timeout (int): Request timeout in seconds
Returns:
List[str]: List of URLs from search results
"""
headers = {"User-Agent": get_random_user_agent()}
params = {
"q": query,
"format": "json",
"categories": "general",
"language": "en",
"time_range": "",
"engines": "duckduckgo,bing,brave",
"results": max_results,
}
try:
response = requests.get(
f"http://localhost:{port}/search",
params=params,
headers=headers,
timeout=timeout,
)
response.raise_for_status()
json_data = response.json()
results = [result["url"] for result in json_data.get("results", [])]
return results[:max_results]
except Exception as e:
raise SearchRequestError(f"SearXNG search failed: {str(e)}")
def _search_serper(
query: str, max_results: int, api_key: str, timeout: int
) -> List[str]:
"""
Helper function for Serper search.
Args:
query (str): Search query
max_results (int): Maximum number of results to return
api_key (str): API key for Serper
timeout (int): Request timeout in seconds
Returns:
List[str]: List of URLs from search results
"""
if not api_key:
raise SearchConfigError("Serper API key is required")
headers = {"X-API-KEY": api_key, "Content-Type": "application/json"}
data = {"q": query, "num": max_results}
try:
response = requests.post(
"https://google.serper.dev/search",
json=data,
headers=headers,
timeout=timeout,
)
response.raise_for_status()
json_data = response.json()
results = []
# Extract organic search results
for item in json_data.get("organic", []):
if "link" in item:
results.append(item["link"])
if len(results) >= max_results:
break
return results
except Exception as e:
raise SearchRequestError(f"Serper search failed: {str(e)}")
def format_proxy(proxy_config: Union[str, Dict, ProxyConfig]) -> str:
"""
Format proxy configuration into a string.
Args:
proxy_config: Proxy configuration as string, dict, or ProxyConfig
Returns:
str: Formatted proxy string
"""
if isinstance(proxy_config, str):
return proxy_config
if isinstance(proxy_config, dict):
proxy_config = ProxyConfig(**proxy_config)
# Format proxy with authentication if provided
if proxy_config.username and proxy_config.password:
auth = f"{proxy_config.username}:{proxy_config.password}@"
return f"http://{auth}{proxy_config.server}"
return f"http://{proxy_config.server}"
def filter_pdf_links(urls: List[str]) -> List[str]:
"""
Filter out PDF links from search results.
Args:
urls (List[str]): List of URLs
Returns:
List[str]: Filtered list of URLs without PDFs
"""
return [url for url in urls if not PDF_REGEX.search(url)]
def verify_request_signature(
request_data: Dict, signature: str, secret_key: str
) -> bool:
"""
Verify the signature of an incoming request.
Args:
request_data (Dict): Request data to verify
signature (str): Provided signature
secret_key (str): Secret key for verification
Returns:
bool: True if signature is valid, False otherwise
"""
import hashlib
import hmac
import json
# Sort keys for consistent serialization
data_string = json.dumps(request_data, sort_keys=True)
# Create HMAC signature
computed_signature = hmac.new(
secret_key.encode(), data_string.encode(), hashlib.sha256
).hexdigest()
# Compare signatures using constant-time comparison to prevent timing attacks
return hmac.compare_digest(computed_signature, signature)