Spaces:
Build error
Build error
Update backend_app/web_search.py
Browse files- backend_app/web_search.py +23 -19
backend_app/web_search.py
CHANGED
|
@@ -1,20 +1,24 @@
|
|
| 1 |
-
|
| 2 |
-
from
|
| 3 |
-
from duckduckgo_search import
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
def web_search(query: str, max_results: int = 3) -> List[Dict]:
|
| 7 |
-
"""
|
| 8 |
-
DuckDuckGo web search (free).
|
| 9 |
-
|
| 10 |
-
"""
|
| 11 |
-
results: List[Dict] = []
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
return results
|
|
|
|
| 1 |
+
from typing import List, Dict
|
| 2 |
+
from duckduckgo_search import DDGS
|
| 3 |
+
from duckduckgo_search.exceptions import RatelimitException
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def web_search(query: str, max_results: int = 3) -> List[Dict]:
|
| 7 |
+
"""
|
| 8 |
+
DuckDuckGo web search (free).
|
| 9 |
+
If rate-limited, returns empty list instead of crashing.
|
| 10 |
+
"""
|
| 11 |
+
results: List[Dict] = []
|
| 12 |
+
try:
|
| 13 |
+
with DDGS() as ddgs:
|
| 14 |
+
for r in ddgs.text(query, max_results=max_results):
|
| 15 |
+
href = r.get("href")
|
| 16 |
+
title = r.get("title")
|
| 17 |
+
if href and title:
|
| 18 |
+
results.append({"title": title, "url": href})
|
| 19 |
+
except RatelimitException:
|
| 20 |
+
return []
|
| 21 |
+
except Exception:
|
| 22 |
+
return []
|
| 23 |
+
|
| 24 |
return results
|