firecrawl-py 2.0.1__py3-none-any.whl → 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of firecrawl-py might be problematic. Click here for more details.

@@ -0,0 +1,4276 @@
1
+ """
2
+ FirecrawlApp Module
3
+
4
+ This module provides a class `FirecrawlApp` for interacting with the Firecrawl API.
5
+ It includes methods to scrape URLs, perform searches, initiate and monitor crawl jobs,
6
+ and check the status of these jobs. The module uses requests for HTTP communication
7
+ and handles retries for certain HTTP status codes.
8
+
9
+ Classes:
10
+ - FirecrawlApp: Main class for interacting with the Firecrawl API.
11
+ """
12
+ import logging
13
+ import os
14
+ import time
15
+ from typing import Any, Dict, Optional, List, Union, Callable, Literal, TypeVar, Generic
16
+ import json
17
+ from datetime import datetime
18
+ import re
19
+ import warnings
20
+ import requests
21
+ import pydantic
22
+ import websockets
23
+ import aiohttp
24
+ import asyncio
25
+ from pydantic import Field
26
+
27
+ # Suppress Pydantic warnings about attribute shadowing
28
+ warnings.filterwarnings("ignore", message="Field name \"json\" in \"FirecrawlDocument\" shadows an attribute in parent \"BaseModel\"")
29
+ warnings.filterwarnings("ignore", message="Field name \"json\" in \"ChangeTrackingData\" shadows an attribute in parent \"BaseModel\"")
30
+ warnings.filterwarnings("ignore", message="Field name \"schema\" in \"JsonConfig\" shadows an attribute in parent \"BaseModel\"")
31
+ warnings.filterwarnings("ignore", message="Field name \"schema\" in \"ExtractParams\" shadows an attribute in parent \"BaseModel\"")
32
+
33
+
34
+ def get_version():
35
+ try:
36
+ from pathlib import Path
37
+ package_path = os.path.dirname(__file__)
38
+ version_file = Path(os.path.join(package_path, '__init__.py')).read_text()
39
+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
40
+ if version_match:
41
+ return version_match.group(1).strip()
42
+ except Exception:
43
+ print("Failed to get version from __init__.py")
44
+ return None
45
+
46
+ version = get_version()
47
+
48
+ logger : logging.Logger = logging.getLogger("firecrawl")
49
+
50
+ T = TypeVar('T')
51
+
52
+ # class FirecrawlDocumentMetadata(pydantic.BaseModel):
53
+ # """Metadata for a Firecrawl document."""
54
+ # title: Optional[str] = None
55
+ # description: Optional[str] = None
56
+ # language: Optional[str] = None
57
+ # keywords: Optional[str] = None
58
+ # robots: Optional[str] = None
59
+ # ogTitle: Optional[str] = None
60
+ # ogDescription: Optional[str] = None
61
+ # ogUrl: Optional[str] = None
62
+ # ogImage: Optional[str] = None
63
+ # ogAudio: Optional[str] = None
64
+ # ogDeterminer: Optional[str] = None
65
+ # ogLocale: Optional[str] = None
66
+ # ogLocaleAlternate: Optional[List[str]] = None
67
+ # ogSiteName: Optional[str] = None
68
+ # ogVideo: Optional[str] = None
69
+ # dctermsCreated: Optional[str] = None
70
+ # dcDateCreated: Optional[str] = None
71
+ # dcDate: Optional[str] = None
72
+ # dctermsType: Optional[str] = None
73
+ # dcType: Optional[str] = None
74
+ # dctermsAudience: Optional[str] = None
75
+ # dctermsSubject: Optional[str] = None
76
+ # dcSubject: Optional[str] = None
77
+ # dcDescription: Optional[str] = None
78
+ # dctermsKeywords: Optional[str] = None
79
+ # modifiedTime: Optional[str] = None
80
+ # publishedTime: Optional[str] = None
81
+ # articleTag: Optional[str] = None
82
+ # articleSection: Optional[str] = None
83
+ # sourceURL: Optional[str] = None
84
+ # statusCode: Optional[int] = None
85
+ # error: Optional[str] = None
86
+
87
+ class AgentOptions(pydantic.BaseModel):
88
+ """Configuration for the agent."""
89
+ model: Literal["FIRE-1"] = "FIRE-1"
90
+ prompt: Optional[str] = None
91
+
92
+ class AgentOptionsExtract(pydantic.BaseModel):
93
+ """Configuration for the agent in extract operations."""
94
+ model: Literal["FIRE-1"] = "FIRE-1"
95
+
96
+ class ActionsResult(pydantic.BaseModel):
97
+ """Result of actions performed during scraping."""
98
+ screenshots: List[str]
99
+
100
+ class ChangeTrackingData(pydantic.BaseModel):
101
+ """
102
+ Data for the change tracking format.
103
+ """
104
+ previousScrapeAt: Optional[str] = None
105
+ changeStatus: str # "new" | "same" | "changed" | "removed"
106
+ visibility: str # "visible" | "hidden"
107
+ diff: Optional[Dict[str, Any]] = None
108
+ json: Optional[Any] = None
109
+
110
+ class FirecrawlDocument(pydantic.BaseModel, Generic[T]):
111
+ """Document retrieved or processed by Firecrawl."""
112
+ url: Optional[str] = None
113
+ markdown: Optional[str] = None
114
+ html: Optional[str] = None
115
+ rawHtml: Optional[str] = None
116
+ links: Optional[List[str]] = None
117
+ extract: Optional[T] = None
118
+ json: Optional[T] = None
119
+ screenshot: Optional[str] = None
120
+ metadata: Optional[Any] = None
121
+ actions: Optional[ActionsResult] = None
122
+ title: Optional[str] = None # v1 search only
123
+ description: Optional[str] = None # v1 search only
124
+ changeTracking: Optional[ChangeTrackingData] = None
125
+
126
+ class LocationConfig(pydantic.BaseModel):
127
+ """Location configuration for scraping."""
128
+ country: Optional[str] = None
129
+ languages: Optional[List[str]] = None
130
+
131
+ class WebhookConfig(pydantic.BaseModel):
132
+ """Configuration for webhooks."""
133
+ url: str
134
+ headers: Optional[Dict[str, str]] = None
135
+ metadata: Optional[Dict[str, str]] = None
136
+ events: Optional[List[Literal["completed", "failed", "page", "started"]]] = None
137
+
138
+ class ScrapeOptions(pydantic.BaseModel):
139
+ """Parameters for scraping operations."""
140
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json", "changeTracking"]]] = None
141
+ headers: Optional[Dict[str, str]] = None
142
+ includeTags: Optional[List[str]] = None
143
+ excludeTags: Optional[List[str]] = None
144
+ onlyMainContent: Optional[bool] = None
145
+ waitFor: Optional[int] = None
146
+ timeout: Optional[int] = None
147
+ location: Optional[LocationConfig] = None
148
+ mobile: Optional[bool] = None
149
+ skipTlsVerification: Optional[bool] = None
150
+ removeBase64Images: Optional[bool] = None
151
+ blockAds: Optional[bool] = None
152
+ proxy: Optional[Literal["basic", "stealth"]] = None
153
+
154
+ class WaitAction(pydantic.BaseModel):
155
+ """Wait action to perform during scraping."""
156
+ type: Literal["wait"]
157
+ milliseconds: int
158
+ selector: Optional[str] = None
159
+
160
+ class ScreenshotAction(pydantic.BaseModel):
161
+ """Screenshot action to perform during scraping."""
162
+ type: Literal["screenshot"]
163
+ fullPage: Optional[bool] = None
164
+
165
+ class ClickAction(pydantic.BaseModel):
166
+ """Click action to perform during scraping."""
167
+ type: Literal["click"]
168
+ selector: str
169
+
170
+ class WriteAction(pydantic.BaseModel):
171
+ """Write action to perform during scraping."""
172
+ type: Literal["write"]
173
+ text: str
174
+
175
+ class PressAction(pydantic.BaseModel):
176
+ """Press action to perform during scraping."""
177
+ type: Literal["press"]
178
+ key: str
179
+
180
+ class ScrollAction(pydantic.BaseModel):
181
+ """Scroll action to perform during scraping."""
182
+ type: Literal["scroll"]
183
+ direction: Literal["up", "down"]
184
+ selector: Optional[str] = None
185
+
186
+ class ScrapeAction(pydantic.BaseModel):
187
+ """Scrape action to perform during scraping."""
188
+ type: Literal["scrape"]
189
+
190
+ class ExecuteJavascriptAction(pydantic.BaseModel):
191
+ """Execute javascript action to perform during scraping."""
192
+ type: Literal["executeJavascript"]
193
+ script: str
194
+
195
+
196
+ class ExtractAgent(pydantic.BaseModel):
197
+ """Configuration for the agent in extract operations."""
198
+ model: Literal["FIRE-1"] = "FIRE-1"
199
+
200
+ class JsonConfig(pydantic.BaseModel):
201
+ """Configuration for extraction."""
202
+ prompt: Optional[str] = None
203
+ schema: Optional[Any] = None
204
+ systemPrompt: Optional[str] = None
205
+ agent: Optional[ExtractAgent] = None
206
+
207
+ class ScrapeParams(ScrapeOptions):
208
+ """Parameters for scraping operations."""
209
+ extract: Optional[JsonConfig] = None
210
+ jsonOptions: Optional[JsonConfig] = None
211
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None
212
+ agent: Optional[AgentOptions] = None
213
+
214
+ class ScrapeResponse(FirecrawlDocument[T], Generic[T]):
215
+ """Response from scraping operations."""
216
+ success: bool = True
217
+ warning: Optional[str] = None
218
+ error: Optional[str] = None
219
+
220
+ class BatchScrapeResponse(pydantic.BaseModel):
221
+ """Response from batch scrape operations."""
222
+ id: Optional[str] = None
223
+ url: Optional[str] = None
224
+ success: bool = True
225
+ error: Optional[str] = None
226
+ invalidURLs: Optional[List[str]] = None
227
+
228
+ class BatchScrapeStatusResponse(pydantic.BaseModel):
229
+ """Response from batch scrape status checks."""
230
+ success: bool = True
231
+ status: Literal["scraping", "completed", "failed", "cancelled"]
232
+ completed: int
233
+ total: int
234
+ creditsUsed: int
235
+ expiresAt: datetime
236
+ next: Optional[str] = None
237
+ data: List[FirecrawlDocument]
238
+
239
+ class CrawlParams(pydantic.BaseModel):
240
+ """Parameters for crawling operations."""
241
+ includePaths: Optional[List[str]] = None
242
+ excludePaths: Optional[List[str]] = None
243
+ maxDepth: Optional[int] = None
244
+ maxDiscoveryDepth: Optional[int] = None
245
+ limit: Optional[int] = None
246
+ allowBackwardLinks: Optional[bool] = None
247
+ allowExternalLinks: Optional[bool] = None
248
+ ignoreSitemap: Optional[bool] = None
249
+ scrapeOptions: Optional[ScrapeOptions] = None
250
+ webhook: Optional[Union[str, WebhookConfig]] = None
251
+ deduplicateSimilarURLs: Optional[bool] = None
252
+ ignoreQueryParameters: Optional[bool] = None
253
+ regexOnFullURL: Optional[bool] = None
254
+
255
+ class CrawlResponse(pydantic.BaseModel):
256
+ """Response from crawling operations."""
257
+ id: Optional[str] = None
258
+ url: Optional[str] = None
259
+ success: bool = True
260
+ error: Optional[str] = None
261
+
262
+ class CrawlStatusResponse(pydantic.BaseModel):
263
+ """Response from crawl status checks."""
264
+ success: bool = True
265
+ status: Literal["scraping", "completed", "failed", "cancelled"]
266
+ completed: int
267
+ total: int
268
+ creditsUsed: int
269
+ expiresAt: datetime
270
+ next: Optional[str] = None
271
+ data: List[FirecrawlDocument]
272
+
273
+ class CrawlErrorsResponse(pydantic.BaseModel):
274
+ """Response from crawl/batch scrape error monitoring."""
275
+ errors: List[Dict[str, str]] # {id: str, timestamp: str, url: str, error: str}
276
+ robotsBlocked: List[str]
277
+
278
+ class MapParams(pydantic.BaseModel):
279
+ """Parameters for mapping operations."""
280
+ search: Optional[str] = None
281
+ ignoreSitemap: Optional[bool] = None
282
+ includeSubdomains: Optional[bool] = None
283
+ sitemapOnly: Optional[bool] = None
284
+ limit: Optional[int] = None
285
+ timeout: Optional[int] = None
286
+
287
+ class MapResponse(pydantic.BaseModel):
288
+ """Response from mapping operations."""
289
+ success: bool = True
290
+ links: Optional[List[str]] = None
291
+ error: Optional[str] = None
292
+
293
+ class ExtractParams(pydantic.BaseModel):
294
+ """Parameters for extracting information from URLs."""
295
+ prompt: Optional[str] = None
296
+ schema: Optional[Any] = None
297
+ systemPrompt: Optional[str] = None
298
+ allowExternalLinks: Optional[bool] = None
299
+ enableWebSearch: Optional[bool] = None
300
+ includeSubdomains: Optional[bool] = None
301
+ origin: Optional[str] = None
302
+ showSources: Optional[bool] = None
303
+ scrapeOptions: Optional[ScrapeOptions] = None
304
+
305
+ class ExtractResponse(pydantic.BaseModel, Generic[T]):
306
+ """Response from extract operations."""
307
+ success: bool = True
308
+ data: Optional[T] = None
309
+ error: Optional[str] = None
310
+ warning: Optional[str] = None
311
+ sources: Optional[List[str]] = None
312
+
313
+ class SearchParams(pydantic.BaseModel):
314
+ query: str
315
+ limit: Optional[int] = 5
316
+ tbs: Optional[str] = None
317
+ filter: Optional[str] = None
318
+ lang: Optional[str] = "en"
319
+ country: Optional[str] = "us"
320
+ location: Optional[str] = None
321
+ origin: Optional[str] = "api"
322
+ timeout: Optional[int] = 60000
323
+ scrapeOptions: Optional[ScrapeOptions] = None
324
+
325
+ class SearchResponse(pydantic.BaseModel):
326
+ """Response from search operations."""
327
+ success: bool = True
328
+ data: List[FirecrawlDocument]
329
+ warning: Optional[str] = None
330
+ error: Optional[str] = None
331
+
332
+ class GenerateLLMsTextParams(pydantic.BaseModel):
333
+ """
334
+ Parameters for the LLMs.txt generation operation.
335
+ """
336
+ maxUrls: Optional[int] = 10
337
+ showFullText: Optional[bool] = False
338
+ __experimental_stream: Optional[bool] = None
339
+
340
+ class DeepResearchParams(pydantic.BaseModel):
341
+ """
342
+ Parameters for the deep research operation.
343
+ """
344
+ maxDepth: Optional[int] = 7
345
+ timeLimit: Optional[int] = 270
346
+ maxUrls: Optional[int] = 20
347
+ analysisPrompt: Optional[str] = None
348
+ systemPrompt: Optional[str] = None
349
+ __experimental_streamSteps: Optional[bool] = None
350
+
351
+ class DeepResearchResponse(pydantic.BaseModel):
352
+ """
353
+ Response from the deep research operation.
354
+ """
355
+ success: bool
356
+ id: str
357
+ error: Optional[str] = None
358
+
359
+ class DeepResearchStatusResponse(pydantic.BaseModel):
360
+ """
361
+ Status response from the deep research operation.
362
+ """
363
+ success: bool
364
+ data: Optional[Dict[str, Any]] = None
365
+ status: str
366
+ error: Optional[str] = None
367
+ expiresAt: str
368
+ currentDepth: int
369
+ maxDepth: int
370
+ activities: List[Dict[str, Any]]
371
+ sources: List[Dict[str, Any]]
372
+ summaries: List[str]
373
+
374
+ class GenerateLLMsTextResponse(pydantic.BaseModel):
375
+ """Response from LLMs.txt generation operations."""
376
+ success: bool = True
377
+ id: str
378
+ error: Optional[str] = None
379
+
380
+ class GenerateLLMsTextStatusResponseData(pydantic.BaseModel):
381
+ llmstxt: str
382
+ llmsfulltxt: Optional[str] = None
383
+
384
+ class GenerateLLMsTextStatusResponse(pydantic.BaseModel):
385
+ """Status response from LLMs.txt generation operations."""
386
+ success: bool = True
387
+ data: Optional[GenerateLLMsTextStatusResponseData] = None
388
+ status: Literal["processing", "completed", "failed"]
389
+ error: Optional[str] = None
390
+ expiresAt: str
391
+
392
+ class SearchResponse(pydantic.BaseModel):
393
+ """
394
+ Response from the search operation.
395
+ """
396
+ success: bool
397
+ data: List[Dict[str, Any]]
398
+ warning: Optional[str] = None
399
+ error: Optional[str] = None
400
+
401
+ class ExtractParams(pydantic.BaseModel):
402
+ """
403
+ Parameters for the extract operation.
404
+ """
405
+ prompt: Optional[str] = None
406
+ schema: Optional[Any] = pydantic.Field(None, alias='schema')
407
+ system_prompt: Optional[str] = None
408
+ allow_external_links: Optional[bool] = False
409
+ enable_web_search: Optional[bool] = False
410
+ # Just for backwards compatibility
411
+ enableWebSearch: Optional[bool] = False
412
+ show_sources: Optional[bool] = False
413
+ agent: Optional[Dict[str, Any]] = None
414
+
415
+ class ExtractResponse(pydantic.BaseModel, Generic[T]):
416
+ """
417
+ Response from the extract operation.
418
+ """
419
+ success: bool
420
+ data: Optional[T] = None
421
+ error: Optional[str] = None
422
+
423
+ class FirecrawlApp:
424
+ def __init__(self, api_key: Optional[str] = None, api_url: Optional[str] = None) -> None:
425
+ """
426
+ Initialize the FirecrawlApp instance with API key, API URL.
427
+
428
+ Args:
429
+ api_key (Optional[str]): API key for authenticating with the Firecrawl API.
430
+ api_url (Optional[str]): Base URL for the Firecrawl API.
431
+ """
432
+ self.api_key = api_key or os.getenv('FIRECRAWL_API_KEY')
433
+ self.api_url = api_url or os.getenv('FIRECRAWL_API_URL', 'https://api.firecrawl.dev')
434
+
435
+ # Only require API key when using cloud service
436
+ if 'api.firecrawl.dev' in self.api_url and self.api_key is None:
437
+ logger.warning("No API key provided for cloud service")
438
+ raise ValueError('No API key provided')
439
+
440
+ logger.debug(f"Initialized FirecrawlApp with API URL: {self.api_url}")
441
+
442
+ def scrape_url(
443
+ self,
444
+ url: str,
445
+ *,
446
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json", "changeTracking"]]] = None,
447
+ include_tags: Optional[List[str]] = None,
448
+ exclude_tags: Optional[List[str]] = None,
449
+ only_main_content: Optional[bool] = None,
450
+ wait_for: Optional[int] = None,
451
+ timeout: Optional[int] = None,
452
+ location: Optional[LocationConfig] = None,
453
+ mobile: Optional[bool] = None,
454
+ skip_tls_verification: Optional[bool] = None,
455
+ remove_base64_images: Optional[bool] = None,
456
+ block_ads: Optional[bool] = None,
457
+ proxy: Optional[Literal["basic", "stealth"]] = None,
458
+ extract: Optional[JsonConfig] = None,
459
+ json_options: Optional[JsonConfig] = None,
460
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None,
461
+ **kwargs) -> ScrapeResponse[Any]:
462
+ """
463
+ Scrape and extract content from a URL.
464
+
465
+ Args:
466
+ url (str): Target URL to scrape
467
+ formats (Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]]): Content types to retrieve (markdown/html/etc)
468
+ include_tags (Optional[List[str]]): HTML tags to include
469
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
470
+ only_main_content (Optional[bool]): Extract main content only
471
+ wait_for (Optional[int]): Wait for a specific element to appear
472
+ timeout (Optional[int]): Request timeout (ms)
473
+ location (Optional[LocationConfig]): Location configuration
474
+ mobile (Optional[bool]): Use mobile user agent
475
+ skip_tls_verification (Optional[bool]): Skip TLS verification
476
+ remove_base64_images (Optional[bool]): Remove base64 images
477
+ block_ads (Optional[bool]): Block ads
478
+ proxy (Optional[Literal["basic", "stealth"]]): Proxy type (basic/stealth)
479
+ extract (Optional[JsonConfig]): Content extraction settings
480
+ json_options (Optional[JsonConfig]): JSON extraction settings
481
+ actions (Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]]): Actions to perform
482
+
483
+
484
+ Returns:
485
+ ScrapeResponse with:
486
+ * Requested content formats
487
+ * Page metadata
488
+ * Extraction results
489
+ * Success/error status
490
+
491
+ Raises:
492
+ Exception: If scraping fails
493
+ """
494
+ headers = self._prepare_headers()
495
+
496
+ # Build scrape parameters
497
+ scrape_params = {
498
+ 'url': url,
499
+ 'origin': f"python-sdk@{version}"
500
+ }
501
+
502
+ # Add optional parameters if provided
503
+ if formats:
504
+ scrape_params['formats'] = formats
505
+ if include_tags:
506
+ scrape_params['includeTags'] = include_tags
507
+ if exclude_tags:
508
+ scrape_params['excludeTags'] = exclude_tags
509
+ if only_main_content is not None:
510
+ scrape_params['onlyMainContent'] = only_main_content
511
+ if wait_for:
512
+ scrape_params['waitFor'] = wait_for
513
+ if timeout:
514
+ scrape_params['timeout'] = timeout
515
+ if location:
516
+ scrape_params['location'] = location.dict(exclude_none=True)
517
+ if mobile is not None:
518
+ scrape_params['mobile'] = mobile
519
+ if skip_tls_verification is not None:
520
+ scrape_params['skipTlsVerification'] = skip_tls_verification
521
+ if remove_base64_images is not None:
522
+ scrape_params['removeBase64Images'] = remove_base64_images
523
+ if block_ads is not None:
524
+ scrape_params['blockAds'] = block_ads
525
+ if proxy:
526
+ scrape_params['proxy'] = proxy
527
+ if extract:
528
+ if hasattr(extract.schema, 'schema'):
529
+ extract.schema = extract.schema.schema()
530
+ scrape_params['extract'] = extract.dict(exclude_none=True)
531
+ if json_options:
532
+ if hasattr(json_options.schema, 'schema'):
533
+ json_options.schema = json_options.schema.schema()
534
+ scrape_params['jsonOptions'] = json_options.dict(exclude_none=True)
535
+ if actions:
536
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
537
+ scrape_params.update(kwargs)
538
+
539
+ # Make request
540
+ response = requests.post(
541
+ f'{self.api_url}/v1/scrape',
542
+ headers=headers,
543
+ json=scrape_params,
544
+ timeout=(timeout + 5000 if timeout else None)
545
+ )
546
+
547
+ if response.status_code == 200:
548
+ try:
549
+ response_json = response.json()
550
+ if response_json.get('success') and 'data' in response_json:
551
+ return ScrapeResponse(**response_json['data'])
552
+ elif "error" in response_json:
553
+ raise Exception(f'Failed to scrape URL. Error: {response_json["error"]}')
554
+ else:
555
+ raise Exception(f'Failed to scrape URL. Error: {response_json}')
556
+ except ValueError:
557
+ raise Exception('Failed to parse Firecrawl response as JSON.')
558
+ else:
559
+ self._handle_error(response, 'scrape URL')
560
+
561
+ def search(
562
+ self,
563
+ query: str,
564
+ *,
565
+ limit: Optional[int] = None,
566
+ tbs: Optional[str] = None,
567
+ filter: Optional[str] = None,
568
+ lang: Optional[str] = None,
569
+ country: Optional[str] = None,
570
+ location: Optional[str] = None,
571
+ timeout: Optional[int] = None,
572
+ scrape_options: Optional[ScrapeOptions] = None,
573
+ params: Optional[Union[Dict[str, Any], SearchParams]] = None,
574
+ **kwargs) -> SearchResponse:
575
+ """
576
+ Search for content using Firecrawl.
577
+
578
+ Args:
579
+ query (str): Search query string
580
+ limit (Optional[int]): Max results (default: 5)
581
+ tbs (Optional[str]): Time filter (e.g. "qdr:d")
582
+ filter (Optional[str]): Custom result filter
583
+ lang (Optional[str]): Language code (default: "en")
584
+ country (Optional[str]): Country code (default: "us")
585
+ location (Optional[str]): Geo-targeting
586
+ timeout (Optional[int]): Request timeout in milliseconds
587
+ scrape_options (Optional[ScrapeOptions]): Result scraping configuration
588
+ params (Optional[Union[Dict[str, Any], SearchParams]]): Additional search parameters
589
+ **kwargs: Additional keyword arguments for future compatibility
590
+
591
+ Returns:
592
+ SearchResponse: Response containing:
593
+ * success (bool): Whether request succeeded
594
+ * data (List[FirecrawlDocument]): Search results
595
+ * warning (Optional[str]): Warning message if any
596
+ * error (Optional[str]): Error message if any
597
+
598
+ Raises:
599
+ Exception: If search fails or response cannot be parsed
600
+ """
601
+ # Build search parameters
602
+ search_params = {}
603
+ if params:
604
+ if isinstance(params, dict):
605
+ search_params.update(params)
606
+ else:
607
+ search_params.update(params.dict(exclude_none=True))
608
+
609
+ # Add individual parameters
610
+ if limit is not None:
611
+ search_params['limit'] = limit
612
+ if tbs is not None:
613
+ search_params['tbs'] = tbs
614
+ if filter is not None:
615
+ search_params['filter'] = filter
616
+ if lang is not None:
617
+ search_params['lang'] = lang
618
+ if country is not None:
619
+ search_params['country'] = country
620
+ if location is not None:
621
+ search_params['location'] = location
622
+ if timeout is not None:
623
+ search_params['timeout'] = timeout
624
+ if scrape_options is not None:
625
+ search_params['scrapeOptions'] = scrape_options.dict(exclude_none=True)
626
+
627
+ # Add any additional kwargs
628
+ search_params.update(kwargs)
629
+
630
+ # Create final params object
631
+ final_params = SearchParams(query=query, **search_params)
632
+ params_dict = final_params.dict(exclude_none=True)
633
+ params_dict['origin'] = f"python-sdk@{version}"
634
+
635
+ # Make request
636
+ response = requests.post(
637
+ f"{self.api_url}/v1/search",
638
+ headers={"Authorization": f"Bearer {self.api_key}"},
639
+ json=params_dict
640
+ )
641
+
642
+ if response.status_code == 200:
643
+ try:
644
+ response_json = response.json()
645
+ if response_json.get('success') and 'data' in response_json:
646
+ return SearchResponse(**response_json)
647
+ elif "error" in response_json:
648
+ raise Exception(f'Search failed. Error: {response_json["error"]}')
649
+ else:
650
+ raise Exception(f'Search failed. Error: {response_json}')
651
+ except ValueError:
652
+ raise Exception('Failed to parse Firecrawl response as JSON.')
653
+ else:
654
+ self._handle_error(response, 'search')
655
+
656
+ def crawl_url(
657
+ self,
658
+ url: str,
659
+ *,
660
+ include_paths: Optional[List[str]] = None,
661
+ exclude_paths: Optional[List[str]] = None,
662
+ max_depth: Optional[int] = None,
663
+ max_discovery_depth: Optional[int] = None,
664
+ limit: Optional[int] = None,
665
+ allow_backward_links: Optional[bool] = None,
666
+ allow_external_links: Optional[bool] = None,
667
+ ignore_sitemap: Optional[bool] = None,
668
+ scrape_options: Optional[ScrapeOptions] = None,
669
+ webhook: Optional[Union[str, WebhookConfig]] = None,
670
+ deduplicate_similar_urls: Optional[bool] = None,
671
+ ignore_query_parameters: Optional[bool] = None,
672
+ regex_on_full_url: Optional[bool] = None,
673
+ poll_interval: Optional[int] = 2,
674
+ idempotency_key: Optional[str] = None,
675
+ **kwargs
676
+ ) -> CrawlStatusResponse:
677
+ """
678
+ Crawl a website starting from a URL.
679
+
680
+ Args:
681
+ url (str): Target URL to start crawling from
682
+ include_paths (Optional[List[str]]): Patterns of URLs to include
683
+ exclude_paths (Optional[List[str]]): Patterns of URLs to exclude
684
+ max_depth (Optional[int]): Maximum crawl depth
685
+ max_discovery_depth (Optional[int]): Maximum depth for finding new URLs
686
+ limit (Optional[int]): Maximum pages to crawl
687
+ allow_backward_links (Optional[bool]): Follow parent directory links
688
+ allow_external_links (Optional[bool]): Follow external domain links
689
+ ignore_sitemap (Optional[bool]): Skip sitemap.xml processing
690
+ scrape_options (Optional[ScrapeOptions]): Page scraping configuration
691
+ webhook (Optional[Union[str, WebhookConfig]]): Notification webhook settings
692
+ deduplicate_similar_urls (Optional[bool]): Remove similar URLs
693
+ ignore_query_parameters (Optional[bool]): Ignore URL parameters
694
+ regex_on_full_url (Optional[bool]): Apply regex to full URLs
695
+ poll_interval (Optional[int]): Seconds between status checks (default: 2)
696
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
697
+ **kwargs: Additional parameters to pass to the API
698
+
699
+ Returns:
700
+ CrawlStatusResponse with:
701
+ * Crawling status and progress
702
+ * Crawled page contents
703
+ * Success/error information
704
+
705
+ Raises:
706
+ Exception: If crawl fails
707
+ """
708
+ crawl_params = {}
709
+
710
+ # Add individual parameters
711
+ if include_paths is not None:
712
+ crawl_params['includePaths'] = include_paths
713
+ if exclude_paths is not None:
714
+ crawl_params['excludePaths'] = exclude_paths
715
+ if max_depth is not None:
716
+ crawl_params['maxDepth'] = max_depth
717
+ if max_discovery_depth is not None:
718
+ crawl_params['maxDiscoveryDepth'] = max_discovery_depth
719
+ if limit is not None:
720
+ crawl_params['limit'] = limit
721
+ if allow_backward_links is not None:
722
+ crawl_params['allowBackwardLinks'] = allow_backward_links
723
+ if allow_external_links is not None:
724
+ crawl_params['allowExternalLinks'] = allow_external_links
725
+ if ignore_sitemap is not None:
726
+ crawl_params['ignoreSitemap'] = ignore_sitemap
727
+ if scrape_options is not None:
728
+ crawl_params['scrapeOptions'] = scrape_options.dict(exclude_none=True)
729
+ if webhook is not None:
730
+ crawl_params['webhook'] = webhook
731
+ if deduplicate_similar_urls is not None:
732
+ crawl_params['deduplicateSimilarURLs'] = deduplicate_similar_urls
733
+ if ignore_query_parameters is not None:
734
+ crawl_params['ignoreQueryParameters'] = ignore_query_parameters
735
+ if regex_on_full_url is not None:
736
+ crawl_params['regexOnFullURL'] = regex_on_full_url
737
+
738
+ # Add any additional kwargs
739
+ crawl_params.update(kwargs)
740
+
741
+ # Create final params object
742
+ final_params = CrawlParams(**crawl_params)
743
+ params_dict = final_params.dict(exclude_none=True)
744
+ params_dict['url'] = url
745
+ params_dict['origin'] = f"python-sdk@{version}"
746
+
747
+ # Make request
748
+ headers = self._prepare_headers(idempotency_key)
749
+ response = self._post_request(f'{self.api_url}/v1/crawl', params_dict, headers)
750
+
751
+ if response.status_code == 200:
752
+ try:
753
+ id = response.json().get('id')
754
+ except:
755
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
756
+ return self._monitor_job_status(id, headers, poll_interval)
757
+ else:
758
+ self._handle_error(response, 'start crawl job')
759
+
760
+ def async_crawl_url(
761
+ self,
762
+ url: str,
763
+ *,
764
+ include_paths: Optional[List[str]] = None,
765
+ exclude_paths: Optional[List[str]] = None,
766
+ max_depth: Optional[int] = None,
767
+ max_discovery_depth: Optional[int] = None,
768
+ limit: Optional[int] = None,
769
+ allow_backward_links: Optional[bool] = None,
770
+ allow_external_links: Optional[bool] = None,
771
+ ignore_sitemap: Optional[bool] = None,
772
+ scrape_options: Optional[ScrapeOptions] = None,
773
+ webhook: Optional[Union[str, WebhookConfig]] = None,
774
+ deduplicate_similar_urls: Optional[bool] = None,
775
+ ignore_query_parameters: Optional[bool] = None,
776
+ regex_on_full_url: Optional[bool] = None,
777
+ idempotency_key: Optional[str] = None,
778
+ **kwargs
779
+ ) -> CrawlResponse:
780
+ """
781
+ Start an asynchronous crawl job.
782
+
783
+ Args:
784
+ url (str): Target URL to start crawling from
785
+ include_paths (Optional[List[str]]): Patterns of URLs to include
786
+ exclude_paths (Optional[List[str]]): Patterns of URLs to exclude
787
+ max_depth (Optional[int]): Maximum crawl depth
788
+ max_discovery_depth (Optional[int]): Maximum depth for finding new URLs
789
+ limit (Optional[int]): Maximum pages to crawl
790
+ allow_backward_links (Optional[bool]): Follow parent directory links
791
+ allow_external_links (Optional[bool]): Follow external domain links
792
+ ignore_sitemap (Optional[bool]): Skip sitemap.xml processing
793
+ scrape_options (Optional[ScrapeOptions]): Page scraping configuration
794
+ webhook (Optional[Union[str, WebhookConfig]]): Notification webhook settings
795
+ deduplicate_similar_urls (Optional[bool]): Remove similar URLs
796
+ ignore_query_parameters (Optional[bool]): Ignore URL parameters
797
+ regex_on_full_url (Optional[bool]): Apply regex to full URLs
798
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
799
+ **kwargs: Additional parameters to pass to the API
800
+
801
+ Returns:
802
+ CrawlResponse with:
803
+ * success - Whether crawl started successfully
804
+ * id - Unique identifier for the crawl job
805
+ * url - Status check URL for the crawl
806
+ * error - Error message if start failed
807
+
808
+ Raises:
809
+ Exception: If crawl initiation fails
810
+ """
811
+ crawl_params = {}
812
+
813
+ # Add individual parameters
814
+ if include_paths is not None:
815
+ crawl_params['includePaths'] = include_paths
816
+ if exclude_paths is not None:
817
+ crawl_params['excludePaths'] = exclude_paths
818
+ if max_depth is not None:
819
+ crawl_params['maxDepth'] = max_depth
820
+ if max_discovery_depth is not None:
821
+ crawl_params['maxDiscoveryDepth'] = max_discovery_depth
822
+ if limit is not None:
823
+ crawl_params['limit'] = limit
824
+ if allow_backward_links is not None:
825
+ crawl_params['allowBackwardLinks'] = allow_backward_links
826
+ if allow_external_links is not None:
827
+ crawl_params['allowExternalLinks'] = allow_external_links
828
+ if ignore_sitemap is not None:
829
+ crawl_params['ignoreSitemap'] = ignore_sitemap
830
+ if scrape_options is not None:
831
+ crawl_params['scrapeOptions'] = scrape_options.dict(exclude_none=True)
832
+ if webhook is not None:
833
+ crawl_params['webhook'] = webhook
834
+ if deduplicate_similar_urls is not None:
835
+ crawl_params['deduplicateSimilarURLs'] = deduplicate_similar_urls
836
+ if ignore_query_parameters is not None:
837
+ crawl_params['ignoreQueryParameters'] = ignore_query_parameters
838
+ if regex_on_full_url is not None:
839
+ crawl_params['regexOnFullURL'] = regex_on_full_url
840
+
841
+ # Add any additional kwargs
842
+ crawl_params.update(kwargs)
843
+
844
+ # Create final params object
845
+ final_params = CrawlParams(**crawl_params)
846
+ params_dict = final_params.dict(exclude_none=True)
847
+ params_dict['url'] = url
848
+ params_dict['origin'] = f"python-sdk@{version}"
849
+
850
+ # Make request
851
+ headers = self._prepare_headers(idempotency_key)
852
+ response = self._post_request(f'{self.api_url}/v1/crawl', params_dict, headers)
853
+
854
+ if response.status_code == 200:
855
+ try:
856
+ return CrawlResponse(**response.json())
857
+ except:
858
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
859
+ else:
860
+ self._handle_error(response, 'start crawl job')
861
+
862
+ def check_crawl_status(self, id: str) -> CrawlStatusResponse:
863
+ """
864
+ Check the status and results of a crawl job.
865
+
866
+ Args:
867
+ id: Unique identifier for the crawl job
868
+
869
+ Returns:
870
+ CrawlStatusResponse containing:
871
+
872
+ Status Information:
873
+ * status - Current state (scraping/completed/failed/cancelled)
874
+ * completed - Number of pages crawled
875
+ * total - Total pages to crawl
876
+ * creditsUsed - API credits consumed
877
+ * expiresAt - Data expiration timestamp
878
+
879
+ Results:
880
+ * data - List of crawled documents
881
+ * next - URL for next page of results (if paginated)
882
+ * success - Whether status check succeeded
883
+ * error - Error message if failed
884
+
885
+ Raises:
886
+ Exception: If status check fails
887
+ """
888
+ endpoint = f'/v1/crawl/{id}'
889
+
890
+ headers = self._prepare_headers()
891
+ response = self._get_request(f'{self.api_url}{endpoint}', headers)
892
+ if response.status_code == 200:
893
+ try:
894
+ status_data = response.json()
895
+ except:
896
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
897
+ if status_data['status'] == 'completed':
898
+ if 'data' in status_data:
899
+ data = status_data['data']
900
+ while 'next' in status_data:
901
+ if len(status_data['data']) == 0:
902
+ break
903
+ next_url = status_data.get('next')
904
+ if not next_url:
905
+ logger.warning("Expected 'next' URL is missing.")
906
+ break
907
+ try:
908
+ status_response = self._get_request(next_url, headers)
909
+ if status_response.status_code != 200:
910
+ logger.error(f"Failed to fetch next page: {status_response.status_code}")
911
+ break
912
+ try:
913
+ next_data = status_response.json()
914
+ except:
915
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
916
+ data.extend(next_data.get('data', []))
917
+ status_data = next_data
918
+ except Exception as e:
919
+ logger.error(f"Error during pagination request: {e}")
920
+ break
921
+ status_data['data'] = data
922
+
923
+ response = {
924
+ 'status': status_data.get('status'),
925
+ 'total': status_data.get('total'),
926
+ 'completed': status_data.get('completed'),
927
+ 'creditsUsed': status_data.get('creditsUsed'),
928
+ 'expiresAt': status_data.get('expiresAt'),
929
+ 'data': status_data.get('data')
930
+ }
931
+
932
+ if 'error' in status_data:
933
+ response['error'] = status_data['error']
934
+
935
+ if 'next' in status_data:
936
+ response['next'] = status_data['next']
937
+
938
+ return CrawlStatusResponse(
939
+ success=False if 'error' in status_data else True,
940
+ **response
941
+ )
942
+ else:
943
+ self._handle_error(response, 'check crawl status')
944
+
945
+ def check_crawl_errors(self, id: str) -> CrawlErrorsResponse:
946
+ """
947
+ Returns information about crawl errors.
948
+
949
+ Args:
950
+ id (str): The ID of the crawl job
951
+
952
+ Returns:
953
+ CrawlErrorsResponse containing:
954
+ * errors (List[Dict[str, str]]): List of errors with fields:
955
+ - id (str): Error ID
956
+ - timestamp (str): When the error occurred
957
+ - url (str): URL that caused the error
958
+ - error (str): Error message
959
+ * robotsBlocked (List[str]): List of URLs blocked by robots.txt
960
+
961
+ Raises:
962
+ Exception: If error check fails
963
+ """
964
+ headers = self._prepare_headers()
965
+ response = self._get_request(f'{self.api_url}/v1/crawl/{id}/errors', headers)
966
+ if response.status_code == 200:
967
+ try:
968
+ return CrawlErrorsResponse(**response.json())
969
+ except:
970
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
971
+ else:
972
+ self._handle_error(response, "check crawl errors")
973
+
974
+ def cancel_crawl(self, id: str) -> Dict[str, Any]:
975
+ """
976
+ Cancel an asynchronous crawl job.
977
+
978
+ Args:
979
+ id (str): The ID of the crawl job to cancel
980
+
981
+ Returns:
982
+ Dict[str, Any] containing:
983
+ * success (bool): Whether cancellation was successful
984
+ * error (str, optional): Error message if cancellation failed
985
+
986
+ Raises:
987
+ Exception: If cancellation fails
988
+ """
989
+ headers = self._prepare_headers()
990
+ response = self._delete_request(f'{self.api_url}/v1/crawl/{id}', headers)
991
+ if response.status_code == 200:
992
+ try:
993
+ return response.json()
994
+ except:
995
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
996
+ else:
997
+ self._handle_error(response, "cancel crawl job")
998
+
999
+ def crawl_url_and_watch(
1000
+ self,
1001
+ url: str,
1002
+ *,
1003
+ include_paths: Optional[List[str]] = None,
1004
+ exclude_paths: Optional[List[str]] = None,
1005
+ max_depth: Optional[int] = None,
1006
+ max_discovery_depth: Optional[int] = None,
1007
+ limit: Optional[int] = None,
1008
+ allow_backward_links: Optional[bool] = None,
1009
+ allow_external_links: Optional[bool] = None,
1010
+ ignore_sitemap: Optional[bool] = None,
1011
+ scrape_options: Optional[ScrapeOptions] = None,
1012
+ webhook: Optional[Union[str, WebhookConfig]] = None,
1013
+ deduplicate_similar_urls: Optional[bool] = None,
1014
+ ignore_query_parameters: Optional[bool] = None,
1015
+ regex_on_full_url: Optional[bool] = None,
1016
+ idempotency_key: Optional[str] = None,
1017
+ **kwargs
1018
+ ) -> 'CrawlWatcher':
1019
+ """
1020
+ Initiate a crawl job and return a CrawlWatcher to monitor the job via WebSocket.
1021
+
1022
+ Args:
1023
+ url (str): Target URL to start crawling from
1024
+ include_paths (Optional[List[str]]): Patterns of URLs to include
1025
+ exclude_paths (Optional[List[str]]): Patterns of URLs to exclude
1026
+ max_depth (Optional[int]): Maximum crawl depth
1027
+ max_discovery_depth (Optional[int]): Maximum depth for finding new URLs
1028
+ limit (Optional[int]): Maximum pages to crawl
1029
+ allow_backward_links (Optional[bool]): Follow parent directory links
1030
+ allow_external_links (Optional[bool]): Follow external domain links
1031
+ ignore_sitemap (Optional[bool]): Skip sitemap.xml processing
1032
+ scrape_options (Optional[ScrapeOptions]): Page scraping configuration
1033
+ webhook (Optional[Union[str, WebhookConfig]]): Notification webhook settings
1034
+ deduplicate_similar_urls (Optional[bool]): Remove similar URLs
1035
+ ignore_query_parameters (Optional[bool]): Ignore URL parameters
1036
+ regex_on_full_url (Optional[bool]): Apply regex to full URLs
1037
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
1038
+ **kwargs: Additional parameters to pass to the API
1039
+
1040
+ Returns:
1041
+ CrawlWatcher: An instance to monitor the crawl job via WebSocket
1042
+
1043
+ Raises:
1044
+ Exception: If crawl job fails to start
1045
+ """
1046
+ crawl_response = self.async_crawl_url(
1047
+ url,
1048
+ include_paths=include_paths,
1049
+ exclude_paths=exclude_paths,
1050
+ max_depth=max_depth,
1051
+ max_discovery_depth=max_discovery_depth,
1052
+ limit=limit,
1053
+ allow_backward_links=allow_backward_links,
1054
+ allow_external_links=allow_external_links,
1055
+ ignore_sitemap=ignore_sitemap,
1056
+ scrape_options=scrape_options,
1057
+ webhook=webhook,
1058
+ deduplicate_similar_urls=deduplicate_similar_urls,
1059
+ ignore_query_parameters=ignore_query_parameters,
1060
+ regex_on_full_url=regex_on_full_url,
1061
+ idempotency_key=idempotency_key,
1062
+ **kwargs
1063
+ )
1064
+ if crawl_response.success and crawl_response.id:
1065
+ return CrawlWatcher(crawl_response.id, self)
1066
+ else:
1067
+ raise Exception("Crawl job failed to start")
1068
+
1069
+ def map_url(
1070
+ self,
1071
+ url: str,
1072
+ *,
1073
+ search: Optional[str] = None,
1074
+ ignore_sitemap: Optional[bool] = None,
1075
+ include_subdomains: Optional[bool] = None,
1076
+ sitemap_only: Optional[bool] = None,
1077
+ limit: Optional[int] = None,
1078
+ timeout: Optional[int] = None,
1079
+ params: Optional[MapParams] = None) -> MapResponse:
1080
+ """
1081
+ Map and discover links from a URL.
1082
+
1083
+ Args:
1084
+ url (str): Target URL to map
1085
+ search (Optional[str]): Filter pattern for URLs
1086
+ ignore_sitemap (Optional[bool]): Skip sitemap.xml processing
1087
+ include_subdomains (Optional[bool]): Include subdomain links
1088
+ sitemap_only (Optional[bool]): Only use sitemap.xml
1089
+ limit (Optional[int]): Maximum URLs to return
1090
+ timeout (Optional[int]): Request timeout in milliseconds
1091
+ params (Optional[MapParams]): Additional mapping parameters
1092
+
1093
+ Returns:
1094
+ MapResponse: Response containing:
1095
+ * success (bool): Whether request succeeded
1096
+ * links (List[str]): Discovered URLs
1097
+ * error (Optional[str]): Error message if any
1098
+
1099
+ Raises:
1100
+ Exception: If mapping fails or response cannot be parsed
1101
+ """
1102
+ # Build map parameters
1103
+ map_params = {}
1104
+ if params:
1105
+ map_params.update(params.dict(exclude_none=True))
1106
+
1107
+ # Add individual parameters
1108
+ if search is not None:
1109
+ map_params['search'] = search
1110
+ if ignore_sitemap is not None:
1111
+ map_params['ignoreSitemap'] = ignore_sitemap
1112
+ if include_subdomains is not None:
1113
+ map_params['includeSubdomains'] = include_subdomains
1114
+ if sitemap_only is not None:
1115
+ map_params['sitemapOnly'] = sitemap_only
1116
+ if limit is not None:
1117
+ map_params['limit'] = limit
1118
+ if timeout is not None:
1119
+ map_params['timeout'] = timeout
1120
+
1121
+ # Create final params object
1122
+ final_params = MapParams(**map_params)
1123
+ params_dict = final_params.dict(exclude_none=True)
1124
+ params_dict['url'] = url
1125
+ params_dict['origin'] = f"python-sdk@{version}"
1126
+
1127
+ # Make request
1128
+ response = requests.post(
1129
+ f"{self.api_url}/v1/map",
1130
+ headers={"Authorization": f"Bearer {self.api_key}"},
1131
+ json=params_dict
1132
+ )
1133
+
1134
+ if response.status_code == 200:
1135
+ try:
1136
+ response_json = response.json()
1137
+ if response_json.get('success') and 'links' in response_json:
1138
+ return MapResponse(**response_json)
1139
+ elif "error" in response_json:
1140
+ raise Exception(f'Map failed. Error: {response_json["error"]}')
1141
+ else:
1142
+ raise Exception(f'Map failed. Error: {response_json}')
1143
+ except ValueError:
1144
+ raise Exception('Failed to parse Firecrawl response as JSON.')
1145
+ else:
1146
+ self._handle_error(response, 'map')
1147
+
1148
+ def batch_scrape_urls(
1149
+ self,
1150
+ urls: List[str],
1151
+ *,
1152
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]] = None,
1153
+ headers: Optional[Dict[str, str]] = None,
1154
+ include_tags: Optional[List[str]] = None,
1155
+ exclude_tags: Optional[List[str]] = None,
1156
+ only_main_content: Optional[bool] = None,
1157
+ wait_for: Optional[int] = None,
1158
+ timeout: Optional[int] = None,
1159
+ location: Optional[LocationConfig] = None,
1160
+ mobile: Optional[bool] = None,
1161
+ skip_tls_verification: Optional[bool] = None,
1162
+ remove_base64_images: Optional[bool] = None,
1163
+ block_ads: Optional[bool] = None,
1164
+ proxy: Optional[Literal["basic", "stealth"]] = None,
1165
+ extract: Optional[JsonConfig] = None,
1166
+ json_options: Optional[JsonConfig] = None,
1167
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None,
1168
+ agent: Optional[AgentOptions] = None,
1169
+ poll_interval: Optional[int] = 2,
1170
+ idempotency_key: Optional[str] = None,
1171
+ **kwargs
1172
+ ) -> BatchScrapeStatusResponse:
1173
+ """
1174
+ Batch scrape multiple URLs and monitor until completion.
1175
+
1176
+ Args:
1177
+ urls (List[str]): URLs to scrape
1178
+ formats (Optional[List[Literal]]): Content formats to retrieve
1179
+ headers (Optional[Dict[str, str]]): Custom HTTP headers
1180
+ include_tags (Optional[List[str]]): HTML tags to include
1181
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
1182
+ only_main_content (Optional[bool]): Extract main content only
1183
+ wait_for (Optional[int]): Wait time in milliseconds
1184
+ timeout (Optional[int]): Request timeout in milliseconds
1185
+ location (Optional[LocationConfig]): Location configuration
1186
+ mobile (Optional[bool]): Use mobile user agent
1187
+ skip_tls_verification (Optional[bool]): Skip TLS verification
1188
+ remove_base64_images (Optional[bool]): Remove base64 encoded images
1189
+ block_ads (Optional[bool]): Block advertisements
1190
+ proxy (Optional[Literal]): Proxy type to use
1191
+ extract (Optional[JsonConfig]): Content extraction config
1192
+ json_options (Optional[JsonConfig]): JSON extraction config
1193
+ actions (Optional[List[Union]]): Actions to perform
1194
+ agent (Optional[AgentOptions]): Agent configuration
1195
+ poll_interval (Optional[int]): Seconds between status checks (default: 2)
1196
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
1197
+ **kwargs: Additional parameters to pass to the API
1198
+
1199
+ Returns:
1200
+ BatchScrapeStatusResponse with:
1201
+ * Scraping status and progress
1202
+ * Scraped content for each URL
1203
+ * Success/error information
1204
+
1205
+ Raises:
1206
+ Exception: If batch scrape fails
1207
+ """
1208
+ scrape_params = {}
1209
+
1210
+ # Add individual parameters
1211
+ if formats is not None:
1212
+ scrape_params['formats'] = formats
1213
+ if headers is not None:
1214
+ scrape_params['headers'] = headers
1215
+ if include_tags is not None:
1216
+ scrape_params['includeTags'] = include_tags
1217
+ if exclude_tags is not None:
1218
+ scrape_params['excludeTags'] = exclude_tags
1219
+ if only_main_content is not None:
1220
+ scrape_params['onlyMainContent'] = only_main_content
1221
+ if wait_for is not None:
1222
+ scrape_params['waitFor'] = wait_for
1223
+ if timeout is not None:
1224
+ scrape_params['timeout'] = timeout
1225
+ if location is not None:
1226
+ scrape_params['location'] = location.dict(exclude_none=True)
1227
+ if mobile is not None:
1228
+ scrape_params['mobile'] = mobile
1229
+ if skip_tls_verification is not None:
1230
+ scrape_params['skipTlsVerification'] = skip_tls_verification
1231
+ if remove_base64_images is not None:
1232
+ scrape_params['removeBase64Images'] = remove_base64_images
1233
+ if block_ads is not None:
1234
+ scrape_params['blockAds'] = block_ads
1235
+ if proxy is not None:
1236
+ scrape_params['proxy'] = proxy
1237
+ if extract is not None:
1238
+ if hasattr(extract.schema, 'schema'):
1239
+ extract.schema = extract.schema.schema()
1240
+ scrape_params['extract'] = extract.dict(exclude_none=True)
1241
+ if json_options is not None:
1242
+ if hasattr(json_options.schema, 'schema'):
1243
+ json_options.schema = json_options.schema.schema()
1244
+ scrape_params['jsonOptions'] = json_options.dict(exclude_none=True)
1245
+ if actions is not None:
1246
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
1247
+ if agent is not None:
1248
+ scrape_params['agent'] = agent.dict(exclude_none=True)
1249
+
1250
+ # Add any additional kwargs
1251
+ scrape_params.update(kwargs)
1252
+
1253
+ # Create final params object
1254
+ final_params = ScrapeParams(**scrape_params)
1255
+ params_dict = final_params.dict(exclude_none=True)
1256
+ params_dict['urls'] = urls
1257
+ params_dict['origin'] = f"python-sdk@{version}"
1258
+
1259
+ # Make request
1260
+ headers = self._prepare_headers(idempotency_key)
1261
+ response = self._post_request(f'{self.api_url}/v1/batch/scrape', params_dict, headers)
1262
+
1263
+ if response.status_code == 200:
1264
+ try:
1265
+ id = response.json().get('id')
1266
+ except:
1267
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1268
+ return self._monitor_job_status(id, headers, poll_interval)
1269
+ else:
1270
+ self._handle_error(response, 'start batch scrape job')
1271
+
1272
+ def async_batch_scrape_urls(
1273
+ self,
1274
+ urls: List[str],
1275
+ *,
1276
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]] = None,
1277
+ headers: Optional[Dict[str, str]] = None,
1278
+ include_tags: Optional[List[str]] = None,
1279
+ exclude_tags: Optional[List[str]] = None,
1280
+ only_main_content: Optional[bool] = None,
1281
+ wait_for: Optional[int] = None,
1282
+ timeout: Optional[int] = None,
1283
+ location: Optional[LocationConfig] = None,
1284
+ mobile: Optional[bool] = None,
1285
+ skip_tls_verification: Optional[bool] = None,
1286
+ remove_base64_images: Optional[bool] = None,
1287
+ block_ads: Optional[bool] = None,
1288
+ proxy: Optional[Literal["basic", "stealth"]] = None,
1289
+ extract: Optional[JsonConfig] = None,
1290
+ json_options: Optional[JsonConfig] = None,
1291
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None,
1292
+ agent: Optional[AgentOptions] = None,
1293
+ idempotency_key: Optional[str] = None,
1294
+ **kwargs
1295
+ ) -> BatchScrapeResponse:
1296
+ """
1297
+ Initiate a batch scrape job asynchronously.
1298
+
1299
+ Args:
1300
+ urls (List[str]): URLs to scrape
1301
+ formats (Optional[List[Literal]]): Content formats to retrieve
1302
+ headers (Optional[Dict[str, str]]): Custom HTTP headers
1303
+ include_tags (Optional[List[str]]): HTML tags to include
1304
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
1305
+ only_main_content (Optional[bool]): Extract main content only
1306
+ wait_for (Optional[int]): Wait time in milliseconds
1307
+ timeout (Optional[int]): Request timeout in milliseconds
1308
+ location (Optional[LocationConfig]): Location configuration
1309
+ mobile (Optional[bool]): Use mobile user agent
1310
+ skip_tls_verification (Optional[bool]): Skip TLS verification
1311
+ remove_base64_images (Optional[bool]): Remove base64 encoded images
1312
+ block_ads (Optional[bool]): Block advertisements
1313
+ proxy (Optional[Literal]): Proxy type to use
1314
+ extract (Optional[JsonConfig]): Content extraction config
1315
+ json_options (Optional[JsonConfig]): JSON extraction config
1316
+ actions (Optional[List[Union]]): Actions to perform
1317
+ agent (Optional[AgentOptions]): Agent configuration
1318
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
1319
+ **kwargs: Additional parameters to pass to the API
1320
+
1321
+ Returns:
1322
+ BatchScrapeResponse with:
1323
+ * success - Whether job started successfully
1324
+ * id - Unique identifier for the job
1325
+ * url - Status check URL
1326
+ * error - Error message if start failed
1327
+
1328
+ Raises:
1329
+ Exception: If job initiation fails
1330
+ """
1331
+ scrape_params = {}
1332
+
1333
+ # Add individual parameters
1334
+ if formats is not None:
1335
+ scrape_params['formats'] = formats
1336
+ if headers is not None:
1337
+ scrape_params['headers'] = headers
1338
+ if include_tags is not None:
1339
+ scrape_params['includeTags'] = include_tags
1340
+ if exclude_tags is not None:
1341
+ scrape_params['excludeTags'] = exclude_tags
1342
+ if only_main_content is not None:
1343
+ scrape_params['onlyMainContent'] = only_main_content
1344
+ if wait_for is not None:
1345
+ scrape_params['waitFor'] = wait_for
1346
+ if timeout is not None:
1347
+ scrape_params['timeout'] = timeout
1348
+ if location is not None:
1349
+ scrape_params['location'] = location.dict(exclude_none=True)
1350
+ if mobile is not None:
1351
+ scrape_params['mobile'] = mobile
1352
+ if skip_tls_verification is not None:
1353
+ scrape_params['skipTlsVerification'] = skip_tls_verification
1354
+ if remove_base64_images is not None:
1355
+ scrape_params['removeBase64Images'] = remove_base64_images
1356
+ if block_ads is not None:
1357
+ scrape_params['blockAds'] = block_ads
1358
+ if proxy is not None:
1359
+ scrape_params['proxy'] = proxy
1360
+ if extract is not None:
1361
+ if hasattr(extract.schema, 'schema'):
1362
+ extract.schema = extract.schema.schema()
1363
+ scrape_params['extract'] = extract.dict(exclude_none=True)
1364
+ if json_options is not None:
1365
+ if hasattr(json_options.schema, 'schema'):
1366
+ json_options.schema = json_options.schema.schema()
1367
+ scrape_params['jsonOptions'] = json_options.dict(exclude_none=True)
1368
+ if actions is not None:
1369
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
1370
+ if agent is not None:
1371
+ scrape_params['agent'] = agent.dict(exclude_none=True)
1372
+
1373
+ # Add any additional kwargs
1374
+ scrape_params.update(kwargs)
1375
+
1376
+ # Create final params object
1377
+ final_params = ScrapeParams(**scrape_params)
1378
+ params_dict = final_params.dict(exclude_none=True)
1379
+ params_dict['urls'] = urls
1380
+ params_dict['origin'] = f"python-sdk@{version}"
1381
+
1382
+ # Make request
1383
+ headers = self._prepare_headers(idempotency_key)
1384
+ response = self._post_request(f'{self.api_url}/v1/batch/scrape', params_dict, headers)
1385
+
1386
+ if response.status_code == 200:
1387
+ try:
1388
+ return BatchScrapeResponse(**response.json())
1389
+ except:
1390
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1391
+ else:
1392
+ self._handle_error(response, 'start batch scrape job')
1393
+
1394
+ def batch_scrape_urls_and_watch(
1395
+ self,
1396
+ urls: List[str],
1397
+ *,
1398
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]] = None,
1399
+ headers: Optional[Dict[str, str]] = None,
1400
+ include_tags: Optional[List[str]] = None,
1401
+ exclude_tags: Optional[List[str]] = None,
1402
+ only_main_content: Optional[bool] = None,
1403
+ wait_for: Optional[int] = None,
1404
+ timeout: Optional[int] = None,
1405
+ location: Optional[LocationConfig] = None,
1406
+ mobile: Optional[bool] = None,
1407
+ skip_tls_verification: Optional[bool] = None,
1408
+ remove_base64_images: Optional[bool] = None,
1409
+ block_ads: Optional[bool] = None,
1410
+ proxy: Optional[Literal["basic", "stealth"]] = None,
1411
+ extract: Optional[JsonConfig] = None,
1412
+ json_options: Optional[JsonConfig] = None,
1413
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None,
1414
+ agent: Optional[AgentOptions] = None,
1415
+ idempotency_key: Optional[str] = None,
1416
+ **kwargs
1417
+ ) -> 'CrawlWatcher':
1418
+ """
1419
+ Initiate a batch scrape job and return a CrawlWatcher to monitor the job via WebSocket.
1420
+
1421
+ Args:
1422
+ urls (List[str]): URLs to scrape
1423
+ formats (Optional[List[Literal]]): Content formats to retrieve
1424
+ headers (Optional[Dict[str, str]]): Custom HTTP headers
1425
+ include_tags (Optional[List[str]]): HTML tags to include
1426
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
1427
+ only_main_content (Optional[bool]): Extract main content only
1428
+ wait_for (Optional[int]): Wait time in milliseconds
1429
+ timeout (Optional[int]): Request timeout in milliseconds
1430
+ location (Optional[LocationConfig]): Location configuration
1431
+ mobile (Optional[bool]): Use mobile user agent
1432
+ skip_tls_verification (Optional[bool]): Skip TLS verification
1433
+ remove_base64_images (Optional[bool]): Remove base64 encoded images
1434
+ block_ads (Optional[bool]): Block advertisements
1435
+ proxy (Optional[Literal]): Proxy type to use
1436
+ extract (Optional[JsonConfig]): Content extraction config
1437
+ json_options (Optional[JsonConfig]): JSON extraction config
1438
+ actions (Optional[List[Union]]): Actions to perform
1439
+ agent (Optional[AgentOptions]): Agent configuration
1440
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
1441
+ **kwargs: Additional parameters to pass to the API
1442
+
1443
+ Returns:
1444
+ CrawlWatcher: An instance to monitor the batch scrape job via WebSocket
1445
+
1446
+ Raises:
1447
+ Exception: If batch scrape job fails to start
1448
+ """
1449
+ scrape_params = {}
1450
+
1451
+ # Add individual parameters
1452
+ if formats is not None:
1453
+ scrape_params['formats'] = formats
1454
+ if headers is not None:
1455
+ scrape_params['headers'] = headers
1456
+ if include_tags is not None:
1457
+ scrape_params['includeTags'] = include_tags
1458
+ if exclude_tags is not None:
1459
+ scrape_params['excludeTags'] = exclude_tags
1460
+ if only_main_content is not None:
1461
+ scrape_params['onlyMainContent'] = only_main_content
1462
+ if wait_for is not None:
1463
+ scrape_params['waitFor'] = wait_for
1464
+ if timeout is not None:
1465
+ scrape_params['timeout'] = timeout
1466
+ if location is not None:
1467
+ scrape_params['location'] = location.dict(exclude_none=True)
1468
+ if mobile is not None:
1469
+ scrape_params['mobile'] = mobile
1470
+ if skip_tls_verification is not None:
1471
+ scrape_params['skipTlsVerification'] = skip_tls_verification
1472
+ if remove_base64_images is not None:
1473
+ scrape_params['removeBase64Images'] = remove_base64_images
1474
+ if block_ads is not None:
1475
+ scrape_params['blockAds'] = block_ads
1476
+ if proxy is not None:
1477
+ scrape_params['proxy'] = proxy
1478
+ if extract is not None:
1479
+ if hasattr(extract.schema, 'schema'):
1480
+ extract.schema = extract.schema.schema()
1481
+ scrape_params['extract'] = extract.dict(exclude_none=True)
1482
+ if json_options is not None:
1483
+ if hasattr(json_options.schema, 'schema'):
1484
+ json_options.schema = json_options.schema.schema()
1485
+ scrape_params['jsonOptions'] = json_options.dict(exclude_none=True)
1486
+ if actions is not None:
1487
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
1488
+ if agent is not None:
1489
+ scrape_params['agent'] = agent.dict(exclude_none=True)
1490
+
1491
+ # Add any additional kwargs
1492
+ scrape_params.update(kwargs)
1493
+
1494
+ # Create final params object
1495
+ final_params = ScrapeParams(**scrape_params)
1496
+ params_dict = final_params.dict(exclude_none=True)
1497
+ params_dict['urls'] = urls
1498
+ params_dict['origin'] = f"python-sdk@{version}"
1499
+
1500
+ # Make request
1501
+ headers = self._prepare_headers(idempotency_key)
1502
+ response = self._post_request(f'{self.api_url}/v1/batch/scrape', params_dict, headers)
1503
+
1504
+ if response.status_code == 200:
1505
+ try:
1506
+ crawl_response = BatchScrapeResponse(**response.json())
1507
+ if crawl_response.success and crawl_response.id:
1508
+ return CrawlWatcher(crawl_response.id, self)
1509
+ else:
1510
+ raise Exception("Batch scrape job failed to start")
1511
+ except:
1512
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1513
+ else:
1514
+ self._handle_error(response, 'start batch scrape job')
1515
+
1516
+ def check_batch_scrape_status(self, id: str) -> BatchScrapeStatusResponse:
1517
+ """
1518
+ Check the status of a batch scrape job using the Firecrawl API.
1519
+
1520
+ Args:
1521
+ id (str): The ID of the batch scrape job.
1522
+
1523
+ Returns:
1524
+ BatchScrapeStatusResponse: The status of the batch scrape job.
1525
+
1526
+ Raises:
1527
+ Exception: If the status check request fails.
1528
+ """
1529
+ endpoint = f'/v1/batch/scrape/{id}'
1530
+
1531
+ headers = self._prepare_headers()
1532
+ response = self._get_request(f'{self.api_url}{endpoint}', headers)
1533
+ if response.status_code == 200:
1534
+ try:
1535
+ status_data = response.json()
1536
+ except:
1537
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1538
+ if status_data['status'] == 'completed':
1539
+ if 'data' in status_data:
1540
+ data = status_data['data']
1541
+ while 'next' in status_data:
1542
+ if len(status_data['data']) == 0:
1543
+ break
1544
+ next_url = status_data.get('next')
1545
+ if not next_url:
1546
+ logger.warning("Expected 'next' URL is missing.")
1547
+ break
1548
+ try:
1549
+ status_response = self._get_request(next_url, headers)
1550
+ if status_response.status_code != 200:
1551
+ logger.error(f"Failed to fetch next page: {status_response.status_code}")
1552
+ break
1553
+ try:
1554
+ next_data = status_response.json()
1555
+ except:
1556
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1557
+ data.extend(next_data.get('data', []))
1558
+ status_data = next_data
1559
+ except Exception as e:
1560
+ logger.error(f"Error during pagination request: {e}")
1561
+ break
1562
+ status_data['data'] = data
1563
+
1564
+ return BatchScrapeStatusResponse(**{
1565
+ 'success': False if 'error' in status_data else True,
1566
+ 'status': status_data.get('status'),
1567
+ 'total': status_data.get('total'),
1568
+ 'completed': status_data.get('completed'),
1569
+ 'creditsUsed': status_data.get('creditsUsed'),
1570
+ 'expiresAt': status_data.get('expiresAt'),
1571
+ 'data': status_data.get('data'),
1572
+ 'next': status_data.get('next'),
1573
+ 'error': status_data.get('error')
1574
+ })
1575
+ else:
1576
+ self._handle_error(response, 'check batch scrape status')
1577
+
1578
+ def check_batch_scrape_errors(self, id: str) -> CrawlErrorsResponse:
1579
+ """
1580
+ Returns information about batch scrape errors.
1581
+
1582
+ Args:
1583
+ id (str): The ID of the crawl job.
1584
+
1585
+ Returns:
1586
+ CrawlErrorsResponse: A response containing:
1587
+ * errors (List[Dict[str, str]]): List of errors with fields:
1588
+ * id (str): Error ID
1589
+ * timestamp (str): When the error occurred
1590
+ * url (str): URL that caused the error
1591
+ * error (str): Error message
1592
+ * robotsBlocked (List[str]): List of URLs blocked by robots.txt
1593
+
1594
+ Raises:
1595
+ Exception: If the error check request fails
1596
+ """
1597
+ headers = self._prepare_headers()
1598
+ response = self._get_request(f'{self.api_url}/v1/batch/scrape/{id}/errors', headers)
1599
+ if response.status_code == 200:
1600
+ try:
1601
+ return CrawlErrorsResponse(**response.json())
1602
+ except:
1603
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1604
+ else:
1605
+ self._handle_error(response, "check batch scrape errors")
1606
+
1607
+ def extract(
1608
+ self,
1609
+ urls: Optional[List[str]] = None,
1610
+ *,
1611
+ prompt: Optional[str] = None,
1612
+ schema: Optional[Any] = None,
1613
+ system_prompt: Optional[str] = None,
1614
+ allow_external_links: Optional[bool] = False,
1615
+ enable_web_search: Optional[bool] = False,
1616
+ show_sources: Optional[bool] = False,
1617
+ agent: Optional[Dict[str, Any]] = None) -> ExtractResponse[Any]:
1618
+ """
1619
+ Extract structured information from URLs.
1620
+
1621
+ Args:
1622
+ urls (Optional[List[str]]): URLs to extract from
1623
+ prompt (Optional[str]): Custom extraction prompt
1624
+ schema (Optional[Any]): JSON schema/Pydantic model
1625
+ system_prompt (Optional[str]): System context
1626
+ allow_external_links (Optional[bool]): Follow external links
1627
+ enable_web_search (Optional[bool]): Enable web search
1628
+ show_sources (Optional[bool]): Include source URLs
1629
+ agent (Optional[Dict[str, Any]]): Agent configuration
1630
+
1631
+ Returns:
1632
+ ExtractResponse[Any] with:
1633
+ * success (bool): Whether request succeeded
1634
+ * data (Optional[Any]): Extracted data matching schema
1635
+ * error (Optional[str]): Error message if any
1636
+
1637
+ Raises:
1638
+ ValueError: If prompt/schema missing or extraction fails
1639
+ """
1640
+ headers = self._prepare_headers()
1641
+
1642
+ if not prompt and not schema:
1643
+ raise ValueError("Either prompt or schema is required")
1644
+
1645
+ if not urls and not prompt:
1646
+ raise ValueError("Either urls or prompt is required")
1647
+
1648
+ if schema:
1649
+ if hasattr(schema, 'model_json_schema'):
1650
+ # Convert Pydantic model to JSON schema
1651
+ schema = schema.model_json_schema()
1652
+ # Otherwise assume it's already a JSON schema dict
1653
+
1654
+ request_data = {
1655
+ 'urls': urls or [],
1656
+ 'allowExternalLinks': allow_external_links,
1657
+ 'enableWebSearch': enable_web_search,
1658
+ 'showSources': show_sources,
1659
+ 'schema': schema,
1660
+ 'origin': f'python-sdk@{get_version()}'
1661
+ }
1662
+
1663
+ # Only add prompt and systemPrompt if they exist
1664
+ if prompt:
1665
+ request_data['prompt'] = prompt
1666
+ if system_prompt:
1667
+ request_data['systemPrompt'] = system_prompt
1668
+
1669
+ if agent:
1670
+ request_data['agent'] = agent
1671
+
1672
+ try:
1673
+ # Send the initial extract request
1674
+ response = self._post_request(
1675
+ f'{self.api_url}/v1/extract',
1676
+ request_data,
1677
+ headers
1678
+ )
1679
+ if response.status_code == 200:
1680
+ try:
1681
+ data = response.json()
1682
+ except:
1683
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1684
+ if data['success']:
1685
+ job_id = data.get('id')
1686
+ if not job_id:
1687
+ raise Exception('Job ID not returned from extract request.')
1688
+
1689
+ # Poll for the extract status
1690
+ while True:
1691
+ status_response = self._get_request(
1692
+ f'{self.api_url}/v1/extract/{job_id}',
1693
+ headers
1694
+ )
1695
+ if status_response.status_code == 200:
1696
+ try:
1697
+ status_data = status_response.json()
1698
+ except:
1699
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1700
+ if status_data['status'] == 'completed':
1701
+ return ExtractResponse(**status_data)
1702
+ elif status_data['status'] in ['failed', 'cancelled']:
1703
+ raise Exception(f'Extract job {status_data["status"]}. Error: {status_data["error"]}')
1704
+ else:
1705
+ self._handle_error(status_response, "extract-status")
1706
+
1707
+ time.sleep(2) # Polling interval
1708
+ else:
1709
+ raise Exception(f'Failed to extract. Error: {data["error"]}')
1710
+ else:
1711
+ self._handle_error(response, "extract")
1712
+ except Exception as e:
1713
+ raise ValueError(str(e), 500)
1714
+
1715
+ return ExtractResponse(success=False, error="Internal server error.")
1716
+
1717
+ def get_extract_status(self, job_id: str) -> ExtractResponse[Any]:
1718
+ """
1719
+ Retrieve the status of an extract job.
1720
+
1721
+ Args:
1722
+ job_id (str): The ID of the extract job.
1723
+
1724
+ Returns:
1725
+ ExtractResponse[Any]: The status of the extract job.
1726
+
1727
+ Raises:
1728
+ ValueError: If there is an error retrieving the status.
1729
+ """
1730
+ headers = self._prepare_headers()
1731
+ try:
1732
+ response = self._get_request(f'{self.api_url}/v1/extract/{job_id}', headers)
1733
+ if response.status_code == 200:
1734
+ try:
1735
+ return ExtractResponse(**response.json())
1736
+ except:
1737
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1738
+ else:
1739
+ self._handle_error(response, "get extract status")
1740
+ except Exception as e:
1741
+ raise ValueError(str(e), 500)
1742
+
1743
+ def async_extract(
1744
+ self,
1745
+ urls: Optional[List[str]] = None,
1746
+ *,
1747
+ prompt: Optional[str] = None,
1748
+ schema: Optional[Any] = None,
1749
+ system_prompt: Optional[str] = None,
1750
+ allow_external_links: Optional[bool] = False,
1751
+ enable_web_search: Optional[bool] = False,
1752
+ show_sources: Optional[bool] = False,
1753
+ agent: Optional[Dict[str, Any]] = None) -> ExtractResponse[Any]:
1754
+ """
1755
+ Initiate an asynchronous extract job.
1756
+
1757
+ Args:
1758
+ urls (List[str]): URLs to extract information from
1759
+ prompt (Optional[str]): Custom extraction prompt
1760
+ schema (Optional[Any]): JSON schema/Pydantic model
1761
+ system_prompt (Optional[str]): System context
1762
+ allow_external_links (Optional[bool]): Follow external links
1763
+ enable_web_search (Optional[bool]): Enable web search
1764
+ show_sources (Optional[bool]): Include source URLs
1765
+ agent (Optional[Dict[str, Any]]): Agent configuration
1766
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
1767
+
1768
+ Returns:
1769
+ ExtractResponse[Any] with:
1770
+ * success (bool): Whether request succeeded
1771
+ * data (Optional[Any]): Extracted data matching schema
1772
+ * error (Optional[str]): Error message if any
1773
+
1774
+ Raises:
1775
+ ValueError: If job initiation fails
1776
+ """
1777
+ headers = self._prepare_headers()
1778
+
1779
+ schema = schema
1780
+ if schema:
1781
+ if hasattr(schema, 'model_json_schema'):
1782
+ # Convert Pydantic model to JSON schema
1783
+ schema = schema.model_json_schema()
1784
+ # Otherwise assume it's already a JSON schema dict
1785
+
1786
+ request_data = {
1787
+ 'urls': urls,
1788
+ 'allowExternalLinks': allow_external_links,
1789
+ 'enableWebSearch': enable_web_search,
1790
+ 'showSources': show_sources,
1791
+ 'schema': schema,
1792
+ 'origin': f'python-sdk@{version}'
1793
+ }
1794
+
1795
+ if prompt:
1796
+ request_data['prompt'] = prompt
1797
+ if system_prompt:
1798
+ request_data['systemPrompt'] = system_prompt
1799
+ if agent:
1800
+ request_data['agent'] = agent
1801
+
1802
+ try:
1803
+ response = self._post_request(f'{self.api_url}/v1/extract', request_data, headers)
1804
+ if response.status_code == 200:
1805
+ try:
1806
+ return ExtractResponse(**response.json())
1807
+ except:
1808
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
1809
+ else:
1810
+ self._handle_error(response, "async extract")
1811
+ except Exception as e:
1812
+ raise ValueError(str(e), 500)
1813
+
1814
+ def generate_llms_text(
1815
+ self,
1816
+ url: str,
1817
+ *,
1818
+ max_urls: Optional[int] = None,
1819
+ show_full_text: Optional[bool] = None,
1820
+ experimental_stream: Optional[bool] = None) -> GenerateLLMsTextStatusResponse:
1821
+ """
1822
+ Generate LLMs.txt for a given URL and poll until completion.
1823
+
1824
+ Args:
1825
+ url (str): Target URL to generate LLMs.txt from
1826
+ max_urls (Optional[int]): Maximum URLs to process (default: 10)
1827
+ show_full_text (Optional[bool]): Include full text in output (default: False)
1828
+ experimental_stream (Optional[bool]): Enable experimental streaming
1829
+
1830
+ Returns:
1831
+ GenerateLLMsTextStatusResponse with:
1832
+ * Generated LLMs.txt content
1833
+ * Full version if requested
1834
+ * Generation status
1835
+ * Success/error information
1836
+
1837
+ Raises:
1838
+ Exception: If generation fails
1839
+ """
1840
+ params = GenerateLLMsTextParams(
1841
+ maxUrls=max_urls,
1842
+ showFullText=show_full_text,
1843
+ __experimental_stream=experimental_stream
1844
+ )
1845
+
1846
+ response = self.async_generate_llms_text(
1847
+ url,
1848
+ max_urls=max_urls,
1849
+ show_full_text=show_full_text,
1850
+ experimental_stream=experimental_stream
1851
+ )
1852
+ if not response.get('success') or 'id' not in response:
1853
+ return response
1854
+
1855
+ job_id = response['id']
1856
+ while True:
1857
+ status = self.check_generate_llms_text_status(job_id)
1858
+
1859
+ if status['status'] == 'completed':
1860
+ return status
1861
+ elif status['status'] == 'failed':
1862
+ raise Exception(f'LLMs.txt generation failed. Error: {status.get("error")}')
1863
+ elif status['status'] != 'processing':
1864
+ break
1865
+
1866
+ time.sleep(2) # Polling interval
1867
+
1868
+ return {'success': False, 'error': 'LLMs.txt generation job terminated unexpectedly'}
1869
+
1870
+ def async_generate_llms_text(
1871
+ self,
1872
+ url: str,
1873
+ *,
1874
+ max_urls: Optional[int] = None,
1875
+ show_full_text: Optional[bool] = None,
1876
+ experimental_stream: Optional[bool] = None) -> GenerateLLMsTextResponse:
1877
+ """
1878
+ Initiate an asynchronous LLMs.txt generation operation.
1879
+
1880
+ Args:
1881
+ url (str): The target URL to generate LLMs.txt from. Must be a valid HTTP/HTTPS URL.
1882
+ max_urls (Optional[int]): Maximum URLs to process (default: 10)
1883
+ show_full_text (Optional[bool]): Include full text in output (default: False)
1884
+ experimental_stream (Optional[bool]): Enable experimental streaming
1885
+
1886
+ Returns:
1887
+ GenerateLLMsTextResponse: A response containing:
1888
+ * success (bool): Whether the generation initiation was successful
1889
+ * id (str): The unique identifier for the generation job
1890
+ * error (str, optional): Error message if initiation failed
1891
+
1892
+ Raises:
1893
+ Exception: If the generation job initiation fails.
1894
+ """
1895
+ params = GenerateLLMsTextParams(
1896
+ maxUrls=max_urls,
1897
+ showFullText=show_full_text,
1898
+ __experimental_stream=experimental_stream
1899
+ )
1900
+
1901
+ headers = self._prepare_headers()
1902
+ json_data = {'url': url, **params.dict(exclude_none=True)}
1903
+ json_data['origin'] = f"python-sdk@{version}"
1904
+
1905
+ try:
1906
+ response = self._post_request(f'{self.api_url}/v1/llmstxt', json_data, headers)
1907
+ if response.status_code == 200:
1908
+ try:
1909
+ return response.json()
1910
+ except:
1911
+ raise Exception('Failed to parse Firecrawl response as JSON.')
1912
+ else:
1913
+ self._handle_error(response, 'start LLMs.txt generation')
1914
+ except Exception as e:
1915
+ raise ValueError(str(e))
1916
+
1917
+ return {'success': False, 'error': 'Internal server error'}
1918
+
1919
+ def check_generate_llms_text_status(self, id: str) -> GenerateLLMsTextStatusResponse:
1920
+ """
1921
+ Check the status of a LLMs.txt generation operation.
1922
+
1923
+ Args:
1924
+ id (str): The unique identifier of the LLMs.txt generation job to check status for.
1925
+
1926
+ Returns:
1927
+ GenerateLLMsTextStatusResponse: A response containing:
1928
+ * success (bool): Whether the generation was successful
1929
+ * status (str): Status of generation ("processing", "completed", "failed")
1930
+ * data (Dict[str, str], optional): Generated text with fields:
1931
+ * llmstxt (str): Generated LLMs.txt content
1932
+ * llmsfulltxt (str, optional): Full version if requested
1933
+ * error (str, optional): Error message if generation failed
1934
+ * expiresAt (str): When the generated data expires
1935
+
1936
+ Raises:
1937
+ Exception: If the status check fails.
1938
+ """
1939
+ headers = self._prepare_headers()
1940
+ try:
1941
+ response = self._get_request(f'{self.api_url}/v1/llmstxt/{id}', headers)
1942
+ if response.status_code == 200:
1943
+ try:
1944
+ return response.json()
1945
+ except:
1946
+ raise Exception('Failed to parse Firecrawl response as JSON.')
1947
+ elif response.status_code == 404:
1948
+ raise Exception('LLMs.txt generation job not found')
1949
+ else:
1950
+ self._handle_error(response, 'check LLMs.txt generation status')
1951
+ except Exception as e:
1952
+ raise ValueError(str(e))
1953
+
1954
+ return {'success': False, 'error': 'Internal server error'}
1955
+
1956
+ def _prepare_headers(
1957
+ self,
1958
+ idempotency_key: Optional[str] = None) -> Dict[str, str]:
1959
+ """
1960
+ Prepare the headers for API requests.
1961
+
1962
+ Args:
1963
+ idempotency_key (Optional[str]): A unique key to ensure idempotency of requests.
1964
+
1965
+ Returns:
1966
+ Dict[str, str]: The headers including content type, authorization, and optionally idempotency key.
1967
+ """
1968
+ if idempotency_key:
1969
+ return {
1970
+ 'Content-Type': 'application/json',
1971
+ 'Authorization': f'Bearer {self.api_key}',
1972
+ 'x-idempotency-key': idempotency_key
1973
+ }
1974
+
1975
+ return {
1976
+ 'Content-Type': 'application/json',
1977
+ 'Authorization': f'Bearer {self.api_key}',
1978
+ }
1979
+
1980
+ def _post_request(
1981
+ self,
1982
+ url: str,
1983
+ data: Dict[str, Any],
1984
+ headers: Dict[str, str],
1985
+ retries: int = 3,
1986
+ backoff_factor: float = 0.5) -> requests.Response:
1987
+ """
1988
+ Make a POST request with retries.
1989
+
1990
+ Args:
1991
+ url (str): The URL to send the POST request to.
1992
+ data (Dict[str, Any]): The JSON data to include in the POST request.
1993
+ headers (Dict[str, str]): The headers to include in the POST request.
1994
+ retries (int): Number of retries for the request.
1995
+ backoff_factor (float): Backoff factor for retries.
1996
+
1997
+ Returns:
1998
+ requests.Response: The response from the POST request.
1999
+
2000
+ Raises:
2001
+ requests.RequestException: If the request fails after the specified retries.
2002
+ """
2003
+ for attempt in range(retries):
2004
+ response = requests.post(url, headers=headers, json=data, timeout=((data["timeout"] + 5000) if "timeout" in data else None))
2005
+ if response.status_code == 502:
2006
+ time.sleep(backoff_factor * (2 ** attempt))
2007
+ else:
2008
+ return response
2009
+ return response
2010
+
2011
+ def _get_request(
2012
+ self,
2013
+ url: str,
2014
+ headers: Dict[str, str],
2015
+ retries: int = 3,
2016
+ backoff_factor: float = 0.5) -> requests.Response:
2017
+ """
2018
+ Make a GET request with retries.
2019
+
2020
+ Args:
2021
+ url (str): The URL to send the GET request to.
2022
+ headers (Dict[str, str]): The headers to include in the GET request.
2023
+ retries (int): Number of retries for the request.
2024
+ backoff_factor (float): Backoff factor for retries.
2025
+
2026
+ Returns:
2027
+ requests.Response: The response from the GET request.
2028
+
2029
+ Raises:
2030
+ requests.RequestException: If the request fails after the specified retries.
2031
+ """
2032
+ for attempt in range(retries):
2033
+ response = requests.get(url, headers=headers)
2034
+ if response.status_code == 502:
2035
+ time.sleep(backoff_factor * (2 ** attempt))
2036
+ else:
2037
+ return response
2038
+ return response
2039
+
2040
+ def _delete_request(
2041
+ self,
2042
+ url: str,
2043
+ headers: Dict[str, str],
2044
+ retries: int = 3,
2045
+ backoff_factor: float = 0.5) -> requests.Response:
2046
+ """
2047
+ Make a DELETE request with retries.
2048
+
2049
+ Args:
2050
+ url (str): The URL to send the DELETE request to.
2051
+ headers (Dict[str, str]): The headers to include in the DELETE request.
2052
+ retries (int): Number of retries for the request.
2053
+ backoff_factor (float): Backoff factor for retries.
2054
+
2055
+ Returns:
2056
+ requests.Response: The response from the DELETE request.
2057
+
2058
+ Raises:
2059
+ requests.RequestException: If the request fails after the specified retries.
2060
+ """
2061
+ for attempt in range(retries):
2062
+ response = requests.delete(url, headers=headers)
2063
+ if response.status_code == 502:
2064
+ time.sleep(backoff_factor * (2 ** attempt))
2065
+ else:
2066
+ return response
2067
+ return response
2068
+
2069
+ def _monitor_job_status(
2070
+ self,
2071
+ id: str,
2072
+ headers: Dict[str, str],
2073
+ poll_interval: int) -> CrawlStatusResponse:
2074
+ """
2075
+ Monitor the status of a crawl job until completion.
2076
+
2077
+ Args:
2078
+ id (str): The ID of the crawl job.
2079
+ headers (Dict[str, str]): The headers to include in the status check requests.
2080
+ poll_interval (int): Seconds between status checks.
2081
+
2082
+ Returns:
2083
+ CrawlStatusResponse: The crawl results if the job is completed successfully.
2084
+
2085
+ Raises:
2086
+ Exception: If the job fails or an error occurs during status checks.
2087
+ """
2088
+ while True:
2089
+ api_url = f'{self.api_url}/v1/crawl/{id}'
2090
+
2091
+ status_response = self._get_request(api_url, headers)
2092
+ if status_response.status_code == 200:
2093
+ try:
2094
+ status_data = status_response.json()
2095
+ except:
2096
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
2097
+ if status_data['status'] == 'completed':
2098
+ if 'data' in status_data:
2099
+ data = status_data['data']
2100
+ while 'next' in status_data:
2101
+ if len(status_data['data']) == 0:
2102
+ break
2103
+ status_response = self._get_request(status_data['next'], headers)
2104
+ try:
2105
+ status_data = status_response.json()
2106
+ except:
2107
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
2108
+ data.extend(status_data.get('data', []))
2109
+ status_data['data'] = data
2110
+ return CrawlStatusResponse(**status_data)
2111
+ else:
2112
+ raise Exception('Crawl job completed but no data was returned')
2113
+ elif status_data['status'] in ['active', 'paused', 'pending', 'queued', 'waiting', 'scraping']:
2114
+ poll_interval=max(poll_interval,2)
2115
+ time.sleep(poll_interval) # Wait for the specified interval before checking again
2116
+ else:
2117
+ raise Exception(f'Crawl job failed or was stopped. Status: {status_data["status"]}')
2118
+ else:
2119
+ self._handle_error(status_response, 'check crawl status')
2120
+
2121
+ def _handle_error(
2122
+ self,
2123
+ response: requests.Response,
2124
+ action: str) -> None:
2125
+ """
2126
+ Handle errors from API responses.
2127
+
2128
+ Args:
2129
+ response (requests.Response): The response object from the API request.
2130
+ action (str): Description of the action that was being performed.
2131
+
2132
+ Raises:
2133
+ Exception: An exception with a message containing the status code and error details from the response.
2134
+ """
2135
+ try:
2136
+ error_message = response.json().get('error', 'No error message provided.')
2137
+ error_details = response.json().get('details', 'No additional error details provided.')
2138
+ except:
2139
+ raise requests.exceptions.HTTPError(f'Failed to parse Firecrawl error response as JSON. Status code: {response.status_code}', response=response)
2140
+
2141
+ message = self._get_error_message(response.status_code, action, error_message, error_details)
2142
+
2143
+ # Raise an HTTPError with the custom message and attach the response
2144
+ raise requests.exceptions.HTTPError(message, response=response)
2145
+
2146
+ def _get_error_message(self, status_code: int, action: str, error_message: str, error_details: str) -> str:
2147
+ """
2148
+ Generate a standardized error message based on HTTP status code.
2149
+
2150
+ Args:
2151
+ status_code (int): The HTTP status code from the response
2152
+ action (str): Description of the action that was being performed
2153
+ error_message (str): The error message from the API response
2154
+ error_details (str): Additional error details from the API response
2155
+
2156
+ Returns:
2157
+ str: A formatted error message
2158
+ """
2159
+ if status_code == 402:
2160
+ return f"Payment Required: Failed to {action}. {error_message} - {error_details}"
2161
+ elif status_code == 403:
2162
+ message = f"Website Not Supported: Failed to {action}. {error_message} - {error_details}"
2163
+ elif status_code == 408:
2164
+ return f"Request Timeout: Failed to {action} as the request timed out. {error_message} - {error_details}"
2165
+ elif status_code == 409:
2166
+ return f"Conflict: Failed to {action} due to a conflict. {error_message} - {error_details}"
2167
+ elif status_code == 500:
2168
+ return f"Internal Server Error: Failed to {action}. {error_message} - {error_details}"
2169
+ else:
2170
+ return f"Unexpected error during {action}: Status code {status_code}. {error_message} - {error_details}"
2171
+
2172
+ def deep_research(
2173
+ self,
2174
+ query: str,
2175
+ *,
2176
+ max_depth: Optional[int] = None,
2177
+ time_limit: Optional[int] = None,
2178
+ max_urls: Optional[int] = None,
2179
+ analysis_prompt: Optional[str] = None,
2180
+ system_prompt: Optional[str] = None,
2181
+ __experimental_stream_steps: Optional[bool] = None,
2182
+ on_activity: Optional[Callable[[Dict[str, Any]], None]] = None,
2183
+ on_source: Optional[Callable[[Dict[str, Any]], None]] = None) -> DeepResearchStatusResponse:
2184
+ """
2185
+ Initiates a deep research operation on a given query and polls until completion.
2186
+
2187
+ Args:
2188
+ query (str): Research query or topic to investigate
2189
+ max_depth (Optional[int]): Maximum depth of research exploration
2190
+ time_limit (Optional[int]): Time limit in seconds for research
2191
+ max_urls (Optional[int]): Maximum number of URLs to process
2192
+ analysis_prompt (Optional[str]): Custom prompt for analysis
2193
+ system_prompt (Optional[str]): Custom system prompt
2194
+ __experimental_stream_steps (Optional[bool]): Enable experimental streaming
2195
+ on_activity (Optional[Callable]): Progress callback receiving {type, status, message, timestamp, depth}
2196
+ on_source (Optional[Callable]): Source discovery callback receiving {url, title, description}
2197
+
2198
+ Returns:
2199
+ DeepResearchStatusResponse containing:
2200
+ * success (bool): Whether research completed successfully
2201
+ * status (str): Current state (processing/completed/failed)
2202
+ * error (Optional[str]): Error message if failed
2203
+ * id (str): Unique identifier for the research job
2204
+ * data (Any): Research findings and analysis
2205
+ * sources (List[Dict]): List of discovered sources
2206
+ * activities (List[Dict]): Research progress log
2207
+ * summaries (List[str]): Generated research summaries
2208
+
2209
+ Raises:
2210
+ Exception: If research fails
2211
+ """
2212
+ research_params = {}
2213
+ if max_depth is not None:
2214
+ research_params['maxDepth'] = max_depth
2215
+ if time_limit is not None:
2216
+ research_params['timeLimit'] = time_limit
2217
+ if max_urls is not None:
2218
+ research_params['maxUrls'] = max_urls
2219
+ if analysis_prompt is not None:
2220
+ research_params['analysisPrompt'] = analysis_prompt
2221
+ if system_prompt is not None:
2222
+ research_params['systemPrompt'] = system_prompt
2223
+ if __experimental_stream_steps is not None:
2224
+ research_params['__experimental_streamSteps'] = __experimental_stream_steps
2225
+ research_params = DeepResearchParams(**research_params)
2226
+
2227
+ response = self.async_deep_research(
2228
+ query,
2229
+ max_depth=max_depth,
2230
+ time_limit=time_limit,
2231
+ max_urls=max_urls,
2232
+ analysis_prompt=analysis_prompt,
2233
+ system_prompt=system_prompt
2234
+ )
2235
+ if not response.get('success') or 'id' not in response:
2236
+ return response
2237
+
2238
+ job_id = response['id']
2239
+ last_activity_count = 0
2240
+ last_source_count = 0
2241
+
2242
+ while True:
2243
+ status = self.check_deep_research_status(job_id)
2244
+
2245
+ if on_activity and 'activities' in status:
2246
+ new_activities = status['activities'][last_activity_count:]
2247
+ for activity in new_activities:
2248
+ on_activity(activity)
2249
+ last_activity_count = len(status['activities'])
2250
+
2251
+ if on_source and 'sources' in status:
2252
+ new_sources = status['sources'][last_source_count:]
2253
+ for source in new_sources:
2254
+ on_source(source)
2255
+ last_source_count = len(status['sources'])
2256
+
2257
+ if status['status'] == 'completed':
2258
+ return status
2259
+ elif status['status'] == 'failed':
2260
+ raise Exception(f'Deep research failed. Error: {status.get("error")}')
2261
+ elif status['status'] != 'processing':
2262
+ break
2263
+
2264
+ time.sleep(2) # Polling interval
2265
+
2266
+ return {'success': False, 'error': 'Deep research job terminated unexpectedly'}
2267
+
2268
+ def async_deep_research(
2269
+ self,
2270
+ query: str,
2271
+ *,
2272
+ max_depth: Optional[int] = None,
2273
+ time_limit: Optional[int] = None,
2274
+ max_urls: Optional[int] = None,
2275
+ analysis_prompt: Optional[str] = None,
2276
+ system_prompt: Optional[str] = None,
2277
+ __experimental_stream_steps: Optional[bool] = None) -> Dict[str, Any]:
2278
+ """
2279
+ Initiates an asynchronous deep research operation.
2280
+
2281
+ Args:
2282
+ query (str): Research query or topic to investigate
2283
+ max_depth (Optional[int]): Maximum depth of research exploration
2284
+ time_limit (Optional[int]): Time limit in seconds for research
2285
+ max_urls (Optional[int]): Maximum number of URLs to process
2286
+ analysis_prompt (Optional[str]): Custom prompt for analysis
2287
+ system_prompt (Optional[str]): Custom system prompt
2288
+ __experimental_stream_steps (Optional[bool]): Enable experimental streaming
2289
+
2290
+ Returns:
2291
+ Dict[str, Any]: A response containing:
2292
+ * success (bool): Whether the research initiation was successful
2293
+ * id (str): The unique identifier for the research job
2294
+ * error (str, optional): Error message if initiation failed
2295
+
2296
+ Raises:
2297
+ Exception: If the research initiation fails.
2298
+ """
2299
+ research_params = {}
2300
+ if max_depth is not None:
2301
+ research_params['maxDepth'] = max_depth
2302
+ if time_limit is not None:
2303
+ research_params['timeLimit'] = time_limit
2304
+ if max_urls is not None:
2305
+ research_params['maxUrls'] = max_urls
2306
+ if analysis_prompt is not None:
2307
+ research_params['analysisPrompt'] = analysis_prompt
2308
+ if system_prompt is not None:
2309
+ research_params['systemPrompt'] = system_prompt
2310
+ if __experimental_stream_steps is not None:
2311
+ research_params['__experimental_streamSteps'] = __experimental_stream_steps
2312
+ research_params = DeepResearchParams(**research_params)
2313
+
2314
+ headers = self._prepare_headers()
2315
+
2316
+ json_data = {'query': query, **research_params.dict(exclude_none=True)}
2317
+ json_data['origin'] = f"python-sdk@{version}"
2318
+
2319
+ # Handle json options schema if present
2320
+ if 'jsonOptions' in json_data:
2321
+ json_opts = json_data['jsonOptions']
2322
+ if json_opts and 'schema' in json_opts and hasattr(json_opts['schema'], 'schema'):
2323
+ json_data['jsonOptions']['schema'] = json_opts['schema'].schema()
2324
+
2325
+ try:
2326
+ response = self._post_request(f'{self.api_url}/v1/deep-research', json_data, headers)
2327
+ if response.status_code == 200:
2328
+ try:
2329
+ return response.json()
2330
+ except:
2331
+ raise Exception('Failed to parse Firecrawl response as JSON.')
2332
+ else:
2333
+ self._handle_error(response, 'start deep research')
2334
+ except Exception as e:
2335
+ raise ValueError(str(e))
2336
+
2337
+ return {'success': False, 'error': 'Internal server error'}
2338
+
2339
+ def check_deep_research_status(self, id: str) -> DeepResearchStatusResponse:
2340
+ """
2341
+ Check the status of a deep research operation.
2342
+
2343
+ Args:
2344
+ id (str): The ID of the deep research operation.
2345
+
2346
+ Returns:
2347
+ DeepResearchResponse containing:
2348
+
2349
+ Status:
2350
+ * success - Whether research completed successfully
2351
+ * status - Current state (processing/completed/failed)
2352
+ * error - Error message if failed
2353
+
2354
+ Results:
2355
+ * id - Unique identifier for the research job
2356
+ * data - Research findings and analysis
2357
+ * sources - List of discovered sources
2358
+ * activities - Research progress log
2359
+ * summaries - Generated research summaries
2360
+
2361
+ Raises:
2362
+ Exception: If the status check fails.
2363
+ """
2364
+ headers = self._prepare_headers()
2365
+ try:
2366
+ response = self._get_request(f'{self.api_url}/v1/deep-research/{id}', headers)
2367
+ if response.status_code == 200:
2368
+ try:
2369
+ return response.json()
2370
+ except:
2371
+ raise Exception('Failed to parse Firecrawl response as JSON.')
2372
+ elif response.status_code == 404:
2373
+ raise Exception('Deep research job not found')
2374
+ else:
2375
+ self._handle_error(response, 'check deep research status')
2376
+ except Exception as e:
2377
+ raise ValueError(str(e))
2378
+
2379
+ return {'success': False, 'error': 'Internal server error'}
2380
+
2381
+ class CrawlWatcher:
2382
+ """
2383
+ A class to watch and handle crawl job events via WebSocket connection.
2384
+
2385
+ Attributes:
2386
+ id (str): The ID of the crawl job to watch
2387
+ app (FirecrawlApp): The FirecrawlApp instance
2388
+ data (List[Dict[str, Any]]): List of crawled documents/data
2389
+ status (str): Current status of the crawl job
2390
+ ws_url (str): WebSocket URL for the crawl job
2391
+ event_handlers (dict): Dictionary of event type to list of handler functions
2392
+ """
2393
+ def __init__(self, id: str, app: FirecrawlApp):
2394
+ self.id = id
2395
+ self.app = app
2396
+ self.data: List[Dict[str, Any]] = []
2397
+ self.status = "scraping"
2398
+ self.ws_url = f"{app.api_url.replace('http', 'ws')}/v1/crawl/{id}"
2399
+ self.event_handlers = {
2400
+ 'done': [],
2401
+ 'error': [],
2402
+ 'document': []
2403
+ }
2404
+
2405
+ async def connect(self) -> None:
2406
+ """
2407
+ Establishes WebSocket connection and starts listening for messages.
2408
+ """
2409
+ async with websockets.connect(
2410
+ self.ws_url,
2411
+ additional_headers=[("Authorization", f"Bearer {self.app.api_key}")]
2412
+ ) as websocket:
2413
+ await self._listen(websocket)
2414
+
2415
+ async def _listen(self, websocket) -> None:
2416
+ """
2417
+ Listens for incoming WebSocket messages and handles them.
2418
+
2419
+ Args:
2420
+ websocket: The WebSocket connection object
2421
+ """
2422
+ async for message in websocket:
2423
+ msg = json.loads(message)
2424
+ await self._handle_message(msg)
2425
+
2426
+ def add_event_listener(self, event_type: str, handler: Callable[[Dict[str, Any]], None]) -> None:
2427
+ """
2428
+ Adds an event handler function for a specific event type.
2429
+
2430
+ Args:
2431
+ event_type (str): Type of event to listen for ('done', 'error', or 'document')
2432
+ handler (Callable): Function to handle the event
2433
+ """
2434
+ if event_type in self.event_handlers:
2435
+ self.event_handlers[event_type].append(handler)
2436
+
2437
+ def dispatch_event(self, event_type: str, detail: Dict[str, Any]) -> None:
2438
+ """
2439
+ Dispatches an event to all registered handlers for that event type.
2440
+
2441
+ Args:
2442
+ event_type (str): Type of event to dispatch
2443
+ detail (Dict[str, Any]): Event details/data to pass to handlers
2444
+ """
2445
+ if event_type in self.event_handlers:
2446
+ for handler in self.event_handlers[event_type]:
2447
+ handler(detail)
2448
+
2449
+ async def _handle_message(self, msg: Dict[str, Any]) -> None:
2450
+ """
2451
+ Handles incoming WebSocket messages based on their type.
2452
+
2453
+ Args:
2454
+ msg (Dict[str, Any]): The message to handle
2455
+ """
2456
+ if msg['type'] == 'done':
2457
+ self.status = 'completed'
2458
+ self.dispatch_event('done', {'status': self.status, 'data': self.data, 'id': self.id})
2459
+ elif msg['type'] == 'error':
2460
+ self.status = 'failed'
2461
+ self.dispatch_event('error', {'status': self.status, 'data': self.data, 'error': msg['error'], 'id': self.id})
2462
+ elif msg['type'] == 'catchup':
2463
+ self.status = msg['data']['status']
2464
+ self.data.extend(msg['data'].get('data', []))
2465
+ for doc in self.data:
2466
+ self.dispatch_event('document', {'data': doc, 'id': self.id})
2467
+ elif msg['type'] == 'document':
2468
+ self.data.append(msg['data'])
2469
+ self.dispatch_event('document', {'data': msg['data'], 'id': self.id})
2470
+
2471
+ class AsyncFirecrawlApp(FirecrawlApp):
2472
+ """
2473
+ Asynchronous version of FirecrawlApp that implements async methods using aiohttp.
2474
+ Provides non-blocking alternatives to all FirecrawlApp operations.
2475
+ """
2476
+
2477
+ async def _async_request(
2478
+ self,
2479
+ method: str,
2480
+ url: str,
2481
+ headers: Dict[str, str],
2482
+ data: Optional[Dict[str, Any]] = None,
2483
+ retries: int = 3,
2484
+ backoff_factor: float = 0.5) -> Dict[str, Any]:
2485
+ """
2486
+ Generic async request method with exponential backoff retry logic.
2487
+
2488
+ Args:
2489
+ method (str): The HTTP method to use (e.g., "GET" or "POST").
2490
+ url (str): The URL to send the request to.
2491
+ headers (Dict[str, str]): Headers to include in the request.
2492
+ data (Optional[Dict[str, Any]]): The JSON data to include in the request body (only for POST requests).
2493
+ retries (int): Maximum number of retry attempts (default: 3).
2494
+ backoff_factor (float): Factor to calculate delay between retries (default: 0.5).
2495
+ Delay will be backoff_factor * (2 ** retry_count).
2496
+
2497
+ Returns:
2498
+ Dict[str, Any]: The parsed JSON response from the server.
2499
+
2500
+ Raises:
2501
+ aiohttp.ClientError: If the request fails after all retries.
2502
+ Exception: If max retries are exceeded or other errors occur.
2503
+ """
2504
+ async with aiohttp.ClientSession() as session:
2505
+ for attempt in range(retries):
2506
+ try:
2507
+ async with session.request(
2508
+ method=method, url=url, headers=headers, json=data
2509
+ ) as response:
2510
+ if response.status == 502:
2511
+ await asyncio.sleep(backoff_factor * (2 ** attempt))
2512
+ continue
2513
+ if response.status >= 300:
2514
+ await self._handle_error(response, f"make {method} request")
2515
+ return await response.json()
2516
+ except aiohttp.ClientError as e:
2517
+ if attempt == retries - 1:
2518
+ raise e
2519
+ await asyncio.sleep(backoff_factor * (2 ** attempt))
2520
+ raise Exception("Max retries exceeded")
2521
+
2522
+ async def _async_post_request(
2523
+ self, url: str, data: Dict[str, Any], headers: Dict[str, str],
2524
+ retries: int = 3, backoff_factor: float = 0.5) -> Dict[str, Any]:
2525
+ """
2526
+ Make an async POST request with exponential backoff retry logic.
2527
+
2528
+ Args:
2529
+ url (str): The URL to send the POST request to.
2530
+ data (Dict[str, Any]): The JSON data to include in the request body.
2531
+ headers (Dict[str, str]): Headers to include in the request.
2532
+ retries (int): Maximum number of retry attempts (default: 3).
2533
+ backoff_factor (float): Factor to calculate delay between retries (default: 0.5).
2534
+ Delay will be backoff_factor * (2 ** retry_count).
2535
+
2536
+ Returns:
2537
+ Dict[str, Any]: The parsed JSON response from the server.
2538
+
2539
+ Raises:
2540
+ aiohttp.ClientError: If the request fails after all retries.
2541
+ Exception: If max retries are exceeded or other errors occur.
2542
+ """
2543
+ return await self._async_request("POST", url, headers, data, retries, backoff_factor)
2544
+
2545
+ async def _async_get_request(
2546
+ self, url: str, headers: Dict[str, str],
2547
+ retries: int = 3, backoff_factor: float = 0.5) -> Dict[str, Any]:
2548
+ """
2549
+ Make an async GET request with exponential backoff retry logic.
2550
+
2551
+ Args:
2552
+ url (str): The URL to send the GET request to.
2553
+ headers (Dict[str, str]): Headers to include in the request.
2554
+ retries (int): Maximum number of retry attempts (default: 3).
2555
+ backoff_factor (float): Factor to calculate delay between retries (default: 0.5).
2556
+ Delay will be backoff_factor * (2 ** retry_count).
2557
+
2558
+ Returns:
2559
+ Dict[str, Any]: The parsed JSON response from the server.
2560
+
2561
+ Raises:
2562
+ aiohttp.ClientError: If the request fails after all retries.
2563
+ Exception: If max retries are exceeded or other errors occur.
2564
+ """
2565
+ return await self._async_request("GET", url, headers, None, retries, backoff_factor)
2566
+
2567
+ async def _handle_error(self, response: aiohttp.ClientResponse, action: str) -> None:
2568
+ """
2569
+ Handle errors from async API responses with detailed error messages.
2570
+
2571
+ Args:
2572
+ response (aiohttp.ClientResponse): The response object from the failed request
2573
+ action (str): Description of the action that was being attempted
2574
+
2575
+ Raises:
2576
+ aiohttp.ClientError: With a detailed error message based on the response status:
2577
+ - 402: Payment Required
2578
+ - 408: Request Timeout
2579
+ - 409: Conflict
2580
+ - 500: Internal Server Error
2581
+ - Other: Unexpected error with status code
2582
+ """
2583
+ try:
2584
+ error_data = await response.json()
2585
+ error_message = error_data.get('error', 'No error message provided.')
2586
+ error_details = error_data.get('details', 'No additional error details provided.')
2587
+ except:
2588
+ raise aiohttp.ClientError(f'Failed to parse Firecrawl error response as JSON. Status code: {response.status}')
2589
+
2590
+ message = await self._get_async_error_message(response.status, action, error_message, error_details)
2591
+
2592
+ raise aiohttp.ClientError(message)
2593
+
2594
+ async def _get_async_error_message(self, status_code: int, action: str, error_message: str, error_details: str) -> str:
2595
+ """
2596
+ Generate a standardized error message based on HTTP status code for async operations.
2597
+
2598
+ Args:
2599
+ status_code (int): The HTTP status code from the response
2600
+ action (str): Description of the action that was being performed
2601
+ error_message (str): The error message from the API response
2602
+ error_details (str): Additional error details from the API response
2603
+
2604
+ Returns:
2605
+ str: A formatted error message
2606
+ """
2607
+ return self._get_error_message(status_code, action, error_message, error_details)
2608
+
2609
+ async def crawl_url_and_watch(
2610
+ self,
2611
+ url: str,
2612
+ params: Optional[CrawlParams] = None,
2613
+ idempotency_key: Optional[str] = None) -> 'AsyncCrawlWatcher':
2614
+ """
2615
+ Initiate an async crawl job and return an AsyncCrawlWatcher to monitor progress via WebSocket.
2616
+
2617
+ Args:
2618
+ url (str): Target URL to start crawling from
2619
+ params (Optional[CrawlParams]): See CrawlParams model for configuration:
2620
+ URL Discovery:
2621
+ * includePaths - Patterns of URLs to include
2622
+ * excludePaths - Patterns of URLs to exclude
2623
+ * maxDepth - Maximum crawl depth
2624
+ * maxDiscoveryDepth - Maximum depth for finding new URLs
2625
+ * limit - Maximum pages to crawl
2626
+
2627
+ Link Following:
2628
+ * allowBackwardLinks - Follow parent directory links
2629
+ * allowExternalLinks - Follow external domain links
2630
+ * ignoreSitemap - Skip sitemap.xml processing
2631
+
2632
+ Advanced:
2633
+ * scrapeOptions - Page scraping configuration
2634
+ * webhook - Notification webhook settings
2635
+ * deduplicateSimilarURLs - Remove similar URLs
2636
+ * ignoreQueryParameters - Ignore URL parameters
2637
+ * regexOnFullURL - Apply regex to full URLs
2638
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
2639
+
2640
+ Returns:
2641
+ AsyncCrawlWatcher: An instance to monitor the crawl job via WebSocket
2642
+
2643
+ Raises:
2644
+ Exception: If crawl job fails to start
2645
+ """
2646
+ crawl_response = await self.async_crawl_url(url, params, idempotency_key)
2647
+ if crawl_response.get('success') and 'id' in crawl_response:
2648
+ return AsyncCrawlWatcher(crawl_response['id'], self)
2649
+ else:
2650
+ raise Exception("Crawl job failed to start")
2651
+
2652
+ async def batch_scrape_urls_and_watch(
2653
+ self,
2654
+ urls: List[str],
2655
+ params: Optional[ScrapeParams] = None,
2656
+ idempotency_key: Optional[str] = None) -> 'AsyncCrawlWatcher':
2657
+ """
2658
+ Initiate an async batch scrape job and return an AsyncCrawlWatcher to monitor progress.
2659
+
2660
+ Args:
2661
+ urls (List[str]): List of URLs to scrape
2662
+ params (Optional[ScrapeParams]): See ScrapeParams model for configuration:
2663
+
2664
+ Content Options:
2665
+ * formats - Content formats to retrieve
2666
+ * includeTags - HTML tags to include
2667
+ * excludeTags - HTML tags to exclude
2668
+ * onlyMainContent - Extract main content only
2669
+
2670
+ Request Options:
2671
+ * headers - Custom HTTP headers
2672
+ * timeout - Request timeout (ms)
2673
+ * mobile - Use mobile user agent
2674
+ * proxy - Proxy type
2675
+
2676
+ Extraction Options:
2677
+ * extract - Content extraction config
2678
+ * jsonOptions - JSON extraction config
2679
+ * actions - Actions to perform
2680
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
2681
+
2682
+ Returns:
2683
+ AsyncCrawlWatcher: An instance to monitor the batch scrape job via WebSocket
2684
+
2685
+ Raises:
2686
+ Exception: If batch scrape job fails to start
2687
+ """
2688
+ batch_response = await self.async_batch_scrape_urls(urls, params, idempotency_key)
2689
+ if batch_response.get('success') and 'id' in batch_response:
2690
+ return AsyncCrawlWatcher(batch_response['id'], self)
2691
+ else:
2692
+ raise Exception("Batch scrape job failed to start")
2693
+
2694
+ async def scrape_url(
2695
+ self,
2696
+ url: str,
2697
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]] = None,
2698
+ include_tags: Optional[List[str]] = None,
2699
+ exclude_tags: Optional[List[str]] = None,
2700
+ only_main_content: Optional[bool] = None,
2701
+ wait_for: Optional[int] = None,
2702
+ timeout: Optional[int] = None,
2703
+ location: Optional[LocationConfig] = None,
2704
+ mobile: Optional[bool] = None,
2705
+ skip_tls_verification: Optional[bool] = None,
2706
+ remove_base64_images: Optional[bool] = None,
2707
+ block_ads: Optional[bool] = None,
2708
+ proxy: Optional[Literal["basic", "stealth"]] = None,
2709
+ extract: Optional[JsonConfig] = None,
2710
+ json_options: Optional[JsonConfig] = None,
2711
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None) -> ScrapeResponse[Any]:
2712
+ """
2713
+ Scrape and extract content from a URL asynchronously.
2714
+
2715
+ Args:
2716
+ url (str): Target URL to scrape
2717
+ formats (Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]]): Content types to retrieve (markdown/html/etc)
2718
+ include_tags (Optional[List[str]]): HTML tags to include
2719
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
2720
+ only_main_content (Optional[bool]): Extract main content only
2721
+ wait_for (Optional[int]): Wait for a specific element to appear
2722
+ timeout (Optional[int]): Request timeout (ms)
2723
+ location (Optional[LocationConfig]): Location configuration
2724
+ mobile (Optional[bool]): Use mobile user agent
2725
+ skip_tls_verification (Optional[bool]): Skip TLS verification
2726
+ remove_base64_images (Optional[bool]): Remove base64 images
2727
+ block_ads (Optional[bool]): Block ads
2728
+ proxy (Optional[Literal["basic", "stealth"]]): Proxy type (basic/stealth)
2729
+ extract (Optional[JsonConfig]): Content extraction settings
2730
+ json_options (Optional[JsonConfig]): JSON extraction settings
2731
+ actions (Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]]): Actions to perform
2732
+
2733
+ Returns:
2734
+ ScrapeResponse with:
2735
+ * Requested content formats
2736
+ * Page metadata
2737
+ * Extraction results
2738
+ * Success/error status
2739
+
2740
+ Raises:
2741
+ Exception: If scraping fails
2742
+ """
2743
+ headers = self._prepare_headers()
2744
+
2745
+ # Build scrape parameters
2746
+ scrape_params = {
2747
+ 'url': url,
2748
+ 'origin': f"python-sdk@{version}"
2749
+ }
2750
+
2751
+ # Add optional parameters if provided and not None
2752
+ if formats:
2753
+ scrape_params['formats'] = formats
2754
+ if include_tags:
2755
+ scrape_params['includeTags'] = include_tags
2756
+ if exclude_tags:
2757
+ scrape_params['excludeTags'] = exclude_tags
2758
+ if only_main_content is not None:
2759
+ scrape_params['onlyMainContent'] = only_main_content
2760
+ if wait_for:
2761
+ scrape_params['waitFor'] = wait_for
2762
+ if timeout:
2763
+ scrape_params['timeout'] = timeout
2764
+ if location:
2765
+ scrape_params['location'] = location.dict(exclude_none=True)
2766
+ if mobile is not None:
2767
+ scrape_params['mobile'] = mobile
2768
+ if skip_tls_verification is not None:
2769
+ scrape_params['skipTlsVerification'] = skip_tls_verification
2770
+ if remove_base64_images is not None:
2771
+ scrape_params['removeBase64Images'] = remove_base64_images
2772
+ if block_ads is not None:
2773
+ scrape_params['blockAds'] = block_ads
2774
+ if proxy:
2775
+ scrape_params['proxy'] = proxy
2776
+ if extract:
2777
+ extract_dict = extract.dict(exclude_none=True)
2778
+ if 'schema' in extract_dict and hasattr(extract.schema, 'schema'):
2779
+ extract_dict['schema'] = extract.schema.schema() # Ensure pydantic model schema is converted
2780
+ scrape_params['extract'] = extract_dict
2781
+ if json_options:
2782
+ json_options_dict = json_options.dict(exclude_none=True)
2783
+ if 'schema' in json_options_dict and hasattr(json_options.schema, 'schema'):
2784
+ json_options_dict['schema'] = json_options.schema.schema() # Ensure pydantic model schema is converted
2785
+ scrape_params['jsonOptions'] = json_options_dict
2786
+ if actions:
2787
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
2788
+
2789
+ # Make async request
2790
+ endpoint = f'/v1/scrape'
2791
+ response = await self._async_post_request(
2792
+ f'{self.api_url}{endpoint}',
2793
+ scrape_params,
2794
+ headers
2795
+ )
2796
+
2797
+ if response.get('success') and 'data' in response:
2798
+ return ScrapeResponse(**response['data'])
2799
+ elif "error" in response:
2800
+ raise Exception(f'Failed to scrape URL. Error: {response["error"]}')
2801
+ else:
2802
+ # Use the response content directly if possible, otherwise a generic message
2803
+ error_content = response.get('error', str(response))
2804
+ raise Exception(f'Failed to scrape URL. Error: {error_content}')
2805
+
2806
+ async def batch_scrape_urls(
2807
+ self,
2808
+ urls: List[str],
2809
+ *,
2810
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]] = None,
2811
+ headers: Optional[Dict[str, str]] = None,
2812
+ include_tags: Optional[List[str]] = None,
2813
+ exclude_tags: Optional[List[str]] = None,
2814
+ only_main_content: Optional[bool] = None,
2815
+ wait_for: Optional[int] = None,
2816
+ timeout: Optional[int] = None,
2817
+ location: Optional[LocationConfig] = None,
2818
+ mobile: Optional[bool] = None,
2819
+ skip_tls_verification: Optional[bool] = None,
2820
+ remove_base64_images: Optional[bool] = None,
2821
+ block_ads: Optional[bool] = None,
2822
+ proxy: Optional[Literal["basic", "stealth"]] = None,
2823
+ extract: Optional[JsonConfig] = None,
2824
+ json_options: Optional[JsonConfig] = None,
2825
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None,
2826
+ agent: Optional[AgentOptions] = None,
2827
+ poll_interval: Optional[int] = 2,
2828
+ idempotency_key: Optional[str] = None,
2829
+ **kwargs
2830
+ ) -> BatchScrapeStatusResponse:
2831
+ """
2832
+ Asynchronously scrape multiple URLs and monitor until completion.
2833
+
2834
+ Args:
2835
+ urls (List[str]): URLs to scrape
2836
+ formats (Optional[List[Literal]]): Content formats to retrieve
2837
+ headers (Optional[Dict[str, str]]): Custom HTTP headers
2838
+ include_tags (Optional[List[str]]): HTML tags to include
2839
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
2840
+ only_main_content (Optional[bool]): Extract main content only
2841
+ wait_for (Optional[int]): Wait time in milliseconds
2842
+ timeout (Optional[int]): Request timeout in milliseconds
2843
+ location (Optional[LocationConfig]): Location configuration
2844
+ mobile (Optional[bool]): Use mobile user agent
2845
+ skip_tls_verification (Optional[bool]): Skip TLS verification
2846
+ remove_base64_images (Optional[bool]): Remove base64 encoded images
2847
+ block_ads (Optional[bool]): Block advertisements
2848
+ proxy (Optional[Literal]): Proxy type to use
2849
+ extract (Optional[JsonConfig]): Content extraction config
2850
+ json_options (Optional[JsonConfig]): JSON extraction config
2851
+ actions (Optional[List[Union]]): Actions to perform
2852
+ agent (Optional[AgentOptions]): Agent configuration
2853
+ poll_interval (Optional[int]): Seconds between status checks (default: 2)
2854
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
2855
+ **kwargs: Additional parameters to pass to the API
2856
+
2857
+ Returns:
2858
+ BatchScrapeStatusResponse with:
2859
+ * Scraping status and progress
2860
+ * Scraped content for each URL
2861
+ * Success/error information
2862
+
2863
+ Raises:
2864
+ Exception: If batch scrape fails
2865
+ """
2866
+ scrape_params = {}
2867
+
2868
+ # Add individual parameters
2869
+ if formats is not None:
2870
+ scrape_params['formats'] = formats
2871
+ if headers is not None:
2872
+ scrape_params['headers'] = headers
2873
+ if include_tags is not None:
2874
+ scrape_params['includeTags'] = include_tags
2875
+ if exclude_tags is not None:
2876
+ scrape_params['excludeTags'] = exclude_tags
2877
+ if only_main_content is not None:
2878
+ scrape_params['onlyMainContent'] = only_main_content
2879
+ if wait_for is not None:
2880
+ scrape_params['waitFor'] = wait_for
2881
+ if timeout is not None:
2882
+ scrape_params['timeout'] = timeout
2883
+ if location is not None:
2884
+ scrape_params['location'] = location.dict(exclude_none=True)
2885
+ if mobile is not None:
2886
+ scrape_params['mobile'] = mobile
2887
+ if skip_tls_verification is not None:
2888
+ scrape_params['skipTlsVerification'] = skip_tls_verification
2889
+ if remove_base64_images is not None:
2890
+ scrape_params['removeBase64Images'] = remove_base64_images
2891
+ if block_ads is not None:
2892
+ scrape_params['blockAds'] = block_ads
2893
+ if proxy is not None:
2894
+ scrape_params['proxy'] = proxy
2895
+ if extract is not None:
2896
+ if hasattr(extract.schema, 'schema'):
2897
+ extract.schema = extract.schema.schema()
2898
+ scrape_params['extract'] = extract.dict(exclude_none=True)
2899
+ if json_options is not None:
2900
+ if hasattr(json_options.schema, 'schema'):
2901
+ json_options.schema = json_options.schema.schema()
2902
+ scrape_params['jsonOptions'] = json_options.dict(exclude_none=True)
2903
+ if actions is not None:
2904
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
2905
+ if agent is not None:
2906
+ scrape_params['agent'] = agent.dict(exclude_none=True)
2907
+
2908
+ # Add any additional kwargs
2909
+ scrape_params.update(kwargs)
2910
+
2911
+ # Create final params object
2912
+ final_params = ScrapeParams(**scrape_params)
2913
+ params_dict = final_params.dict(exclude_none=True)
2914
+ params_dict['urls'] = urls
2915
+ params_dict['origin'] = f"python-sdk@{version}"
2916
+
2917
+ # Make request
2918
+ headers = self._prepare_headers(idempotency_key)
2919
+ response = await self._async_post_request(
2920
+ f'{self.api_url}/v1/batch/scrape',
2921
+ params_dict,
2922
+ headers
2923
+ )
2924
+
2925
+ if response.get('success'):
2926
+ try:
2927
+ id = response.get('id')
2928
+ except:
2929
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
2930
+ return self._monitor_job_status(id, headers, poll_interval)
2931
+ else:
2932
+ self._handle_error(response, 'start batch scrape job')
2933
+
2934
+
2935
+ async def async_batch_scrape_urls(
2936
+ self,
2937
+ urls: List[str],
2938
+ *,
2939
+ formats: Optional[List[Literal["markdown", "html", "rawHtml", "content", "links", "screenshot", "screenshot@fullPage", "extract", "json"]]] = None,
2940
+ headers: Optional[Dict[str, str]] = None,
2941
+ include_tags: Optional[List[str]] = None,
2942
+ exclude_tags: Optional[List[str]] = None,
2943
+ only_main_content: Optional[bool] = None,
2944
+ wait_for: Optional[int] = None,
2945
+ timeout: Optional[int] = None,
2946
+ location: Optional[LocationConfig] = None,
2947
+ mobile: Optional[bool] = None,
2948
+ skip_tls_verification: Optional[bool] = None,
2949
+ remove_base64_images: Optional[bool] = None,
2950
+ block_ads: Optional[bool] = None,
2951
+ proxy: Optional[Literal["basic", "stealth"]] = None,
2952
+ extract: Optional[JsonConfig] = None,
2953
+ json_options: Optional[JsonConfig] = None,
2954
+ actions: Optional[List[Union[WaitAction, ScreenshotAction, ClickAction, WriteAction, PressAction, ScrollAction, ScrapeAction, ExecuteJavascriptAction]]] = None,
2955
+ agent: Optional[AgentOptions] = None,
2956
+ idempotency_key: Optional[str] = None,
2957
+ **kwargs
2958
+ ) -> BatchScrapeResponse:
2959
+ """
2960
+ Initiate a batch scrape job asynchronously.
2961
+
2962
+ Args:
2963
+ urls (List[str]): URLs to scrape
2964
+ formats (Optional[List[Literal]]): Content formats to retrieve
2965
+ headers (Optional[Dict[str, str]]): Custom HTTP headers
2966
+ include_tags (Optional[List[str]]): HTML tags to include
2967
+ exclude_tags (Optional[List[str]]): HTML tags to exclude
2968
+ only_main_content (Optional[bool]): Extract main content only
2969
+ wait_for (Optional[int]): Wait time in milliseconds
2970
+ timeout (Optional[int]): Request timeout in milliseconds
2971
+ location (Optional[LocationConfig]): Location configuration
2972
+ mobile (Optional[bool]): Use mobile user agent
2973
+ skip_tls_verification (Optional[bool]): Skip TLS verification
2974
+ remove_base64_images (Optional[bool]): Remove base64 encoded images
2975
+ block_ads (Optional[bool]): Block advertisements
2976
+ proxy (Optional[Literal]): Proxy type to use
2977
+ extract (Optional[JsonConfig]): Content extraction config
2978
+ json_options (Optional[JsonConfig]): JSON extraction config
2979
+ actions (Optional[List[Union]]): Actions to perform
2980
+ agent (Optional[AgentOptions]): Agent configuration
2981
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
2982
+ **kwargs: Additional parameters to pass to the API
2983
+
2984
+ Returns:
2985
+ BatchScrapeResponse with:
2986
+ * success - Whether job started successfully
2987
+ * id - Unique identifier for the job
2988
+ * url - Status check URL
2989
+ * error - Error message if start failed
2990
+
2991
+ Raises:
2992
+ Exception: If job initiation fails
2993
+ """
2994
+ scrape_params = {}
2995
+
2996
+ # Add individual parameters
2997
+ if formats is not None:
2998
+ scrape_params['formats'] = formats
2999
+ if headers is not None:
3000
+ scrape_params['headers'] = headers
3001
+ if include_tags is not None:
3002
+ scrape_params['includeTags'] = include_tags
3003
+ if exclude_tags is not None:
3004
+ scrape_params['excludeTags'] = exclude_tags
3005
+ if only_main_content is not None:
3006
+ scrape_params['onlyMainContent'] = only_main_content
3007
+ if wait_for is not None:
3008
+ scrape_params['waitFor'] = wait_for
3009
+ if timeout is not None:
3010
+ scrape_params['timeout'] = timeout
3011
+ if location is not None:
3012
+ scrape_params['location'] = location.dict(exclude_none=True)
3013
+ if mobile is not None:
3014
+ scrape_params['mobile'] = mobile
3015
+ if skip_tls_verification is not None:
3016
+ scrape_params['skipTlsVerification'] = skip_tls_verification
3017
+ if remove_base64_images is not None:
3018
+ scrape_params['removeBase64Images'] = remove_base64_images
3019
+ if block_ads is not None:
3020
+ scrape_params['blockAds'] = block_ads
3021
+ if proxy is not None:
3022
+ scrape_params['proxy'] = proxy
3023
+ if extract is not None:
3024
+ if hasattr(extract.schema, 'schema'):
3025
+ extract.schema = extract.schema.schema()
3026
+ scrape_params['extract'] = extract.dict(exclude_none=True)
3027
+ if json_options is not None:
3028
+ if hasattr(json_options.schema, 'schema'):
3029
+ json_options.schema = json_options.schema.schema()
3030
+ scrape_params['jsonOptions'] = json_options.dict(exclude_none=True)
3031
+ if actions is not None:
3032
+ scrape_params['actions'] = [action.dict(exclude_none=True) for action in actions]
3033
+ if agent is not None:
3034
+ scrape_params['agent'] = agent.dict(exclude_none=True)
3035
+
3036
+ # Add any additional kwargs
3037
+ scrape_params.update(kwargs)
3038
+
3039
+ # Create final params object
3040
+ final_params = ScrapeParams(**scrape_params)
3041
+ params_dict = final_params.dict(exclude_none=True)
3042
+ params_dict['urls'] = urls
3043
+ params_dict['origin'] = f"python-sdk@{version}"
3044
+
3045
+ # Make request
3046
+ headers = self._prepare_headers(idempotency_key)
3047
+ response = await self._async_post_request(
3048
+ f'{self.api_url}/v1/batch/scrape',
3049
+ params_dict,
3050
+ headers
3051
+ )
3052
+
3053
+ if response.get('status_code') == 200:
3054
+ try:
3055
+ return BatchScrapeResponse(**response.json())
3056
+ except:
3057
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
3058
+ else:
3059
+ self._handle_error(response, 'start batch scrape job')
3060
+
3061
+ async def crawl_url(
3062
+ self,
3063
+ url: str,
3064
+ *,
3065
+ include_paths: Optional[List[str]] = None,
3066
+ exclude_paths: Optional[List[str]] = None,
3067
+ max_depth: Optional[int] = None,
3068
+ max_discovery_depth: Optional[int] = None,
3069
+ limit: Optional[int] = None,
3070
+ allow_backward_links: Optional[bool] = None,
3071
+ allow_external_links: Optional[bool] = None,
3072
+ ignore_sitemap: Optional[bool] = None,
3073
+ scrape_options: Optional[ScrapeOptions] = None,
3074
+ webhook: Optional[Union[str, WebhookConfig]] = None,
3075
+ deduplicate_similar_urls: Optional[bool] = None,
3076
+ ignore_query_parameters: Optional[bool] = None,
3077
+ regex_on_full_url: Optional[bool] = None,
3078
+ poll_interval: Optional[int] = 2,
3079
+ idempotency_key: Optional[str] = None,
3080
+ **kwargs
3081
+ ) -> CrawlStatusResponse:
3082
+ """
3083
+ Crawl a website starting from a URL.
3084
+
3085
+ Args:
3086
+ url (str): Target URL to start crawling from
3087
+ include_paths (Optional[List[str]]): Patterns of URLs to include
3088
+ exclude_paths (Optional[List[str]]): Patterns of URLs to exclude
3089
+ max_depth (Optional[int]): Maximum crawl depth
3090
+ max_discovery_depth (Optional[int]): Maximum depth for finding new URLs
3091
+ limit (Optional[int]): Maximum pages to crawl
3092
+ allow_backward_links (Optional[bool]): Follow parent directory links
3093
+ allow_external_links (Optional[bool]): Follow external domain links
3094
+ ignore_sitemap (Optional[bool]): Skip sitemap.xml processing
3095
+ scrape_options (Optional[ScrapeOptions]): Page scraping configuration
3096
+ webhook (Optional[Union[str, WebhookConfig]]): Notification webhook settings
3097
+ deduplicate_similar_urls (Optional[bool]): Remove similar URLs
3098
+ ignore_query_parameters (Optional[bool]): Ignore URL parameters
3099
+ regex_on_full_url (Optional[bool]): Apply regex to full URLs
3100
+ poll_interval (Optional[int]): Seconds between status checks (default: 2)
3101
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
3102
+ **kwargs: Additional parameters to pass to the API
3103
+
3104
+ Returns:
3105
+ CrawlStatusResponse with:
3106
+ * Crawling status and progress
3107
+ * Crawled page contents
3108
+ * Success/error information
3109
+
3110
+ Raises:
3111
+ Exception: If crawl fails
3112
+ """
3113
+ crawl_params = {}
3114
+
3115
+ # Add individual parameters
3116
+ if include_paths is not None:
3117
+ crawl_params['includePaths'] = include_paths
3118
+ if exclude_paths is not None:
3119
+ crawl_params['excludePaths'] = exclude_paths
3120
+ if max_depth is not None:
3121
+ crawl_params['maxDepth'] = max_depth
3122
+ if max_discovery_depth is not None:
3123
+ crawl_params['maxDiscoveryDepth'] = max_discovery_depth
3124
+ if limit is not None:
3125
+ crawl_params['limit'] = limit
3126
+ if allow_backward_links is not None:
3127
+ crawl_params['allowBackwardLinks'] = allow_backward_links
3128
+ if allow_external_links is not None:
3129
+ crawl_params['allowExternalLinks'] = allow_external_links
3130
+ if ignore_sitemap is not None:
3131
+ crawl_params['ignoreSitemap'] = ignore_sitemap
3132
+ if scrape_options is not None:
3133
+ crawl_params['scrapeOptions'] = scrape_options.dict(exclude_none=True)
3134
+ if webhook is not None:
3135
+ crawl_params['webhook'] = webhook
3136
+ if deduplicate_similar_urls is not None:
3137
+ crawl_params['deduplicateSimilarURLs'] = deduplicate_similar_urls
3138
+ if ignore_query_parameters is not None:
3139
+ crawl_params['ignoreQueryParameters'] = ignore_query_parameters
3140
+ if regex_on_full_url is not None:
3141
+ crawl_params['regexOnFullURL'] = regex_on_full_url
3142
+
3143
+ # Add any additional kwargs
3144
+ crawl_params.update(kwargs)
3145
+
3146
+ # Create final params object
3147
+ final_params = CrawlParams(**crawl_params)
3148
+ params_dict = final_params.dict(exclude_none=True)
3149
+ params_dict['url'] = url
3150
+ params_dict['origin'] = f"python-sdk@{version}"
3151
+ # Make request
3152
+ headers = self._prepare_headers(idempotency_key)
3153
+ response = await self._async_post_request(
3154
+ f'{self.api_url}/v1/crawl', params_dict, headers)
3155
+
3156
+ print(response)
3157
+ if response.get('success'):
3158
+ try:
3159
+ id = response.get('id')
3160
+ except:
3161
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
3162
+ return self._monitor_job_status(id, headers, poll_interval)
3163
+ else:
3164
+ self._handle_error(response, 'start crawl job')
3165
+
3166
+
3167
+ async def async_crawl_url(
3168
+ self,
3169
+ url: str,
3170
+ *,
3171
+ include_paths: Optional[List[str]] = None,
3172
+ exclude_paths: Optional[List[str]] = None,
3173
+ max_depth: Optional[int] = None,
3174
+ max_discovery_depth: Optional[int] = None,
3175
+ limit: Optional[int] = None,
3176
+ allow_backward_links: Optional[bool] = None,
3177
+ allow_external_links: Optional[bool] = None,
3178
+ ignore_sitemap: Optional[bool] = None,
3179
+ scrape_options: Optional[ScrapeOptions] = None,
3180
+ webhook: Optional[Union[str, WebhookConfig]] = None,
3181
+ deduplicate_similar_urls: Optional[bool] = None,
3182
+ ignore_query_parameters: Optional[bool] = None,
3183
+ regex_on_full_url: Optional[bool] = None,
3184
+ poll_interval: Optional[int] = 2,
3185
+ idempotency_key: Optional[str] = None,
3186
+ **kwargs
3187
+ ) -> CrawlResponse:
3188
+ """
3189
+ Start an asynchronous crawl job.
3190
+
3191
+ Args:
3192
+ url (str): Target URL to start crawling from
3193
+ include_paths (Optional[List[str]]): Patterns of URLs to include
3194
+ exclude_paths (Optional[List[str]]): Patterns of URLs to exclude
3195
+ max_depth (Optional[int]): Maximum crawl depth
3196
+ max_discovery_depth (Optional[int]): Maximum depth for finding new URLs
3197
+ limit (Optional[int]): Maximum pages to crawl
3198
+ allow_backward_links (Optional[bool]): Follow parent directory links
3199
+ allow_external_links (Optional[bool]): Follow external domain links
3200
+ ignore_sitemap (Optional[bool]): Skip sitemap.xml processing
3201
+ scrape_options (Optional[ScrapeOptions]): Page scraping configuration
3202
+ webhook (Optional[Union[str, WebhookConfig]]): Notification webhook settings
3203
+ deduplicate_similar_urls (Optional[bool]): Remove similar URLs
3204
+ ignore_query_parameters (Optional[bool]): Ignore URL parameters
3205
+ regex_on_full_url (Optional[bool]): Apply regex to full URLs
3206
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
3207
+ **kwargs: Additional parameters to pass to the API
3208
+
3209
+ Returns:
3210
+ CrawlResponse with:
3211
+ * success - Whether crawl started successfully
3212
+ * id - Unique identifier for the crawl job
3213
+ * url - Status check URL for the crawl
3214
+ * error - Error message if start failed
3215
+
3216
+ Raises:
3217
+ Exception: If crawl initiation fails
3218
+ """
3219
+ crawl_params = {}
3220
+
3221
+ # Add individual parameters
3222
+ if include_paths is not None:
3223
+ crawl_params['includePaths'] = include_paths
3224
+ if exclude_paths is not None:
3225
+ crawl_params['excludePaths'] = exclude_paths
3226
+ if max_depth is not None:
3227
+ crawl_params['maxDepth'] = max_depth
3228
+ if max_discovery_depth is not None:
3229
+ crawl_params['maxDiscoveryDepth'] = max_discovery_depth
3230
+ if limit is not None:
3231
+ crawl_params['limit'] = limit
3232
+ if allow_backward_links is not None:
3233
+ crawl_params['allowBackwardLinks'] = allow_backward_links
3234
+ if allow_external_links is not None:
3235
+ crawl_params['allowExternalLinks'] = allow_external_links
3236
+ if ignore_sitemap is not None:
3237
+ crawl_params['ignoreSitemap'] = ignore_sitemap
3238
+ if scrape_options is not None:
3239
+ crawl_params['scrapeOptions'] = scrape_options.dict(exclude_none=True)
3240
+ if webhook is not None:
3241
+ crawl_params['webhook'] = webhook
3242
+ if deduplicate_similar_urls is not None:
3243
+ crawl_params['deduplicateSimilarURLs'] = deduplicate_similar_urls
3244
+ if ignore_query_parameters is not None:
3245
+ crawl_params['ignoreQueryParameters'] = ignore_query_parameters
3246
+ if regex_on_full_url is not None:
3247
+ crawl_params['regexOnFullURL'] = regex_on_full_url
3248
+
3249
+ # Add any additional kwargs
3250
+ crawl_params.update(kwargs)
3251
+
3252
+ # Create final params object
3253
+ final_params = CrawlParams(**crawl_params)
3254
+ params_dict = final_params.dict(exclude_none=True)
3255
+ params_dict['url'] = url
3256
+ params_dict['origin'] = f"python-sdk@{version}"
3257
+
3258
+ # Make request
3259
+ headers = self._prepare_headers(idempotency_key)
3260
+ response = await self._async_post_request(
3261
+ f'{self.api_url}/v1/crawl',
3262
+ params_dict,
3263
+ headers
3264
+ )
3265
+
3266
+ if response.get('success'):
3267
+ try:
3268
+ return CrawlResponse(**response)
3269
+ except:
3270
+ raise Exception(f'Failed to parse Firecrawl response as JSON.')
3271
+ else:
3272
+ self._handle_error(response, 'start crawl job')
3273
+
3274
+ async def check_crawl_status(self, id: str) -> CrawlStatusResponse:
3275
+ """
3276
+ Check the status and results of an asynchronous crawl job.
3277
+
3278
+ Args:
3279
+ id (str): Unique identifier for the crawl job
3280
+
3281
+ Returns:
3282
+ CrawlStatusResponse containing:
3283
+ Status Information:
3284
+ * status - Current state (scraping/completed/failed/cancelled)
3285
+ * completed - Number of pages crawled
3286
+ * total - Total pages to crawl
3287
+ * creditsUsed - API credits consumed
3288
+ * expiresAt - Data expiration timestamp
3289
+
3290
+ Results:
3291
+ * data - List of crawled documents
3292
+ * next - URL for next page of results (if paginated)
3293
+ * success - Whether status check succeeded
3294
+ * error - Error message if failed
3295
+
3296
+ Raises:
3297
+ Exception: If status check fails
3298
+ """
3299
+ headers = self._prepare_headers()
3300
+ endpoint = f'/v1/crawl/{id}'
3301
+
3302
+ status_data = await self._async_get_request(
3303
+ f'{self.api_url}{endpoint}',
3304
+ headers
3305
+ )
3306
+
3307
+ if status_data.get('status') == 'completed':
3308
+ if 'data' in status_data:
3309
+ data = status_data['data']
3310
+ while 'next' in status_data:
3311
+ if len(status_data['data']) == 0:
3312
+ break
3313
+ next_url = status_data.get('next')
3314
+ if not next_url:
3315
+ logger.warning("Expected 'next' URL is missing.")
3316
+ break
3317
+ next_data = await self._async_get_request(next_url, headers)
3318
+ data.extend(next_data.get('data', []))
3319
+ status_data = next_data
3320
+ status_data['data'] = data
3321
+ # Create CrawlStatusResponse object from status data
3322
+ response = CrawlStatusResponse(
3323
+ status=status_data.get('status'),
3324
+ total=status_data.get('total'),
3325
+ completed=status_data.get('completed'),
3326
+ creditsUsed=status_data.get('creditsUsed'),
3327
+ expiresAt=status_data.get('expiresAt'),
3328
+ data=status_data.get('data'),
3329
+ success=False if 'error' in status_data else True
3330
+ )
3331
+
3332
+ if 'error' in status_data:
3333
+ response.error = status_data.get('error')
3334
+
3335
+ if 'next' in status_data:
3336
+ response.next = status_data.get('next')
3337
+
3338
+ return response
3339
+
3340
+ async def _async_monitor_job_status(self, id: str, headers: Dict[str, str], poll_interval: int = 2) -> CrawlStatusResponse:
3341
+ """
3342
+ Monitor the status of an asynchronous job until completion.
3343
+
3344
+ Args:
3345
+ id (str): The ID of the job to monitor
3346
+ headers (Dict[str, str]): Headers to include in status check requests
3347
+ poll_interval (int): Seconds between status checks (default: 2)
3348
+
3349
+ Returns:
3350
+ CrawlStatusResponse: The job results if completed successfully
3351
+
3352
+ Raises:
3353
+ Exception: If the job fails or an error occurs during status checks
3354
+ """
3355
+ while True:
3356
+ status_data = await self._async_get_request(
3357
+ f'{self.api_url}/v1/crawl/{id}',
3358
+ headers
3359
+ )
3360
+
3361
+ if status_data.get('status') == 'completed':
3362
+ if 'data' in status_data:
3363
+ data = status_data['data']
3364
+ while 'next' in status_data:
3365
+ if len(status_data['data']) == 0:
3366
+ break
3367
+ next_url = status_data.get('next')
3368
+ if not next_url:
3369
+ logger.warning("Expected 'next' URL is missing.")
3370
+ break
3371
+ next_data = await self._async_get_request(next_url, headers)
3372
+ data.extend(next_data.get('data', []))
3373
+ status_data = next_data
3374
+ status_data['data'] = data
3375
+ return status_data
3376
+ else:
3377
+ raise Exception('Job completed but no data was returned')
3378
+ elif status_data.get('status') in ['active', 'paused', 'pending', 'queued', 'waiting', 'scraping']:
3379
+ await asyncio.sleep(max(poll_interval, 2))
3380
+ else:
3381
+ raise Exception(f'Job failed or was stopped. Status: {status_data["status"]}')
3382
+
3383
+ async def map_url(
3384
+ self,
3385
+ url: str,
3386
+ *,
3387
+ search: Optional[str] = None,
3388
+ ignore_sitemap: Optional[bool] = None,
3389
+ include_subdomains: Optional[bool] = None,
3390
+ sitemap_only: Optional[bool] = None,
3391
+ limit: Optional[int] = None,
3392
+ timeout: Optional[int] = None,
3393
+ params: Optional[MapParams] = None) -> MapResponse:
3394
+ """
3395
+ Asynchronously map and discover links from a URL.
3396
+
3397
+ Args:
3398
+ url (str): Target URL to map
3399
+ params (Optional[MapParams]): See MapParams model:
3400
+ Discovery Options:
3401
+ * search - Filter pattern for URLs
3402
+ * ignoreSitemap - Skip sitemap.xml
3403
+ * includeSubdomains - Include subdomain links
3404
+ * sitemapOnly - Only use sitemap.xml
3405
+
3406
+ Limits:
3407
+ * limit - Max URLs to return
3408
+ * timeout - Request timeout (ms)
3409
+
3410
+ Returns:
3411
+ MapResponse with:
3412
+ * Discovered URLs
3413
+ * Success/error status
3414
+
3415
+ Raises:
3416
+ Exception: If mapping fails
3417
+ """
3418
+ map_params = {}
3419
+ if params:
3420
+ map_params.update(params.dict(exclude_none=True))
3421
+
3422
+ # Add individual parameters
3423
+ if search is not None:
3424
+ map_params['search'] = search
3425
+ if ignore_sitemap is not None:
3426
+ map_params['ignoreSitemap'] = ignore_sitemap
3427
+ if include_subdomains is not None:
3428
+ map_params['includeSubdomains'] = include_subdomains
3429
+ if sitemap_only is not None:
3430
+ map_params['sitemapOnly'] = sitemap_only
3431
+ if limit is not None:
3432
+ map_params['limit'] = limit
3433
+ if timeout is not None:
3434
+ map_params['timeout'] = timeout
3435
+
3436
+ # Create final params object
3437
+ final_params = MapParams(**map_params)
3438
+ params_dict = final_params.dict(exclude_none=True)
3439
+ params_dict['url'] = url
3440
+ params_dict['origin'] = f"python-sdk@{version}"
3441
+
3442
+ # Make request
3443
+ endpoint = f'/v1/map'
3444
+ response = await self._async_post_request(
3445
+ f'{self.api_url}{endpoint}',
3446
+ params_dict,
3447
+ headers={"Authorization": f"Bearer {self.api_key}"}
3448
+ )
3449
+
3450
+ if response.get('success') and 'links' in response:
3451
+ return MapResponse(**response)
3452
+ elif 'error' in response:
3453
+ raise Exception(f'Failed to map URL. Error: {response["error"]}')
3454
+ else:
3455
+ raise Exception(f'Failed to map URL. Error: {response}')
3456
+
3457
+ async def extract(
3458
+ self,
3459
+ urls: Optional[List[str]] = None,
3460
+ *,
3461
+ prompt: Optional[str] = None,
3462
+ schema: Optional[Any] = None,
3463
+ system_prompt: Optional[str] = None,
3464
+ allow_external_links: Optional[bool] = False,
3465
+ enable_web_search: Optional[bool] = False,
3466
+ show_sources: Optional[bool] = False,
3467
+ agent: Optional[Dict[str, Any]] = None) -> ExtractResponse[Any]:
3468
+
3469
+ """
3470
+ Asynchronously extract structured information from URLs.
3471
+
3472
+ Args:
3473
+ urls (Optional[List[str]]): URLs to extract from
3474
+ prompt (Optional[str]): Custom extraction prompt
3475
+ schema (Optional[Any]): JSON schema/Pydantic model
3476
+ system_prompt (Optional[str]): System context
3477
+ allow_external_links (Optional[bool]): Follow external links
3478
+ enable_web_search (Optional[bool]): Enable web search
3479
+ show_sources (Optional[bool]): Include source URLs
3480
+ agent (Optional[Dict[str, Any]]): Agent configuration
3481
+
3482
+ Returns:
3483
+ ExtractResponse with:
3484
+ * Structured data matching schema
3485
+ * Source information if requested
3486
+ * Success/error status
3487
+
3488
+ Raises:
3489
+ ValueError: If prompt/schema missing or extraction fails
3490
+ """
3491
+ headers = self._prepare_headers()
3492
+
3493
+ if not prompt and not schema:
3494
+ raise ValueError("Either prompt or schema is required")
3495
+
3496
+ if not urls and not prompt:
3497
+ raise ValueError("Either urls or prompt is required")
3498
+
3499
+ if schema:
3500
+ if hasattr(schema, 'model_json_schema'):
3501
+ # Convert Pydantic model to JSON schema
3502
+ schema = schema.model_json_schema()
3503
+ # Otherwise assume it's already a JSON schema dict
3504
+
3505
+ request_data = {
3506
+ 'urls': urls or [],
3507
+ 'allowExternalLinks': allow_external_links,
3508
+ 'enableWebSearch': enable_web_search,
3509
+ 'showSources': show_sources,
3510
+ 'schema': schema,
3511
+ 'origin': f'python-sdk@{get_version()}'
3512
+ }
3513
+
3514
+ # Only add prompt and systemPrompt if they exist
3515
+ if prompt:
3516
+ request_data['prompt'] = prompt
3517
+ if system_prompt:
3518
+ request_data['systemPrompt'] = system_prompt
3519
+
3520
+ if agent:
3521
+ request_data['agent'] = agent
3522
+
3523
+ response = await self._async_post_request(
3524
+ f'{self.api_url}/v1/extract',
3525
+ request_data,
3526
+ headers
3527
+ )
3528
+
3529
+ if response.get('success'):
3530
+ job_id = response.get('id')
3531
+ if not job_id:
3532
+ raise Exception('Job ID not returned from extract request.')
3533
+
3534
+ while True:
3535
+ status_data = await self._async_get_request(
3536
+ f'{self.api_url}/v1/extract/{job_id}',
3537
+ headers
3538
+ )
3539
+
3540
+ if status_data['status'] == 'completed':
3541
+ return ExtractResponse(**status_data)
3542
+ elif status_data['status'] in ['failed', 'cancelled']:
3543
+ raise Exception(f'Extract job {status_data["status"]}. Error: {status_data["error"]}')
3544
+
3545
+ await asyncio.sleep(2)
3546
+ else:
3547
+ raise Exception(f'Failed to extract. Error: {response.get("error")}')
3548
+
3549
+ async def check_batch_scrape_status(self, id: str) -> BatchScrapeStatusResponse:
3550
+ """
3551
+ Check the status of an asynchronous batch scrape job.
3552
+
3553
+ Args:
3554
+ id (str): The ID of the batch scrape job
3555
+
3556
+ Returns:
3557
+ BatchScrapeStatusResponse containing:
3558
+ Status Information:
3559
+ * status - Current state (scraping/completed/failed/cancelled)
3560
+ * completed - Number of URLs scraped
3561
+ * total - Total URLs to scrape
3562
+ * creditsUsed - API credits consumed
3563
+ * expiresAt - Data expiration timestamp
3564
+
3565
+ Results:
3566
+ * data - List of scraped documents
3567
+ * next - URL for next page of results (if paginated)
3568
+ * success - Whether status check succeeded
3569
+ * error - Error message if failed
3570
+
3571
+ Raises:
3572
+ Exception: If status check fails
3573
+ """
3574
+ headers = self._prepare_headers()
3575
+ endpoint = f'/v1/batch/scrape/{id}'
3576
+
3577
+ status_data = await self._async_get_request(
3578
+ f'{self.api_url}{endpoint}',
3579
+ headers
3580
+ )
3581
+
3582
+ if status_data['status'] == 'completed':
3583
+ if 'data' in status_data:
3584
+ data = status_data['data']
3585
+ while 'next' in status_data:
3586
+ if len(status_data['data']) == 0:
3587
+ break
3588
+ next_url = status_data.get('next')
3589
+ if not next_url:
3590
+ logger.warning("Expected 'next' URL is missing.")
3591
+ break
3592
+ next_data = await self._async_get_request(next_url, headers)
3593
+ data.extend(next_data.get('data', []))
3594
+ status_data = next_data
3595
+ status_data['data'] = data
3596
+
3597
+ response = BatchScrapeStatusResponse(
3598
+ status=status_data.get('status'),
3599
+ total=status_data.get('total'),
3600
+ completed=status_data.get('completed'),
3601
+ creditsUsed=status_data.get('creditsUsed'),
3602
+ expiresAt=status_data.get('expiresAt'),
3603
+ data=status_data.get('data')
3604
+ )
3605
+
3606
+ if 'error' in status_data:
3607
+ response['error'] = status_data['error']
3608
+
3609
+ if 'next' in status_data:
3610
+ response['next'] = status_data['next']
3611
+
3612
+ return {
3613
+ 'success': False if 'error' in status_data else True,
3614
+ **response
3615
+ }
3616
+
3617
+ async def check_batch_scrape_errors(self, id: str) -> CrawlErrorsResponse:
3618
+ """
3619
+ Get information about errors from an asynchronous batch scrape job.
3620
+
3621
+ Args:
3622
+ id (str): The ID of the batch scrape job
3623
+
3624
+ Returns:
3625
+ CrawlErrorsResponse containing:
3626
+ errors (List[Dict[str, str]]): List of errors with fields:
3627
+ * id (str): Error ID
3628
+ * timestamp (str): When the error occurred
3629
+ * url (str): URL that caused the error
3630
+ * error (str): Error message
3631
+ * robotsBlocked (List[str]): List of URLs blocked by robots.txt
3632
+
3633
+ Raises:
3634
+ Exception: If error check fails
3635
+ """
3636
+ headers = self._prepare_headers()
3637
+ return await self._async_get_request(
3638
+ f'{self.api_url}/v1/batch/scrape/{id}/errors',
3639
+ headers
3640
+ )
3641
+
3642
+ async def check_crawl_errors(self, id: str) -> CrawlErrorsResponse:
3643
+ """
3644
+ Get information about errors from an asynchronous crawl job.
3645
+
3646
+ Args:
3647
+ id (str): The ID of the crawl job
3648
+
3649
+ Returns:
3650
+ CrawlErrorsResponse containing:
3651
+ * errors (List[Dict[str, str]]): List of errors with fields:
3652
+ - id (str): Error ID
3653
+ - timestamp (str): When the error occurred
3654
+ - url (str): URL that caused the error
3655
+ - error (str): Error message
3656
+ * robotsBlocked (List[str]): List of URLs blocked by robots.txt
3657
+
3658
+ Raises:
3659
+ Exception: If error check fails
3660
+ """
3661
+ headers = self._prepare_headers()
3662
+ return await self._async_get_request(
3663
+ f'{self.api_url}/v1/crawl/{id}/errors',
3664
+ headers
3665
+ )
3666
+
3667
+ async def cancel_crawl(self, id: str) -> Dict[str, Any]:
3668
+ """
3669
+ Cancel an asynchronous crawl job.
3670
+
3671
+ Args:
3672
+ id (str): The ID of the crawl job to cancel
3673
+
3674
+ Returns:
3675
+ Dict[str, Any] containing:
3676
+ * success (bool): Whether cancellation was successful
3677
+ * error (str, optional): Error message if cancellation failed
3678
+
3679
+ Raises:
3680
+ Exception: If cancellation fails
3681
+ """
3682
+ headers = self._prepare_headers()
3683
+ async with aiohttp.ClientSession() as session:
3684
+ async with session.delete(f'{self.api_url}/v1/crawl/{id}', headers=headers) as response:
3685
+ return await response.json()
3686
+
3687
+ async def get_extract_status(self, job_id: str) -> ExtractResponse[Any]:
3688
+ """
3689
+ Check the status of an asynchronous extraction job.
3690
+
3691
+ Args:
3692
+ job_id (str): The ID of the extraction job
3693
+
3694
+ Returns:
3695
+ ExtractResponse[Any] with:
3696
+ * success (bool): Whether request succeeded
3697
+ * data (Optional[Any]): Extracted data matching schema
3698
+ * error (Optional[str]): Error message if any
3699
+ * warning (Optional[str]): Warning message if any
3700
+ * sources (Optional[List[str]]): Source URLs if requested
3701
+
3702
+ Raises:
3703
+ ValueError: If status check fails
3704
+ """
3705
+ headers = self._prepare_headers()
3706
+ try:
3707
+ return await self._async_get_request(
3708
+ f'{self.api_url}/v1/extract/{job_id}',
3709
+ headers
3710
+ )
3711
+ except Exception as e:
3712
+ raise ValueError(str(e))
3713
+
3714
+ async def async_extract(
3715
+ self,
3716
+ urls: Optional[List[str]] = None,
3717
+ *,
3718
+ prompt: Optional[str] = None,
3719
+ schema: Optional[Any] = None,
3720
+ system_prompt: Optional[str] = None,
3721
+ allow_external_links: Optional[bool] = False,
3722
+ enable_web_search: Optional[bool] = False,
3723
+ show_sources: Optional[bool] = False,
3724
+ agent: Optional[Dict[str, Any]] = None) -> ExtractResponse[Any]:
3725
+ """
3726
+ Initiate an asynchronous extraction job without waiting for completion.
3727
+
3728
+ Args:
3729
+ urls (Optional[List[str]]): URLs to extract from
3730
+ prompt (Optional[str]): Custom extraction prompt
3731
+ schema (Optional[Any]): JSON schema/Pydantic model
3732
+ system_prompt (Optional[str]): System context
3733
+ allow_external_links (Optional[bool]): Follow external links
3734
+ enable_web_search (Optional[bool]): Enable web search
3735
+ show_sources (Optional[bool]): Include source URLs
3736
+ agent (Optional[Dict[str, Any]]): Agent configuration
3737
+ idempotency_key (Optional[str]): Unique key to prevent duplicate requests
3738
+
3739
+ Returns:
3740
+ ExtractResponse[Any] with:
3741
+ * success (bool): Whether request succeeded
3742
+ * data (Optional[Any]): Extracted data matching schema
3743
+ * error (Optional[str]): Error message if any
3744
+
3745
+ Raises:
3746
+ ValueError: If job initiation fails
3747
+ """
3748
+ headers = self._prepare_headers()
3749
+
3750
+ if not prompt and not schema:
3751
+ raise ValueError("Either prompt or schema is required")
3752
+
3753
+ if not urls and not prompt:
3754
+ raise ValueError("Either urls or prompt is required")
3755
+
3756
+ if schema:
3757
+ if hasattr(schema, 'model_json_schema'):
3758
+ schema = schema.model_json_schema()
3759
+
3760
+ request_data = ExtractResponse(
3761
+ urls=urls or [],
3762
+ allowExternalLinks=allow_external_links,
3763
+ enableWebSearch=enable_web_search,
3764
+ showSources=show_sources,
3765
+ schema=schema,
3766
+ origin=f'python-sdk@{version}'
3767
+ )
3768
+
3769
+ if prompt:
3770
+ request_data['prompt'] = prompt
3771
+ if system_prompt:
3772
+ request_data['systemPrompt'] = system_prompt
3773
+ if agent:
3774
+ request_data['agent'] = agent
3775
+
3776
+ try:
3777
+ return await self._async_post_request(
3778
+ f'{self.api_url}/v1/extract',
3779
+ request_data,
3780
+ headers
3781
+ )
3782
+ except Exception as e:
3783
+ raise ValueError(str(e))
3784
+
3785
+ async def generate_llms_text(
3786
+ self,
3787
+ url: str,
3788
+ *,
3789
+ max_urls: Optional[int] = None,
3790
+ show_full_text: Optional[bool] = None,
3791
+ experimental_stream: Optional[bool] = None) -> GenerateLLMsTextStatusResponse:
3792
+ """
3793
+ Generate LLMs.txt for a given URL and monitor until completion.
3794
+
3795
+ Args:
3796
+ url (str): Target URL to generate LLMs.txt from
3797
+ max_urls (Optional[int]): Maximum URLs to process (default: 10)
3798
+ show_full_text (Optional[bool]): Include full text in output (default: False)
3799
+ experimental_stream (Optional[bool]): Enable experimental streaming
3800
+
3801
+ Returns:
3802
+ GenerateLLMsTextStatusResponse containing:
3803
+ * success (bool): Whether generation completed successfully
3804
+ * status (str): Status of generation (processing/completed/failed)
3805
+ * data (Dict[str, str], optional): Generated text with fields:
3806
+ - llmstxt (str): Generated LLMs.txt content
3807
+ - llmsfulltxt (str, optional): Full version if requested
3808
+ * error (str, optional): Error message if generation failed
3809
+ * expiresAt (str): When the generated data expires
3810
+
3811
+ Raises:
3812
+ Exception: If generation fails
3813
+ """
3814
+ params = {}
3815
+ if max_urls is not None:
3816
+ params['maxUrls'] = max_urls
3817
+ if show_full_text is not None:
3818
+ params['showFullText'] = show_full_text
3819
+ if experimental_stream is not None:
3820
+ params['__experimental_stream'] = experimental_stream
3821
+
3822
+ response = await self.async_generate_llms_text(
3823
+ url,
3824
+ max_urls=max_urls,
3825
+ show_full_text=show_full_text,
3826
+ experimental_stream=experimental_stream
3827
+ )
3828
+ if not response.get('success') or 'id' not in response:
3829
+ return response
3830
+
3831
+ job_id = response['id']
3832
+ while True:
3833
+ status = await self.check_generate_llms_text_status(job_id)
3834
+
3835
+ if status['status'] == 'completed':
3836
+ return status
3837
+ elif status['status'] == 'failed':
3838
+ raise Exception(f'LLMs.txt generation failed. Error: {status.get("error")}')
3839
+ elif status['status'] != 'processing':
3840
+ break
3841
+
3842
+ await asyncio.sleep(2)
3843
+
3844
+ return GenerateLLMsTextStatusResponse(success=False, error='LLMs.txt generation job terminated unexpectedly')
3845
+
3846
+ async def async_generate_llms_text(
3847
+ self,
3848
+ url: str,
3849
+ *,
3850
+ max_urls: Optional[int] = None,
3851
+ show_full_text: Optional[bool] = None,
3852
+ experimental_stream: Optional[bool] = None) -> GenerateLLMsTextResponse:
3853
+ """
3854
+ Initiate an asynchronous LLMs.txt generation job without waiting for completion.
3855
+
3856
+ Args:
3857
+ url (str): Target URL to generate LLMs.txt from
3858
+ max_urls (Optional[int]): Maximum URLs to process (default: 10)
3859
+ show_full_text (Optional[bool]): Include full text in output (default: False)
3860
+ experimental_stream (Optional[bool]): Enable experimental streaming
3861
+
3862
+ Returns:
3863
+ GenerateLLMsTextResponse containing:
3864
+ * success (bool): Whether job started successfully
3865
+ * id (str): Unique identifier for the job
3866
+ * error (str, optional): Error message if start failed
3867
+
3868
+ Raises:
3869
+ ValueError: If job initiation fails
3870
+ """
3871
+ params = {}
3872
+ if max_urls is not None:
3873
+ params['maxUrls'] = max_urls
3874
+ if show_full_text is not None:
3875
+ params['showFullText'] = show_full_text
3876
+ if experimental_stream is not None:
3877
+ params['__experimental_stream'] = experimental_stream
3878
+
3879
+ params = GenerateLLMsTextParams(
3880
+ maxUrls=max_urls,
3881
+ showFullText=show_full_text,
3882
+ __experimental_stream=experimental_stream
3883
+ )
3884
+
3885
+ headers = self._prepare_headers()
3886
+ json_data = {'url': url, **params.dict(exclude_none=True)}
3887
+ json_data['origin'] = f"python-sdk@{version}"
3888
+
3889
+ try:
3890
+ return await self._async_post_request(
3891
+ f'{self.api_url}/v1/llmstxt',
3892
+ json_data,
3893
+ headers
3894
+ )
3895
+ except Exception as e:
3896
+ raise ValueError(str(e))
3897
+
3898
+ async def check_generate_llms_text_status(self, id: str) -> GenerateLLMsTextStatusResponse:
3899
+ """
3900
+ Check the status of an asynchronous LLMs.txt generation job.
3901
+
3902
+ Args:
3903
+ id (str): The ID of the generation job
3904
+
3905
+ Returns:
3906
+ GenerateLLMsTextStatusResponse containing:
3907
+ * success (bool): Whether generation completed successfully
3908
+ * status (str): Status of generation (processing/completed/failed)
3909
+ * data (Dict[str, str], optional): Generated text with fields:
3910
+ - llmstxt (str): Generated LLMs.txt content
3911
+ - llmsfulltxt (str, optional): Full version if requested
3912
+ * error (str, optional): Error message if generation failed
3913
+ * expiresAt (str): When the generated data expires
3914
+
3915
+ Raises:
3916
+ ValueError: If status check fails
3917
+ """
3918
+ headers = self._prepare_headers()
3919
+ try:
3920
+ return await self._async_get_request(
3921
+ f'{self.api_url}/v1/llmstxt/{id}',
3922
+ headers
3923
+ )
3924
+ except Exception as e:
3925
+ raise ValueError(str(e))
3926
+
3927
+ async def deep_research(
3928
+ self,
3929
+ query: str,
3930
+ *,
3931
+ max_depth: Optional[int] = None,
3932
+ time_limit: Optional[int] = None,
3933
+ max_urls: Optional[int] = None,
3934
+ analysis_prompt: Optional[str] = None,
3935
+ system_prompt: Optional[str] = None,
3936
+ __experimental_stream_steps: Optional[bool] = None,
3937
+ on_activity: Optional[Callable[[Dict[str, Any]], None]] = None,
3938
+ on_source: Optional[Callable[[Dict[str, Any]], None]] = None) -> DeepResearchStatusResponse:
3939
+ """
3940
+ Initiates a deep research operation on a given query and polls until completion.
3941
+
3942
+ Args:
3943
+ query (str): Research query or topic to investigate
3944
+ max_depth (Optional[int]): Maximum depth of research exploration
3945
+ time_limit (Optional[int]): Time limit in seconds for research
3946
+ max_urls (Optional[int]): Maximum number of URLs to process
3947
+ analysis_prompt (Optional[str]): Custom prompt for analysis
3948
+ system_prompt (Optional[str]): Custom system prompt
3949
+ __experimental_stream_steps (Optional[bool]): Enable experimental streaming
3950
+ on_activity (Optional[Callable]): Progress callback receiving {type, status, message, timestamp, depth}
3951
+ on_source (Optional[Callable]): Source discovery callback receiving {url, title, description}
3952
+
3953
+ Returns:
3954
+ DeepResearchStatusResponse containing:
3955
+ * success (bool): Whether research completed successfully
3956
+ * status (str): Current state (processing/completed/failed)
3957
+ * error (Optional[str]): Error message if failed
3958
+ * id (str): Unique identifier for the research job
3959
+ * data (Any): Research findings and analysis
3960
+ * sources (List[Dict]): List of discovered sources
3961
+ * activities (List[Dict]): Research progress log
3962
+ * summaries (List[str]): Generated research summaries
3963
+
3964
+ Raises:
3965
+ Exception: If research fails
3966
+ """
3967
+ research_params = {}
3968
+ if max_depth is not None:
3969
+ research_params['maxDepth'] = max_depth
3970
+ if time_limit is not None:
3971
+ research_params['timeLimit'] = time_limit
3972
+ if max_urls is not None:
3973
+ research_params['maxUrls'] = max_urls
3974
+ if analysis_prompt is not None:
3975
+ research_params['analysisPrompt'] = analysis_prompt
3976
+ if system_prompt is not None:
3977
+ research_params['systemPrompt'] = system_prompt
3978
+ if __experimental_stream_steps is not None:
3979
+ research_params['__experimental_streamSteps'] = __experimental_stream_steps
3980
+ research_params = DeepResearchParams(**research_params)
3981
+
3982
+ response = await self.async_deep_research(
3983
+ query,
3984
+ max_depth=max_depth,
3985
+ time_limit=time_limit,
3986
+ max_urls=max_urls,
3987
+ analysis_prompt=analysis_prompt,
3988
+ system_prompt=system_prompt
3989
+ )
3990
+ if not response.get('success') or 'id' not in response:
3991
+ return response
3992
+
3993
+ job_id = response['id']
3994
+ last_activity_count = 0
3995
+ last_source_count = 0
3996
+
3997
+ while True:
3998
+ status = await self.check_deep_research_status(job_id)
3999
+
4000
+ if on_activity and 'activities' in status:
4001
+ new_activities = status['activities'][last_activity_count:]
4002
+ for activity in new_activities:
4003
+ on_activity(activity)
4004
+ last_activity_count = len(status['activities'])
4005
+
4006
+ if on_source and 'sources' in status:
4007
+ new_sources = status['sources'][last_source_count:]
4008
+ for source in new_sources:
4009
+ on_source(source)
4010
+ last_source_count = len(status['sources'])
4011
+
4012
+ if status['status'] == 'completed':
4013
+ return status
4014
+ elif status['status'] == 'failed':
4015
+ raise Exception(f'Deep research failed. Error: {status.get("error")}')
4016
+ elif status['status'] != 'processing':
4017
+ break
4018
+
4019
+ await asyncio.sleep(2)
4020
+
4021
+ return DeepResearchStatusResponse(success=False, error='Deep research job terminated unexpectedly')
4022
+
4023
+ async def async_deep_research(
4024
+ self,
4025
+ query: str,
4026
+ *,
4027
+ max_depth: Optional[int] = None,
4028
+ time_limit: Optional[int] = None,
4029
+ max_urls: Optional[int] = None,
4030
+ analysis_prompt: Optional[str] = None,
4031
+ system_prompt: Optional[str] = None,
4032
+ __experimental_stream_steps: Optional[bool] = None) -> Dict[str, Any]:
4033
+ """
4034
+ Initiates an asynchronous deep research operation.
4035
+
4036
+ Args:
4037
+ query (str): Research query or topic to investigate
4038
+ max_depth (Optional[int]): Maximum depth of research exploration
4039
+ time_limit (Optional[int]): Time limit in seconds for research
4040
+ max_urls (Optional[int]): Maximum number of URLs to process
4041
+ analysis_prompt (Optional[str]): Custom prompt for analysis
4042
+ system_prompt (Optional[str]): Custom system prompt
4043
+ __experimental_stream_steps (Optional[bool]): Enable experimental streaming
4044
+
4045
+ Returns:
4046
+ Dict[str, Any]: A response containing:
4047
+ * success (bool): Whether the research initiation was successful
4048
+ * id (str): The unique identifier for the research job
4049
+ * error (str, optional): Error message if initiation failed
4050
+
4051
+ Raises:
4052
+ Exception: If the research initiation fails.
4053
+ """
4054
+ research_params = {}
4055
+ if max_depth is not None:
4056
+ research_params['maxDepth'] = max_depth
4057
+ if time_limit is not None:
4058
+ research_params['timeLimit'] = time_limit
4059
+ if max_urls is not None:
4060
+ research_params['maxUrls'] = max_urls
4061
+ if analysis_prompt is not None:
4062
+ research_params['analysisPrompt'] = analysis_prompt
4063
+ if system_prompt is not None:
4064
+ research_params['systemPrompt'] = system_prompt
4065
+ if __experimental_stream_steps is not None:
4066
+ research_params['__experimental_streamSteps'] = __experimental_stream_steps
4067
+ research_params = DeepResearchParams(**research_params)
4068
+
4069
+ headers = self._prepare_headers()
4070
+
4071
+ json_data = {'query': query, **research_params.dict(exclude_none=True)}
4072
+ json_data['origin'] = f"python-sdk@{version}"
4073
+
4074
+ try:
4075
+ return await self._async_post_request(
4076
+ f'{self.api_url}/v1/deep-research',
4077
+ json_data,
4078
+ headers
4079
+ )
4080
+ except Exception as e:
4081
+ raise ValueError(str(e))
4082
+
4083
+ async def check_deep_research_status(self, id: str) -> DeepResearchStatusResponse:
4084
+ """
4085
+ Check the status of a deep research operation.
4086
+
4087
+ Args:
4088
+ id (str): The ID of the deep research operation.
4089
+
4090
+ Returns:
4091
+ DeepResearchResponse containing:
4092
+
4093
+ Status:
4094
+ * success - Whether research completed successfully
4095
+ * status - Current state (processing/completed/failed)
4096
+ * error - Error message if failed
4097
+
4098
+ Results:
4099
+ * id - Unique identifier for the research job
4100
+ * data - Research findings and analysis
4101
+ * sources - List of discovered sources
4102
+ * activities - Research progress log
4103
+ * summaries - Generated research summaries
4104
+
4105
+ Raises:
4106
+ Exception: If the status check fails.
4107
+ """
4108
+ headers = self._prepare_headers()
4109
+ try:
4110
+ return await self._async_get_request(
4111
+ f'{self.api_url}/v1/deep-research/{id}',
4112
+ headers
4113
+ )
4114
+ except Exception as e:
4115
+ raise ValueError(str(e))
4116
+
4117
+ async def search(
4118
+ self,
4119
+ query: str,
4120
+ *,
4121
+ limit: Optional[int] = None,
4122
+ tbs: Optional[str] = None,
4123
+ filter: Optional[str] = None,
4124
+ lang: Optional[str] = None,
4125
+ country: Optional[str] = None,
4126
+ location: Optional[str] = None,
4127
+ timeout: Optional[int] = None,
4128
+ scrape_options: Optional[ScrapeOptions] = None,
4129
+ params: Optional[Union[Dict[str, Any], SearchParams]] = None,
4130
+ **kwargs) -> SearchResponse:
4131
+ """
4132
+ Asynchronously search for content using Firecrawl.
4133
+
4134
+ Args:
4135
+ query (str): Search query string
4136
+ limit (Optional[int]): Max results (default: 5)
4137
+ tbs (Optional[str]): Time filter (e.g. "qdr:d")
4138
+ filter (Optional[str]): Custom result filter
4139
+ lang (Optional[str]): Language code (default: "en")
4140
+ country (Optional[str]): Country code (default: "us")
4141
+ location (Optional[str]): Geo-targeting
4142
+ timeout (Optional[int]): Request timeout in milliseconds
4143
+ scrape_options (Optional[ScrapeOptions]): Result scraping configuration
4144
+ params (Optional[Union[Dict[str, Any], SearchParams]]): Additional search parameters
4145
+ **kwargs: Additional keyword arguments for future compatibility
4146
+
4147
+ Returns:
4148
+ SearchResponse: Response containing:
4149
+ * success (bool): Whether request succeeded
4150
+ * data (List[FirecrawlDocument]): Search results
4151
+ * warning (Optional[str]): Warning message if any
4152
+ * error (Optional[str]): Error message if any
4153
+
4154
+ Raises:
4155
+ Exception: If search fails or response cannot be parsed
4156
+ """
4157
+ # Build search parameters
4158
+ search_params = {}
4159
+ if params:
4160
+ if isinstance(params, dict):
4161
+ search_params.update(params)
4162
+ else:
4163
+ search_params.update(params.dict(exclude_none=True))
4164
+
4165
+ # Add individual parameters
4166
+ if limit is not None:
4167
+ search_params['limit'] = limit
4168
+ if tbs is not None:
4169
+ search_params['tbs'] = tbs
4170
+ if filter is not None:
4171
+ search_params['filter'] = filter
4172
+ if lang is not None:
4173
+ search_params['lang'] = lang
4174
+ if country is not None:
4175
+ search_params['country'] = country
4176
+ if location is not None:
4177
+ search_params['location'] = location
4178
+ if timeout is not None:
4179
+ search_params['timeout'] = timeout
4180
+ if scrape_options is not None:
4181
+ search_params['scrapeOptions'] = scrape_options.dict(exclude_none=True)
4182
+
4183
+ # Add any additional kwargs
4184
+ search_params.update(kwargs)
4185
+
4186
+ # Create final params object
4187
+ final_params = SearchParams(query=query, **search_params)
4188
+ params_dict = final_params.dict(exclude_none=True)
4189
+ params_dict['origin'] = f"python-sdk@{version}"
4190
+
4191
+ return await self._async_post_request(
4192
+ f"{self.api_url}/v1/search",
4193
+ params_dict,
4194
+ {"Authorization": f"Bearer {self.api_key}"}
4195
+ )
4196
+
4197
+ class AsyncCrawlWatcher(CrawlWatcher):
4198
+ """
4199
+ Async version of CrawlWatcher that properly handles async operations.
4200
+ """
4201
+ def __init__(self, id: str, app: AsyncFirecrawlApp):
4202
+ super().__init__(id, app)
4203
+
4204
+ async def connect(self) -> None:
4205
+ """
4206
+ Establishes async WebSocket connection and starts listening for messages.
4207
+ """
4208
+ async with websockets.connect(
4209
+ self.ws_url,
4210
+ additional_headers=[("Authorization", f"Bearer {self.app.api_key}")]
4211
+ ) as websocket:
4212
+ await self._listen(websocket)
4213
+
4214
+ async def _listen(self, websocket) -> None:
4215
+ """
4216
+ Listens for incoming WebSocket messages and handles them asynchronously.
4217
+
4218
+ Args:
4219
+ websocket: The WebSocket connection object
4220
+ """
4221
+ async for message in websocket:
4222
+ msg = json.loads(message)
4223
+ await self._handle_message(msg)
4224
+
4225
+ async def _handle_message(self, msg: Dict[str, Any]) -> None:
4226
+ """
4227
+ Handles incoming WebSocket messages based on their type asynchronously.
4228
+
4229
+ Args:
4230
+ msg (Dict[str, Any]): The message to handle
4231
+ """
4232
+ if msg['type'] == 'done':
4233
+ self.status = 'completed'
4234
+ self.dispatch_event('done', {'status': self.status, 'data': self.data, 'id': self.id})
4235
+ elif msg['type'] == 'error':
4236
+ self.status = 'failed'
4237
+ self.dispatch_event('error', {'status': self.status, 'data': self.data, 'error': msg['error'], 'id': self.id})
4238
+ elif msg['type'] == 'catchup':
4239
+ self.status = msg['data']['status']
4240
+ self.data.extend(msg['data'].get('data', []))
4241
+ for doc in self.data:
4242
+ self.dispatch_event('document', {'data': doc, 'id': self.id})
4243
+ elif msg['type'] == 'document':
4244
+ self.data.append(msg['data'])
4245
+ self.dispatch_event('document', {'data': msg['data'], 'id': self.id})
4246
+
4247
+ async def _handle_error(self, response: aiohttp.ClientResponse, action: str) -> None:
4248
+ """
4249
+ Handle errors from async API responses.
4250
+ """
4251
+ try:
4252
+ error_data = await response.json()
4253
+ error_message = error_data.get('error', 'No error message provided.')
4254
+ error_details = error_data.get('details', 'No additional error details provided.')
4255
+ except:
4256
+ raise aiohttp.ClientError(f'Failed to parse Firecrawl error response as JSON. Status code: {response.status}')
4257
+
4258
+ # Use the app's method to get the error message
4259
+ message = await self.app._get_async_error_message(response.status, action, error_message, error_details)
4260
+
4261
+ raise aiohttp.ClientError(message)
4262
+
4263
+ async def _get_async_error_message(self, status_code: int, action: str, error_message: str, error_details: str) -> str:
4264
+ """
4265
+ Generate a standardized error message based on HTTP status code for async operations.
4266
+
4267
+ Args:
4268
+ status_code (int): The HTTP status code from the response
4269
+ action (str): Description of the action that was being performed
4270
+ error_message (str): The error message from the API response
4271
+ error_details (str): Additional error details from the API response
4272
+
4273
+ Returns:
4274
+ str: A formatted error message
4275
+ """
4276
+ return self._get_error_message(status_code, action, error_message, error_details)