Spaces:
Sleeping

research-agent / web_tools.py
xstard's picture
Verify runtime compatibility and evidence handling
75e3836 verified
Raw History Blame Contribute Delete
7.86 kB
"""Search and fetch are separate Exa MCP calls. A snippet cannot become evidence."""
import json
import math
import re
from collections import Counter
from dataclasses import dataclass
from urllib.parse import urlsplit, urlunsplit
import httpx
class WebError(Exception):
pass
@dataclass(frozen=True)
class Hit:
title: str
url: str
snippet: str
@dataclass(frozen=True)
class Page:
title: str
url: str
text: str
def public_link(value):
try:
parsed = urlsplit(value)
if (parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname
or parsed.username or parsed.password or re.search(r"[\s<>\\\x00-\x1f]", value)):
return ""
return urlunsplit((parsed.scheme.lower(), parsed.netloc.lower(), parsed.path, parsed.query, ""))
except ValueError:
return ""
def parse_search(text):
hits = []
for block in re.split(r"(?m)(?=^Title: )", text):
match = re.match(r"Title: (.+)\nURL: (\S+)", block)
if not match or not (url := public_link(match[2])):
continue
content = re.split(r"(?m)^(?:Highlights|Text|Summary):\s*", block, maxsplit=1)
snippet = content[1].strip().removesuffix("---").strip() if len(content) > 1 else ""
hits.append(Hit(match[1].strip()[:240], url, " ".join(snippet.split())[:350]))
return hits
def parse_page(text, requested_url):
match = re.match(r"# ([^\n]+)\nURL: (\S+)[^\n]*\n(.*)", text.strip(), re.S)
if not match or not (url := public_link(match[2])):
raise WebError("Сервіс читання не повернув текст сторінки.")
body = match[3].strip()
if not body or re.match(r"(?i)^(?:failed to (?:fetch|crawl)|access denied|403 forbidden|404 not found)\b", body):
raise WebError("Текст сторінки недоступний.")
return Page(match[1][:240], url, body)
class Web:
def __init__(self, client):
self.client = client
def _call(self, name, arguments):
try:
response = self.client.post(
"https://mcp.exa.ai/mcp", timeout=35,
headers={"Accept": "application/json, text/event-stream"},
json={"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": name, "arguments": arguments}})
response.raise_for_status()
if "event-stream" in response.headers.get("content-type", ""):
events = [json.loads(line[5:]) for line in response.text.splitlines() if line.startswith("data:")]
payload = next(event for event in events if event.get("id") == 1)
else:
payload = response.json()
result = payload["result"]
if result.get("isError"):
raise WebError("Exa повідомив про помилку обробки запиту.")
return "\n\n".join(item["text"] for item in result["content"] if item.get("type") == "text")
except httpx.HTTPStatusError as exc:
raise WebError(f"Exa повернув HTTP {exc.response.status_code}.") from exc
except (httpx.HTTPError, KeyError, ValueError, TypeError, StopIteration) as exc:
raise WebError("Немає доступу до відповіді Exa.") from exc
def search_web(self, query):
return parse_search(self._call("web_search_exa", {
"query": query, "objective": f"Find independent original sources answering: {query}", "numResults": 5}))
def read_page(self, url):
model = re.fullmatch(r"https://huggingface\.co/([\w.-]+/[\w.-]+)/?", url)
if model:
repo = model[1]
try:
with self.client.stream("GET", f"https://huggingface.co/{repo}/raw/main/README.md",
timeout=15) as response:
if response.is_success:
content = bytearray()
for chunk in response.iter_bytes(chunk_size=16384):
content.extend(chunk)
if len(content) >= 180000:
break
body = re.sub(r"\A---\r?\n.*?\r?\n---\r?\n", "",
content.decode("utf-8", errors="replace"), count=1, flags=re.S).strip()
revision = response.headers.get("x-repo-commit", "")
if body:
link = url
if re.fullmatch(r"[a-f0-9]{40}", revision):
link = f"https://huggingface.co/{repo}/blob/{revision}/README.md"
return Page(repo, link, body)
except httpx.HTTPError:
pass
return parse_page(self._call("web_fetch_exa", {"urls": [url], "maxCharacters": 95000}), url)
def passages(body, focus):
"""Keep contiguous excerpts, including late rows in long benchmark tables."""
terms = {w[:6] for w in re.findall(r"\w{4,}", focus.casefold())}
blocks, current = [], ""
for line in body.splitlines():
line = line.strip()
if not line:
if len(current) > 160:
blocks.append(current)
current = ""
continue
for start in range(0, len(line), 600):
piece = line[start:start + 600]
if current and len(current) + len(piece) > 650:
blocks.append(current)
current = ""
current = (current + "\n" + piece).strip()
if current:
blocks.append(current)
hits = [terms & {w[:6] for w in re.findall(r"\w{4,}", b.casefold())} for b in blocks]
frequency = Counter(term for matched in hits for term in matched)
weights = {term: 1 + math.log((1 + len(blocks)) / (1 + count)) for term, count in frequency.items()}
# Cover new search concepts before selecting another paragraph with the same generic terms.
chosen, covered = set(), set()
for _ in range(min(6, len(blocks))):
def score(index):
return (sum(weights[t] for t in hits[index] - covered),
sum(weights[t] for t in hits[index]), -index)
best = max((i for i in range(len(blocks)) if i not in chosen), key=score)
chosen.add(best)
covered.update(hits[best])
if blocks:
chosen.add(0)
# Give the model column names when a chosen row is far below a Markdown table header.
headers = [i for i, block in enumerate(blocks) if re.search(r"(?m)^\|[\s|:\-]+\|$", block)]
for i in sorted(chosen):
if "|" in blocks[i] and (previous := [h for h in headers if h <= i]):
chosen.add(previous[-1])
if len(chosen) >= 8:
break
return [blocks[i] for i in sorted(chosen)]
def table_rows(body, selected):
"""Pair cells in selected rows with their original table's column headings."""
selected_lines = {line.strip(): i for i, part in enumerate(selected) for line in part.splitlines()
if line.strip().startswith("|")}
if not selected_lines:
return []
rows, counts = [], Counter()
previous, header = [], []
for line in body.splitlines():
line = line.strip()
if not line.startswith("|"):
previous, header = [], []
continue
cells = [v.strip() for v in line.strip("|").split("|")]
if cells and all(re.fullmatch(r":?-+:?", v) for v in cells):
header = previous
elif line in selected_lines and header and len(cells) == len(header):
part = selected_lines[line]
if counts[part] < 2:
rows.append(dict(zip(header, cells)))
counts[part] += 1
previous = cells
return rows