~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
feat(searxng): add opt-in JSON result format (#5078) (#5191)
Ehsan1e52383b72db
diff --git a/changelog.d/+searxng-json-format.feature.md b/changelog.d/+searxng-json-format.feature.mdnew file mode 100644index 0000000000..7e01c2b136--- /dev/null+++ b/changelog.d/+searxng-json-format.feature.md@@ -0,0 +1 @@+SearXNG can now be queried via its JSON API. A new **Result Format** option (`search.engine.web.searxng.default_params.result_format`) requests `format=json` and parses the structured response instead of scraping HTML. This supports instances that enable the JSON API but disable HTML output. HTML remains the default, so existing setups are unchanged.diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 117a79e464..1e19744841 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -2716,6 +2716,29 @@"value": 15,"visible": true},+ "search.engine.web.searxng.default_params.result_format": {+ "category": "searxng",+ "description": "Response format to request from SearXNG. Use 'json' for instances that enable the JSON API but disable HTML output; 'html' scrapes the results page.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Result Format",+ "options": [+ {+ "label": "HTML",+ "value": "html"+ },+ {+ "label": "JSON",+ "value": "json"+ }+ ],+ "step": null,+ "type": "SEARCH",+ "ui_element": "select",+ "value": "html",+ "visible": true+ },"search.engine.web.searxng.default_params.safe_search": {"category": "searxng","description": "Configure the safe search level",diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex e27e959afa..515d495472 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py@@ -102,6 +102,7 @@ class SearXNGSearchEngine(BaseSearchEngine):language: str = "en",safe_search: str = SafeSearchSetting.OFF.name,time_range: Optional[str] = None,+ result_format: str = "html",delay_between_requests: float = 0.0,llm: Optional[BaseLLM] = None,max_filtered_results: Optional[int] = None,@@ -120,6 +121,9 @@ class SearXNGSearchEngine(BaseSearchEngine):language: Language code for search resultssafe_search: Safe search level (0=off, 1=moderate, 2=strict)time_range: Time range for results (day, week, month, year)+ result_format: Response format to request from SearXNG, either+ "html" (default, scraped) or "json". Use "json" for instances+ whose ``search.formats`` enables JSON but not HTML.delay_between_requests: Seconds to wait between requestsllm: Language model for relevance filteringmax_filtered_results: Maximum number of results to keep after filtering@@ -188,6 +192,15 @@ class SearXNGSearchEngine(BaseSearchEngine):self.safe_search = SafeSearchSetting.OFFself.time_range = time_range+ normalized_format = str(result_format).strip().lower()+ if normalized_format not in ("html", "json"):+ logger.warning(+ f"'{result_format}' is not a supported SearXNG result_format "+ "('html' or 'json'). Falling back to 'html'."+ )+ normalized_format = "html"+ self.result_format = normalized_format+self.delay_between_requests = float(delay_between_requests)if self.is_available:@@ -268,7 +281,7 @@ class SearXNGSearchEngine(BaseSearchEngine):"q": query,"categories": ",".join(self.categories),"language": self.language,- "format": "html", # Use HTML format instead of JSON+ "format": self.result_format,"pageno": 1,"safesearch": self.safe_search.value,"count": self.max_results,@@ -303,6 +316,9 @@ class SearXNGSearchEngine(BaseSearchEngine):)if response.status_code == 200:+ if self.result_format == "json":+ return self._parse_json_results(response, query)+try:from bs4 import BeautifulSoup@@ -444,6 +460,70 @@ class SearXNGSearchEngine(BaseSearchEngine):)return []+ def _parse_json_results(+ self, response: Any, query: str+ ) -> List[Dict[str, Any]]:+ """Parse SearXNG's ``format=json`` response.++ SearXNG returns a JSON document whose ``results`` array already+ carries structured ``url``/``title``/``content`` fields, so no HTML+ scraping is needed. The output shape matches the HTML parse path+ (``title``, ``url``, ``content``, ``engine``, ``category``) and the+ same ``_is_valid_search_result`` filter is applied so both paths+ reject SearXNG's own internal/stats pages identically.+ """+ try:+ data = response.json()+ except (json.JSONDecodeError, ValueError) as e:+ safe_msg = self._scrub_error(e)+ logger.exception(+ f"Error parsing JSON results ({type(e).__name__}): {safe_msg}. "+ "Ensure the SearXNG instance enables the 'json' format."+ )+ return []++ # Surface backend engine failures the same way the HTML path does.+ unresponsive = data.get("unresponsive_engines") or []+ if unresponsive:+ logger.warning(+ f"SearXNG reported unresponsive engines: {unresponsive}"+ )++ results: List[Dict[str, Any]] = []+ for item in data.get("results", []):+ if len(results) >= self.max_results:+ break+ if not isinstance(item, dict):+ continue++ url = self._clean_result_url(item.get("url"))+ if not self._is_valid_search_result(url):+ logger.debug(+ f"Filtered invalid SearXNG result: url={redact_url_for_log(url)}"+ )+ continue++ results.append(+ {+ "title": item.get("title") or "",+ "url": url,+ "content": item.get("content") or "",+ "engine": item.get("engine") or "searxng",+ "category": item.get("category") or "general",+ }+ )++ if results:+ logger.info(+ f"SearXNG returned {len(results)} valid results from JSON parsing"+ )+ else:+ logger.warning(+ f"SearXNG returned no valid results for query: {query}. "+ "This may indicate SearXNG backend engine issues or rate limiting."+ )+ return results+def _get_previews(self, query: str) -> List[Dict[str, Any]]:"""Get preview information for SearXNG search results.diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 0af0244fec..35df7918b9 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -6030,6 +6030,29 @@"value": 15,"visible": true},+ "search.engine.web.searxng.default_params.result_format": {+ "category": "searxng",+ "description": "Response format to request from SearXNG. Use 'json' for instances that enable the JSON API but disable HTML output; 'html' scrapes the results page.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Result Format",+ "options": [+ {+ "label": "HTML",+ "value": "html"+ },+ {+ "label": "JSON",+ "value": "json"+ }+ ],+ "step": null,+ "type": "SEARCH",+ "ui_element": "select",+ "value": "html",+ "visible": true+ },"search.engine.web.searxng.default_params.safe_search": {"category": "searxng","description": "Configure the safe search level",diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.pyindex a5c6a4d522..eccdf363f6 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py@@ -1020,3 +1020,184 @@ class TestCategoriesNormalization:)assert engine.engines == ["google", "bing"]+++class TestResultFormat:+ """Tests for the opt-in JSON result_format (issue #5078)."""++ @staticmethod+ def _search_params(mock_get):+ """Return the ``params`` dict of the search request safe_get call."""+ for call in mock_get.call_args_list:+ if "params" in call.kwargs:+ return call.kwargs["params"]+ raise AssertionError("no safe_get call carried a params kwarg")++ def test_default_format_is_html(self):+ """Without an override the engine still requests format=html."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+ ) as mock_get:+ mock_response_init = Mock()+ mock_response_init.status_code = 200+ mock_response_init.cookies = {}++ mock_response_search = Mock()+ mock_response_search.status_code = 200+ mock_response_search.text = "<html><body></body></html>"+ mock_response_search.cookies = {}++ mock_get.side_effect = [+ mock_response_init,+ mock_response_init,+ mock_response_search,+ ]++ engine = SearXNGSearchEngine(instance_url="http://localhost:8080")+ assert engine.result_format == "html"++ engine._get_search_results("test query")+ assert self._search_params(mock_get)["format"] == "html"++ def test_json_format_requests_json_and_parses_results(self):+ """result_format='json' requests format=json and parses the JSON body.++ On the HTML-only code path a JSON document is handed to+ BeautifulSoup, which finds no result elements, so this returns an+ empty list. The JSON path returns the two structured results.+ """+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ json_body = {+ "query": "test query",+ "results": [+ {+ "url": "https://example.com/page1",+ "title": "Result 1",+ "content": "First result content.",+ "engine": "duckduckgo",+ "category": "general",+ },+ {+ "url": "https://example.com/page2",+ "title": "Result 2",+ "content": "Second result content.",+ "engine": "brave",+ "category": "general",+ },+ ],+ "unresponsive_engines": [],+ }++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+ ) as mock_get:+ mock_response_init = Mock()+ mock_response_init.status_code = 200+ mock_response_init.cookies = {}++ mock_response_search = Mock()+ mock_response_search.status_code = 200+ mock_response_search.cookies = {}+ mock_response_search.json.return_value = json_body++ mock_get.side_effect = [+ mock_response_init,+ mock_response_init,+ mock_response_search,+ ]++ engine = SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ result_format="json",+ )+ assert engine.result_format == "json"++ results = engine._get_search_results("test query")++ assert self._search_params(mock_get)["format"] == "json"+ assert len(results) == 2+ assert results[0] == {+ "title": "Result 1",+ "url": "https://example.com/page1",+ "content": "First result content.",+ "engine": "duckduckgo",+ "category": "general",+ }+ assert results[1]["url"] == "https://example.com/page2"+ assert results[1]["engine"] == "brave"++ def test_json_format_filters_internal_urls(self):+ """The JSON path rejects the same internal/stats pages the HTML path does."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ json_body = {+ "results": [+ {+ "url": "http://localhost:8080/stats?engine=google",+ "title": "internal stats",+ "content": "",+ },+ {+ "url": "https://example.com/real",+ "title": "Real Result",+ "content": "kept",+ },+ ],+ }++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+ ) as mock_get:+ mock_response_init = Mock()+ mock_response_init.status_code = 200+ mock_response_init.cookies = {}++ mock_response_search = Mock()+ mock_response_search.status_code = 200+ mock_response_search.cookies = {}+ mock_response_search.json.return_value = json_body++ mock_get.side_effect = [+ mock_response_init,+ mock_response_init,+ mock_response_search,+ ]++ engine = SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ result_format="json",+ )++ results = engine._get_search_results("test query")++ assert len(results) == 1+ assert results[0]["url"] == "https://example.com/real"++ def test_invalid_format_falls_back_to_html(self):+ """An unsupported result_format is coerced to 'html' with a warning."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+ ) as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_get.return_value = mock_response++ engine = SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ result_format="csv",+ )++ assert engine.result_format == "html"