Skip to content

~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.

Feature: Add Exa.ai search engine implementation (#2075)

NimbleAINinja151983552ec0
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index c41212c969..599fda4871 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -219,27 +219,90 @@
"min_value": null,
"name": "UI Theme",
"options": [
- {"label": "Dark (Default)", "value": "dark"},
- {"label": "Light", "value": "light"},
- {"label": "Sepia (Reading)", "value": "sepia"},
- {"label": "High Contrast", "value": "high-contrast"},
- {"label": "Midnight Blue", "value": "midnight"},
- {"label": "Ocean", "value": "ocean"},
- {"label": "Forest", "value": "forest"},
- {"label": "Sunset", "value": "sunset"},
- {"label": "Rose", "value": "rose"},
- {"label": "Lavender", "value": "lavender"},
- {"label": "Nord", "value": "nord"},
- {"label": "Dracula", "value": "dracula"},
- {"label": "Monokai", "value": "monokai"},
- {"label": "Solarized Dark", "value": "solarized-dark"},
- {"label": "Solarized Light", "value": "solarized-light"},
- {"label": "Gruvbox Dark", "value": "gruvbox-dark"},
- {"label": "Gruvbox Light", "value": "gruvbox-light"},
- {"label": "Tokyo Night", "value": "tokyo-night"},
- {"label": "Catppuccin", "value": "catppuccin"},
- {"label": "One Dark", "value": "one-dark"},
- {"label": "System Default", "value": "system"}
+ {
+ "label": "Dark (Default)",
+ "value": "dark"
+ },
+ {
+ "label": "Light",
+ "value": "light"
+ },
+ {
+ "label": "Sepia (Reading)",
+ "value": "sepia"
+ },
+ {
+ "label": "High Contrast",
+ "value": "high-contrast"
+ },
+ {
+ "label": "Midnight Blue",
+ "value": "midnight"
+ },
+ {
+ "label": "Ocean",
+ "value": "ocean"
+ },
+ {
+ "label": "Forest",
+ "value": "forest"
+ },
+ {
+ "label": "Sunset",
+ "value": "sunset"
+ },
+ {
+ "label": "Rose",
+ "value": "rose"
+ },
+ {
+ "label": "Lavender",
+ "value": "lavender"
+ },
+ {
+ "label": "Nord",
+ "value": "nord"
+ },
+ {
+ "label": "Dracula",
+ "value": "dracula"
+ },
+ {
+ "label": "Monokai",
+ "value": "monokai"
+ },
+ {
+ "label": "Solarized Dark",
+ "value": "solarized-dark"
+ },
+ {
+ "label": "Solarized Light",
+ "value": "solarized-light"
+ },
+ {
+ "label": "Gruvbox Dark",
+ "value": "gruvbox-dark"
+ },
+ {
+ "label": "Gruvbox Light",
+ "value": "gruvbox-light"
+ },
+ {
+ "label": "Tokyo Night",
+ "value": "tokyo-night"
+ },
+ {
+ "label": "Catppuccin",
+ "value": "catppuccin"
+ },
+ {
+ "label": "One Dark",
+ "value": "one-dark"
+ },
+ {
+ "label": "System Default",
+ "value": "system"
+ }
],
"step": null,
"type": "APP",
@@ -1889,9 +1952,18 @@
"min_value": null,
"name": "Knowledge Accumulation",
"options": [
- {"label": "Per Iteration", "value": "ITERATION"},
- {"label": "Per Question", "value": "QUESTION"},
- {"label": "No Knowledge Accumulation", "value": "NO_KNOWLEDGE"}
+ {
+ "label": "Per Iteration",
+ "value": "ITERATION"
+ },
+ {
+ "label": "Per Question",
+ "value": "QUESTION"
+ },
+ {
+ "label": "No Knowledge Accumulation",
+ "value": "NO_KNOWLEDGE"
+ }
],
"step": null,
"type": "APP",
@@ -4979,7 +5051,7 @@
},
"research_library.shared_library": {
"category": "research_library",
- "description": "\u26a0\ufe0f WARNING: When enabled, all users share the same library directory. Documents from all users will be visible to each other. Only enable in trusted environments.",
+ "description": "⚠️ WARNING: When enabled, all users share the same library directory. Documents from all users will be visible to each other. Only enable in trusted environments.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -5158,5 +5230,203 @@
"ui_element": "checkbox",
"value": false,
"visible": true
+ },
+ "search.engine.web.exa.display_name": {
+ "category": "exa",
+ "description": "Display name to use in the U.I. for this search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Display Name",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "Exa",
+ "visible": false
+ },
+ "search.engine.web.exa.description": {
+ "category": "exa",
+ "description": "Human-readable description of the search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Description",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "Neural search engine built for AI with semantic understanding and high-quality results optimized for LLM consumption.",
+ "visible": false
+ },
+ "search.engine.web.exa.api_key": {
+ "category": "exa",
+ "description": "The Exa API key to use. Get one at exa.ai.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Api Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
+ "search.engine.web.exa.class_name": {
+ "category": "exa",
+ "description": "Internal: Python class implementing Exa search. Do not modify.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Class Name",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "ExaSearchEngine",
+ "visible": false
+ },
+ "search.engine.web.exa.default_params.search_type": {
+ "category": "exa",
+ "description": "Search type - auto (default), neural (semantic), fast, or deep (comprehensive multi-query)",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Search Type",
+ "options": [
+ "auto",
+ "neural",
+ "fast",
+ "deep"
+ ],
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "select",
+ "value": "auto",
+ "visible": true
+ },
+ "search.engine.web.exa.default_params.include_full_content": {
+ "category": "exa",
+ "description": "Include full webpage content in results",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include Full Content",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.exa.module_path": {
+ "category": "exa",
+ "description": "Internal: Python module path for this search engine implementation. Do not modify.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Module Path",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": ".engines.search_engine_exa",
+ "visible": false
+ },
+ "search.engine.web.exa.requires_api_key": {
+ "category": "exa",
+ "description": "Indicates this engine requires an Exa API key. Get one at exa.ai.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires Api Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.exa.reliability": {
+ "category": "exa",
+ "description": "Reliability score (0-1). Exa rated high (0.85) - neural search with semantic understanding designed for AI applications.",
+ "editable": true,
+ "max_value": 1.0,
+ "min_value": 0.0,
+ "name": "Reliability",
+ "options": null,
+ "step": 0.05,
+ "type": "SEARCH",
+ "ui_element": "range",
+ "value": 0.85,
+ "visible": true
+ },
+ "search.engine.web.exa.strengths": {
+ "category": "exa",
+ "description": "Advantages: Neural search with semantic understanding, results optimized for LLM consumption, high-quality content, supports deep search mode.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Strengths",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "neural search with semantic understanding",
+ "results optimized for LLM consumption",
+ "high-quality, clean content",
+ "supports deep search for comprehensive results",
+ "built-in highlights and summaries",
+ "date filtering and domain controls"
+ ],
+ "visible": true
+ },
+ "search.engine.web.exa.supports_full_search": {
+ "category": "exa",
+ "description": "Indicates this engine can fetch full page content after initial search, not just snippets.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Supports Full Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.exa.weaknesses": {
+ "category": "exa",
+ "description": "Limitations: Requires paid API key with usage limits, newer service with evolving features.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Weaknesses",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "requires API key with usage limits",
+ "newer service still evolving",
+ "costs scale with usage"
+ ],
+ "visible": true
+ },
+ "search.engine.web.exa.use_in_auto_search": {
+ "category": "exa",
+ "description": "Include Exa in auto search mode",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
}
}
diff --git a/src/local_deep_research/security/module_whitelist.py b/src/local_deep_research/security/module_whitelist.py
index b15d754e40..4e3340bd10 100644
--- a/src/local_deep_research/security/module_whitelist.py
+++ b/src/local_deep_research/security/module_whitelist.py
@@ -36,6 +36,7 @@ ALLOWED_MODULE_PATHS: frozenset[str] = frozenset(
".engines.search_engine_collection",
".engines.search_engine_ddg",
".engines.search_engine_elasticsearch",
+ ".engines.search_engine_exa",
".engines.search_engine_github",
".engines.search_engine_google_pse",
".engines.search_engine_guardian",
@@ -75,6 +76,7 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset(
"CollectionSearchEngine",
"DuckDuckGoSearchEngine",
"ElasticsearchSearchEngine",
+ "ExaSearchEngine",
"FullSearchResults",
"GitHubSearchEngine",
"GooglePSESearchEngine",
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_exa.py b/src/local_deep_research/web_search_engines/engines/search_engine_exa.py
new file mode 100644
index 0000000000..0b9fa4056e
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_exa.py
@@ -0,0 +1,369 @@
+from typing import Any, Dict, List, Optional
+from urllib.parse import urlparse
+
+import requests
+from langchain_core.language_models import BaseLLM
+from loguru import logger
+
+from ...security.safe_requests import safe_post
+from ..rate_limiting import RateLimitError
+from ..search_engine_base import BaseSearchEngine
+
+
+class ExaSearchEngine(BaseSearchEngine):
+ """Exa.ai search engine implementation with neural search capabilities"""
+
+ # Mark as public search engine
+ is_public = True
+ # Mark as generic search engine (general web search)
+ is_generic = True
+
+ def __init__(
+ self,
+ max_results: int = 10,
+ region: str = "US",
+ time_period: str = "y",
+ safe_search: bool = True,
+ search_language: str = "English",
+ api_key: Optional[str] = None,
+ llm: Optional[BaseLLM] = None,
+ include_full_content: bool = True,
+ max_filtered_results: Optional[int] = None,
+ search_type: str = "auto",
+ include_domains: Optional[List[str]] = None,
+ exclude_domains: Optional[List[str]] = None,
+ start_published_date: Optional[str] = None,
+ end_published_date: Optional[str] = None,
+ category: Optional[str] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the Exa search engine.
+
+ Args:
+ max_results: Maximum number of search results
+ region: Region code for search results (not used by Exa currently)
+ time_period: Time period for search results (not used by Exa currently)
+ safe_search: Whether to enable safe search (not used by Exa currently)
+ search_language: Language for search results (not used by Exa currently)
+ api_key: Exa API key (can also be set in UI settings)
+ llm: Language model for relevance filtering
+ include_full_content: Whether to include full webpage content in results
+ max_filtered_results: Maximum number of results to keep after filtering
+ search_type: "auto" (default), "neural", "fast", or "deep"
+ include_domains: List of domains to include in search
+ exclude_domains: List of domains to exclude from search
+ start_published_date: Only links published after this date (YYYY-MM-DD)
+ end_published_date: Only links published before this date (YYYY-MM-DD)
+ category: Data category to focus on (e.g. 'company', 'news', 'research paper')
+ settings_snapshot: Settings snapshot for thread context
+ **kwargs: Additional parameters (ignored but accepted for compatibility)
+ """
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
+ )
+ self.include_full_content = include_full_content
+ self.search_type = search_type
+ self.include_domains = include_domains or []
+ self.exclude_domains = exclude_domains or []
+ self.start_published_date = start_published_date
+ self.end_published_date = end_published_date
+ self.category = category
+
+ # Get API key - check params, database, or env vars
+ from ...config.search_config import get_setting_from_snapshot
+
+ exa_api_key = api_key
+ if not exa_api_key:
+ exa_api_key = get_setting_from_snapshot(
+ "search.engine.web.exa.api_key",
+ settings_snapshot=settings_snapshot,
+ )
+
+ if not exa_api_key:
+ raise ValueError(
+ "Exa API key not found. Please provide api_key parameter "
+ "or set it in the UI settings."
+ )
+
+ self.api_key = exa_api_key
+ self.base_url = "https://api.exa.ai"
+
+ # If full content is requested, initialize FullSearchResults
+ if include_full_content:
+ # Import FullSearchResults only if needed
+ try:
+ from .full_search import FullSearchResults
+
+ # Create a simple wrapper for Exa API calls
+ class ExaWrapper:
+ def __init__(self, parent):
+ self.parent = parent
+
+ def run(self, query):
+ return self.parent._get_previews(query)
+
+ self.full_search = FullSearchResults(
+ llm=llm,
+ web_search=ExaWrapper(self),
+ language=search_language,
+ max_results=max_results,
+ region=region,
+ time=time_period,
+ safesearch="moderate" if safe_search else "off",
+ )
+ except ImportError:
+ logger.warning(
+ "Warning: FullSearchResults not available. Full content retrieval disabled."
+ )
+ self.include_full_content = False
+
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Get preview information from Exa Search.
+
+ Args:
+ query: The search query
+
+ Returns:
+ List of preview dictionaries
+ """
+ logger.info("Getting search results from Exa")
+
+ try:
+ # Prepare the request payload
+ payload = {
+ "query": query[:400], # Limit query length
+ "type": self.search_type,
+ "numResults": min(
+ 100, self.max_results
+ ), # Exa supports up to 100
+ }
+
+ # Add optional parameters if specified
+ if self.include_domains:
+ payload["includeDomains"] = self.include_domains
+ if self.exclude_domains:
+ payload["excludeDomains"] = self.exclude_domains
+ if self.start_published_date:
+ payload["startPublishedDate"] = self.start_published_date
+ if self.end_published_date:
+ payload["endPublishedDate"] = self.end_published_date
+ if self.category:
+ payload["category"] = self.category
+
+ # Request text content if full content is enabled
+ if self.include_full_content:
+ payload["contents"] = {"text": {"maxCharacters": 10000}}
+
+ # Apply rate limiting before request
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+
+ # Make the API request
+ response = safe_post(
+ f"{self.base_url}/search",
+ json=payload,
+ headers={
+ "Content-Type": "application/json",
+ "x-api-key": self.api_key,
+ },
+ timeout=30,
+ )
+
+ # Check for errors
+ if response.status_code == 429:
+ raise RateLimitError(
+ f"Exa rate limit hit: {response.status_code} - {response.text}"
+ )
+
+ response.raise_for_status()
+
+ # Parse the response
+ data = response.json()
+ results = data.get("results", [])
+
+ # Format results as previews
+ previews = []
+ for i, result in enumerate(results):
+ # Extract text content if available
+ text_content = ""
+ if "text" in result:
+ text_content = result.get("text", "")
+
+ # Use highlights or summary as snippet if available, otherwise use text
+ snippet = ""
+ if "highlights" in result and result["highlights"]:
+ # Join highlights with ellipsis
+ snippet = " ... ".join(result["highlights"][:3])
+ elif "summary" in result:
+ snippet = result.get("summary", "")
+ elif text_content:
+ # Use first 500 chars of text as snippet
+ snippet = text_content[:500]
+
+ # Extract display link safely using urlparse
+ link = result.get("url", "")
+ display_link = ""
+ if link:
+ try:
+ parsed_url = urlparse(link)
+ display_link = parsed_url.netloc or ""
+ except Exception:
+ logger.debug(
+ f"Failed to parse URL for display: {link[:50]}"
+ )
+
+ preview = {
+ "id": result.get("id", result.get("url", str(i))),
+ "title": result.get("title", ""),
+ "link": link,
+ "snippet": snippet,
+ "displayed_link": display_link,
+ "position": i,
+ }
+
+ # Add optional fields if available
+ if "publishedDate" in result:
+ preview["published_date"] = result["publishedDate"]
+ if "author" in result:
+ preview["author"] = result["author"]
+ if "score" in result:
+ preview["score"] = result["score"]
+
+ # Store full Exa result for later
+ preview["_full_result"] = result
+
+ previews.append(preview)
+
+ # Store the previews for potential full content retrieval
+ self._search_results = previews
+
+ logger.info(f"Exa returned {len(previews)} results")
+ return previews
+
+ except RateLimitError:
+ raise # Re-raise rate limit errors
+ except requests.exceptions.RequestException as e:
+ error_msg = str(e)
+ logger.exception("Error getting Exa results")
+
+ # Check for rate limit patterns in error message
+ if any(
+ pattern in error_msg.lower()
+ for pattern in [
+ "429",
+ "rate limit",
+ "quota",
+ "too many requests",
+ ]
+ ):
+ raise RateLimitError(f"Exa rate limit hit: {error_msg}")
+
+ return []
+ except Exception:
+ logger.exception("Unexpected error getting Exa results")
+ return []
+
+ def _get_full_content(
+ self, relevant_items: List[Dict[str, Any]]
+ ) -> List[Dict[str, Any]]:
+ """
+ Get full content for the relevant search results.
+ If include_full_content is True and text content was retrieved,
+ includes it in the results.
+
+ Args:
+ relevant_items: List of relevant preview dictionaries
+
+ Returns:
+ List of result dictionaries with full content if available
+ """
+ from ...config import search_config
+
+ # Check if we should get full content
+ if (
+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
+ and search_config.SEARCH_SNIPPETS_ONLY
+ ):
+ logger.info("Snippet-only mode, skipping full content retrieval")
+
+ # Return the relevant items with their full Exa information
+ results = []
+ for item in relevant_items:
+ # Use the full result if available, otherwise use the preview
+ if "_full_result" in item:
+ result = item["_full_result"].copy()
+ # Remove temporary field
+ if "_full_result" in result:
+ del result["_full_result"]
+ else:
+ result = item.copy()
+
+ results.append(result)
+
+ return results
+
+ # If full content retrieval is enabled
+ if self.include_full_content and hasattr(self, "full_search"):
+ logger.info("Retrieving full webpage content")
+
+ try:
+ # Use FullSearchResults to get full content
+ results_with_content = self.full_search._get_full_content(
+ relevant_items
+ )
+
+ return results_with_content
+
+ except Exception:
+ logger.exception("Error retrieving full content")
+ # Fall back to returning the items without full content
+
+ # Return items with their full Exa information
+ results = []
+ for item in relevant_items:
+ # Use the full result if available, otherwise use the preview
+ if "_full_result" in item:
+ result = item["_full_result"].copy()
+
+ # Remove temporary field
+ if "_full_result" in result:
+ del result["_full_result"]
+ else:
+ result = item.copy()
+ if "_full_result" in result:
+ del result["_full_result"]
+
+ results.append(result)
+
+ return results
+
+ def run(
+ self, query: str, research_context: Dict[str, Any] | None = None
+ ) -> List[Dict[str, Any]]:
+ """
+ Execute a search using Exa with the two-phase approach.
+
+ Args:
+ query: The search query
+ research_context: Context from previous research to use.
+
+ Returns:
+ List of search results
+ """
+ logger.info("---Execute a search using Exa---")
+
+ # Use the implementation from the parent class which handles all phases
+ results = super().run(query, research_context=research_context)
+
+ # Clean up
+ if hasattr(self, "_search_results"):
+ del self._search_results
+
+ return results
diff --git a/tests/web_search_engines/engines/test_search_engine_exa.py b/tests/web_search_engines/engines/test_search_engine_exa.py
new file mode 100644
index 0000000000..4ba2ab7f9a
--- /dev/null
+++ b/tests/web_search_engines/engines/test_search_engine_exa.py
@@ -0,0 +1,559 @@
+"""
+Tests for the ExaSearchEngine class.
+
+Tests cover:
+- Initialization and configuration
+- API key handling
+- Preview generation
+- Full content retrieval
+- Rate limit error handling
+- Run method
+- Search types
+- Domain and date filtering
+"""
+
+from unittest.mock import Mock, patch
+import pytest
+
+
+class TestExaSearchEngineInit:
+ """Tests for ExaSearchEngine initialization."""
+
+ def test_init_with_api_key(self):
+ """Initialize with API key."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-api-key")
+
+ assert engine.api_key == "test-api-key"
+ assert engine.max_results == 10
+ assert engine.search_type == "auto"
+ assert engine.include_full_content is True
+
+ def test_init_with_custom_max_results(self):
+ """Initialize with custom max_results."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key", max_results=25)
+
+ assert engine.max_results == 25
+
+ def test_init_with_custom_search_type(self):
+ """Initialize with custom search_type."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key", search_type="neural")
+
+ assert engine.search_type == "neural"
+
+ def test_init_with_domain_filters(self):
+ """Initialize with domain filters."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(
+ api_key="test-key",
+ include_domains=["example.com", "test.com"],
+ exclude_domains=["spam.com"],
+ )
+
+ assert engine.include_domains == ["example.com", "test.com"]
+ assert engine.exclude_domains == ["spam.com"]
+
+ def test_init_with_date_filters(self):
+ """Initialize with date filters."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(
+ api_key="test-key",
+ start_published_date="2024-01-01",
+ end_published_date="2024-12-31",
+ )
+
+ assert engine.start_published_date == "2024-01-01"
+ assert engine.end_published_date == "2024-12-31"
+
+ def test_init_with_category(self):
+ """Initialize with category filter."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key", category="research paper")
+
+ assert engine.category == "research paper"
+
+ def test_init_without_api_key_raises(self):
+ """Initialize without API key raises ValueError."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with pytest.raises(ValueError) as exc_info:
+ ExaSearchEngine()
+
+ assert "Exa API key not found" in str(exc_info.value)
+
+ def test_init_with_api_key_from_settings(self):
+ """Initialize with API key from settings snapshot."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot",
+ return_value="settings-api-key",
+ ):
+ engine = ExaSearchEngine()
+
+ assert engine.api_key == "settings-api-key"
+
+ def test_init_with_llm(self):
+ """Initialize with LLM."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_llm = Mock()
+ engine = ExaSearchEngine(api_key="test-key", llm=mock_llm)
+
+ assert engine.llm is mock_llm
+
+ def test_init_with_include_full_content_false(self):
+ """Initialize with include_full_content=False."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key", include_full_content=False)
+
+ assert engine.include_full_content is False
+
+
+class TestGetPreviews:
+ """Tests for _get_previews method."""
+
+ def test_get_previews_returns_results(self):
+ """Get previews returns formatted results."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "results": [
+ {
+ "id": "https://example1.com",
+ "title": "Result 1",
+ "url": "https://example1.com",
+ "text": "Full text content 1",
+ },
+ {
+ "id": "https://example2.com",
+ "title": "Result 2",
+ "url": "https://example2.com",
+ "highlights": ["Highlight 1", "Highlight 2"],
+ },
+ ]
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+ previews = engine._get_previews("test query")
+
+ assert len(previews) == 2
+ assert previews[0]["title"] == "Result 1"
+ assert previews[0]["link"] == "https://example1.com"
+ assert previews[0]["displayed_link"] == "example1.com"
+ assert "Full text content 1" in previews[0]["snippet"]
+ assert previews[1]["snippet"] == "Highlight 1 ... Highlight 2"
+ assert previews[1]["displayed_link"] == "example2.com"
+
+ def test_get_previews_summary_as_snippet(self):
+ """Get previews uses summary field as snippet when no highlights."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "results": [
+ {
+ "id": "https://example.com",
+ "title": "Result",
+ "url": "https://example.com",
+ "summary": "A brief summary of the page",
+ },
+ ]
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+ previews = engine._get_previews("test query")
+
+ assert previews[0]["snippet"] == "A brief summary of the page"
+
+ def test_get_previews_optional_fields(self):
+ """Get previews includes optional fields when present."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "results": [
+ {
+ "id": "https://example.com",
+ "title": "Result",
+ "url": "https://example.com",
+ "text": "Content",
+ "publishedDate": "2024-06-15",
+ "author": "Test Author",
+ "score": 0.95,
+ },
+ ]
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+ previews = engine._get_previews("test query")
+
+ assert previews[0]["published_date"] == "2024-06-15"
+ assert previews[0]["author"] == "Test Author"
+ assert previews[0]["score"] == 0.95
+
+ def test_get_previews_rate_limit_in_request_exception(self):
+ """Get previews detects rate limit patterns in request exceptions."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+ import requests
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ side_effect=requests.exceptions.RequestException(
+ "429 Too Many Requests"
+ ),
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError):
+ engine._get_previews("test query")
+
+ def test_get_previews_with_domain_filters(self):
+ """Get previews sends domain filters to API."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ) as mock_post:
+ engine = ExaSearchEngine(
+ api_key="test-key",
+ include_domains=["example.com"],
+ exclude_domains=["spam.com"],
+ )
+ engine._get_previews("test query")
+
+ # Check that domain filters were sent
+ call_args = mock_post.call_args
+ payload = call_args[1]["json"]
+ assert payload["includeDomains"] == ["example.com"]
+ assert payload["excludeDomains"] == ["spam.com"]
+
+ def test_get_previews_with_date_filters(self):
+ """Get previews sends date filters to API."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ) as mock_post:
+ engine = ExaSearchEngine(
+ api_key="test-key",
+ start_published_date="2024-01-01",
+ end_published_date="2024-12-31",
+ )
+ engine._get_previews("test query")
+
+ # Check that date filters were sent
+ call_args = mock_post.call_args
+ payload = call_args[1]["json"]
+ assert payload["startPublishedDate"] == "2024-01-01"
+ assert payload["endPublishedDate"] == "2024-12-31"
+
+ def test_get_previews_with_category(self):
+ """Get previews sends category to API."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ) as mock_post:
+ engine = ExaSearchEngine(
+ api_key="test-key", category="research paper"
+ )
+ engine._get_previews("test query")
+
+ # Check that category was sent
+ call_args = mock_post.call_args
+ payload = call_args[1]["json"]
+ assert payload["category"] == "research paper"
+
+ def test_get_previews_with_search_type(self):
+ """Get previews sends search type to API."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ) as mock_post:
+ engine = ExaSearchEngine(api_key="test-key", search_type="neural")
+ engine._get_previews("test query")
+
+ # Check that search type was sent
+ call_args = mock_post.call_args
+ payload = call_args[1]["json"]
+ assert payload["type"] == "neural"
+
+ def test_get_previews_rate_limit_error(self):
+ """Get previews raises RateLimitError on 429."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 429
+ mock_response.text = "Rate limit exceeded"
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError):
+ engine._get_previews("test query")
+
+ def test_get_previews_empty_results(self):
+ """Get previews handles empty results."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+ previews = engine._get_previews("test query")
+
+ assert previews == []
+
+ def test_get_previews_request_exception(self):
+ """Get previews handles request exceptions."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+ import requests
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ side_effect=requests.exceptions.RequestException(
+ "Connection error"
+ ),
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+ previews = engine._get_previews("test query")
+
+ assert previews == []
+
+ def test_get_previews_unexpected_error(self):
+ """Get previews handles unexpected errors."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.side_effect = Exception("Parse error")
+ mock_response.raise_for_status = Mock()
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_exa.safe_post",
+ return_value=mock_response,
+ ):
+ engine = ExaSearchEngine(api_key="test-key")
+ previews = engine._get_previews("test query")
+
+ assert previews == []
+
+
+class TestGetFullContent:
+ """Tests for _get_full_content method."""
+
+ def test_get_full_content_returns_items(self):
+ """Get full content returns processed items."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key", include_full_content=False)
+
+ items = [
+ {
+ "title": "Result",
+ "link": "https://example.com",
+ "_full_result": {
+ "title": "Result",
+ "url": "https://example.com",
+ "text": "Full text content",
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ assert results[0]["title"] == "Result"
+ assert results[0]["text"] == "Full text content"
+
+ def test_get_full_content_without_full_result(self):
+ """Get full content handles items without _full_result."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key", include_full_content=False)
+
+ items = [{"title": "Result", "link": "https://example.com"}]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ assert results[0]["title"] == "Result"
+
+
+class TestRun:
+ """Tests for run method."""
+
+ def test_run_returns_results(self):
+ """Run returns search results."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key")
+
+ with patch.object(
+ engine,
+ "_get_previews",
+ return_value=[
+ {
+ "id": "https://example.com",
+ "title": "Result",
+ "snippet": "Snippet",
+ "link": "https://example.com",
+ }
+ ],
+ ):
+ with patch.object(
+ engine,
+ "_get_full_content",
+ return_value=[{"title": "Result", "text": "Full"}],
+ ):
+ results = engine.run("test query")
+
+ assert len(results) == 1
+
+ def test_run_handles_empty_results(self):
+ """Run handles empty results."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ engine = ExaSearchEngine(api_key="test-key")
+
+ with patch.object(engine, "_get_previews", return_value=[]):
+ results = engine.run("test query")
+
+ assert results == []
+
+
+class TestClassAttributes:
+ """Tests for class attributes."""
+
+ def test_is_public(self):
+ """ExaSearchEngine is marked as public."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ assert ExaSearchEngine.is_public is True
+
+ def test_is_generic(self):
+ """ExaSearchEngine is marked as generic."""
+ from local_deep_research.web_search_engines.engines.search_engine_exa import (
+ ExaSearchEngine,
+ )
+
+ assert ExaSearchEngine.is_generic is True