Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(python-sdk): construct without an API key, keep the sync watcher working on Python 3.8 (#5245)
Erik Engervall5c1fb26173ac
diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.pyindex 059816501..5c559d264 100644--- a/apps/python-sdk/firecrawl/__init__.py+++ b/apps/python-sdk/firecrawl/__init__.py@@ -42,7 +42,7 @@ from .v1 import (V1ChangeTrackingOptions,)-__version__ = "4.53.0"+__version__ = "4.53.1"# Define the logger for the Firecrawl projectlogger: logging.Logger = logging.getLogger("firecrawl")diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/watcher/test_ws_watcher.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/watcher/test_ws_watcher.pyindex 6f5888664..24a62b1b7 100644--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/watcher/test_ws_watcher.py+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/watcher/test_ws_watcher.py@@ -330,3 +330,59 @@ def test_ws_watcher_uses_correct_ws_uri(monkeypatch, kind):assert captured_uri["uri"] is not Noneexpected = "ws://localhost/v2/crawl/jid" if kind == "crawl" else "ws://localhost/v2/batch/scrape/jid"assert captured_uri["uri"] == expected+++class PollingClient(DummyClient):+ def __init__(self, statuses):+ super().__init__()+ self._statuses = list(statuses)++ def get_crawl_status(self, job_id):+ from firecrawl.v2.types import CrawlJob++ status = self._statuses.pop(0)+ if isinstance(status, Exception):+ raise status+ return CrawlJob(status=status, total=1, completed=1 if status == "completed" else 0)+++def _run_until_done(watcher, seconds=3):+ watcher.start()+ deadline = time.time() + seconds+ while watcher._thread and watcher._thread.is_alive() and time.time() < deadline:+ time.sleep(0.01)+ watcher.stop()+++def _failing_connect(uri, *args, **kwargs):+ raise TypeError("connect() got an unexpected keyword argument 'additional_headers'")+++def test_ws_watcher_polls_http_when_connect_fails(monkeypatch):+ import websockets+ monkeypatch.setattr(websockets, "connect", _failing_connect)++ watcher = Watcher(PollingClient(["scraping", "completed"]), job_id="jid", kind="crawl", poll_interval=0.01)+ statuses = []+ done = []+ watcher.add_listener(lambda s: statuses.append(s.status))+ watcher.add_event_listener("done", lambda d: done.append(d))++ _run_until_done(watcher)++ assert statuses == ["scraping", "completed"]+ assert len(done) == 1+++def test_ws_watcher_reports_error_when_polling_keeps_failing(monkeypatch):+ import websockets+ monkeypatch.setattr(websockets, "connect", _failing_connect)++ watcher = Watcher(PollingClient([RuntimeError("401")] * 10), job_id="jid", kind="crawl", poll_interval=0.01)+ errors = []+ watcher.add_event_listener("error", lambda d: errors.append(d))++ _run_until_done(watcher)++ assert len(errors) == 1+ assert watcher._thread is not None and not watcher._thread.is_alive()diff --git a/apps/python-sdk/firecrawl/client.py b/apps/python-sdk/firecrawl/client.pyindex 5833a85ba..6b2b60616 100644--- a/apps/python-sdk/firecrawl/client.py+++ b/apps/python-sdk/firecrawl/client.py@@ -40,6 +40,8 @@ from .v2.methods.research_docs import (doc,)from .v2.types import Document, ParseOptions, ScrapeOptions+from .v2.utils.caller_origin import default_origin+from .v2.utils.get_version import get_versionlogger = logging.getLogger("firecrawl")@@ -272,8 +274,10 @@ class Firecrawl:self.api_key = api_keyself.api_url = api_url- # Initialize version-specific clients- self._v1_client = V1FirecrawlApp(api_key=api_key, api_url=api_url, origin=origin) if V1FirecrawlApp else None+ # Resolved here: caller detection reads the stack of whoever constructs the client.+ self._origin = origin or default_origin(get_version())+ self._v1: Optional[V1Proxy] = None+self._v2_client = V2FirecrawlClient(api_key=api_key,api_url=api_url,@@ -283,8 +287,6 @@ class Firecrawl:origin=origin,) if V2FirecrawlClient else None- # Create version-specific proxies- self.v1 = V1Proxy(self._v1_client) if self._v1_client else Noneself.v2 = V2Proxy(self._v2_client)self.scrape = self._v2_client.scrape@@ -364,6 +366,13 @@ class Firecrawl:self.check_batch_scrape_status = self._v2_client.check_batch_scrape_statusself.check_batch_scrape_errors = self._v2_client.check_batch_scrape_errors+ @property+ def v1(self) -> V1Proxy:+ """Feature-frozen v1 client, created on first use because it requires an API key on the cloud API."""+ if self._v1 is None:+ self._v1 = V1Proxy(V1FirecrawlApp(api_key=self.api_key, api_url=self.api_url, origin=self._origin))+ return self._v1+def parse(self,file: Union[str, Path, bytes, bytearray, BinaryIO],@@ -419,8 +428,9 @@ class AsyncFirecrawl:self.api_key = api_keyself.api_url = api_url- # Initialize version-specific clients- self._v1_client = AsyncV1FirecrawlApp(api_key=api_key, api_url=api_url, origin=origin) if AsyncV1FirecrawlApp else None+ self._origin = origin or default_origin(get_version())+ self._v1: Optional[AsyncV1Proxy] = None+self._v2_client = AsyncFirecrawlClient(api_key=api_key,api_url=api_url,@@ -430,8 +440,6 @@ class AsyncFirecrawl:origin=origin,) if AsyncFirecrawlClient else None- # Create version-specific proxies- self.v1 = AsyncV1Proxy(self._v1_client) if self._v1_client else Noneself.v2 = AsyncV2Proxy(self._v2_client)# Expose v2 async surface directly on the top-level client for ergonomic access@@ -512,6 +520,13 @@ class AsyncFirecrawl:self.check_batch_scrape_status = self._v2_client.check_batch_scrape_statusself.check_batch_scrape_errors = self._v2_client.check_batch_scrape_errors+ @property+ def v1(self) -> AsyncV1Proxy:+ """Feature-frozen async v1 client, created on first use because it requires an API key on the cloud API."""+ if self._v1 is None:+ self._v1 = AsyncV1Proxy(AsyncV1FirecrawlApp(api_key=self.api_key, api_url=self.api_url, origin=self._origin))+ return self._v1+async def parse(self,file: Union[str, Path, bytes, bytearray, BinaryIO],diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.pyindex 96820a08e..7ce44290f 100644--- a/apps/python-sdk/firecrawl/v2/client_async.py+++ b/apps/python-sdk/firecrawl/v2/client_async.py@@ -99,10 +99,6 @@ def _consume_task_outcome(task: "asyncio.Future[Any]") -> None:class AsyncFirecrawlClient:- @staticmethod- def _is_cloud_service(url: str) -> bool:- return "api.firecrawl.dev" in url.lower()-def __init__(self,api_key: Optional[str] = None,@@ -114,8 +110,6 @@ class AsyncFirecrawlClient:):if api_key is None:api_key = os.getenv("FIRECRAWL_API_KEY")- if self._is_cloud_service(api_url) and not api_key:- raise ValueError("API key is required for the cloud API. Set FIRECRAWL_API_KEY or pass api_key.")self.http_client = HttpClient(api_key,api_url,diff --git a/apps/python-sdk/firecrawl/v2/watcher.py b/apps/python-sdk/firecrawl/v2/watcher.pyindex 086823c41..94d83aeea 100644--- a/apps/python-sdk/firecrawl/v2/watcher.py+++ b/apps/python-sdk/firecrawl/v2/watcher.py@@ -21,6 +21,8 @@ from .utils.normalize import normalize_document_inputJobKind = Literal["crawl", "batch"]JobType = Union[CrawlJob, BatchScrapeJob]+_MAX_POLL_FAILURES = 5+class Watcher:def __init__(@@ -54,6 +56,7 @@ class Watcher:}self._sent_done: bool = Falseself._sent_error: bool = False+ self._poll_failures: int = 0def add_listener(self, callback: Callable[[JobType], None]) -> None:self._listeners.append(callback)@@ -92,10 +95,12 @@ class Watcher:if self._api_key:headers_list.append(("Authorization", f"Bearer {self._api_key}"))+ deadline = asyncio.get_event_loop().time() + self._timeout if self._timeout else Nonetry:async with websockets.connect(uri, max_size=None, additional_headers=headers_list) as websocket:- deadline = asyncio.get_event_loop().time() + self._timeout if self._timeout else Nonewhile not self._stop.is_set():+ if deadline is not None and asyncio.get_event_loop().time() >= deadline:+ break# Use short recv timeouts to allow HTTP polling fallbackif deadline is not None:remaining = max(0.0, deadline - asyncio.get_event_loop().time())@@ -106,20 +111,13 @@ class Watcher:msg = await asyncio.wait_for(websocket.recv(), timeout=timeout)except asyncio.TimeoutError:# Quiet period: poll HTTP once to progress statuses- if await self._poll_status_once():+ if await self._poll_status_once() or self._gave_up_polling():break- else:- continue+ continueexcept asyncio.CancelledError:breakexcept Exception:- # Connection error: switch to HTTP polling until terminal or timeout- while not self._stop.is_set():- if await self._poll_status_once():- return- if deadline is not None and asyncio.get_event_loop().time() >= deadline:- return- await asyncio.sleep(self._poll_interval or 2)+ await self._poll_until_terminal(deadline)returntry:@@ -255,23 +253,49 @@ class Watcher:self._sent_error = Truebreakexcept Exception:- pass+ # websockets < 14 (all of Python 3.8) rejects additional_headers, and proxies can block+ # WebSockets; either way keep reporting progress over HTTP.+ await self._poll_until_terminal(deadline)finally:# Ensure terminal event parity with v1 even on abrupt disconnectsif self.status == "completed" and not self._sent_done:self.dispatch_event("done", {"status": self.status, "data": self.data, "id": self._job_id})self._sent_done = True+ def _gave_up_polling(self) -> bool:+ """After repeated failed status requests, dispatch one error event and report True."""+ if self._poll_failures < _MAX_POLL_FAILURES:+ return False+ if not self._sent_error:+ self.dispatch_event("error", {+ "status": self.status,+ "data": self.data,+ "error": "Could not get the job status",+ "id": self._job_id,+ })+ self._sent_error = True+ return True++ async def _poll_until_terminal(self, deadline: Optional[float]) -> None:+ while not self._stop.is_set():+ if await self._poll_status_once() or self._gave_up_polling():+ return+ if deadline is not None and asyncio.get_event_loop().time() >= deadline:+ return+ await asyncio.sleep(self._poll_interval or 2)+async def _poll_status_once(self) -> bool:"""Poll job status over HTTP once. Returns True if terminal."""try:if self._kind == "crawl":- job: CrawlJob = await asyncio.to_thread(self._client.get_crawl_status, self._job_id)+ job: CrawlJob = await asyncio.get_event_loop().run_in_executor(None, self._client.get_crawl_status, self._job_id)else:- job: BatchScrapeJob = await asyncio.to_thread(self._client.get_batch_scrape_status, self._job_id)+ job: BatchScrapeJob = await asyncio.get_event_loop().run_in_executor(None, self._client.get_batch_scrape_status, self._job_id)except Exception:+ self._poll_failures += 1return False+ self._poll_failures = 0self.status = job.statusself._emit(job)if job.status in ("completed", "failed", "cancelled"):diff --git a/apps/python-sdk/firecrawl/v2/watcher_async.py b/apps/python-sdk/firecrawl/v2/watcher_async.pyindex ba7f1d290..9a7bd1f3c 100644--- a/apps/python-sdk/firecrawl/v2/watcher_async.py+++ b/apps/python-sdk/firecrawl/v2/watcher_async.py@@ -176,36 +176,18 @@ class AsyncWatcher:return await self._call_status_method("get_batch_scrape_status")async def _call_status_method(self, method_name: str):- # Try on client directlymeth = getattr(self._client, method_name, None)- if meth is not None:- try:- result = meth(self._job_id)- except TypeError:- result = None- if result is not None:- if inspect.isawaitable(result):- return await result- return result- # Fallback: if we couldn't call directly, try to_thread- return await asyncio.to_thread(meth, self._job_id)-- # Try on client.v2- v2 = getattr(self._client, "v2", None)- if v2 is not None:- meth = getattr(v2, method_name, None)- if meth is not None:- try:- result = meth(self._job_id)- except TypeError:- result = None- if result is not None:- if inspect.isawaitable(result):- return await result- return result- return await asyncio.to_thread(meth, self._job_id)-- raise RuntimeError(f"Client does not expose {method_name}")+ if meth is None:+ meth = getattr(getattr(self._client, "v2", None), method_name, None)+ if meth is None:+ raise RuntimeError(f"Client does not expose {method_name}")+ if inspect.iscoroutinefunction(meth):+ return await meth(self._job_id)+ # Sync clients block on HTTP, so keep them off the event loop.+ result = await asyncio.get_event_loop().run_in_executor(None, meth, self._job_id)+ if inspect.isawaitable(result):+ return await result+ return resultasync def _safe_fetch(self):try: