Spaces:
Sleeping
Sleeping
Upload tools.py with huggingface_hub
Browse files209 unmodified lines21021121221321421321421521621721821922022122222322422522622722814 unmodified lines243244245235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302246247248209 unmodified lines return cached_results try: # Try alternative search engines in sequence results = self._try_alternative_searches(query, max_results) # Add delay to avoid rate limiting import time time.sleep(3.0) # 3 second delay between searches results = [] search_results = self.ddgs.text(query, max_results=max_results) for result in search_results: results.append({ 'title': result.get('title', ''), 'link': result.get('link', ''), 'snippet': result.get('body', '') }) # Cache successful results if results:14 unmodified lines # Return empty list for search failures return [] def _try_alternative_searches(self, query: str, max_results: int) -> List[Dict[str, str]]: """Try alternative search engines in sequence""" # Method 1: Wikipedia API (no rate limits) try: results = self._search_wikipedia(query, max_results) if results: logger.info(f"Wikipedia search successful for '{query}'") return results except Exception as e: logger.debug(f"Wikipedia search failed: {e}") # Method 2: DuckDuckGo with retry (original method) try: import time time.sleep(2.0) # Reduced delay results = [] search_results = self.ddgs.text(query, max_results=max_results) for result in search_results: results.append({ 'title': result.get('title', ''), 'link': result.get('link', ''), 'snippet': result.get('body', '') }) if results: logger.info(f"DuckDuckGo search successful for '{query}'") return results except Exception as e: logger.debug(f"DuckDuckGo search failed: {e}") # Method 3: Direct knowledge fallback return self._get_fallback_results(query) def _search_wikipedia(self, query: str, max_results: int) -> List[Dict[str, str]]: """Search Wikipedia API directly (no rate limits)""" import requests url = "https://en.wikipedia.org/w/api.php" params = { 'action': 'opensearch', 'search': query, 'limit': max_results, 'format': 'json' } response = requests.get(url, params=params, timeout=10) if response.status_code == 200: data = response.json() if len(data) >= 4: titles = data[1] descriptions = data[2] urls = data[3] results = [] for i in range(min(len(titles), max_results)): if titles[i] and urls[i]: # Skip empty results results.append({ 'title': titles[i], 'link': urls[i], 'snippet': descriptions[i] if i < len(descriptions) else '' }) return results return []
def _get_fallback_results(self, query: str) -> List[Dict[str, str]]: """Provide fallback results for common queries when search fails""" q_lower = query.lower()tools.py+13-70