Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

feat(sdk): auto-resume large-document scrapes (JS + Python) (#4420)

Abimael Martellab339031f69c
diff --git a/apps/js-sdk/firecrawl/package.json b/apps/js-sdk/firecrawl/package.json
index b75edc94b..09e2fc6f1 100644
--- a/apps/js-sdk/firecrawl/package.json
+++ b/apps/js-sdk/firecrawl/package.json
@@ -1,6 +1,6 @@
{
"name": "@mendable/firecrawl-js",
- "version": "4.36.0",
+ "version": "4.37.0",
"description": "JavaScript SDK for the Firecrawl API: web scraping, crawling, web search, and scientific literature search over a research paper index of PubMed, bioRxiv, medRxiv and arXiv abstracts",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/scrapeAutoResume.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/scrapeAutoResume.test.ts
new file mode 100644
index 000000000..6ca30ba46
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/scrapeAutoResume.test.ts
@@ -0,0 +1,145 @@
+import { describe, expect, test } from "@jest/globals";
+import {
+ processingContinuesDelayMs,
+ scrape,
+} from "../../../v2/methods/scrape";
+
+const DOC = { markdown: "# big doc" };
+
+function processingContinues408(retryAfterSeconds = 10) {
+ return {
+ isAxiosError: true,
+ response: {
+ status: 408,
+ headers: { "retry-after": String(retryAfterSeconds) },
+ data: {
+ success: false,
+ code: "SCRAPE_TIMEOUT",
+ error: "Request timed out, but this 700-page PDF is still being processed on our side.",
+ details: {
+ state: "processing_continues",
+ documentPages: 700,
+ jobStatus: "running",
+ estimatedRemainingSeconds: retryAfterSeconds,
+ retryAfterSeconds,
+ },
+ },
+ },
+ };
+}
+
+describe("v2.scrape auto-resume", () => {
+ test("resumes after processing_continues and returns the finished document", async () => {
+ const post = jest
+ .fn()
+ .mockRejectedValueOnce(processingContinues408(10))
+ .mockResolvedValueOnce({ status: 200, data: { success: true, data: DOC } });
+ const sleeps: number[] = [];
+ const sleepImpl = async (ms: number) => {
+ sleeps.push(ms);
+ };
+
+ const doc = await scrape({ post } as any, "https://example.com/big.pdf", undefined, {
+ sleepImpl,
+ });
+
+ expect(doc).toEqual(DOC);
+ expect(post).toHaveBeenCalledTimes(2);
+ expect(sleeps).toEqual([10_000]);
+ });
+
+ test("autoResume: false surfaces the timeout immediately and never sleeps", async () => {
+ const post = jest.fn().mockRejectedValueOnce(processingContinues408());
+ const sleepImpl = jest.fn();
+
+ await expect(
+ scrape({ post } as any, "https://example.com/big.pdf", { autoResume: false }, {
+ sleepImpl: sleepImpl as any,
+ }),
+ ).rejects.toBeDefined();
+ expect(post).toHaveBeenCalledTimes(1);
+ expect(sleepImpl).not.toHaveBeenCalled();
+ });
+
+ test("autoResume never enters the wire payload", async () => {
+ const post = jest
+ .fn()
+ .mockResolvedValueOnce({ status: 200, data: { success: true, data: DOC } });
+ await scrape({ post } as any, "https://example.com/x", { autoResume: true });
+ const payload = post.mock.calls[0][1];
+ expect(payload).toEqual({ url: "https://example.com/x" });
+ });
+
+ test("gives up after the attempt bound and surfaces the error", async () => {
+ const post = jest.fn().mockRejectedValue(processingContinues408(10));
+ const sleepImpl = jest.fn().mockResolvedValue(undefined);
+
+ await expect(
+ scrape({ post } as any, "https://example.com/big.pdf", undefined, {
+ sleepImpl: sleepImpl as any,
+ }),
+ ).rejects.toBeDefined();
+ // 1 initial + 5 resumes.
+ expect(post).toHaveBeenCalledTimes(6);
+ expect(sleepImpl).toHaveBeenCalledTimes(5);
+ });
+
+ test("plain timeouts without the processing signal do not resume", async () => {
+ const post = jest.fn().mockRejectedValueOnce({
+ isAxiosError: true,
+ response: {
+ status: 408,
+ headers: {},
+ data: { success: false, code: "SCRAPE_TIMEOUT", error: "Request timed out" },
+ },
+ });
+ const sleepImpl = jest.fn();
+
+ await expect(
+ scrape({ post } as any, "https://example.com/slow", undefined, {
+ sleepImpl: sleepImpl as any,
+ }),
+ ).rejects.toBeDefined();
+ expect(post).toHaveBeenCalledTimes(1);
+ expect(sleepImpl).not.toHaveBeenCalled();
+ });
+
+ test("request timeout: opt-out keeps legacy behavior, resume adds the cushion", async () => {
+ const ok = { status: 200, data: { success: true, data: DOC } };
+ // Opt-out, no explicit timeout β†’ no per-request override at all.
+ const post1 = jest.fn().mockResolvedValueOnce(ok);
+ await scrape({ post: post1 } as any, "https://example.com/x", { autoResume: false });
+ expect(post1.mock.calls[0][2]).toEqual({});
+ // Opt-out with explicit timeout β†’ the pre-existing +5s.
+ const post2 = jest.fn().mockResolvedValueOnce(ok);
+ await scrape({ post: post2 } as any, "https://example.com/x", {
+ autoResume: false,
+ timeout: 10_000,
+ });
+ expect(post2.mock.calls[0][2]).toEqual({ timeoutMs: 15_000 });
+ // Resume enabled β†’ cushion over the server wall, respecting a larger
+ // configured client default as the floor.
+ const post3 = jest.fn().mockResolvedValueOnce(ok);
+ await scrape(
+ { post: post3, getTimeoutMs: () => 600_000 } as any,
+ "https://example.com/x",
+ );
+ expect(post3.mock.calls[0][2]).toEqual({ timeoutMs: 630_000 });
+ // Resume enabled, no client getter β†’ server wall default + cushion.
+ const post4 = jest.fn().mockResolvedValueOnce(ok);
+ await scrape({ post: post4 } as any, "https://example.com/x", { timeout: 900_000 });
+ expect(post4.mock.calls[0][2]).toEqual({ timeoutMs: 930_000 });
+ });
+
+ test("processingContinuesDelayMs clamps and falls back sensibly", () => {
+ expect(processingContinuesDelayMs(processingContinues408(1))).toBe(5_000);
+ expect(processingContinuesDelayMs(processingContinues408(3_600))).toBe(600_000);
+ // No payload field β†’ Retry-After header.
+ const headerOnly = processingContinues408(0);
+ delete (headerOnly.response.data.details as any).retryAfterSeconds;
+ headerOnly.response.headers["retry-after"] = "90";
+ expect(processingContinuesDelayMs(headerOnly)).toBe(90_000);
+ expect(processingContinuesDelayMs(new Error("net"))).toBeUndefined();
+ expect(processingContinuesDelayMs(undefined)).toBeUndefined();
+ });
+});
diff --git a/apps/js-sdk/firecrawl/src/v2/client.ts b/apps/js-sdk/firecrawl/src/v2/client.ts
index e38659f51..a5993a21e 100644
--- a/apps/js-sdk/firecrawl/src/v2/client.ts
+++ b/apps/js-sdk/firecrawl/src/v2/client.ts
@@ -1,6 +1,6 @@
import { HttpClient } from "./utils/httpClient";
import {
- scrape,
+ scrape, type ScrapeCallOptions,
interact as interactMethod,
stopInteraction as stopInteractionMethod,
} from "./methods/scrape";
@@ -170,8 +170,8 @@ export class FirecrawlClient {
url: string,
options: Opts
): Promise<Omit<Document, "json"> & { json?: InferredJsonFromOptions<Opts> }>;
- async scrape(url: string, options?: ScrapeOptions): Promise<Document>;
- async scrape(url: string, options?: ScrapeOptions): Promise<Document> {
+ async scrape(url: string, options?: ScrapeCallOptions): Promise<Document>;
+ async scrape(url: string, options?: ScrapeCallOptions): Promise<Document> {
return scrape(this.http, url, options);
}
/**
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts b/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts
index 1ea236b85..14a3577af 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts
@@ -12,38 +12,142 @@ import {
normalizeAxiosError,
} from "../utils/errorHandler";
+/** Auto-resume bounds: a resume only ever follows the server's explicit
+ * "processing continues" signal, and stops after this many resumes or
+ * this much total sleeping β€” whichever comes first. */
+const RESUME_MAX_ATTEMPTS = 5;
+const RESUME_MAX_TOTAL_WAIT_MS = 20 * 60 * 1000;
+const RESUME_MIN_DELAY_MS = 5 * 1000;
+const RESUME_MAX_DELAY_MS = 10 * 60 * 1000;
+
+/**
+ * When a request failed because the document is still processing
+ * server-side (large PDFs outlive their request window by design), the
+ * error carries `details.state === "processing_continues"` plus a retry
+ * delay. Returns that delay in ms, or undefined for every other error.
+ */
+export function processingContinuesDelayMs(err: unknown): number | undefined {
+ const response = (err as { isAxiosError?: boolean; response?: any })
+ ?.isAxiosError
+ ? (err as { response?: any }).response
+ : undefined;
+ if (!response || response.status !== 408) return undefined;
+ const body = response.data as
+ | { code?: string; details?: { state?: string; retryAfterSeconds?: number } }
+ | undefined;
+ if (
+ body?.code !== "SCRAPE_TIMEOUT" ||
+ body?.details?.state !== "processing_continues"
+ ) {
+ return undefined;
+ }
+ const headerSeconds = Number(response.headers?.["retry-after"]);
+ const seconds =
+ typeof body.details.retryAfterSeconds === "number" &&
+ Number.isFinite(body.details.retryAfterSeconds)
+ ? body.details.retryAfterSeconds
+ : Number.isFinite(headerSeconds)
+ ? headerSeconds
+ : 60;
+ return Math.min(RESUME_MAX_DELAY_MS, Math.max(RESUME_MIN_DELAY_MS, seconds * 1000));
+}
+
+/**
+ * Options for a direct scrape call. `autoResume` lives here β€” NOT on the
+ * shared ScrapeOptions β€” because that type is reused verbatim inside
+ * batch/crawl/search/extract payloads, where an SDK-only key would leak
+ * onto the wire and fail strict endpoints.
+ */
+export type ScrapeCallOptions = ScrapeOptions & {
+ /**
+ * SDK-only (never sent to the API). Large documents (big PDFs) that
+ * outlive the request window keep processing server-side; the API's
+ * timeout error then carries `details.state === "processing_continues"`
+ * and a Retry-After. When this is not `false`, the SDK sleeps that
+ * long and re-issues the same request β€” the retry attaches to the
+ * in-flight job and returns the finished result, so a large document
+ * behaves like one slow successful call. Bounded (at most 5 resumes /
+ * 20 minutes total wait); set `false` to surface the timeout error
+ * immediately instead.
+ */
+ autoResume?: boolean;
+};
+
export async function scrape(
http: HttpClient,
url: string,
- options?: ScrapeOptions,
+ options?: ScrapeCallOptions,
+ deps: { sleepImpl?: (ms: number) => Promise<void> } = {},
): Promise<Document> {
+ const sleep =
+ deps.sleepImpl ??
+ ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));
if (!url || !url.trim()) {
throw new Error("URL cannot be empty");
}
if (options) ensureValidScrapeOptions(options);
+ // autoResume is SDK behavior, never part of the wire payload.
+ const { autoResume, ...requestOptions } = options ?? {};
const payload: Record<string, unknown> = { url: url.trim() };
- if (options) Object.assign(payload, options);
+ Object.assign(payload, requestOptions);
- try {
- const res = await http.post<{
- success: boolean;
- data?: Document;
- error?: string;
- }>(
- "/v2/scrape",
- payload,
- typeof options?.timeout === "number"
+ // Per-request timeout. With auto-resume disabled this is exactly the
+ // pre-existing behavior (explicit timeout +5s, else the client's own
+ // default). With auto-resume on, the client-side timeout must outlast
+ // the SERVER's wall β€” options.timeout, or the API's 5-minute default β€”
+ // otherwise axios can abort in a photo-finish with the server's
+ // processing_continues response and the resume signal is lost exactly
+ // when it matters. The caller's configured client timeout is
+ // respected as a floor, never overridden downward.
+ const requestTimeout: { timeoutMs?: number } =
+ autoResume === false
+ ? typeof options?.timeout === "number"
? { timeoutMs: options.timeout + 5000 }
- : {},
- );
- if (res.status !== 200 || !res.data?.success) {
- throwForBadResponse(res, "scrape");
+ : {}
+ : {
+ timeoutMs:
+ Math.max(
+ typeof options?.timeout === "number" ? options.timeout : 300_000,
+ typeof http.getTimeoutMs === "function" ? http.getTimeoutMs() : 0,
+ ) + 30_000,
+ };
+
+ let resumes = 0;
+ let resumeWaitedMs = 0;
+ while (true) {
+ try {
+ const res = await http.post<{
+ success: boolean;
+ data?: Document;
+ error?: string;
+ }>(
+ "/v2/scrape",
+ payload,
+ requestTimeout,
+ );
+ if (res.status !== 200 || !res.data?.success) {
+ throwForBadResponse(res, "scrape");
+ }
+ return (res.data.data || {}) as Document;
+ } catch (err: any) {
+ const delayMs = autoResume !== false ? processingContinuesDelayMs(err) : undefined;
+ if (
+ delayMs !== undefined &&
+ resumes < RESUME_MAX_ATTEMPTS &&
+ resumeWaitedMs + delayMs <= RESUME_MAX_TOTAL_WAIT_MS
+ ) {
+ // The document keeps processing server-side; the retry attaches
+ // to the same in-flight job (content adoption) and returns the
+ // finished result instead of restarting the work.
+ resumes += 1;
+ resumeWaitedMs += delayMs;
+ await sleep(delayMs);
+ continue;
+ }
+ if (err?.isAxiosError) return normalizeAxiosError(err, "scrape");
+ throw err;
}
- return (res.data.data || {}) as Document;
- } catch (err: any) {
- if (err?.isAxiosError) return normalizeAxiosError(err, "scrape");
- throw err;
}
}
diff --git a/apps/js-sdk/firecrawl/src/v2/utils/httpClient.ts b/apps/js-sdk/firecrawl/src/v2/utils/httpClient.ts
index dc0560ed1..64bb2e601 100644
--- a/apps/js-sdk/firecrawl/src/v2/utils/httpClient.ts
+++ b/apps/js-sdk/firecrawl/src/v2/utils/httpClient.ts
@@ -51,6 +51,12 @@ export class HttpClient {
return this.apiKey;
}
+ /** The client-wide default request timeout, for callers that need to
+ * extend a specific request beyond it (e.g. scrape auto-resume). */
+ getTimeoutMs(): number {
+ return (this.instance.defaults.timeout as number | undefined) ?? 300000;
+ }
+
private async request<T = any>(
config: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.py
index c841a54f7..ddd5f8ad7 100644
--- a/apps/python-sdk/firecrawl/__init__.py
+++ b/apps/python-sdk/firecrawl/__init__.py
@@ -18,7 +18,7 @@ from .v1 import (
V1ChangeTrackingOptions,
)
-__version__ = "4.39.0"
+__version__ = "4.40.0"
# Define the logger for the Firecrawl project
logger: logging.Logger = logging.getLogger("firecrawl")
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/test_scrape_auto_resume.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/test_scrape_auto_resume.py
new file mode 100644
index 000000000..f80b8f3d0
--- /dev/null
+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/test_scrape_auto_resume.py
@@ -0,0 +1,155 @@
+"""Auto-resume on processing_continues timeouts (large-PDF phase 3)."""
+
+import asyncio
+from unittest.mock import MagicMock
+
+import pytest
+
+from firecrawl.v2.methods import scrape as scrape_module
+from firecrawl.v2.methods.aio import scrape as aio_scrape_module
+from firecrawl.v2.utils import auto_resume as auto_resume_module
+from firecrawl.v2.utils.error_handler import FirecrawlError
+
+DOC_BODY = {"success": True, "data": {"markdown": "# big doc"}}
+
+
+def _response(status_code, body, headers=None, ok=None):
+ r = MagicMock()
+ r.status_code = status_code
+ r.ok = ok if ok is not None else status_code < 400
+ r.json.return_value = body
+ r.headers = headers or {}
+ return r
+
+
+def _processing_continues_408(retry_after_seconds=10):
+ return _response(
+ 408,
+ {
+ "success": False,
+ "code": "SCRAPE_TIMEOUT",
+ "error": "Request timed out, but this PDF is still being processed on our side.",
+ "details": {
+ "state": "processing_continues",
+ "jobStatus": "running",
+ "retryAfterSeconds": retry_after_seconds,
+ },
+ },
+ headers={"Retry-After": str(retry_after_seconds)},
+ )
+
+
+def test_resumes_and_returns_document(monkeypatch):
+ sleeps = []
+ monkeypatch.setattr(scrape_module.time, "sleep", sleeps.append)
+ client = MagicMock()
+ client.post.side_effect = [_processing_continues_408(10), _response(200, DOC_BODY)]
+
+ doc = scrape_module.scrape(client, "https://example.com/big.pdf")
+
+ assert doc.markdown == "# big doc"
+ assert client.post.call_count == 2
+ assert sleeps == [10.0]
+
+
+def test_auto_resume_false_surfaces_timeout(monkeypatch):
+ monkeypatch.setattr(scrape_module.time, "sleep", lambda s: pytest.fail("slept"))
+ client = MagicMock()
+ client.post.side_effect = [_processing_continues_408()]
+
+ with pytest.raises(FirecrawlError):
+ scrape_module.scrape(client, "https://example.com/big.pdf", auto_resume=False)
+ assert client.post.call_count == 1
+
+
+def test_auto_resume_never_reaches_payload(monkeypatch):
+ monkeypatch.setattr(scrape_module.time, "sleep", lambda s: None)
+ client = MagicMock()
+ client.post.side_effect = [_response(200, DOC_BODY)]
+ scrape_module.scrape(client, "https://example.com/x", auto_resume=True)
+ payload = client.post.call_args[0][1]
+ assert payload == {"url": "https://example.com/x"}
+
+
+def test_gives_up_after_attempt_bound(monkeypatch):
+ sleeps = []
+ monkeypatch.setattr(scrape_module.time, "sleep", sleeps.append)
+ client = MagicMock()
+ client.post.side_effect = [_processing_continues_408(10)] * 10
+
+ with pytest.raises(FirecrawlError):
+ scrape_module.scrape(client, "https://example.com/big.pdf")
+ # 1 initial + 5 resumes.
+ assert client.post.call_count == 6
+ assert len(sleeps) == 5
+
+
+def test_gives_up_after_total_wait_bound(monkeypatch):
+ # Delays at the 600s clamp trip the 20-minute wait bound (after two
+ # resumes) before the 5-attempt bound would.
+ sleeps = []
+ monkeypatch.setattr(scrape_module.time, "sleep", sleeps.append)
+ client = MagicMock()
+ client.post.side_effect = [_processing_continues_408(600)] * 10
+
+ with pytest.raises(FirecrawlError):
+ scrape_module.scrape(client, "https://example.com/big.pdf")
+ assert sleeps == [600.0, 600.0]
+ assert client.post.call_count == 3
+
+
+def test_plain_timeout_does_not_resume(monkeypatch):
+ monkeypatch.setattr(scrape_module.time, "sleep", lambda s: pytest.fail("slept"))
+ client = MagicMock()
+ client.post.side_effect = [
+ _response(408, {"success": False, "code": "SCRAPE_TIMEOUT", "error": "Request timed out"})
+ ]
+
+ with pytest.raises(FirecrawlError):
+ scrape_module.scrape(client, "https://example.com/slow")
+ assert client.post.call_count == 1
+
+
+def test_delay_clamps_and_header_fallback():
+ assert auto_resume_module.processing_continues_delay_s(_processing_continues_408(1)) == 5
+ assert auto_resume_module.processing_continues_delay_s(_processing_continues_408(3600)) == 600
+ header_only = _processing_continues_408(0)
+ body = header_only.json.return_value
+ del body["details"]["retryAfterSeconds"]
+ header_only.headers = {"Retry-After": "90"}
+ assert auto_resume_module.processing_continues_delay_s(header_only) == 90
+ assert auto_resume_module.processing_continues_delay_s(_response(500, {})) is None
+ # bool / non-finite payload values fall back instead of clamping.
+ bool_payload = _processing_continues_408(0)
+ bool_payload.json.return_value["details"]["retryAfterSeconds"] = True
+ bool_payload.headers = {"Retry-After": "45"}
+ assert auto_resume_module.processing_continues_delay_s(bool_payload) == 45
+ inf_payload = _processing_continues_408(0)
+ inf_payload.json.return_value["details"]["retryAfterSeconds"] = float("inf")
+ inf_payload.headers = {}
+ assert auto_resume_module.processing_continues_delay_s(inf_payload) == 60
+ huge_payload = _processing_continues_408(0)
+ huge_payload.json.return_value["details"]["retryAfterSeconds"] = 10**400
+ huge_payload.headers = {}
+ assert auto_resume_module.processing_continues_delay_s(huge_payload) == 60
+
+
+def test_async_scrape_resumes(monkeypatch):
+ sleeps = []
+
+ async def fake_sleep(s):
+ sleeps.append(s)
+
+ monkeypatch.setattr(aio_scrape_module.asyncio, "sleep", fake_sleep)
+
+ client = MagicMock()
+ responses = [_processing_continues_408(10), _response(200, DOC_BODY)]
+
+ async def fake_post(path, payload):
+ return responses.pop(0)
+
+ client.post = fake_post
+
+ doc = asyncio.run(aio_scrape_module.scrape(client, "https://example.com/big.pdf"))
+ assert doc.markdown == "# big doc"
+ assert sleeps == [10.0]
diff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.py
index e24aee9f7..b7d47ebc6 100644
--- a/apps/python-sdk/firecrawl/v2/client.py
+++ b/apps/python-sdk/firecrawl/v2/client.py
@@ -151,6 +151,7 @@ class FirecrawlClient:
self,
url: str,
*,
+ auto_resume: Optional[bool] = None,
formats: Optional[List['FormatOption']] = None,
headers: Optional[Dict[str, str]] = None,
include_tags: Optional[List[str]] = None,
@@ -234,7 +235,7 @@ class FirecrawlClient:
integration=integration,
).items() if v is not None}
) if any(v is not None for v in [formats, headers, include_tags, exclude_tags, only_main_content, timeout, wait_for, mobile, parsers, actions, location, skip_tls_verification, remove_base64_images, fast_mode, use_mock, block_ads, proxy, max_age, store_in_cache, lockdown, threat_protection, profile, audit_metadata, integration]) else None
- return scrape_module.scrape(self.http_client, url, options)
+ return scrape_module.scrape(self.http_client, url, options, auto_resume=auto_resume)
# Research paper index (/v2/search/research)
@doc(CLIENT_SEARCH_PAPERS_DOC)
diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.py
index 28df0cc87..ec1743a9b 100644
--- a/apps/python-sdk/firecrawl/v2/client_async.py
+++ b/apps/python-sdk/firecrawl/v2/client_async.py
@@ -114,10 +114,14 @@ class AsyncFirecrawlClient:
async def scrape(
self,
url: str,
+ *,
+ auto_resume: Optional[bool] = None,
**kwargs,
):
options = ScrapeOptions(**{k: v for k, v in kwargs.items() if v is not None}) if kwargs else None
- return await async_scrape.scrape(self.async_http_client, url, options)
+ return await async_scrape.scrape(
+ self.async_http_client, url, options, auto_resume=auto_resume
+ )
# Research paper index (/v2/search/research)
@doc(ASYNC_CLIENT_SEARCH_PAPERS_DOC)
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py b/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py
index a7ecf3fcb..3748e9f48 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py
@@ -1,3 +1,4 @@
+import asyncio
from typing import Optional, Dict, Any, Literal
from ...types import (
ScrapeOptions,
@@ -9,6 +10,7 @@ from ...utils.normalize import normalize_document_input
from ...utils.error_handler import handle_response_error
from ...utils.validation import prepare_scrape_options, validate_scrape_options
from ...utils.http_client_async import AsyncHttpClient
+from ...utils.auto_resume import ResumeTracker
async def _prepare_scrape_request(url: str, options: Optional[ScrapeOptions] = None) -> Dict[str, Any]:
@@ -24,17 +26,33 @@ async def _prepare_scrape_request(url: str, options: Optional[ScrapeOptions] = N
return payload
-async def scrape(client: AsyncHttpClient, url: str, options: Optional[ScrapeOptions] = None) -> Document:
+async def scrape(
+ client: AsyncHttpClient,
+ url: str,
+ options: Optional[ScrapeOptions] = None,
+ *,
+ auto_resume: Optional[bool] = None,
+) -> Document:
payload = await _prepare_scrape_request(url, options)
- response = await client.post("/v2/scrape", payload)
- if response.status_code >= 400:
- handle_response_error(response, "scrape")
- body = response.json()
- if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
- document_data = body.get("data", {})
- normalized = normalize_document_input(document_data)
- return Document(**normalized)
+
+ resume = ResumeTracker(enabled=auto_resume is not False)
+ while True:
+ response = await client.post("/v2/scrape", payload)
+ if response.status_code >= 400:
+ delay_s = resume.delay_or_none(response)
+ if delay_s is not None:
+ # The document keeps processing server-side; the retry
+ # attaches to the same in-flight job (content adoption)
+ # and returns the finished result.
+ await asyncio.sleep(delay_s)
+ continue
+ handle_response_error(response, "scrape")
+ body = response.json()
+ if not body.get("success"):
+ raise Exception(body.get("error", "Unknown error occurred"))
+ document_data = body.get("data", {})
+ normalized = normalize_document_input(document_data)
+ return Document(**normalized)
async def interact(
diff --git a/apps/python-sdk/firecrawl/v2/methods/scrape.py b/apps/python-sdk/firecrawl/v2/methods/scrape.py
index b0dec7e06..069a2d503 100644
--- a/apps/python-sdk/firecrawl/v2/methods/scrape.py
+++ b/apps/python-sdk/firecrawl/v2/methods/scrape.py
@@ -2,6 +2,7 @@
Scraping functionality for Firecrawl v2 API.
"""
+import time
from typing import Optional, Dict, Any, Literal
from ..types import (
ScrapeOptions,
@@ -11,6 +12,7 @@ from ..types import (
)
from ..utils.normalize import normalize_document_input
from ..utils import HttpClient, handle_response_error, prepare_scrape_options, validate_scrape_options
+from ..utils.auto_resume import ResumeTracker
def _prepare_scrape_request(url: str, options: Optional[ScrapeOptions] = None) -> Dict[str, Any]:
@@ -38,7 +40,15 @@ def _prepare_scrape_request(url: str, options: Optional[ScrapeOptions] = None) -
return request_data
-def scrape(client: HttpClient, url: str, options: Optional[ScrapeOptions] = None) -> Document:
+
+
+def scrape(
+ client: HttpClient,
+ url: str,
+ options: Optional[ScrapeOptions] = None,
+ *,
+ auto_resume: Optional[bool] = None,
+) -> Document:
"""
Scrape a single URL and return the document.
@@ -55,18 +65,27 @@ def scrape(client: HttpClient, url: str, options: Optional[ScrapeOptions] = None
"""
payload = _prepare_scrape_request(url, options)
- response = client.post("/v2/scrape", payload)
-
- if not response.ok:
- handle_response_error(response, "scrape")
-
- body = response.json()
- if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
-
- document_data = body.get("data", {})
- normalized = normalize_document_input(document_data)
- return Document(**normalized)
+ resume = ResumeTracker(enabled=auto_resume is not False)
+ while True:
+ response = client.post("/v2/scrape", payload)
+
+ if not response.ok:
+ delay_s = resume.delay_or_none(response)
+ if delay_s is not None:
+ # The document keeps processing server-side; the retry
+ # attaches to the same in-flight job (content adoption)
+ # and returns the finished result.
+ time.sleep(delay_s)
+ continue
+ handle_response_error(response, "scrape")
+
+ body = response.json()
+ if not body.get("success"):
+ raise Exception(body.get("error", "Unknown error occurred"))
+
+ document_data = body.get("data", {})
+ normalized = normalize_document_input(document_data)
+ return Document(**normalized)
def interact(
diff --git a/apps/python-sdk/firecrawl/v2/utils/auto_resume.py b/apps/python-sdk/firecrawl/v2/utils/auto_resume.py
new file mode 100644
index 000000000..d72f66de5
--- /dev/null
+++ b/apps/python-sdk/firecrawl/v2/utils/auto_resume.py
@@ -0,0 +1,89 @@
+"""
+Auto-resume policy for scrapes whose document keeps processing
+server-side (large PDFs outlive their request window by design).
+
+Shared by the sync and async scrape methods so the resume policy cannot
+drift between transports. A resume only ever follows the server's
+explicit ``details.state == "processing_continues"`` signal, and stops
+after ``RESUME_MAX_ATTEMPTS`` resumes or ``RESUME_MAX_TOTAL_WAIT_S`` of
+total sleeping - whichever comes first.
+"""
+
+import math
+from typing import Optional
+
+RESUME_MAX_ATTEMPTS = 5
+RESUME_MAX_TOTAL_WAIT_S = 20 * 60
+RESUME_MIN_DELAY_S = 5
+RESUME_MAX_DELAY_S = 10 * 60
+
+
+def processing_continues_delay_s(response) -> Optional[float]:
+ """Delay (seconds) to wait before re-issuing a request whose document
+ is still processing server-side, or None for every other response.
+
+ The retry attaches to the in-flight job instead of restarting the
+ work, so the eventual response is the finished document.
+ """
+ if response.status_code != 408:
+ return None
+ try:
+ body = response.json()
+ except Exception:
+ return None
+ details = body.get("details") if isinstance(body, dict) else None
+ if (
+ not isinstance(body, dict)
+ or body.get("code") != "SCRAPE_TIMEOUT"
+ or not isinstance(details, dict)
+ or details.get("state") != "processing_continues"
+ ):
+ return None
+ seconds = _finite_seconds(details.get("retryAfterSeconds"))
+ if seconds is None:
+ try:
+ seconds = _finite_seconds(float(response.headers.get("Retry-After", "")))
+ except (TypeError, ValueError):
+ seconds = None
+ if seconds is None:
+ seconds = 60.0
+ return min(RESUME_MAX_DELAY_S, max(RESUME_MIN_DELAY_S, seconds))
+
+
+def _finite_seconds(value) -> Optional[float]:
+ # bool is an int subclass in Python β€” a payload `true` must not read
+ # as 1 second; NaN/Infinity must not survive into the clamp.
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ try:
+ value = float(value)
+ except OverflowError:
+ # Arbitrarily large JSON integers overflow float conversion.
+ return None
+ return value if math.isfinite(value) else None
+
+
+class ResumeTracker:
+ """The full resume decision, stateful, shared by both transports so
+ bounds and accounting cannot drift between sync and async."""
+
+ def __init__(self, enabled: bool):
+ self._enabled = enabled
+ self._resumes = 0
+ self._waited_s = 0.0
+
+ def delay_or_none(self, response) -> Optional[float]:
+ """Delay to sleep before re-issuing, or None to surface the error.
+ Recording is internal: a returned delay counts against the bounds."""
+ if not self._enabled:
+ return None
+ delay_s = processing_continues_delay_s(response)
+ if delay_s is None:
+ return None
+ if self._resumes >= RESUME_MAX_ATTEMPTS:
+ return None
+ if self._waited_s + delay_s > RESUME_MAX_TOTAL_WAIT_S:
+ return None
+ self._resumes += 1
+ self._waited_s += delay_s
+ return delay_s