~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
fix: address review issues in Exa search engine (#2075) (#2660)
LearningCircuit5bb9097c13e8
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.pyindex 0b9fa4056e..714f1c75f3 100644--- 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@@ -65,6 +65,7 @@ class ExaSearchEngine(BaseSearchEngine):llm=llm,max_filtered_results=max_filtered_results,max_results=max_results,+ settings_snapshot=settings_snapshot,)self.include_full_content = include_full_contentself.search_type = search_type@@ -74,54 +75,15 @@ class ExaSearchEngine(BaseSearchEngine):self.end_published_date = end_published_dateself.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+ # Resolve API key using base class method+ self.api_key = self._resolve_api_key(+ api_key,+ "search.engine.web.exa.api_key",+ engine_name="Exa",+ settings_snapshot=settings_snapshot,+ )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.@@ -158,7 +120,11 @@ class ExaSearchEngine(BaseSearchEngine):# Request text content if full content is enabledif self.include_full_content:- payload["contents"] = {"text": {"maxCharacters": 10000}}+ payload["contents"] = {+ "text": {"maxCharacters": 10000},+ "highlights": {"maxCharacters": 500, "query": query},+ "summary": {"query": query},+ }# Apply rate limiting before requestself._last_wait_time = self.rate_tracker.apply_rate_limit(@@ -176,11 +142,8 @@ class ExaSearchEngine(BaseSearchEngine):timeout=30,)- # Check for errors- if response.status_code == 429:- raise RateLimitError(- f"Exa rate limit hit: {response.status_code} - {response.text}"- )+ # Check for rate limits+ self._raise_if_rate_limit(response.status_code)response.raise_for_status()@@ -192,15 +155,14 @@ class ExaSearchEngine(BaseSearchEngine):previews = []for i, result in enumerate(results):# Extract text content if available- text_content = ""- if "text" in result:- text_content = result.get("text", "")+ text_content = result.get("text", "")# Use highlights or summary as snippet if available, otherwise use textsnippet = ""- if "highlights" in result and result["highlights"]:+ highlights = result.get("highlights")+ if highlights and isinstance(highlights, list):# Join highlights with ellipsis- snippet = " ... ".join(result["highlights"][:3])+ snippet = " ... ".join(highlights[:3])elif "summary" in result:snippet = result.get("summary", "")elif text_content:@@ -241,129 +203,22 @@ class ExaSearchEngine(BaseSearchEngine):previews.append(preview)- # Store the previews for potential full content retrieval- self._search_results = previews-logger.info(f"Exa returned {len(previews)} results")return previewsexcept RateLimitError:raise # Re-raise rate limit errorsexcept 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}")-+ self._raise_if_rate_limit(e)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- """+ """Execute a search using Exa with the two-phase approach."""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+ return super().run(query, research_context=research_context)diff --git a/tests/web_search_engines/engines/test_search_engine_exa.py b/tests/web_search_engines/engines/test_search_engine_exa.pyindex 4ba2ab7f9a..99b5f0a137 100644--- a/tests/web_search_engines/engines/test_search_engine_exa.py+++ b/tests/web_search_engines/engines/test_search_engine_exa.py@@ -98,14 +98,10 @@ class TestExaSearchEngineInit:ExaSearchEngine,)- with patch(- "local_deep_research.config.search_config.get_setting_from_snapshot",- return_value=None,- ):- with pytest.raises(ValueError) as exc_info:- ExaSearchEngine()+ with pytest.raises(ValueError) as exc_info:+ ExaSearchEngine(settings_snapshot={})- assert "Exa API key not found" in str(exc_info.value)+ assert "No valid API key found for Exa" in str(exc_info.value)def test_init_with_api_key_from_settings(self):"""Initialize with API key from settings snapshot."""@@ -113,13 +109,13 @@ class TestExaSearchEngineInit:ExaSearchEngine,)- with patch(- "local_deep_research.config.search_config.get_setting_from_snapshot",- return_value="settings-api-key",- ):- engine = ExaSearchEngine()+ engine = ExaSearchEngine(+ settings_snapshot={+ "search.engine.web.exa.api_key": "settings-api-key"+ }+ )- assert engine.api_key == "settings-api-key"+ assert engine.api_key == "settings-api-key"def test_init_with_llm(self):"""Initialize with LLM."""@@ -452,12 +448,12 @@ class TestGetFullContent:"""Tests for _get_full_content method."""def test_get_full_content_returns_items(self):- """Get full content returns processed items."""+ """Get full content returns processed items using _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)+ engine = ExaSearchEngine(api_key="test-key")items = [{@@ -476,6 +472,7 @@ class TestGetFullContent:assert len(results) == 1assert results[0]["title"] == "Result"assert results[0]["text"] == "Full text content"+ assert "_full_result" not in results[0]def test_get_full_content_without_full_result(self):"""Get full content handles items without _full_result."""@@ -483,7 +480,7 @@ class TestGetFullContent:ExaSearchEngine,)- engine = ExaSearchEngine(api_key="test-key", include_full_content=False)+ engine = ExaSearchEngine(api_key="test-key")items = [{"title": "Result", "link": "https://example.com"}]@@ -491,6 +488,7 @@ class TestGetFullContent:assert len(results) == 1assert results[0]["title"] == "Result"+ assert results[0]["link"] == "https://example.com"class TestRun:@@ -557,3 +555,150 @@ class TestClassAttributes:)assert ExaSearchEngine.is_generic is True+++class TestContentsPayload:+ """Tests for contents payload in _get_previews."""++ def test_contents_includes_highlights_and_summary(self):+ """Contents payload includes text, highlights, and summary."""+ 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_full_content=True+ )+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ contents = payload["contents"]+ assert "text" in contents+ assert contents["text"] == {"maxCharacters": 10000}+ assert "highlights" in contents+ assert contents["highlights"] == {+ "maxCharacters": 500,+ "query": "test query",+ }+ assert "summary" in contents+ assert contents["summary"] == {"query": "test query"}++ def test_no_contents_when_full_content_disabled(self):+ """No contents payload when include_full_content is False."""+ 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_full_content=False+ )+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert "contents" not in payload+++class TestHighlightsTypeSafety:+ """Tests for highlights type safety in _get_previews."""++ def test_highlights_as_string_ignored(self):+ """Non-list highlights are ignored, falls through to summary or text."""+ 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": [+ {+ "title": "Result",+ "url": "https://example.com",+ "highlights": "not a list",+ "text": "Some text content",+ },+ ]+ }++ 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")++ # Should fall through to text since highlights is not a list+ assert previews[0]["snippet"] == "Some text content"[:500]++ def test_highlights_as_list_used(self):+ """List highlights are properly joined."""+ 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": [+ {+ "title": "Result",+ "url": "https://example.com",+ "highlights": ["First highlight", "Second highlight"],+ },+ ]+ }++ 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"] == "First highlight ... Second highlight"+ )++ def test_empty_highlights_list_falls_through(self):+ """Empty highlights list falls through to summary or text."""+ 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": [+ {+ "title": "Result",+ "url": "https://example.com",+ "highlights": [],+ "summary": "A summary",+ },+ ]+ }++ 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 summary"