~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
bug fixes and added wayback machine. Github in progress
LearningCircuit478bdf14731f
diff --git a/web_search_engines/engines/full_search.py b/web_search_engines/engines/full_search.pynew file mode 100644index 0000000000..b29060616f--- /dev/null+++ b/web_search_engines/engines/full_search.py@@ -0,0 +1,121 @@++from langchain_anthropic import ChatAnthropic+from langchain_openai import ChatOpenAI+from langchain_ollama import ChatOllama+from dotenv import load_dotenv++from web_search_engines.full_serp_search_results_old import FullSerpAPISearchResults # Added import for SerpAPI class+from web_search_engines.full_search import FullSearchResults+++from web_search_engines.search_engine_ddg import DuckDuckGoSearchEngine+from web_search_engines.search_engine_wikipedia import WikipediaSearchEngine+from web_search_engines.search_engine_serpapi import SerpAPISearchEngine+import os+# Load environment variables+load_dotenv()+++# LLM Configuration+DEFAULT_MODEL = "mistral" # try to use the largest model that fits into your GPU memory+DEFAULT_TEMPERATURE = 0.7+MAX_TOKENS = 15000++# Search System Settings+SEARCH_ITERATIONS = 3+QUESTIONS_PER_ITERATION = 3++# Report settings+SEARCHES_PER_SECTION = 5+CONTEXT_CUT_OFF = 10000++# citation handler+ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better with larger LLMs?++# URL Quality Check (applies to both DDG and SerpAPI)+QUALITY_CHECK_DDG_URLS = True # Keep True for better quality results.++# Search Configuration (applies to both DDG and SerpAPI)+MAX_SEARCH_RESULTS = 40+SEARCH_REGION = "us"+TIME_PERIOD = "y"+SAFE_SEARCH = True+SEARCH_SNIPPETS_ONLY = False+SEARCH_LANGUAGE = "English"++# Output Configuration+OUTPUT_DIR = "research_outputs"++# Choose search tool: "serp" or "duckduckgo" (serp requires API key)+search_tool = "wiki" # Change this variable to switch between search tools+++def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):+ """Get LLM instance - easy to switch between models"""+ common_params = {+ "temperature": temperature,+ "max_tokens": MAX_TOKENS,+ }++ if "claude" in model_name:+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ raise ValueError("ANTHROPIC_API_KEY not found in environment variables")+ return ChatAnthropic(+ model=model_name, anthropic_api_key=api_key, **common_params+ )++ elif "gpt" in model_name:+ api_key = os.getenv("OPENAI_API_KEY")+ if not api_key:+ raise ValueError("OPENAI_API_KEY not found in environment variables")+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)++ else:+ return ChatOllama(model=model_name, base_url="http://localhost:11434", **common_params)+++def get_search():+ """Get search tool instance based on the chosen search_tool variable"""+ llm_instance = get_llm()+ if "serp" in search_tool.lower():+ search_engine = SerpAPISearchEngine(+ max_results=MAX_SEARCH_RESULTS,+ region=SEARCH_REGION,+ time_period=TIME_PERIOD,+ safe_search=SAFE_SEARCH,+ search_language=SEARCH_LANGUAGE+ )+ elif "wiki" in search_tool.lower():+ wiki = WikipediaSearchEngine(max_results=3, include_content=SEARCH_SNIPPETS_ONLY)+ return wiki+ else:+ search_engine = DuckDuckGoSearchEngine(+ max_results=MAX_SEARCH_RESULTS,+ region=SEARCH_REGION,+ safe_search=SAFE_SEARCH,+ )++ if SEARCH_SNIPPETS_ONLY:+ return search_engine++ else :+ if "serp_old" in search_tool.lower():+ return FullSerpAPISearchResults(+ llm=llm_instance,+ serpapi_api_key=os.getenv("SERP_API_KEY"),+ max_results=MAX_SEARCH_RESULTS,+ language = SEARCH_LANGUAGE,+ region=SEARCH_REGION,+ time_period=TIME_PERIOD,+ safesearch="active" if SAFE_SEARCH else "off"+ )+ else:+ return FullSearchResults(+ web_search=search_engine,+ llm=llm_instance,+ max_results=MAX_SEARCH_RESULTS,+ region=SEARCH_REGION,+ time=TIME_PERIOD,+ safesearch="Moderate" if SAFE_SEARCH else "Off",+ )\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_ddg.py b/web_search_engines/engines/search_engine_ddg.pyindex 16ce2dac47..99a5e34685 100644--- a/web_search_engines/engines/search_engine_ddg.py+++ b/web_search_engines/engines/search_engine_ddg.py@@ -3,7 +3,7 @@ from typing import Dict, List, Any, Optionalfrom langchain_core.language_models import BaseLLMfrom web_search_engines.search_engine_base import BaseSearchEngine-from full_search import FullSearchResults # Import the FullSearchResults class+from web_search_engines.engines.full_search import FullSearchResults # Import the FullSearchResults classclass DuckDuckGoSearchEngine(BaseSearchEngine):"""DuckDuckGo search engine implementation with two-phase retrieval"""diff --git a/web_search_engines/engines/search_engine_github.py b/web_search_engines/engines/search_engine_github.pynew file mode 100644index 0000000000..0e7ca986cf--- /dev/null+++ b/web_search_engines/engines/search_engine_github.py@@ -0,0 +1,663 @@+import requests+import logging+import base64+import os+import time+from typing import Dict, List, Any, Optional, Union+from langchain_core.language_models import BaseLLM++from web_search_engines.search_engine_base import BaseSearchEngine+import config++# Setup logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++class GitHubSearchEngine(BaseSearchEngine):+ """+ GitHub search engine implementation.+ Provides search across GitHub repositories, code, issues, and users.+ """++ def __init__(self,+ max_results: int = 15,+ api_key: Optional[str] = None,+ search_type: str = "repositories",+ include_readme: bool = True,+ include_issues: bool = False,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None):+ """+ Initialize the GitHub search engine.++ Args:+ max_results: Maximum number of search results+ api_key: GitHub API token (can also be set in GITHUB_API_KEY env)+ search_type: Type of GitHub search ("repositories", "code", "issues", "users")+ include_readme: Whether to include README content for repositories+ include_issues: Whether to include recent issues for repositories+ llm: Language model for relevance filtering+ max_filtered_results: Maximum number of results to keep after filtering+ """+ # Initialize the BaseSearchEngine with the LLM and max_filtered_results+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)++ self.max_results = max_results+ self.api_key = api_key or os.getenv("GITHUB_API_KEY")+ self.search_type = search_type+ self.include_readme = include_readme+ self.include_issues = include_issues++ # API endpoints+ self.api_base = "https://api.github.com"+ self.search_endpoint = f"{self.api_base}/search/{search_type}"++ # Set up API headers+ self.headers = {+ "Accept": "application/vnd.github.v3+json",+ "User-Agent": "Local-Deep-Research-Agent"+ }++ # Add authentication if API key provided+ if self.api_key:+ self.headers["Authorization"] = f"token {self.api_key}"+ logger.info("Using authenticated GitHub API requests")+ else:+ logger.warning("No GitHub API key provided. Rate limits will be restricted.")++ def _handle_rate_limits(self, response):+ """Handle GitHub API rate limits by logging warnings and sleeping if necessary"""+ remaining = int(response.headers.get("X-RateLimit-Remaining", 60))+ reset_time = int(response.headers.get("X-RateLimit-Reset", 0))++ if remaining < 5:+ current_time = time.time()+ wait_time = max(reset_time - current_time, 0)+ logger.warning(f"GitHub API rate limit almost reached. {remaining} requests remaining.")++ if wait_time > 0 and remaining == 0:+ logger.warning(f"GitHub API rate limit exceeded. Waiting {wait_time:.0f} seconds.")+ time.sleep(min(wait_time, 60)) # Wait at most 60 seconds++ def _search_github(self, query: str) -> List[Dict[str, Any]]:+ """+ Perform a GitHub search based on the configured search type.++ Args:+ query: The search query++ Returns:+ List of GitHub search result items+ """+ results = []++ try:+ # Optimize GitHub query format+ github_query = query++ # For long queries, focus on keywords and add filters for better results+ if len(query) > 80:+ # Extract key terms if it's a recommendation request+ if "recommend" in query.lower() or "looking for" in query.lower():+ github_query = "stars:>100 " + " ".join([+ word for word in query.split()+ if len(word) > 3 and word.lower() not in+ ["recommend", "recommended", "github", "repositories", "looking", "developers"]+ ])++ logger.info(f"Optimized GitHub query: {github_query}")++ # Construct search parameters+ params = {+ "q": github_query,+ "per_page": min(self.max_results, 100), # GitHub API max is 100 per page+ "page": 1+ }++ # Add sort parameters based on search type+ if self.search_type == "repositories":+ params["sort"] = "stars"+ params["order"] = "desc"+ elif self.search_type == "code":+ params["sort"] = "indexed"+ params["order"] = "desc"+ elif self.search_type == "issues":+ params["sort"] = "updated"+ params["order"] = "desc"+ elif self.search_type == "users":+ params["sort"] = "followers"+ params["order"] = "desc"++ # Execute the API request+ response = requests.get(+ self.search_endpoint,+ headers=self.headers,+ params=params+ )++ # Check for rate limiting+ self._handle_rate_limits(response)++ # Handle response with detailed logging+ if response.status_code == 200:+ data = response.json()+ total_count = data.get("total_count", 0)+ results = data.get("items", [])+ logger.info(f"GitHub search returned {len(results)} results (total available: {total_count})")++ # Log the rate limit information+ rate_limit_remaining = response.headers.get("X-RateLimit-Remaining", "unknown")+ rate_limit_reset = response.headers.get("X-RateLimit-Reset", "unknown")+ logger.info(f"GitHub API rate limit: {rate_limit_remaining} requests remaining")++ # If no results, try to provide more guidance+ if not results:+ logger.warning(f"No results found. Consider these search tips:")+ logger.warning(f"1. Use shorter, more specific queries")+ logger.warning(f"2. For repositories, try adding 'stars:>100' or 'language:python'")+ logger.warning(f"3. For contribution opportunities, search for 'good-first-issue' or 'help-wanted'")+ else:+ logger.error(f"GitHub API error: {response.status_code} - {response.text}")++ except Exception as e:+ logger.error(f"Error searching GitHub: {e}")++ return results++ def _get_readme_content(self, repo_full_name: str) -> str:+ """+ Get README content for a repository.++ Args:+ repo_full_name: Full name of the repository (owner/repo)++ Returns:+ Decoded README content or empty string if not found+ """+ try:+ # Get README+ response = requests.get(+ f"{self.api_base}/repos/{repo_full_name}/readme",+ headers=self.headers+ )++ # Check for rate limiting+ self._handle_rate_limits(response)++ if response.status_code == 200:+ data = response.json()+ content = data.get("content", "")+ encoding = data.get("encoding", "")++ if encoding == "base64" and content:+ return base64.b64decode(content).decode('utf-8', errors='replace')+ return content+ else:+ logger.warning(f"Could not get README for {repo_full_name}: {response.status_code}")+ return ""++ except Exception as e:+ logger.error(f"Error getting README for {repo_full_name}: {e}")+ return ""++ def _get_recent_issues(self, repo_full_name: str, limit: int = 5) -> List[Dict[str, Any]]:+ """+ Get recent issues for a repository.++ Args:+ repo_full_name: Full name of the repository (owner/repo)+ limit: Maximum number of issues to return++ Returns:+ List of recent issues+ """+ issues = []++ try:+ # Get recent issues+ response = requests.get(+ f"{self.api_base}/repos/{repo_full_name}/issues",+ headers=self.headers,+ params={+ "state": "all",+ "per_page": limit,+ "sort": "updated",+ "direction": "desc"+ }+ )++ # Check for rate limiting+ self._handle_rate_limits(response)++ if response.status_code == 200:+ issues = response.json()+ logger.info(f"Got {len(issues)} recent issues for {repo_full_name}")+ else:+ logger.warning(f"Could not get issues for {repo_full_name}: {response.status_code}")++ except Exception as e:+ logger.error(f"Error getting issues for {repo_full_name}: {e}")++ return issues++ def _get_file_content(self, file_url: str) -> str:+ """+ Get content of a file from GitHub.++ Args:+ file_url: API URL for the file++ Returns:+ Decoded file content or empty string if not found+ """+ try:+ # Get file content+ response = requests.get(+ file_url,+ headers=self.headers+ )++ # Check for rate limiting+ self._handle_rate_limits(response)++ if response.status_code == 200:+ data = response.json()+ content = data.get("content", "")+ encoding = data.get("encoding", "")++ if encoding == "base64" and content:+ return base64.b64decode(content).decode('utf-8', errors='replace')+ return content+ else:+ logger.warning(f"Could not get file content: {response.status_code}")+ return ""++ except Exception as e:+ logger.error(f"Error getting file content: {e}")+ return ""++ def _format_repository_preview(self, repo: Dict[str, Any]) -> Dict[str, Any]:+ """Format repository search result as preview"""+ return {+ "id": str(repo.get("id", "")),+ "title": repo.get("full_name", ""),+ "link": repo.get("html_url", ""),+ "snippet": repo.get("description", "No description provided"),+ "stars": repo.get("stargazers_count", 0),+ "forks": repo.get("forks_count", 0),+ "language": repo.get("language", ""),+ "updated_at": repo.get("updated_at", ""),+ "created_at": repo.get("created_at", ""),+ "topics": repo.get("topics", []),+ "owner": repo.get("owner", {}).get("login", ""),+ "is_fork": repo.get("fork", False),+ "search_type": "repository",+ "repo_full_name": repo.get("full_name", "")+ }++ def _format_code_preview(self, code: Dict[str, Any]) -> Dict[str, Any]:+ """Format code search result as preview"""+ repo = code.get("repository", {})+ return {+ "id": f"code_{code.get('sha', '')}",+ "title": f"{code.get('name', '')} in {repo.get('full_name', '')}",+ "link": code.get("html_url", ""),+ "snippet": f"Match in {code.get('path', '')}",+ "path": code.get("path", ""),+ "repo_name": repo.get("full_name", ""),+ "repo_url": repo.get("html_url", ""),+ "search_type": "code",+ "file_url": code.get("url", "")+ }++ def _format_issue_preview(self, issue: Dict[str, Any]) -> Dict[str, Any]:+ """Format issue search result as preview"""+ repo = issue.get("repository", {}) if "repository" in issue else {"full_name": ""}+ return {+ "id": f"issue_{issue.get('number', '')}",+ "title": issue.get("title", ""),+ "link": issue.get("html_url", ""),+ "snippet": issue.get("body", "")[:200] + "..." if len(issue.get("body", "")) > 200 else issue.get("body", ""),+ "state": issue.get("state", ""),+ "created_at": issue.get("created_at", ""),+ "updated_at": issue.get("updated_at", ""),+ "user": issue.get("user", {}).get("login", ""),+ "comments": issue.get("comments", 0),+ "search_type": "issue",+ "repo_name": repo.get("full_name", "")+ }++ def _format_user_preview(self, user: Dict[str, Any]) -> Dict[str, Any]:+ """Format user search result as preview"""+ return {+ "id": f"user_{user.get('id', '')}",+ "title": user.get("login", ""),+ "link": user.get("html_url", ""),+ "snippet": user.get("bio", "No bio provided"),+ "name": user.get("name", ""),+ "followers": user.get("followers", 0),+ "public_repos": user.get("public_repos", 0),+ "location": user.get("location", ""),+ "search_type": "user",+ "user_login": user.get("login", "")+ }++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for GitHub search results.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting GitHub previews for query: {query}")++ # For contribution-focused queries, automatically adjust search type and add filters+ if any(term in query.lower() for term in ["contribute", "contributing", "contribution", "beginner", "newcomer"]):+ # Use repositories search with help-wanted or good-first-issue labels+ original_search_type = self.search_type+ self.search_type = "repositories"+ self.search_endpoint = f"{self.api_base}/search/repositories"++ # Create a specialized query for finding beginner-friendly projects+ specialized_query = "good-first-issues:>5 is:public archived:false"++ # Extract language preferences if present+ languages = []+ for lang in ["python", "javascript", "java", "rust", "go", "typescript", "c#", "c++", "ruby"]:+ if lang in query.lower():+ languages.append(lang)++ if languages:+ specialized_query += f" language:{' language:'.join(languages)}"++ # Extract keywords+ keywords = [word for word in query.split() if len(word) > 3 and word.lower() not in+ ["recommend", "recommended", "github", "repositories", "looking",+ "developers", "contribute", "contributing", "beginner", "newcomer"]]++ if keywords:+ specialized_query += " " + " ".join(keywords[:5]) # Add up to 5 keywords++ logger.info(f"Using specialized contribution query: {specialized_query}")++ # Perform GitHub search with specialized query+ results = self._search_github(specialized_query)++ # Restore original search type+ self.search_type = original_search_type+ self.search_endpoint = f"{self.api_base}/search/{self.search_type}"+ else:+ # Perform standard GitHub search+ results = self._search_github(query)++ if not results:+ logger.warning(f"No GitHub results found for query: {query}")+ return []++ # Format results as previews+ previews = []+ for result in results:+ # Format based on search type+ if self.search_type == "repositories":+ preview = self._format_repository_preview(result)+ elif self.search_type == "code":+ preview = self._format_code_preview(result)+ elif self.search_type == "issues":+ preview = self._format_issue_preview(result)+ elif self.search_type == "users":+ preview = self._format_user_preview(result)+ else:+ logger.warning(f"Unknown search type: {self.search_type}")+ continue++ previews.append(preview)++ logger.info(f"Formatted {len(previews)} GitHub preview results")+ return previews++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant GitHub search results.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Check if we should add full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ logger.info("Snippet-only mode, skipping full content retrieval")+ return relevant_items++ logger.info(f"Getting full content for {len(relevant_items)} GitHub results")++ results = []+ for item in relevant_items:+ result = item.copy()+ search_type = item.get("search_type", "")++ # Add content based on search type+ if search_type == "repository" and self.include_readme:+ repo_full_name = item.get("repo_full_name", "")+ if repo_full_name:+ # Get README content+ readme_content = self._get_readme_content(repo_full_name)+ result["full_content"] = readme_content+ result["content_type"] = "readme"++ # Get recent issues if requested+ if self.include_issues:+ issues = self._get_recent_issues(repo_full_name)+ result["recent_issues"] = issues++ elif search_type == "code":+ file_url = item.get("file_url", "")+ if file_url:+ # Get file content+ file_content = self._get_file_content(file_url)+ result["full_content"] = file_content+ result["content_type"] = "file"++ elif search_type == "issue":+ # For issues, the snippet usually contains a summary already+ # We'll just keep it as is+ result["full_content"] = item.get("snippet", "")+ result["content_type"] = "issue"++ elif search_type == "user":+ # For users, construct a profile summary+ user_login = item.get("user_login", "")+ profile_summary = f"GitHub user: {item.get('title', '')}\n"++ if item.get("name"):+ profile_summary += f"Name: {item.get('name')}\n"++ if item.get("location"):+ profile_summary += f"Location: {item.get('location')}\n"++ profile_summary += f"Followers: {item.get('followers', 0)}\n"+ profile_summary += f"Public repositories: {item.get('public_repos', 0)}\n"++ if item.get("snippet") and item.get("snippet") != "No bio provided":+ profile_summary += f"\nBio: {item.get('snippet')}\n"++ result["full_content"] = profile_summary+ result["content_type"] = "user_profile"++ results.append(result)++ return results++ def search_repository(self, repo_owner: str, repo_name: str) -> Dict[str, Any]:+ """+ Get detailed information about a specific repository.++ Args:+ repo_owner: Owner of the repository+ repo_name: Name of the repository++ Returns:+ Dictionary with repository information+ """+ repo_full_name = f"{repo_owner}/{repo_name}"+ logger.info(f"Getting details for repository: {repo_full_name}")++ try:+ # Get repository details+ response = requests.get(+ f"{self.api_base}/repos/{repo_full_name}",+ headers=self.headers+ )++ # Check for rate limiting+ self._handle_rate_limits(response)++ if response.status_code == 200:+ repo = response.json()++ # Format as repository preview+ result = self._format_repository_preview(repo)++ # Add README content if requested+ if self.include_readme:+ readme_content = self._get_readme_content(repo_full_name)+ result["full_content"] = readme_content+ result["content_type"] = "readme"++ # Add recent issues if requested+ if self.include_issues:+ issues = self._get_recent_issues(repo_full_name)+ result["recent_issues"] = issues++ return result+ else:+ logger.error(f"Error getting repository details: {response.status_code} - {response.text}")+ return {}++ except Exception as e:+ logger.error(f"Error getting repository details: {e}")+ return {}++ def search_code(self, query: str, language: Optional[str] = None, user: Optional[str] = None) -> List[Dict[str, Any]]:+ """+ Search for code with more specific parameters.++ Args:+ query: Code search query+ language: Filter by programming language+ user: Filter by GitHub username/organization++ Returns:+ List of code search results+ """+ # Build advanced query+ advanced_query = query++ if language:+ advanced_query += f" language:{language}"++ if user:+ advanced_query += f" user:{user}"++ # Save current search type+ original_search_type = self.search_type++ try:+ # Set search type to code+ self.search_type = "code"+ self.search_endpoint = f"{self.api_base}/search/code"++ # Perform search+ results = self._search_github(advanced_query)++ # Format results+ previews = [self._format_code_preview(result) for result in results]++ # Get full content if requested+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and not config.SEARCH_SNIPPETS_ONLY:+ return self._get_full_content(previews)++ return previews++ finally:+ # Restore original search type+ self.search_type = original_search_type+ self.search_endpoint = f"{self.api_base}/search/{self.search_type}"++ def search_issues(self, query: str, state: str = "open", sort: str = "updated") -> List[Dict[str, Any]]:+ """+ Search for issues with more specific parameters.++ Args:+ query: Issue search query+ state: Filter by issue state ("open", "closed", "all")+ sort: Sort order ("updated", "created", "comments")++ Returns:+ List of issue search results+ """+ # Build advanced query+ advanced_query = query + f" state:{state}"++ # Save current search type+ original_search_type = self.search_type++ try:+ # Set search type to issues+ self.search_type = "issues"+ self.search_endpoint = f"{self.api_base}/search/issues"++ # Set sort parameter+ params = {+ "q": advanced_query,+ "per_page": min(self.max_results, 100),+ "page": 1,+ "sort": sort,+ "order": "desc"+ }++ # Perform search+ response = requests.get(+ self.search_endpoint,+ headers=self.headers,+ params=params+ )++ # Check for rate limiting+ self._handle_rate_limits(response)++ if response.status_code == 200:+ data = response.json()+ results = data.get("items", [])++ # Format results+ previews = [self._format_issue_preview(result) for result in results]++ # For issues, we don't need to get full content+ return previews+ else:+ logger.error(f"GitHub API error: {response.status_code} - {response.text}")+ return []++ finally:+ # Restore original search type+ self.search_type = original_search_type+ self.search_endpoint = f"{self.api_base}/search/{self.search_type}"++ def set_search_type(self, search_type: str):+ """+ Set the search type for subsequent searches.++ Args:+ search_type: Type of GitHub search ("repositories", "code", "issues", "users")+ """+ if search_type in ["repositories", "code", "issues", "users"]:+ self.search_type = search_type+ self.search_endpoint = f"{self.api_base}/search/{search_type}"+ logger.info(f"Set GitHub search type to: {search_type}")+ else:+ logger.error(f"Invalid GitHub search type: {search_type}")\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_serpapi.py b/web_search_engines/engines/search_engine_serpapi.pyindex bf0d724eac..049517c550 100644--- a/web_search_engines/engines/search_engine_serpapi.py+++ b/web_search_engines/engines/search_engine_serpapi.py@@ -83,7 +83,7 @@ class SerpAPISearchEngine(BaseSearchEngine):if include_full_content:# Import FullSearchResults only if neededtry:- from full_search import FullSearchResults+ from web_search_engines.engines.full_search import FullSearchResultsself.full_search = FullSearchResults(llm=llm,web_search=self.engine,diff --git a/web_search_engines/engines/search_engine_wayback.py b/web_search_engines/engines/search_engine_wayback.pynew file mode 100644index 0000000000..7fafb24030--- /dev/null+++ b/web_search_engines/engines/search_engine_wayback.py@@ -0,0 +1,474 @@+import requests+import logging+from typing import Dict, List, Any, Optional, Tuple+from langchain_core.language_models import BaseLLM+import re+import time+from datetime import datetime++from web_search_engines.search_engine_base import BaseSearchEngine+import config+import justext++# Setup logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++class WaybackSearchEngine(BaseSearchEngine):+ """+ Internet Archive Wayback Machine search engine implementation+ Provides access to historical versions of web pages+ """++ def __init__(self,+ max_results: int = 10,+ max_snapshots_per_url: int = 3,+ llm: Optional[BaseLLM] = None,+ language: str = "English",+ max_filtered_results: Optional[int] = None,+ closest_only: bool = False):+ """+ Initialize the Wayback Machine search engine.++ Args:+ max_results: Maximum number of search results+ max_snapshots_per_url: Maximum snapshots to retrieve per URL+ llm: Language model for relevance filtering+ language: Language for content processing+ max_filtered_results: Maximum number of results to keep after filtering+ closest_only: If True, only retrieves the closest snapshot for each URL+ """+ # Initialize the BaseSearchEngine with the LLM and max_filtered_results+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)++ self.max_results = max_results+ self.max_snapshots_per_url = max_snapshots_per_url+ self.language = language+ self.closest_only = closest_only++ # API endpoints+ self.available_api = "https://archive.org/wayback/available"+ self.cdx_api = "https://web.archive.org/cdx/search/cdx"++ def _extract_urls_from_query(self, query: str) -> List[str]:+ """+ Extract URLs from a query string or interpret as an URL if possible.+ For non-URL queries, use a DuckDuckGo search to find relevant URLs.++ Args:+ query: The search query or URL++ Returns:+ List of URLs to search in the Wayback Machine+ """+ # Check if the query is already a URL+ url_pattern = re.compile(r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+')+ urls = url_pattern.findall(query)++ if urls:+ logger.info(f"Found {len(urls)} URLs in query")+ return urls++ # Check if query is a domain without http prefix+ domain_pattern = re.compile(r'^(?:[-\w.]|(?:%[\da-fA-F]{2}))+\.\w+$')+ if domain_pattern.match(query):+ logger.info(f"Query appears to be a domain: {query}")+ return [f"http://{query}"]++ # For non-URL queries, use DuckDuckGo to find relevant URLs+ logger.info(f"Query is not a URL, using DuckDuckGo to find relevant URLs")+ try:+ # Import DuckDuckGo search engine+ from langchain_community.utilities import DuckDuckGoSearchAPIWrapper+ ddg = DuckDuckGoSearchAPIWrapper(max_results=5)+ results = ddg.results(query)++ # Extract URLs from results+ ddg_urls = [result.get("link") for result in results if result.get("link")]+ if ddg_urls:+ logger.info(f"Found {len(ddg_urls)} URLs from DuckDuckGo search")+ return ddg_urls+ except Exception as e:+ logger.error(f"Error using DuckDuckGo for URL discovery: {e}")++ # Fallback: treat the query as a potential domain or path+ if "/" in query and "." in query:+ logger.info(f"Treating query as a partial URL: {query}")+ return [f"http://{query}"]+ elif "." in query:+ logger.info(f"Treating query as a domain: {query}")+ return [f"http://{query}"]++ # Return empty list if nothing worked+ logger.warning(f"Could not extract any URLs from query: {query}")+ return []++ def _format_timestamp(self, timestamp: str) -> str:+ """Format Wayback Machine timestamp into readable date"""+ if len(timestamp) < 14:+ return timestamp++ try:+ year = timestamp[0:4]+ month = timestamp[4:6]+ day = timestamp[6:8]+ hour = timestamp[8:10]+ minute = timestamp[10:12]+ second = timestamp[12:14]+ return f"{year}-{month}-{day} {hour}:{minute}:{second}"+ except:+ return timestamp++ def _get_wayback_snapshots(self, url: str) -> List[Dict[str, Any]]:+ """+ Get snapshots from the Wayback Machine for a specific URL.++ Args:+ url: URL to get snapshots for++ Returns:+ List of snapshot dictionaries+ """+ snapshots = []++ try:+ if self.closest_only:+ # Get only the closest snapshot+ response = requests.get(+ self.available_api,+ params={"url": url}+ )+ data = response.json()++ if "archived_snapshots" in data and "closest" in data["archived_snapshots"]:+ snapshot = data["archived_snapshots"]["closest"]+ snapshot_url = snapshot["url"]+ timestamp = snapshot["timestamp"]++ snapshots.append({+ "timestamp": timestamp,+ "formatted_date": self._format_timestamp(timestamp),+ "url": snapshot_url,+ "original_url": url,+ "available": snapshot.get("available", True),+ "status": snapshot.get("status", "200")+ })+ else:+ # Get multiple snapshots using CDX API+ response = requests.get(+ self.cdx_api,+ params={+ "url": url,+ "output": "json",+ "fl": "timestamp,original,statuscode,mimetype",+ "collapse": "timestamp:4", # Group by year+ "limit": self.max_snapshots_per_url+ }+ )++ # Check if response is valid JSON+ data = response.json()++ # First item is the header+ if len(data) > 1:+ headers = data[0]+ for item in data[1:]:+ snapshot = dict(zip(headers, item))+ timestamp = snapshot.get("timestamp", "")++ wayback_url = f"https://web.archive.org/web/{timestamp}/{url}"++ snapshots.append({+ "timestamp": timestamp,+ "formatted_date": self._format_timestamp(timestamp),+ "url": wayback_url,+ "original_url": url,+ "available": True,+ "status": snapshot.get("statuscode", "200")+ })++ # Limit to max snapshots per URL+ snapshots = snapshots[:self.max_snapshots_per_url]++ except Exception as e:+ logger.error(f"Error getting Wayback snapshots for {url}: {e}")++ return snapshots++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for Wayback Machine snapshots.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting Wayback Machine previews for query: {query}")++ # Extract URLs from query+ urls = self._extract_urls_from_query(query)++ if not urls:+ logger.warning(f"No URLs found in query: {query}")+ return []++ # Get snapshots for each URL+ all_snapshots = []+ for url in urls:+ snapshots = self._get_wayback_snapshots(url)+ all_snapshots.extend(snapshots)++ # Respect rate limits+ if len(urls) > 1:+ time.sleep(0.5)++ # Format as previews+ previews = []+ for snapshot in all_snapshots:+ preview = {+ "id": f"{snapshot['timestamp']}_{snapshot['original_url']}",+ "title": f"Archive of {snapshot['original_url']} ({snapshot['formatted_date']})",+ "link": snapshot["url"],+ "snippet": f"Archived version from {snapshot['formatted_date']}",+ "original_url": snapshot["original_url"],+ "timestamp": snapshot["timestamp"],+ "formatted_date": snapshot["formatted_date"]+ }+ previews.append(preview)++ logger.info(f"Found {len(previews)} Wayback Machine snapshots")+ return previews++ def _remove_boilerplate(self, html: str) -> str:+ """+ Remove boilerplate content from HTML.++ Args:+ html: HTML content++ Returns:+ Cleaned text content+ """+ if not html or not html.strip():+ return ""+ try:+ paragraphs = justext.justext(html, justext.get_stoplist(self.language))+ cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])+ return cleaned+ except Exception as e:+ logger.error(f"Error removing boilerplate: {e}")+ return html++ def _get_wayback_content(self, url: str) -> Tuple[str, str]:+ """+ Retrieve content from a Wayback Machine URL.++ Args:+ url: Wayback Machine URL++ Returns:+ Tuple of (raw_html, cleaned_text)+ """+ try:+ headers = {+ "User-Agent": "Mozilla/5.0 (Local Deep Research Bot; research project)"+ }+ response = requests.get(url, headers=headers, timeout=10)+ raw_html = response.text++ # Clean the HTML+ cleaned_text = self._remove_boilerplate(raw_html)++ return raw_html, cleaned_text+ except Exception as e:+ logger.error(f"Error retrieving content from {url}: {e}")+ return "", f"Error retrieving content: {str(e)}"++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Wayback Machine snapshots.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Check if we should add full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ logger.info("Snippet-only mode, skipping full content retrieval")+ return relevant_items++ logger.info(f"Getting full content for {len(relevant_items)} Wayback Machine snapshots")++ results = []+ for item in relevant_items:+ wayback_url = item.get("link")+ if not wayback_url:+ results.append(item)+ continue++ logger.info(f"Retrieving content from {wayback_url}")++ try:+ # Retrieve content+ raw_html, full_content = self._get_wayback_content(wayback_url)++ # Add full content to the result+ result = item.copy()+ result["raw_html"] = raw_html+ result["full_content"] = full_content++ results.append(result)++ # Brief pause for rate limiting+ time.sleep(0.5)+ except Exception as e:+ logger.error(f"Error processing {wayback_url}: {e}")+ results.append(item)++ return results++ def search_by_url(self, url: str, max_snapshots: int = None) -> List[Dict[str, Any]]:+ """+ Search for archived versions of a specific URL.++ Args:+ url: The URL to search for archives+ max_snapshots: Maximum number of snapshots to return++ Returns:+ List of snapshot dictionaries+ """+ max_snapshots = max_snapshots or self.max_snapshots_per_url++ snapshots = self._get_wayback_snapshots(url)+ previews = []++ for snapshot in snapshots[:max_snapshots]:+ preview = {+ "id": f"{snapshot['timestamp']}_{snapshot['original_url']}",+ "title": f"Archive of {snapshot['original_url']} ({snapshot['formatted_date']})",+ "link": snapshot["url"],+ "snippet": f"Archived version from {snapshot['formatted_date']}",+ "original_url": snapshot["original_url"],+ "timestamp": snapshot["timestamp"],+ "formatted_date": snapshot["formatted_date"]+ }+ previews.append(preview)++ # Get full content if not in snippets-only mode+ if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:+ return self._get_full_content(previews)++ return previews++ def search_by_date_range(self, url: str, start_date: str, end_date: str) -> List[Dict[str, Any]]:+ """+ Search for archived versions of a URL within a date range.++ Args:+ url: The URL to search for archives+ start_date: Start date in format YYYYMMDD+ end_date: End date in format YYYYMMDD++ Returns:+ List of snapshot dictionaries+ """+ try:+ # Use CDX API with date range+ response = requests.get(+ self.cdx_api,+ params={+ "url": url,+ "output": "json",+ "fl": "timestamp,original,statuscode,mimetype",+ "from": start_date,+ "to": end_date,+ "limit": self.max_snapshots_per_url+ }+ )++ # Process response+ data = response.json()++ # First item is the header+ if len(data) <= 1:+ return []++ headers = data[0]+ snapshots = []++ for item in data[1:]:+ snapshot = dict(zip(headers, item))+ timestamp = snapshot.get("timestamp", "")++ wayback_url = f"https://web.archive.org/web/{timestamp}/{url}"++ snapshots.append({+ "id": f"{timestamp}_{url}",+ "title": f"Archive of {url} ({self._format_timestamp(timestamp)})",+ "link": wayback_url,+ "snippet": f"Archived version from {self._format_timestamp(timestamp)}",+ "original_url": url,+ "timestamp": timestamp,+ "formatted_date": self._format_timestamp(timestamp)+ })++ # Get full content if not in snippets-only mode+ if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:+ return self._get_full_content(snapshots)++ return snapshots++ except Exception as e:+ logger.error(f"Error searching date range for {url}: {e}")+ return []++ def get_latest_snapshot(self, url: str) -> Optional[Dict[str, Any]]:+ """+ Get the most recent snapshot of a URL.++ Args:+ url: The URL to get the latest snapshot for++ Returns:+ Dictionary with snapshot information or None if not found+ """+ try:+ response = requests.get(+ self.available_api,+ params={"url": url}+ )+ data = response.json()++ if "archived_snapshots" in data and "closest" in data["archived_snapshots"]:+ snapshot = data["archived_snapshots"]["closest"]+ timestamp = snapshot["timestamp"]+ wayback_url = snapshot["url"]++ result = {+ "id": f"{timestamp}_{url}",+ "title": f"Latest archive of {url} ({self._format_timestamp(timestamp)})",+ "link": wayback_url,+ "snippet": f"Archived version from {self._format_timestamp(timestamp)}",+ "original_url": url,+ "timestamp": timestamp,+ "formatted_date": self._format_timestamp(timestamp)+ }++ # Get full content if not in snippets-only mode+ if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:+ raw_html, full_content = self._get_wayback_content(wayback_url)+ result["raw_html"] = raw_html+ result["full_content"] = full_content++ return result++ return None++ except Exception as e:+ logger.error(f"Error getting latest snapshot for {url}: {e}")+ return None\ No newline at end of filediff --git a/web_search_engines/search_engines_config.py b/web_search_engines/search_engines_config.pyindex 86a017fc25..1dae43f3f1 100644--- a/web_search_engines/search_engines_config.py+++ b/web_search_engines/search_engines_config.py@@ -34,7 +34,24 @@ SEARCH_ENGINES = {}},-+ # GitHub search engine+ "github": {+ "module_path": "web_search_engines.engines.search_engine_github",+ "class_name": "GitHubSearchEngine",+ "requires_api_key": False, # Works without API key but rate limited+ #"api_key_env": "GITHUB_API_KEY",+ "reliability": 0.99,+ "strengths": ["code repositories", "software documentation", "open source projects",+ "programming issues", "developer information", "technical documentation"],+ "weaknesses": ["non-technical content", "content outside GitHub", "rate limits without API key"],+ "default_params": {+ "max_results": 15,+ "search_type": "repositories", # Options: "repositories", "code", "issues", "users"+ "include_readme": True,+ "include_issues": False+ },+ "supports_full_search": True+ },# DuckDuckGo search engine"duckduckgo": {"module_path": "web_search_engines.engines.search_engine_ddg",@@ -87,6 +104,24 @@ SEARCH_ENGINES = {"order_by": "relevance"}},+ # Wayback Machine search engine - not sure if it is usefull+ "wayback": {+ "module_path": "web_search_engines.engines.search_engine_wayback",+ "class_name": "WaybackSearchEngine",+ "requires_api_key": False,+ "reliability": 0.5,+ "strengths": ["historical web content", "archived websites", "content verification",+ "deleted or changed web pages", "website evolution tracking"],+ "weaknesses": ["limited to previously archived content", "may miss recent changes",+ "archiving quality varies"],+ "default_params": {+ "max_results": 15,+ "max_snapshots_per_url": 3,+ "closest_only": False,+ "language": "English"+ },+ "supports_full_search": True+ },# Meta search engine (intelligent engine selection)"auto": {"module_path": "web_search_engines.engines.meta_search_engine",