Skip to content

Commit 5c5d44a

Browse files
feat(search): add self-hosted Firecrawl provider
1 parent 45c4f28 commit 5c5d44a

7 files changed

Lines changed: 191 additions & 6 deletions

File tree

‎routes/search/search_routes.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@
99

1010
from services.search import get_search_config, comprehensive_web_search, PROVIDER_INFO
1111
from services.search.core import _call_provider
12-
from services.search.providers import _get_provider_key, _get_search_instance
12+
from services.search.providers import (
13+
_get_firecrawl_instance,
14+
_get_provider_key,
15+
_get_search_instance,
16+
)
1317

1418
logger = logging.getLogger(__name__)
1519

@@ -77,6 +81,8 @@ async def list_search_providers():
7781
available = False
7882
if needs_url and pid == "searxng" and not _get_search_instance():
7983
available = False
84+
if needs_url and pid == "firecrawl" and not _get_firecrawl_instance():
85+
available = False
8086
providers.append({
8187
"id": pid,
8288
"label": label,

‎services/search/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
update_search_config,
99
)
1010
from .content import fetch_webpage_content
11-
from .providers import searxng_search, searxng_search_api, PROVIDER_INFO
11+
from .providers import firecrawl_search, searxng_search, searxng_search_api, PROVIDER_INFO
1212
from .analytics import get_search_stats, SearchEngineError, NetworkError, ParseError, RateLimitError
1313
from .service import SearchService, SearchResult, SearchResponse
1414

@@ -23,6 +23,7 @@
2323
"get_search_config",
2424
"get_search_stats",
2525
"invalidate_search_cache",
26+
"firecrawl_search",
2627
"searxng_search",
2728
"searxng_search_api",
2829
"searxng_search_results",

‎services/search/core.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from .query import _cache_duration_for_query
2424
from .ranking import rank_search_results
2525
from .providers import (
26+
firecrawl_search,
2627
searxng_search_api,
2728
brave_search,
2829
duckduckgo_search,
@@ -67,7 +68,10 @@ def get_search_config() -> Dict[str, Any]:
6768
config["active_provider"] = provider
6869
config["has_api_key"] = bool(_get_provider_key(provider))
6970
config["result_count"] = _get_result_count()
70-
if provider == "searxng":
71+
if provider == "firecrawl":
72+
from .providers import _get_firecrawl_instance
73+
config["firecrawl_url"] = _get_firecrawl_instance()
74+
elif provider == "searxng":
7175
from .providers import _get_search_instance
7276
config["search_url"] = _get_search_instance()
7377
# Strip any string-valued credential so secrets never reach the response;
@@ -95,7 +99,9 @@ def update_search_config(api_key: str = None, **kwargs):
9599

96100
def _call_provider(provider_name: str, query: str, count: int, time_filter: str = None) -> List[dict]:
97101
"""Call a search provider by name. Returns list of results or empty list."""
98-
if provider_name == "searxng":
102+
if provider_name == "firecrawl":
103+
return firecrawl_search(query, count, time_filter)
104+
elif provider_name == "searxng":
99105
return searxng_search_api(query, count, time_filter=time_filter)
100106
elif provider_name == "brave":
101107
return brave_search(query, count, time_filter)

‎services/search/providers.py‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Search provider implementations: SearXNG, Brave, DuckDuckGo, Google PSE, Tavily, Serper."""
1+
"""Search provider implementations, including local Firecrawl and SearXNG."""
22

33
import json
44
import logging
@@ -17,6 +17,7 @@
1717

1818
# Provider registry — maps setting value to (label, needs_key, needs_url)
1919
PROVIDER_INFO = {
20+
"firecrawl": ("Firecrawl (self-hosted)", False, True),
2021
"searxng": ("SearXNG", False, True),
2122
"brave": ("Brave Search", True, False),
2223
"duckduckgo": ("DuckDuckGo", False, False),
@@ -47,10 +48,22 @@ def _get_search_instance() -> str:
4748
return SEARXNG_INSTANCE
4849

4950

51+
def _get_firecrawl_instance() -> str:
52+
"""Return the self-hosted Firecrawl API URL without a hosted fallback."""
53+
settings = _get_search_settings()
54+
url = (
55+
settings.get("firecrawl_url")
56+
or os.environ.get("FIRECRAWL_API_URL")
57+
or "http://localhost:3002"
58+
)
59+
return str(url).strip().rstrip("/")
60+
61+
5062
def _get_provider_key(provider: str) -> str:
5163
"""Return the API key for a specific provider, with legacy fallback."""
5264
settings = _get_search_settings()
5365
key_map = {
66+
"firecrawl": "firecrawl_api_key",
5467
"brave": "brave_api_key",
5568
"google_pse": "google_pse_key",
5669
"tavily": "tavily_api_key",
@@ -66,6 +79,7 @@ def _get_provider_key(provider: str) -> str:
6679
if legacy:
6780
return legacy
6881
env_map = {
82+
"firecrawl": "FIRECRAWL_API_KEY",
6983
"brave": "DATA_BRAVE_API_KEY",
7084
"google_pse": "GOOGLE_API_KEY",
7185
"tavily": "TAVILY_API_KEY",
@@ -121,6 +135,72 @@ def _safesearch_for(provider: str) -> Optional[str]:
121135
return None
122136

123137

138+
# ── Firecrawl (self-hosted) ──
139+
140+
def firecrawl_search(
141+
query: str,
142+
count: Optional[int] = None,
143+
time_filter: Optional[str] = None,
144+
) -> List[dict]:
145+
"""Search through the local Firecrawl v2 API.
146+
147+
Firecrawl is treated as a local search appliance: the URL defaults to the
148+
loopback service and never falls back to Firecrawl's hosted API. Returning
149+
an empty list on failure lets Diogenes continue through its configured
150+
provider chain (normally the independently managed SearXNG instance).
151+
"""
152+
count = count if count is not None else _get_result_count()
153+
instance = _get_firecrawl_instance()
154+
if not instance:
155+
logger.warning("Firecrawl search skipped: no local endpoint configured")
156+
return []
157+
158+
payload = {
159+
"query": query,
160+
"limit": count,
161+
"sources": [{"type": "web"}],
162+
}
163+
tbs_map = {
164+
"day": "qdr:d",
165+
"week": "qdr:w",
166+
"month": "qdr:m",
167+
"year": "qdr:y",
168+
}
169+
if time_filter in tbs_map:
170+
payload["tbs"] = tbs_map[time_filter]
171+
172+
headers = {"User-Agent": WEB_FETCH_USER_AGENT}
173+
api_key = _get_provider_key("firecrawl")
174+
if api_key:
175+
headers["Authorization"] = f"Bearer {api_key}"
176+
177+
try:
178+
response = httpx.post(
179+
f"{instance}/v2/search",
180+
json=payload,
181+
headers=headers,
182+
timeout=REQUEST_TIMEOUT,
183+
)
184+
response.raise_for_status()
185+
data = response.json()
186+
web = data.get("data", {}).get("web", []) if isinstance(data, dict) else []
187+
results = []
188+
for item in web[:count]:
189+
if not isinstance(item, dict) or not item.get("url"):
190+
continue
191+
snippet = item.get("description") or item.get("markdown") or ""
192+
results.append({
193+
"title": item.get("title") or item["url"],
194+
"url": item["url"],
195+
"snippet": str(snippet)[:2000],
196+
})
197+
logger.info("Firecrawl returned %d results for: %s", len(results), query)
198+
return results
199+
except Exception as exc:
200+
logger.warning("Local Firecrawl search failed: %s", exc)
201+
return []
202+
203+
124204
# ── SearXNG ──
125205

126206
_NEWS_HINTS = ("news", "nyheter", "headlines", "breaking", "latest", "today", "idag")

‎src/search/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
update_search_config,
99
)
1010
from .content import fetch_webpage_content
11-
from .providers import searxng_search, searxng_search_api, PROVIDER_INFO
11+
from .providers import firecrawl_search, searxng_search, searxng_search_api, PROVIDER_INFO
1212
from .analytics import get_search_stats, SearchEngineError, NetworkError, ParseError, RateLimitError
1313

1414
__all__ = [
@@ -17,6 +17,7 @@
1717
"get_search_config",
1818
"get_search_stats",
1919
"invalidate_search_cache",
20+
"firecrawl_search",
2021
"searxng_search",
2122
"searxng_search_api",
2223
"searxng_search_results",

‎src/settings.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ def _invalidate_caches():
6262
# safe to ship on by default for every user.
6363
"search_fallback_chain": ["duckduckgo"],
6464
"search_url": "",
65+
"firecrawl_url": "http://localhost:3002",
66+
"firecrawl_api_key": "",
6567
"search_result_count": 5,
6668
# SafeSearch level applied to every provider that exposes one.
6769
# "strict" — apply the provider's strongest filtering level (default;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
from __future__ import annotations
2+
3+
from services.search import core, providers
4+
5+
6+
class _Response:
7+
def __init__(self, payload):
8+
self._payload = payload
9+
10+
def raise_for_status(self):
11+
return None
12+
13+
def json(self):
14+
return self._payload
15+
16+
17+
def test_firecrawl_search_uses_local_v2_contract(monkeypatch):
18+
captured = {}
19+
monkeypatch.setattr(
20+
providers,
21+
"_get_search_settings",
22+
lambda: {
23+
"firecrawl_url": "http://127.0.0.1:3002/",
24+
"firecrawl_api_key": "fc-local",
25+
},
26+
)
27+
28+
def fake_post(url, **kwargs):
29+
captured["url"] = url
30+
captured.update(kwargs)
31+
return _Response({
32+
"success": True,
33+
"data": {"web": [{
34+
"title": "Local result",
35+
"url": "https://example.test/result",
36+
"description": "Found through the local appliance.",
37+
}]},
38+
})
39+
40+
monkeypatch.setattr(providers.httpx, "post", fake_post)
41+
42+
results = providers.firecrawl_search("private search", count=3, time_filter="week")
43+
44+
assert captured["url"] == "http://127.0.0.1:3002/v2/search"
45+
assert captured["json"] == {
46+
"query": "private search",
47+
"limit": 3,
48+
"sources": [{"type": "web"}],
49+
"tbs": "qdr:w",
50+
}
51+
assert captured["headers"]["Authorization"] == "Bearer fc-local"
52+
assert results == [{
53+
"title": "Local result",
54+
"url": "https://example.test/result",
55+
"snippet": "Found through the local appliance.",
56+
}]
57+
58+
59+
def test_firecrawl_search_fails_closed_for_provider_fallback(monkeypatch):
60+
monkeypatch.setattr(
61+
providers,
62+
"_get_search_settings",
63+
lambda: {"firecrawl_url": "http://127.0.0.1:3002"},
64+
)
65+
monkeypatch.setattr(
66+
providers.httpx,
67+
"post",
68+
lambda *args, **kwargs: (_ for _ in ()).throw(ConnectionError("offline")),
69+
)
70+
71+
assert providers.firecrawl_search("query") == []
72+
73+
74+
def test_core_dispatches_firecrawl(monkeypatch):
75+
monkeypatch.setattr(
76+
core,
77+
"firecrawl_search",
78+
lambda query, count, time_filter: [{
79+
"title": query,
80+
"url": "https://example.test",
81+
"snippet": f"{count}:{time_filter}",
82+
}],
83+
)
84+
85+
assert core._call_provider("firecrawl", "needle", 7, "day") == [{
86+
"title": "needle",
87+
"url": "https://example.test",
88+
"snippet": "7:day",
89+
}]

0 commit comments

Comments
 (0)