"""Live technical web search and page content extraction tools.
Enables the agent to search online documentation, code references,
and error solutions without third-party python dependencies.
"""
from __future__ import annotations
import asyncio
import html
import json
import os
import re
import urllib.parse
import urllib.request
from typing import Any, Dict, List, Optional
from ..errors import ToolError
from .base import BaseTool
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Agentux/0.2.0"
#: Words that carry no subject, so they must not drive a Wikipedia lookup.
_WIKI_STOPWORDS = frozenset(
{
"what", "who", "whom", "whose", "when", "where", "why", "how", "which",
"is", "are", "was", "were", "do", "does", "did", "can", "could",
"should", "would", "will", "the", "and", "for", "with", "that",
"this", "from", "tell", "explain", "please", "about", "your", "you",
}
)
class WebSearchTool(BaseTool):
"""Search technical documentation and code solutions on the live web."""
def __init__(self) -> None:
pass
@property
def name(self) -> str:
return "web_search"
@property
def description(self) -> str:
return (
"Search technical documentation, error messages, and API references "
"on the live web. Uses DuckDuckGo HTML search by default, or Tavily/Brave "
"if API keys are configured."
)
@property
def parameters(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Technical search query (e.g. 'pydantic v2 field_validator example').",
},
"max_results": {
"type": "integer",
"description": "Maximum number of search results to return (default: 5).",
},
},
"required": ["query"],
}
def search(self, query: str, max_results: int = 5) -> str:
"""Run a search synchronously.
Exists so callers outside the async tool path -- Agentux Solo grounds a
question before the model answers it -- can use it without an event
loop. ``execute`` is the tool-facing wrapper.
"""
query = query.strip()
if not query:
raise ToolError("Query cannot be empty.")
# Check for Tavily API key
tavily_key = os.environ.get("TAVILY_API_KEY")
if tavily_key:
return self._search_tavily(query, tavily_key, max_results)
# Check for Brave API key
brave_key = os.environ.get("BRAVE_API_KEY")
if brave_key:
return self._search_brave(query, brave_key, max_results)
# Default: Zero-dependency DuckDuckGo HTML scraper
return self._search_duckduckgo(query, max_results)
async def execute(self, query: str, max_results: int = 5, **kwargs: Any) -> str:
if "num_results" in kwargs:
max_results = int(kwargs["num_results"])
return await asyncio.to_thread(self.search, query, max_results)
def _fetch(self, url: str) -> str:
"""GET a URL and return the decoded body."""
req = urllib.request.Request(
url,
headers={"User-Agent": USER_AGENT, "Accept": "application/json, text/html"},
)
with urllib.request.urlopen(req, timeout=20) as resp:
return resp.read().decode("utf-8", errors="replace")
def search_wikipedia(self, query: str, max_chars: int = 1200) -> str:
"""Look a topic up on Wikipedia and return its lead sentence.
Keyless and reliable, which makes it the best grounding source for a
small model: it returns a sentence containing the fact rather than a
headline the model can misread.
Each candidate phrase is searched on its own and the best-matching
article wins. Opensearch matches whole phrases, so a question finds
nothing while its content words find the article; a single word often
lands on a disambiguation page ("Mojo" is one), so the phrase is tried
first. A title that merely contains the word is not enough either --
the extract has to mention it, and a short title beats a long one when
the mentions tie.
"""
words = self._subject_words(query)
if not words:
return ""
terms = set(words)
candidates: List[str] = []
phrase = " ".join(words)
if phrase:
candidates.append(phrase)
candidates.extend(word for word in words if word != phrase)
best_score = None
best_title = ""
best_extract = ""
try:
for candidate in candidates[:4]:
for title in self._wikipedia_titles(candidate)[:2]:
extract = self._wikipedia_summary(title)
if not extract:
continue
haystack = (title + " " + extract).lower()
hits = sum(1 for term in terms if term in haystack)
score = (hits, -len(title.split()))
if best_score is None or score > best_score:
best_score = score
best_title = title
best_extract = extract
if not best_extract:
return ""
# The lead paragraph may not answer the question -- "who invented
# the transistor" is not answered by a definition. Pick the
# paragraph that mentions the subject words most.
paragraph = self._wikipedia_best_paragraph(best_title, list(terms))
return (paragraph or best_extract)[:max_chars]
except Exception:
return ""
def _wikipedia_best_paragraph(self, title: str, terms: List[str]) -> str:
"""The paragraph of an article that mentions the subject words most."""
text = self._wikipedia_full_extract(title)
if not text:
return ""
best = ""
best_hits = 0
for paragraph in text.split("\n"):
clean = " ".join(paragraph.split())
if len(clean) < 40:
continue
lowered = clean.lower()
hits = sum(1 for term in terms if term in lowered)
if hits > best_hits:
best, best_hits = clean, hits
return best
def _wikipedia_full_extract(self, title: str) -> str:
url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode(
{
"action": "query",
"prop": "extracts",
"explaintext": 1,
"format": "json",
"redirects": 1,
"titles": title,
}
)
data = json.loads(self._fetch(url))
for page in data.get("query", {}).get("pages", {}).values():
extract = page.get("extract")
if extract:
return str(extract)
return ""
@staticmethod
def _subject_words(query: str) -> List[str]:
"""The words in a question that could name its subject, in order."""
return [
word
for word in re.findall(r"[a-z0-9]+", str(query).lower())
if len(word) >= 4 and word not in _WIKI_STOPWORDS
]
def _wikipedia_titles(self, query: str) -> List[str]:
url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode(
{
"action": "opensearch",
"search": query,
"limit": 5,
"format": "json",
"profile": "fuzzy",
}
)
data = json.loads(self._fetch(url))
if len(data) > 1 and isinstance(data[1], list):
return [str(title) for title in data[1]]
return []
def _wikipedia_summary(self, title: str) -> str:
path = urllib.parse.quote(title.replace(" ", "_"), safe="()_")
data = json.loads(
self._fetch(f"https://en.wikipedia.org/api/rest_v1/page/summary/{path}")
)
extract = data.get("extract")
if not extract or data.get("type") == "disambiguation":
return ""
return f"{data.get('title', title)}: {extract}"
def _search_duckduckgo(self, query: str, max_results: int) -> str:
encoded_query = urllib.parse.urlencode({"q": query, "b": ""})
url = f"https://html.duckduckgo.com/html/?{encoded_query}"
req = urllib.request.Request(
url,
headers={
"User-Agent": USER_AGENT,
"Accept": "text/html,application/xhtml+xml",
"Accept-Language": "en-US,en;q=0.9",
},
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
content = resp.read().decode("utf-8", errors="replace")
except Exception as exc:
return f"Web search failed: {exc}"
# Parse results with regex
results: List[Dict[str, str]] = []
pattern = re.compile(
r']+class="result__snippet"[^>]*href="(?P[^"]+)"[^>]*>(?P
]*>(.*?)
", r"\n\n\1\n\n", content, flags=re.DOTALL | re.IGNORECASE) content = re.sub(r"