Create modules/web_tools.py
Browse files- modules/web_tools.py +32 -0
modules/web_tools.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modules/web_tools.py
|
| 2 |
+
import os
|
| 3 |
+
import aiohttp
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
|
| 6 |
+
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
|
| 7 |
+
|
| 8 |
+
async def search_web(query, language="en"):
|
| 9 |
+
url = "https://google.serper.dev/search"
|
| 10 |
+
headers = {"X-API-KEY": SERPER_API_KEY, "Content-Type": "application/json"}
|
| 11 |
+
payload = {
|
| 12 |
+
"q": query,
|
| 13 |
+
"gl": language,
|
| 14 |
+
"hl": language,
|
| 15 |
+
"num": 3
|
| 16 |
+
}
|
| 17 |
+
async with aiohttp.ClientSession() as session:
|
| 18 |
+
async with session.post(url, headers=headers, json=payload) as resp:
|
| 19 |
+
data = await resp.json()
|
| 20 |
+
return [r["link"] for r in data.get("organic", []) if "link" in r]
|
| 21 |
+
|
| 22 |
+
async def summarize_url(url):
|
| 23 |
+
try:
|
| 24 |
+
async with aiohttp.ClientSession() as session:
|
| 25 |
+
async with session.get(url, timeout=10) as resp:
|
| 26 |
+
html = await resp.text()
|
| 27 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 28 |
+
paragraphs = soup.find_all("p")
|
| 29 |
+
text = " ".join(p.get_text() for p in paragraphs[:5])
|
| 30 |
+
return {"url": url, "summary": text[:1000]}
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return {"url": url, "summary": f"Failed to summarize due to: {e}"}
|