Spaces:
Running on Zero
Running on Zero
Update agent/tools/web.py
Browse files- agent/tools/web.py +95 -18
agent/tools/web.py
CHANGED
|
@@ -27,32 +27,109 @@ def web_search(query: str) -> str:
|
|
| 27 |
return f"Web search error: {e}"
|
| 28 |
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
-
headers = {
|
| 35 |
-
"User-Agent": (
|
| 36 |
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 37 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 38 |
-
"Chrome/124.0.0.0 Safari/537.36"
|
| 39 |
-
)
|
| 40 |
-
}
|
| 41 |
response = requests.get(url, headers=headers, timeout=20)
|
| 42 |
response.raise_for_status()
|
| 43 |
|
| 44 |
-
#
|
| 45 |
if response.content[:4] == b"%PDF":
|
| 46 |
reader = PdfReader(io.BytesIO(response.content))
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
text = " ".join(soup.get_text(separator=" ").split())
|
| 55 |
-
return text[:5500]
|
| 56 |
except Exception as e:
|
| 57 |
return f"Error fetching webpage: {e}"
|
| 58 |
|
|
|
|
| 27 |
return f"Web search error: {e}"
|
| 28 |
|
| 29 |
|
| 30 |
+
_PAGE_CACHE: dict[str, str] = {}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _fetch_raw_text(url: str) -> str:
|
| 34 |
+
"""Fetch full text from a URL (PDF, HTML, or Jina Reader fallback)."""
|
| 35 |
+
if url in _PAGE_CACHE:
|
| 36 |
+
return _PAGE_CACHE[url]
|
| 37 |
+
|
| 38 |
+
headers = {
|
| 39 |
+
"User-Agent": (
|
| 40 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 41 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 42 |
+
"Chrome/124.0.0.0 Safari/537.36"
|
| 43 |
+
)
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
text = ""
|
| 47 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
response = requests.get(url, headers=headers, timeout=20)
|
| 49 |
response.raise_for_status()
|
| 50 |
|
| 51 |
+
# 1. Raw PDF bytes
|
| 52 |
if response.content[:4] == b"%PDF":
|
| 53 |
reader = PdfReader(io.BytesIO(response.content))
|
| 54 |
+
text = "\n".join(page.extract_text() or "" for page in reader.pages)
|
| 55 |
+
else:
|
| 56 |
+
# 2. Standard HTML
|
| 57 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 58 |
+
for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
|
| 59 |
+
tag.decompose()
|
| 60 |
+
text = " ".join(soup.get_text(separator=" ").split())
|
| 61 |
+
except Exception:
|
| 62 |
+
text = ""
|
| 63 |
|
| 64 |
+
# 3. Fallback to Jina Reader if blocked, empty, or JS-walled
|
| 65 |
+
if len(text) < 400 or "just a moment" in text[:300].lower() or "enable javascript" in text[:300].lower():
|
| 66 |
+
try:
|
| 67 |
+
jina_resp = requests.get(
|
| 68 |
+
f"https://r.jina.ai/{url}",
|
| 69 |
+
headers={"User-Agent": headers["User-Agent"]},
|
| 70 |
+
timeout=25,
|
| 71 |
+
)
|
| 72 |
+
if jina_resp.status_code == 200 and len(jina_resp.text) > len(text):
|
| 73 |
+
text = jina_resp.text
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
if not text:
|
| 78 |
+
return ""
|
| 79 |
+
|
| 80 |
+
_PAGE_CACHE[url] = text
|
| 81 |
+
return text
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@tool
|
| 85 |
+
def fetch_webpage(url: str, search_term: str = "", offset: int = 0) -> str:
|
| 86 |
+
"""Fetch a webpage or PDF URL.
|
| 87 |
+
- Use `search_term` to jump directly to a keyword/section (e.g., 'Discography', '1977', 'NASA').
|
| 88 |
+
- Use `offset` (character index) to read further down a long page.
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
full_text = _fetch_raw_text(url)
|
| 92 |
+
if not full_text:
|
| 93 |
+
return f"Error: Could not extract readable text from {url}."
|
| 94 |
+
|
| 95 |
+
total_len = len(full_text)
|
| 96 |
+
chunk_size = 5000
|
| 97 |
+
|
| 98 |
+
# Mode A: Keyword search inside the page
|
| 99 |
+
if search_term:
|
| 100 |
+
matches = [
|
| 101 |
+
m.start()
|
| 102 |
+
for m in re.finditer(re.escape(search_term), full_text, re.IGNORECASE)
|
| 103 |
+
]
|
| 104 |
+
if not matches:
|
| 105 |
+
return (
|
| 106 |
+
f"[Term '{search_term}' not found in {total_len} chars. "
|
| 107 |
+
f"Showing start of page instead:]\n\n{full_text[:3500]}"
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
snippets = []
|
| 111 |
+
used_ranges = []
|
| 112 |
+
for pos in matches[:3]:
|
| 113 |
+
start = max(0, pos - 700)
|
| 114 |
+
end = min(total_len, pos + 1000)
|
| 115 |
+
if any(start < u_end and end > u_start for u_start, u_end in used_ranges):
|
| 116 |
+
continue
|
| 117 |
+
used_ranges.append((start, end))
|
| 118 |
+
snippets.append(f"--- Match at char {pos} ---\n{full_text[start:end]}")
|
| 119 |
+
|
| 120 |
+
header = f"[Found {len(matches)} match(es) for '{search_term}' in {total_len} chars]"
|
| 121 |
+
return f"{header}\n\n" + "\n\n".join(snippets)[:5500]
|
| 122 |
+
|
| 123 |
+
# Mode B: Sequential / offset reading
|
| 124 |
+
offset = max(0, offset)
|
| 125 |
+
chunk = full_text[offset : offset + chunk_size]
|
| 126 |
+
end_pos = min(total_len, offset + chunk_size)
|
| 127 |
+
header = (
|
| 128 |
+
f"[Showing chars {offset}-{end_pos} of {total_len}. "
|
| 129 |
+
f"Pass search_term='...' or offset={end_pos} to read more.]"
|
| 130 |
+
)
|
| 131 |
+
return f"{header}\n\n{chunk}"
|
| 132 |
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
return f"Error fetching webpage: {e}"
|
| 135 |
|