import io import re import requests import wikipedia from bs4 import BeautifulSoup from ddgs import DDGS from langchain_core.tools import tool from pypdf import PdfReader from youtube_transcript_api import YouTubeTranscriptApi @tool def web_search(query: str) -> str: """Search the web using DuckDuckGo and return top results.""" try: with DDGS() as ddgs: results = list(ddgs.text(query, max_results=5)) if not results: return "No results found." formatted = [] for r in results: formatted.append( f"Title: {r.get('title')}\nURL: {r.get('href')}\nSnippet: {r.get('body')}\n" ) return "\n---\n".join(formatted)[:5500] except Exception as e: return f"Web search error: {e}" _PAGE_CACHE: dict[str, str] = {} def _fetch_raw_text(url: str) -> str: """Fetch full text from a URL (PDF, HTML, or Jina Reader fallback).""" if url in _PAGE_CACHE: return _PAGE_CACHE[url] headers = { "User-Agent": ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/124.0.0.0 Safari/537.36" ) } text = "" try: response = requests.get(url, headers=headers, timeout=20) response.raise_for_status() # 1. Raw PDF bytes if response.content[:4] == b"%PDF": reader = PdfReader(io.BytesIO(response.content)) text = "\n".join(page.extract_text() or "" for page in reader.pages) else: # 2. Standard HTML soup = BeautifulSoup(response.text, "html.parser") for tag in soup(["script", "style", "nav", "footer", "header", "aside"]): tag.decompose() text = " ".join(soup.get_text(separator=" ").split()) except Exception: text = "" # 3. Fallback to Jina Reader if blocked, empty, or JS-walled if len(text) < 400 or "just a moment" in text[:300].lower() or "enable javascript" in text[:300].lower(): try: jina_resp = requests.get( f"https://r.jina.ai/{url}", headers={"User-Agent": headers["User-Agent"]}, timeout=25, ) if jina_resp.status_code == 200 and len(jina_resp.text) > len(text): text = jina_resp.text except Exception: pass if not text: return "" _PAGE_CACHE[url] = text return text @tool def fetch_webpage(url: str, search_term: str = "", offset: int = 0) -> str: """Fetch a webpage or PDF URL. - Use `search_term` to jump directly to a keyword/section (e.g., 'Discography', '1977', 'NASA'). - Use `offset` (character index) to read further down a long page. """ try: full_text = _fetch_raw_text(url) if not full_text: return f"Error: Could not extract readable text from {url}." total_len = len(full_text) chunk_size = 5000 # Mode A: Keyword search inside the page if search_term: matches = [ m.start() for m in re.finditer(re.escape(search_term), full_text, re.IGNORECASE) ] if not matches: return ( f"[Term '{search_term}' not found in {total_len} chars. " f"Showing start of page instead:]\n\n{full_text[:3500]}" ) snippets = [] used_ranges = [] for pos in matches[:3]: start = max(0, pos - 700) end = min(total_len, pos + 1000) if any(start < u_end and end > u_start for u_start, u_end in used_ranges): continue used_ranges.append((start, end)) snippets.append(f"--- Match at char {pos} ---\n{full_text[start:end]}") header = f"[Found {len(matches)} match(es) for '{search_term}' in {total_len} chars]" return f"{header}\n\n" + "\n\n".join(snippets)[:5500] # Mode B: Sequential / offset reading offset = max(0, offset) chunk = full_text[offset : offset + chunk_size] end_pos = min(total_len, offset + chunk_size) header = ( f"[Showing chars {offset}-{end_pos} of {total_len}. " f"Pass search_term='...' or offset={end_pos} to read more.]" ) return f"{header}\n\n{chunk}" except Exception as e: return f"Error fetching webpage: {e}" @tool def wikipedia_search(query: str) -> str: """Search Wikipedia for matching article titles and a brief summary of the top match.""" try: titles = wikipedia.search(query, results=5) if not titles: return "No Wikipedia articles found." summary = "" try: summary = wikipedia.summary(titles[0], sentences=5, auto_suggest=False) except Exception: pass return f"Matching titles: {', '.join(titles)}\n\nTop summary ({titles[0]}):\n{summary}"[:5500] except Exception as e: return f"Wikipedia search error: {e}" @tool def get_wikipedia_page(title: str) -> str: """Fetch the text content of a specific Wikipedia article by exact title.""" try: page = wikipedia.page(title, auto_suggest=False) return f"Title: {page.title}\nURL: {page.url}\n\n{page.content[:5500]}" except Exception as e: return f"Error fetching Wikipedia page '{title}': {e}" @tool def get_youtube_transcript(url: str) -> str: """Fetch the spoken transcript/captions of a YouTube video from its URL.""" match = re.search(r"(?:v=|youtu\.be/|shorts/)([a-zA-Z0-9_-]{11})", url) if not match: return "Error: Could not extract a valid YouTube video ID from the URL." video_id = match.group(1) try: if hasattr(YouTubeTranscriptApi, "fetch"): fetched = YouTubeTranscriptApi().fetch(video_id) text = " ".join(snippet.text for snippet in fetched) else: fetched = YouTubeTranscriptApi.get_transcript(video_id) text = " ".join(entry["text"] for entry in fetched) return text[:5500] except Exception as e: return f"Error fetching YouTube transcript: {e}"