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
(python-sdk): crawl done
rafaelmmiller7a85b9f43302
diff --git a/.gitignore b/.gitignoreindex fad26481d..1955a8183 100644--- a/.gitignore+++ b/.gitignore@@ -43,3 +43,5 @@ mapped-links.txtgke-key.jsonCLAUDE.local.md++*.egg-info/\ No newline at end of filediff --git a/apps/python-sdk/example.py b/apps/python-sdk/example.pyindex 29dc8e9e4..8cf3147dc 100644--- a/apps/python-sdk/example.py+++ b/apps/python-sdk/example.py@@ -9,7 +9,6 @@ from dotenv import load_dotenvfrom firecrawl import Firecrawlfrom firecrawl.v2.types import ScrapeOptions, ScrapeFormats-load_dotenv()def main():@@ -36,6 +35,13 @@ def main():print(crawl_job)+ # crawl params preview+ params_data = firecrawl.crawl_params_preview(+ url="https://docs.firecrawl.dev",+ prompt="Extract all blog posts and documentation"+ )+ print(params_data)+# search examplessearch_response = firecrawl.search(query="What is the capital of France?",diff --git a/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py b/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.pyindex d4139d312..47db5bded 100644--- a/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py+++ b/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py@@ -1,4 +1,5 @@import pytest+import timeimport osfrom dotenv import load_dotenvfrom firecrawl import Firecrawl@@ -21,35 +22,37 @@ class TestCrawlE2E:def test_start_crawl_minimal_request(self):"""Test starting a crawl with minimal parameters."""- crawl_job = self.client.start_crawl("https://example.com")-- # Check response structure+ crawl_job = self.client.start_crawl("https://docs.firecrawl.dev", limit=3)+assert crawl_job.id is not None- assert crawl_job.status in ["scraping", "completed", "failed"]+ assert crawl_job.url is not Nonedef test_start_crawl_with_options(self):"""Test starting a crawl with options."""crawl_job = self.client.start_crawl(- "https://example.com",+ "https://docs.firecrawl.dev",limit=5,max_discovery_depth=2)assert crawl_job.id is not None+ assert crawl_job.url is not Nonedef test_start_crawl_with_prompt(self):"""Test starting a crawl with prompt."""crawl_job = self.client.start_crawl(- "https://example.com",- prompt="Extract all blog posts"+ "https://firecrawl.dev",+ prompt="Extract all blog posts",+ limit=3)assert crawl_job.id is not None+ assert crawl_job.url is not Nonedef test_get_crawl_status(self):"""Test getting crawl status."""# First start a crawl- start_job = self.client.start_crawl("https://example.com")+ start_job = self.client.start_crawl("https://docs.firecrawl.dev", limit=3)assert start_job.id is not Nonejob_id = start_job.id@@ -58,23 +61,21 @@ class TestCrawlE2E:status_job = self.client.get_crawl_status(job_id)assert status_job.status in ["scraping", "completed", "failed"]- assert status_job.current >= 0- assert status_job.total >= 0+ assert status_job.completed >= 0+ assert status_job.expires_at is not None+ assert status_job.next is not Noneassert isinstance(status_job.data, list)def test_cancel_crawl(self):"""Test canceling a crawl."""- # First start a crawl- start_job = self.client.start_crawl("https://example.com")+ start_job = self.client.start_crawl("https://docs.firecrawl.dev", limit=3)assert start_job.id is not Nonejob_id = start_job.id-- # Cancel the crawlcancel_job = self.client.cancel_crawl(job_id)- print(f"DEBUG: cancel_job: {cancel_job}")- assert cancel_job.status == "failed"+ time.sleep(5)+ assert cancel_job == Truedef test_crawl_with_wait(self):"""Test crawl with wait for completion."""@@ -83,25 +84,26 @@ class TestCrawlE2E:limit=3,max_discovery_depth=2,poll_interval=1,- timeout=60+ timeout=120)assert crawl_job.status in ["completed", "failed"]- assert crawl_job.current >= 0+ assert crawl_job.completed >= 0assert crawl_job.total >= 0assert isinstance(crawl_job.data, list)def test_crawl_with_prompt_and_wait(self):"""Test crawl with prompt and wait for completion."""crawl_job = self.client.crawl(- "https://example.com",+ "https://docs.firecrawl.dev",prompt="Extract all blog posts",+ limit=3,poll_interval=1,- timeout=30+ timeout=120)assert crawl_job.status in ["completed", "failed"]- assert crawl_job.current >= 0+ assert crawl_job.completed >= 0assert crawl_job.total >= 0assert isinstance(crawl_job.data, list)@@ -110,11 +112,11 @@ class TestCrawlE2E:scrape_opts = ScrapeOptions(formats=["markdown"],only_main_content=False,- mobile=True+ mobile=True,)crawl_job = self.client.start_crawl(- "https://example.com",+ "https://docs.firecrawl.dev",limit=2,scrape_options=scrape_opts)@@ -134,11 +136,10 @@ class TestCrawlE2E:mobile=True,skip_tls_verification=True,remove_base64_images=False- # Note: raw_html and screenshot_full_page are not supported by v2 API yet)crawl_job = self.client.start_crawl(- "https://example.com",+ "https://docs.firecrawl.dev",prompt="Extract all blog posts and documentation",include_paths=["/blog/*", "/docs/*"],exclude_paths=["/admin/*"],@@ -152,38 +153,15 @@ class TestCrawlE2E:assert crawl_job.id is not None- def test_crawl_progress_callback(self):- """Test crawl with progress callback."""- progress_calls = []-- def progress_callback(status_data):- progress_calls.append(status_data)-- crawl_job = self.client.crawl(- "https://docs.firecrawl.dev",- limit=2,- poll_interval=1,- timeout=60,- progress_callback=progress_callback- )-- # Progress callback should have been called at least once- assert len(progress_calls) > 0-- # Check that callback received proper data- for call in progress_calls:- assert call.status in ["scraping", "completed", "failed"]- assert call.current >= 0- assert call.total >= 0- assert isinstance(call.data, list)-- def test_crawl_params(self):++ def test_crawl_params_preview(self):"""Test crawl_params function."""- params_data = self.client.crawl_params(- "https://example.com",+ params_data = self.client.crawl_params_preview(+ "https://docs.firecrawl.dev","Extract all blog posts and documentation")-+assert params_data is not None- # The LLM should return some reasonable options- assert params_data.limit is not None or params_data.include_paths is not None or params_data.max_discovery_depth is not None\ No newline at end of file+ assert params_data.limit is not None or params_data.include_paths is not None or params_data.max_discovery_depth is not None+ assert 'blog/.*' in params_data.include_paths+ assert 'documentation/.*' in params_data.include_paths\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/crawl/test_crawl_params.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/crawl/test_crawl_params.pyindex e665deb4c..388b259a0 100644--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/crawl/test_crawl_params.py+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/crawl/test_crawl_params.py@@ -1,7 +1,7 @@import pytestfrom unittest.mock import Mock, patchfrom firecrawl.v2.types import CrawlParamsRequest, CrawlParamsResponse, CrawlParamsData-from firecrawl.v2.methods.crawl import crawl_params+from firecrawl.v2.methods.crawl import crawl_params_previewclass TestCrawlParams:@@ -31,7 +31,7 @@ class TestCrawlParams:)# Call function- result = crawl_params(mock_client, request)+ result = crawl_params_preview(mock_client, request)# Verify client callmock_client.post.assert_called_once_with("/v2/crawl-params", {@@ -64,7 +64,7 @@ class TestCrawlParams:# Call function and expect exceptionwith pytest.raises(Exception, match="crawl params"):- crawl_params(mock_client, request)+ crawl_params_preview(mock_client, request)def test_crawl_params_success_false(self):"""Test crawl_params with success=False in response."""@@ -86,7 +86,7 @@ class TestCrawlParams:# Call function and expect exceptionwith pytest.raises(Exception, match="Invalid URL provided"):- crawl_params(mock_client, request)+ crawl_params_preview(mock_client, request)def test_crawl_params_empty_url(self):"""Test crawl_params with empty URL."""@@ -98,7 +98,7 @@ class TestCrawlParams:# Call function and expect exceptionwith pytest.raises(ValueError, match="URL cannot be empty"):- crawl_params(Mock(), request)+ crawl_params_preview(Mock(), request)def test_crawl_params_whitespace_url(self):"""Test crawl_params with whitespace-only URL."""@@ -110,7 +110,7 @@ class TestCrawlParams:# Call function and expect exceptionwith pytest.raises(ValueError, match="URL cannot be empty"):- crawl_params(Mock(), request)+ crawl_params_preview(Mock(), request)def test_crawl_params_empty_prompt(self):"""Test crawl_params with empty prompt."""@@ -122,7 +122,7 @@ class TestCrawlParams:# Call function and expect exceptionwith pytest.raises(ValueError, match="Prompt cannot be empty"):- crawl_params(Mock(), request)+ crawl_params_preview(Mock(), request)def test_crawl_params_whitespace_prompt(self):"""Test crawl_params with whitespace-only prompt."""@@ -134,7 +134,7 @@ class TestCrawlParams:# Call function and expect exceptionwith pytest.raises(ValueError, match="Prompt cannot be empty"):- crawl_params(Mock(), request)+ crawl_params_preview(Mock(), request)def test_crawl_params_complex_options(self):"""Test crawl_params with complex options in response."""@@ -172,7 +172,7 @@ class TestCrawlParams:)# Call function- result = crawl_params(mock_client, request)+ result = crawl_params_preview(mock_client, request)# Verify resultassert result is not Nonediff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/search/test_search_request_preparation.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/search/test_search_request_preparation.pyindex 7d7e37b7d..293cb8442 100644--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/search/test_search_request_preparation.py+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/search/test_search_request_preparation.py@@ -99,11 +99,9 @@ class TestSearchRequestPreparation:data = _prepare_search_request(request)- # Default values should be included+ # When limit and timeout are explicitly None, they should be excludedassert "query" in data- assert "limit" in data # limit has default value 5- assert "timeout" in data # timeout has default value 60000- assert len(data) == 3 # query, limit, and timeout should be present+ assert len(data) == 1 # Only query should be presentdef test_empty_scrape_options(self):"""Test that empty scrape options are handled correctly."""@@ -129,14 +127,14 @@ class TestSearchRequestPreparation:"""Test that the shared prepare_scrape_options function is being used."""# Test with all snake_case fields to ensure conversionscrape_opts = ScrapeOptions(+ formats=["markdown", "rawHtml"],include_tags=["h1", "h2"],exclude_tags=["nav"],only_main_content=False,wait_for=2000,skip_tls_verification=True,- remove_base64_images=False,- raw_html=True,- screenshot_full_page=True+ remove_base64_images=False+ # Note: raw_html should be in formats array, not as a separate field)request = SearchRequest(@@ -151,14 +149,14 @@ class TestSearchRequestPreparation:scrape_data = data["scrapeOptions"]# Check all conversions are working+ assert "formats" in scrape_data+ assert scrape_data["formats"] == ["markdown", "rawHtml"]assert "includeTags" in scrape_dataassert "excludeTags" in scrape_dataassert "onlyMainContent" in scrape_dataassert "waitFor" in scrape_dataassert "skipTlsVerification" in scrape_dataassert "removeBase64Images" in scrape_data- assert "rawHtml" in scrape_data- assert "screenshot@fullPage" in scrape_data# Check that snake_case fields are not presentassert "include_tags" not in scrape_data@@ -166,6 +164,4 @@ class TestSearchRequestPreparation:assert "only_main_content" not in scrape_dataassert "wait_for" not in scrape_dataassert "skip_tls_verification" not in scrape_data- assert "remove_base64_images" not in scrape_data- assert "raw_html" not in scrape_data- assert "screenshot_full_page" not in scrape_data\ No newline at end of file+ assert "remove_base64_images" not in scrape_data\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_validation.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_validation.pyindex 6048b7153..015c8f6b8 100644--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_validation.py+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_validation.py@@ -116,12 +116,11 @@ class TestPrepareScrapeOptions:only_main_content=False,wait_for=2000,skip_tls_verification=True,- remove_base64_images=False,- raw_html=True,- screenshot_full_page=True+ remove_base64_images=False+ # Note: raw_html should be in formats array, not as a separate field)result = prepare_scrape_options(options)-+# Check conversionsassert "includeTags" in resultassert result["includeTags"] == ["h1", "h2"]@@ -135,10 +134,6 @@ class TestPrepareScrapeOptions:assert result["skipTlsVerification"] is Trueassert "removeBase64Images" in resultassert result["removeBase64Images"] is False- assert "rawHtml" in result- assert result["rawHtml"] is True- assert "screenshot@fullPage" in result- assert result["screenshot@fullPage"] is True# Check that snake_case fields are not presentassert "include_tags" not in result@@ -147,13 +142,11 @@ class TestPrepareScrapeOptions:assert "wait_for" not in resultassert "skip_tls_verification" not in resultassert "remove_base64_images" not in result- assert "raw_html" not in result- assert "screenshot_full_page" not in resultdef test_prepare_complex_options(self):"""Test preparation with complex options."""options = ScrapeOptions(- formats=["markdown", "html"],+ formats=["markdown", "html", "rawHtml"],headers={"User-Agent": "Test Bot"},include_tags=["h1", "h2", "h3"],exclude_tags=["nav", "footer"],@@ -162,9 +155,7 @@ class TestPrepareScrapeOptions:wait_for=2000,mobile=True,skip_tls_verification=True,- remove_base64_images=False,- raw_html=True,- screenshot_full_page=True+ remove_base64_images=False)result = prepare_scrape_options(options)@@ -179,11 +170,9 @@ class TestPrepareScrapeOptions:assert "mobile" in resultassert "skipTlsVerification" in resultassert "removeBase64Images" in result- assert "rawHtml" in result- assert "screenshot@fullPage" in result# Check values- assert result["formats"] == ["markdown", "html"]+ assert result["formats"] == ["markdown", "html", "rawHtml"]assert result["headers"] == {"User-Agent": "Test Bot"}assert result["includeTags"] == ["h1", "h2", "h3"]assert result["excludeTags"] == ["nav", "footer"]@@ -193,8 +182,6 @@ class TestPrepareScrapeOptions:assert result["mobile"] is Trueassert result["skipTlsVerification"] is Trueassert result["removeBase64Images"] is False- assert result["rawHtml"] is True- assert result["screenshot@fullPage"] is Truedef test_prepare_invalid_options(self):"""Test preparation with invalid options (should raise error)."""@@ -229,4 +216,23 @@ class TestPrepareScrapeOptions:assert isinstance(result, dict)# Should have default values for required fieldsassert "onlyMainContent" in result- assert "mobile" in result\ No newline at end of file+ assert "mobile" in result++ def test_format_schema_conversion(self):+ """Test that Format schema is properly handled."""+ from firecrawl.v2.types import Format++ # Create a Format object with schema+ format_obj = Format(+ type="json",+ prompt="Extract product info",+ schema={"type": "object", "properties": {"name": {"type": "string"}}}+ )++ print(f"DEBUG: format_obj.schema = {format_obj.schema}")+ print(f"DEBUG: format_obj.model_dump() = {format_obj.model_dump()}")++ # Check that model_dump() shows schema+ dumped = format_obj.model_dump()+ assert "schema" in dumped+ assert dumped["schema"] == {"type": "object", "properties": {"name": {"type": "string"}}}\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/client.py b/apps/python-sdk/firecrawl/client.pyindex 20f78545f..a99e9326d 100644--- a/apps/python-sdk/firecrawl/client.py+++ b/apps/python-sdk/firecrawl/client.py@@ -60,7 +60,7 @@ class V2Proxy:self.get_crawl_status = client_instance.get_crawl_statusself.cancel_crawl = client_instance.cancel_crawlself.start_crawl = client_instance.start_crawl- self.crawl_params = client_instance.crawl_params+ self.crawl_params_preview = client_instance.crawl_params_preview# self.batch_scrape = client_instance.batch_scrape# self.map = client_instance.map@@ -134,7 +134,7 @@ class Firecrawl:# self.scrape = self._v2_client.scrapeself.crawl = self._v2_client.crawlself.start_crawl = self._v2_client.start_crawl- self.crawl_params = self._v2_client.crawl_params+ self.crawl_params_preview = self._v2_client.crawl_params_previewself.get_crawl_status = self._v2_client.get_crawl_statusself.cancel_crawl = self._v2_client.cancel_crawl# self.batch_scrape = self._v2_client.batch_scrapediff --git a/apps/python-sdk/firecrawl/types.py b/apps/python-sdk/firecrawl/types.pyindex f82d6dea4..755b8e40a 100644--- a/apps/python-sdk/firecrawl/types.py+++ b/apps/python-sdk/firecrawl/types.py@@ -23,8 +23,6 @@ from .v2.types import (# Crawl typesCrawlRequest,CrawlJob,- CrawlJobData,- CrawlData,CrawlResponse,CrawlParamsRequest,CrawlParamsData,@@ -79,14 +77,6 @@ from .v2.types import (# Configuration typesClientConfig,-- # Union types- ScrapeResult,- CrawlResult,- BatchResult,- JobResult,- StatusResult,- AnyResponse,)__all__ = [@@ -108,7 +98,6 @@ __all__ = ['CrawlRequest','CrawlJob','CrawlJobData',- 'CrawlData','CrawlResponse','CrawlParamsRequest','CrawlParamsData',@@ -163,12 +152,4 @@ __all__ = [# Configuration types'ClientConfig',-- # Union types- 'ScrapeResult',- 'CrawlResult',- 'BatchResult',- 'JobResult',- 'StatusResult',- 'AnyResponse',]\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/v2/__init__.py b/apps/python-sdk/firecrawl/v2/__init__.pyindex 98769c735..fad147bce 100644--- a/apps/python-sdk/firecrawl/v2/__init__.py+++ b/apps/python-sdk/firecrawl/v2/__init__.py@@ -1,7 +1,7 @@from typing import Optional, List, Union, Dict, Callable, Literal, Anyfrom ..types import (SearchData, SearchResult, Document, ScrapeOptions, SearchRequest,- SourceOption, FormatOption, CrawlRequest, CrawlJobData, CrawlData,+ SourceOption, FormatOption, CrawlRequest, CrawlJob, CrawlResponse,CrawlParamsRequest, CrawlParamsData)from .methods.search import search as search_method@@ -10,7 +10,7 @@ from .methods.crawl import (start_crawl as start_crawl_method,cancel_crawl as cancel_crawl_method,get_crawl_status as get_crawl_status_method,- crawl_params as crawl_params_method+ crawl_params_preview as crawl_params_preview_method)from .utils.http_client import HttpClient@@ -79,9 +79,8 @@ class FirecrawlClient:scrape_options: Optional[ScrapeOptions] = None,zero_data_retention: bool = False,poll_interval: int = 2,- timeout: Optional[int] = None,- progress_callback: Optional[Callable[[CrawlJobData], None]] = None- ):+ timeout: Optional[int] = None+ ) -> CrawlJob:"""Start a crawl job and wait for it to complete."""request = CrawlRequest(url=url,@@ -101,7 +100,7 @@ class FirecrawlClient:scrape_options=scrape_options,zero_data_retention=zero_data_retention)- return crawl_method(self._client, request, poll_interval, timeout, progress_callback)+ return crawl_method(self._client, request, poll_interval, timeout)# start-crawldef start_crawl(@@ -122,7 +121,7 @@ class FirecrawlClient:webhook: Optional[Dict[str, Any]] = None,scrape_options: Optional[ScrapeOptions] = None,zero_data_retention: bool = False- ) -> CrawlJobData:+ ) -> CrawlResponse:"""Start a crawl job and return immediately."""request = CrawlRequest(url=url,@@ -148,7 +147,7 @@ class FirecrawlClient:def get_crawl_status(self,job_id: str- ):+ ) -> CrawlJob:"""Get the status of a crawl job."""return get_crawl_status_method(self._client, job_id)@@ -156,19 +155,19 @@ class FirecrawlClient:def cancel_crawl(self,job_id: str- ):+ ) -> bool:"""Cancel a running crawl job."""return cancel_crawl_method(self._client, job_id)- # crawl-params- def crawl_params(+ # crawl-params-preview+ def crawl_params_preview(self,url: str,prompt: str) -> CrawlParamsData:"""Get crawl parameters from LLM based on URL and prompt."""request = CrawlParamsRequest(url=url, prompt=prompt)- return crawl_params_method(self._client, request)+ return crawl_params_preview_method(self._client, request)# get-active-crawlsdef get_active_crawls(diff --git a/apps/python-sdk/firecrawl/v2/methods/batch.py b/apps/python-sdk/firecrawl/v2/methods/batch.pyindex d0d6bdc4a..2a19eda02 100644--- a/apps/python-sdk/firecrawl/v2/methods/batch.py+++ b/apps/python-sdk/firecrawl/v2/methods/batch.py@@ -167,8 +167,7 @@ def wait_for_batch_completion(client: HttpClient,job_id: str,poll_interval: int = 2,- timeout: Optional[int] = None,- progress_callback: Optional[Callable[[BatchScrapeData], None]] = None+ timeout: Optional[int] = None) -> BatchScrapeResponse:"""Wait for a batch scrape job to complete, polling for status updates.@@ -178,7 +177,6 @@ def wait_for_batch_completion(job_id: ID of the batch scrape jobpoll_interval: Seconds between status checkstimeout: Maximum seconds to wait (None for no timeout)- progress_callback: Optional callback for progress updatesReturns:BatchScrapeStatusResponse when job completes@@ -197,10 +195,6 @@ def wait_for_batch_completion(status_data = status_response.data- # Call progress callback if provided- if progress_callback and status_data:- progress_callback(status_data)-# Check if job is completeif status_data and status_data.status in ["completed", "failed", "cancelled"]:return status_response@@ -218,8 +212,7 @@ def batch_scrape_and_wait(urls: List[str],options: Optional[ScrapeOptions] = None,poll_interval: int = 2,- timeout: Optional[int] = None,- progress_callback: Optional[Callable[[BatchScrapeData], None]] = None+ timeout: Optional[int] = None) -> BatchScrapeResponse:"""Start a batch scrape job and wait for it to complete.@@ -230,7 +223,6 @@ def batch_scrape_and_wait(options: Scraping optionspoll_interval: Seconds between status checkstimeout: Maximum seconds to wait (None for no timeout)- progress_callback: Optional callback for progress updatesReturns:BatchScrapeStatusResponse when job completes@@ -252,7 +244,7 @@ def batch_scrape_and_wait(# Wait for completionreturn wait_for_batch_completion(- client, job_id, poll_interval, timeout, progress_callback+ client, job_id, poll_interval, timeout)@@ -335,8 +327,7 @@ def process_large_batch(options: Optional[ScrapeOptions] = None,chunk_size: int = 100,poll_interval: int = 2,- timeout: Optional[int] = None,- progress_callback: Optional[Callable[[int, int, List[Document]], None]] = None+ timeout: Optional[int] = None) -> List[Document]:"""Process a large batch of URLs by splitting into smaller chunks.@@ -348,7 +339,6 @@ def process_large_batch(chunk_size: Size of each batch chunkpoll_interval: Seconds between status checkstimeout: Maximum seconds to wait per chunk- progress_callback: Optional callback for overall progress (completed, total, documents)Returns:List of all scraped documents@@ -374,9 +364,5 @@ def process_large_batch(all_documents.extend(result.data.data)completed_chunks += 1-- # Call progress callback if provided- if progress_callback:- progress_callback(completed_chunks, len(url_chunks), all_documents)return all_documents\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/v2/methods/crawl.py b/apps/python-sdk/firecrawl/v2/methods/crawl.pyindex 8312f9824..c86c85302 100644--- a/apps/python-sdk/firecrawl/v2/methods/crawl.py+++ b/apps/python-sdk/firecrawl/v2/methods/crawl.py@@ -3,10 +3,11 @@ Crawling functionality for Firecrawl v2 API."""import time-from typing import Optional, Callable+from typing import Optionalfrom ..types import (- CrawlRequest, CrawlResponse, CrawlStartResponse,- CrawlJob, CrawlJobData, CrawlData, Document, CrawlParamsRequest, CrawlParamsResponse, CrawlParamsData+ CrawlRequest,+ CrawlJob,+ CrawlResponse, Document, CrawlParamsRequest, CrawlParamsResponse, CrawlParamsData)from ..utils import HttpClient, handle_response_error, validate_scrape_options, prepare_scrape_options@@ -93,7 +94,7 @@ def _prepare_crawl_request(request: CrawlRequest) -> dict:return data-def start_crawl(client: HttpClient, request: CrawlRequest) -> CrawlJob:+def start_crawl(client: HttpClient, request: CrawlRequest) -> CrawlResponse:"""Start a crawl job for a website.@@ -102,33 +103,28 @@ def start_crawl(client: HttpClient, request: CrawlRequest) -> CrawlJob:request: CrawlRequest containing URL and optionsReturns:- CrawlJob with job information+ CrawlResponse with job informationRaises:ValueError: If request is invalidException: If the crawl operation fails to start"""- # Prepare request datarequest_data = _prepare_crawl_request(request)- # Make the API requestresponse = client.post("/v2/crawl", request_data)- # Handle errorsif not response.ok:handle_response_error(response, "start crawl")- # Parse responseresponse_data = response.json()if response_data.get("success"):- # The API returns id and url at the top level, not in a data fieldjob_data = {"id": response_data.get("id"),- "url": request.url, # Use the original request URL- "status": "scraping" # Default status for new jobs+ "url": response_data.get("url")}- return CrawlJob(**job_data)++ return CrawlResponse(**job_data)else:raise Exception(response_data.get("error", "Unknown error occurred"))@@ -171,34 +167,21 @@ def get_crawl_status(client: HttpClient, job_id: str) -> CrawlJob:else:documents.append(Document(**doc_data))- # Convert partial data if present- partial_documents = []- partial_data_list = response_data.get("partialData", [])- for doc_data in partial_data_list:- if isinstance(doc_data, str):- # Handle case where API returns just URLs - this shouldn't happen for crawl- # but we'll handle it gracefully- continue- else:- partial_documents.append(Document(**doc_data))-# Create CrawlJob with current status and datareturn CrawlJob(- id=job_id,- url=response_data.get("url", ""), # URL might not be in status responsestatus=response_data.get("status"),- current=response_data.get("completed", 0), # API uses "completed" instead of "current"+ completed=response_data.get("completed", 0),total=response_data.get("total", 0),- created_at=response_data.get("createdAt"),- completed_at=response_data.get("completedAt"),- data=documents,- partial_data=partial_documents if partial_documents else None+ credits_used=response_data.get("creditsUsed", 0),+ expires_at=response_data.get("expiresAt"),+ next=response_data.get("next", None),+ data=documents)else:raise Exception(response_data.get("error", "Unknown error occurred"))-def cancel_crawl(client: HttpClient, job_id: str) -> CrawlResponse:+def cancel_crawl(client: HttpClient, job_id: str) -> bool:"""Cancel a running crawl job.@@ -207,50 +190,25 @@ def cancel_crawl(client: HttpClient, job_id: str) -> CrawlResponse:job_id: ID of the crawl job to cancelReturns:- CrawlResponse with updated status+ bool: True if the crawl was cancelled, False otherwiseRaises:Exception: If the cancellation fails"""- # Make the API requestresponse = client.delete(f"/v2/crawl/{job_id}")- # Handle errorsif not response.ok:handle_response_error(response, "cancel crawl")- # Parse responseresponse_data = response.json()- if response_data.get("success"):- status_data = response_data.get("data", {})-- crawl_job_data = CrawlJobData(- id=job_id, # Use the job_id parameter- status=status_data.get("status", "failed"),- current=status_data.get("current", 0),- total=status_data.get("total", 0),- data=[]- )-- return CrawlResponse(- success=True,- data=crawl_job_data,- warning=response_data.get("warning")- )- else:- return CrawlResponse(- success=False,- error=response_data.get("error", "Unknown error occurred")- )-+ return response_data.get("status") == "cancelled"def wait_for_crawl_completion(client: HttpClient,job_id: str,poll_interval: int = 2,- timeout: Optional[int] = None,- progress_callback: Optional[Callable[[CrawlJob], None]] = None+ timeout: Optional[int] = None) -> CrawlJob:"""Wait for a crawl job to complete, polling for status updates.@@ -260,7 +218,6 @@ def wait_for_crawl_completion(job_id: ID of the crawl jobpoll_interval: Seconds between status checkstimeout: Maximum seconds to wait (None for no timeout)- progress_callback: Optional callback for progress updatesReturns:CrawlJob when job completes@@ -274,10 +231,6 @@ def wait_for_crawl_completion(while True:crawl_job = get_crawl_status(client, job_id)- # Call progress callback if provided- if progress_callback:- progress_callback(crawl_job)-# Check if job is completeif crawl_job.status in ["completed", "failed"]:return crawl_job@@ -294,8 +247,7 @@ def crawl(client: HttpClient,request: CrawlRequest,poll_interval: int = 2,- timeout: Optional[int] = None,- progress_callback: Optional[Callable[[CrawlJob], None]] = None+ timeout: Optional[int] = None) -> CrawlJob:"""Start a crawl job and wait for it to complete.@@ -305,7 +257,6 @@ def crawl(request: CrawlRequest containing URL and optionspoll_interval: Seconds between status checkstimeout: Maximum seconds to wait (None for no timeout)- progress_callback: Optional callback for progress updatesReturns:CrawlJob when job completes@@ -321,11 +272,11 @@ def crawl(# Wait for completionreturn wait_for_crawl_completion(- client, job_id, poll_interval, timeout, progress_callback+ client, job_id, poll_interval, timeout)-def crawl_params(client: HttpClient, request: CrawlParamsRequest) -> CrawlParamsData:+def crawl_params_preview(client: HttpClient, request: CrawlParamsRequest) -> CrawlParamsData:"""Get crawl parameters from LLM based on URL and prompt.@@ -354,11 +305,11 @@ def crawl_params(client: HttpClient, request: CrawlParamsRequest) -> CrawlParams}# Make the API request- response = client.post("/v2/crawl-params", request_data)+ response = client.post("/v2/crawl/params-preview", request_data)# Handle errorsif not response.ok:- handle_response_error(response, "crawl params")+ handle_response_error(response, "crawl params preview")# Parse responseresponse_data = response.json()@@ -425,6 +376,10 @@ def crawl_params(client: HttpClient, request: CrawlParamsRequest) -> CrawlParamsif key not in field_mappings:converted_params[key] = value+ # Add warning if present+ if "warning" in response_data:+ converted_params["warning"] = response_data["warning"]+return CrawlParamsData(**converted_params)else:raise Exception(response_data.get("error", "Unknown error occurred"))\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/v2/methods/search.py b/apps/python-sdk/firecrawl/v2/methods/search.pyindex c60ed7a01..6ac1d76c8 100644--- a/apps/python-sdk/firecrawl/v2/methods/search.py+++ b/apps/python-sdk/firecrawl/v2/methods/search.py@@ -140,6 +140,12 @@ def _prepare_search_request(request: SearchRequest) -> Dict[str, Any]:validated_request = _validate_search_request(request)data = validated_request.model_dump(exclude_none=True, by_alias=True)+ # Ensure default values are included only if not explicitly set to None+ if "limit" not in data and validated_request.limit is not None:+ data["limit"] = validated_request.limit+ if "timeout" not in data and validated_request.timeout is not None:+ data["timeout"] = validated_request.timeout+# Handle snake_case to camelCase conversions manually# (Pydantic Field() aliases interfere with value assignment)diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.pyindex 64fd8d97a..c3e461c66 100644--- a/apps/python-sdk/firecrawl/v2/types.py+++ b/apps/python-sdk/firecrawl/v2/types.py@@ -4,9 +4,17 @@ Type definitions for Firecrawl v2 API.This module contains clean, modern type definitions for the v2 API."""-from typing import Dict, List, Optional, Union, Literal, Any, TypeVar, Generic-from pydantic import BaseModel, Field, field_validator+import warningsfrom datetime import datetime+from typing import Any, Dict, Generic, List, Literal, Optional, TypeVar, Union+from pydantic import BaseModel, Field, field_validator++# Suppress pydantic warnings about schema field shadowing+# Tested using schema_field alias="schema" but it doesn't work.+warnings.filterwarnings("ignore", message="Field name \"schema\" in \"Format\" shadows an attribute in parent \"BaseModel\"")+warnings.filterwarnings("ignore", message="Field name \"schema\" in \"JsonFormat\" shadows an attribute in parent \"Format\"")+warnings.filterwarnings("ignore", message="Field name \"schema\" in \"ChangeTrackingFormat\" shadows an attribute in parent \"Format\"")+warnings.filterwarnings("ignore", message="Field name \"json\" in \"ScrapeFormats\" shadows an attribute in parent \"BaseModel\"")T = TypeVar('T')@@ -52,11 +60,31 @@ class Source(BaseModel):SourceOption = Union[str, Source]++FormatString = Literal[+ # camelCase versions (API format)+ "markdown", "html", "rawHtml", "links", "screenshot", "json", "changeTracking",+ # snake_case versions (user-friendly)+ "raw_html", "change_tracking"+]+class Format(BaseModel):"""Configuration for a format."""- type: str+ type: FormatString-FormatOption = Union[str, Format]+class JsonFormat(Format):+ """Configuration for JSON extraction."""+ prompt: Optional[str] = None+ schema: Optional[Dict[str, Any]] = None++class ChangeTrackingFormat(Format):+ """Configuration for change tracking."""+ modes: List[Literal["git-diff", "json"]]+ schema: Optional[Dict[str, Any]] = None+ prompt: Optional[str] = None+ tag: Optional[str] = None++FormatOption = Union[FormatString, Format, JsonFormat, ChangeTrackingFormat]# Scrape typesclass ScrapeFormats(BaseModel):@@ -65,10 +93,10 @@ class ScrapeFormats(BaseModel):markdown: bool = Truehtml: bool = Falseraw_html: bool = Field(False, alias="rawHtml")- content: bool = Falselinks: bool = Falsescreenshot: bool = False- screenshot_full_page: bool = Field(False, alias="screenshot@fullPage")+ change_tracking: bool = False+ json: bool = False@field_validator('formats')@classmethod@@ -102,9 +130,6 @@ class ScrapeOptions(BaseModel):mobile: bool = Falseskip_tls_verification: bool = Falseremove_base64_images: bool = True- # Note: raw_html and screenshot_full_page are not supported by v2 API yet- # raw_html: bool = False- # screenshot_full_page: bool = Falseblock_ads: bool = Falseproxy: Optional[str] = Nonemax_age: Optional[int] = None@@ -162,30 +187,20 @@ class CrawlRequest(BaseModel):scrape_options: Optional[ScrapeOptions] = Nonezero_data_retention: bool = False-class CrawlJob(BaseModel):+class CrawlResponse(BaseModel):"""Information about a crawl job."""id: strurl: str- status: Literal["scraping", "completed", "failed"]- current: Optional[int] = None- total: Optional[int] = None- created_at: Optional[datetime] = Field(None, alias="createdAt")- completed_at: Optional[datetime] = Field(None, alias="completedAt")- data: Optional[List[Document]] = None- partial_data: Optional[List[Document]] = Field(None, alias="partialData")-class CrawlJobData(BaseModel):+class CrawlJob(BaseModel):"""Crawl job status and progress data."""- id: strstatus: Literal["scraping", "completed", "failed"]- current: inttotal: int+ completed: int+ credits_used: int+ expires_at: datetime+ next: Optional[str] = Nonedata: List[Document]- partial_data: Optional[List[Document]] = Field(None, alias="partialData")--class CrawlData(List[Document]):- """Crawl results - just the documents."""- passclass SearchDocument(Document):"""A document from a search operation with URL and description."""@@ -197,14 +212,6 @@ class MapDocument(Document):url: strdescription: Optional[str] = None-class CrawlStartResponse(BaseResponse[CrawlJob]):- """Response for starting a crawl job."""- pass--class CrawlResponse(BaseResponse[CrawlJobData]):- """Response for crawl operations."""- pass-# Crawl params typesclass CrawlParamsRequest(BaseModel):"""Request for getting crawl parameters from LLM."""@@ -227,6 +234,7 @@ class CrawlParamsData(BaseModel):webhook: Optional[Dict[str, Any]] = Nonescrape_options: Optional[ScrapeOptions] = Nonezero_data_retention: bool = False+ warning: Optional[str] = Noneclass CrawlParamsResponse(BaseResponse[CrawlParamsData]):"""Response from crawl params endpoint."""@@ -431,13 +439,6 @@ class ClientConfig(BaseModel):max_retries: int = 3backoff_factor: float = 0.5-# Union types for convenience-ScrapeResult = Union[Document, List[Document]]-CrawlResult = Union[CrawlJob, CrawlJobData]-BatchResult = Union[BatchScrapeJob, BatchScrapeData]-JobResult = Union[CrawlJob, BatchScrapeJob]-StatusResult = Union[CrawlJobData, BatchScrapeData]-# Response union typesAnyResponse = Union[ScrapeResponse,diff --git a/apps/python-sdk/firecrawl/v2/utils/get_version.py b/apps/python-sdk/firecrawl/v2/utils/get_version.pyindex e7295ceea..16761f854 100644--- a/apps/python-sdk/firecrawl/v2/utils/get_version.py+++ b/apps/python-sdk/firecrawl/v2/utils/get_version.py@@ -1,14 +1,15 @@import osimport re+from pathlib import Pathdef get_version():- try:- from pathlib import Path- package_path = os.path.dirname(__file__)- version_file = Path(os.path.join(package_path, '__init__.py')).read_text()- version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)- if version_match:- return version_match.group(1).strip()- except Exception:- print("Failed to get version from __init__.py")- return None\ No newline at end of file+ try:+ package_path = Path(__file__).parents[2]+ version_file = (package_path / "__init__.py").read_text()+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)+ if version_match:+ return version_match.group(1).strip()+ return "3.x.x"+ except Exception as e:+ print(f"Failed to get version from __init__.py: {e}")+ return "3.x.x"\ No newline at end of filediff --git a/apps/python-sdk/firecrawl/v2/utils/validation.py b/apps/python-sdk/firecrawl/v2/utils/validation.pyindex 4782be013..4f85c19b9 100644--- a/apps/python-sdk/firecrawl/v2/utils/validation.py+++ b/apps/python-sdk/firecrawl/v2/utils/validation.py@@ -6,6 +6,52 @@ from typing import Optional, Dict, Anyfrom ..types import ScrapeOptions+def _convert_format_string(format_str: str) -> str:+ """+ Convert format string from snake_case to camelCase.++ Args:+ format_str: Format string in snake_case++ Returns:+ Format string in camelCase+ """+ format_mapping = {+ "raw_html": "rawHtml",+ "change_tracking": "changeTracking",+ "screenshot_full_page": "screenshot@fullPage"+ }+ return format_mapping.get(format_str, format_str)+++def _validate_json_format(format_obj: Any) -> Dict[str, Any]:+ """+ Validate and prepare json format object.++ Args:+ format_obj: Format object that should be json type++ Returns:+ Validated json format dict++ Raises:+ ValueError: If json format is missing required fields+ """+ if not isinstance(format_obj, dict):+ raise ValueError("json format must be an object with 'type', 'prompt', and 'schema' fields")++ if format_obj.get('type') != 'json':+ raise ValueError("json format must have type='json'")++ if 'prompt' not in format_obj:+ raise ValueError("json format requires 'prompt' field")++ if 'schema' not in format_obj:+ raise ValueError("json format requires 'schema' field")++ return format_obj++def validate_scrape_options(options: Optional[ScrapeOptions]) -> Optional[ScrapeOptions]:"""Validate and normalize scrape options.@@ -59,8 +105,24 @@ def prepare_scrape_options(options: Optional[ScrapeOptions]) -> Optional[Dict[stif value is not None:if key == "formats":# Handle formats - if it's a ScrapeFormats object, convert boolean flags to format strings- if hasattr(value, 'formats') and value.formats is not None:- scrape_data["formats"] = value.formats+ if isinstance(value, dict) and any(key in value for key in ['markdown', 'html', 'raw_html', 'content', 'links', 'screenshot', 'screenshot_full_page']):+ # Convert ScrapeFormats boolean flags to format strings+ formats = []+ if value.get('markdown', False):+ formats.append("markdown")+ if value.get('html', False):+ formats.append("html")+ if value.get('raw_html', False):+ formats.append("rawHtml")+ if value.get('content', False):+ formats.append("content")+ if value.get('links', False):+ formats.append("links")+ if value.get('screenshot', False):+ formats.append("screenshot")+ if value.get('screenshot_full_page', False):+ formats.append("screenshot@fullPage")+ scrape_data["formats"] = formatselif hasattr(value, 'markdown') or hasattr(value, 'html') or hasattr(value, 'raw_html') or hasattr(value, 'content') or hasattr(value, 'links') or hasattr(value, 'screenshot') or hasattr(value, 'screenshot_full_page'):# Convert ScrapeFormats boolean flags to format stringsformats = []@@ -79,9 +141,47 @@ def prepare_scrape_options(options: Optional[ScrapeOptions]) -> Optional[Dict[stif getattr(value, 'screenshot_full_page', False):formats.append("screenshot@fullPage")scrape_data["formats"] = formats+ elif hasattr(value, 'formats') and value.formats is not None:+ # Convert format strings from snake_case to camelCase+ converted_formats = []+ for fmt in value.formats:+ if isinstance(fmt, str):+ converted_formats.append(_convert_format_string(fmt))+ elif hasattr(fmt, 'type'):+ converted_formats.append(_convert_format_string(fmt.type))+ else:+ converted_formats.append(fmt)+ scrape_data["formats"] = converted_formatselif isinstance(value, list):- # If it's already a list, use it directly- scrape_data["formats"] = value+ # If it's already a list, convert format strings from snake_case to camelCase+ converted_formats = []+ for fmt in value:+ if isinstance(fmt, str):+ # Handle json format specially - it can't be a string+ if fmt == "json":+ raise ValueError("json format must be an object with 'type', 'prompt', and 'schema' fields")+ converted_formats.append(_convert_format_string(fmt))+ elif isinstance(fmt, dict):+ # Handle format objects (like json format)+ if fmt.get('type') == 'json':+ validated_json = _validate_json_format(fmt)+ converted_formats.append(validated_json)+ else:+ # Convert other format objects+ if 'type' in fmt:+ fmt['type'] = _convert_format_string(fmt['type'])+ converted_formats.append(fmt)+ elif hasattr(fmt, 'type'):+ # Handle Format objects+ if fmt.type == 'json':+ # For json format, we need the full object+ converted_formats.append(fmt.model_dump())+ else:+ # For other formats, just convert the type+ converted_formats.append(_convert_format_string(fmt.type))+ else:+ converted_formats.append(fmt)+ scrape_data["formats"] = converted_formatselse:# Fallback - use the value as-isscrape_data["formats"] = value@@ -103,9 +203,8 @@ def prepare_scrape_options(options: Optional[ScrapeOptions]) -> Optional[Dict[stscrape_data["storeInCache"] = valueelif key == "max_age":scrape_data["maxAge"] = value- # Note: raw_html and screenshot_full_page are not supported by v2 API yet- # elif key == "raw_html":- # scrape_data["rawHtml"] = value+ # Note: raw_html should be in formats array, not as a separate field+ # Note: screenshot_full_page is not supported by v2 API# elif key == "screenshot_full_page":# scrape_data["screenshot@fullPage"] = valueelse: