Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
Merge branch 'main' into v1/llm-extract
Nicolas0732997a1385
diff --cc apps/api/src/controllers/v1/types.tsindex 0db8c78d3,12d1c5011..4049dbda6--- a/apps/api/src/controllers/v1/types.ts+++ b/apps/api/src/controllers/v1/types.ts@@@ -327,16 -291,9 +327,18 @@@ export function legacyScrapeOptions(x:};}+export function legacyExtractorOptions(x: ExtractOptions): ExtractorOptions {+ return {+ mode: x.mode ? "llm-extraction" : "markdown",+ extractionPrompt: x.prompt ?? "Based on the information on the page, extract the information from the schema.",+ extractionSchema: x.schema,+ userPrompt: x.prompt ?? "",+ };+}+export function legacyDocumentConverter(doc: any): Document {+ if (doc === null || doc === undefined) return doc;+if (doc.metadata) {if (doc.metadata.screenshot) {doc.screenshot = doc.metadata.screenshot;diff --cc apps/js-sdk/firecrawl/build/cjs/index.jsindex 4f7c531fa,7b0730f5f..31bb27150--- a/apps/js-sdk/firecrawl/build/cjs/index.js+++ b/apps/js-sdk/firecrawl/build/cjs/index.js@@@ -50,22 -49,8 +49,22 @@@ class FirecrawlApp},};}+ else if (this.version === 'v1' && jsonData?.extract?.schema) {+ let schema = jsonData.extract.schema;+ // Check if schema is an instance of ZodSchema to correctly identify Zod schemas+ if (schema instanceof zod_1.z.ZodSchema) {+ schema = (0, zod_to_json_schema_1.zodToJsonSchema)(schema);+ }+ jsonData = {+ ...jsonData,+ extract: {+ ...jsonData.extract,+ schema: schema,+ },+ };+ }try {- const response = await axios_1.default.post(this.apiUrl + `/${this.version}/scrape`, jsonData, { headers });+ const response = await axios_1.default.post(this.apiUrl + `/v1/scrape`, jsonData, { headers });if (response.status === 200) {const responseData = response.data;if (responseData.success) {diff --cc apps/js-sdk/firecrawl/build/esm/index.jsindex a9aeb92d7,cccd17701..b846e44ba--- a/apps/js-sdk/firecrawl/build/esm/index.js+++ b/apps/js-sdk/firecrawl/build/esm/index.js@@@ -45,22 -43,8 +43,22 @@@ export default class FirecrawlApp},};}+ else if (this.version === 'v1' && jsonData?.extract?.schema) {+ let schema = jsonData.extract.schema;+ // Check if schema is an instance of ZodSchema to correctly identify Zod schemas+ if (schema instanceof z.ZodSchema) {+ schema = zodToJsonSchema(schema);+ }+ jsonData = {+ ...jsonData,+ extract: {+ ...jsonData.extract,+ schema: schema,+ },+ };+ }try {- const response = await axios.post(this.apiUrl + `/${this.version}/scrape`, jsonData, { headers });+ const response = await axios.post(this.apiUrl + `/v1/scrape`, jsonData, { headers });if (response.status === 200) {const responseData = response.data;if (responseData.success) {diff --cc apps/js-sdk/firecrawl/src/index.tsindex 3cdd2a990,586e9240a..cdde4e20e--- a/apps/js-sdk/firecrawl/src/index.ts+++ b/apps/js-sdk/firecrawl/src/index.ts@@@ -75,30 -64,8 +64,9 @@@ export interface FirecrawlDocumenthtml?: string;rawHtml?: string;links?: string[];+ extract?: Record<any, any>;screenshot?: string;- metadata: FirecrawlDocumentMetadata;- }-- /**- * Document interface for Firecrawl on v0.- * Represents a document specifically for API version v0 with additional properties.- */- export interface FirecrawlDocumentV0 {- id?: string;- url?: string;- content: string;- markdown?: string;- html?: string;- llm_extraction?: Record<string, any>;- createdAt?: Date;- updatedAt?: Date;- type?: string;- metadata: FirecrawlDocumentMetadataV0;- childrenLinks?: string[];- provider?: string;- warning?: string;- index?: number;+ metadata?: FirecrawlDocumentMetadata;}/**@@@ -106,43 -73,12 +74,17 @@@* Defines the options and configurations available for scraping web content.*/export interface ScrapeParams {- formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "extract")[];- formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "full@scrennshot")[];++ formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "extract" | "full@scrennshot")[];headers?: Record<string, string>;includeTags?: string[];excludeTags?: string[];onlyMainContent?: boolean;- screenshotMode?: "desktop" | "full-desktop" | "mobile" | "full-mobile";- waitFor?: number;- timeout?: number;- waitFor?: number;+ extract?: {+ prompt?: string;+ schema?: z.ZodSchema | any;+ systemPrompt?: string;+ };- }-- /**- * Parameters for scraping operations on v0.- * Includes page and extractor options specific to API version v0.- */- export interface ScrapeParamsV0 {- pageOptions?: {- headers?: Record<string, string>;- includeHtml?: boolean;- includeRawHtml?: boolean;- onlyIncludeTags?: string[];- onlyMainContent?: boolean;- removeTags?: string[];- replaceAllPathsWithAbsolutePaths?: boolean;- screenshot?: boolean;- fullPageScreenshot?: boolean;- waitFor?: number;- };- extractorOptions?: {- mode?: "markdown" | "llm-extraction" | "llm-extraction-from-raw-html" | "llm-extraction-from-markdown";- extractionPrompt?: string;- extractionSchema?: Record<string, any> | z.ZodSchema | any;- };++ waitFor?: number;timeout?: number;}diff --cc apps/js-sdk/firecrawl/types/index.d.tsindex 2552a1b08,6b5166b39..95e61531f--- a/apps/js-sdk/firecrawl/types/index.d.ts+++ b/apps/js-sdk/firecrawl/types/index.d.ts@@@ -69,73 -58,22 +58,28 @@@ export interface FirecrawlDocumenthtml?: string;rawHtml?: string;links?: string[];+ extract?: Record<any, any>;screenshot?: string;- metadata: FirecrawlDocumentMetadata;- }- /**- * Document interface for Firecrawl on v0.- * Represents a document specifically for API version v0 with additional properties.- */- export interface FirecrawlDocumentV0 {- id?: string;- url?: string;- content: string;- markdown?: string;- html?: string;- llm_extraction?: Record<string, any>;- createdAt?: Date;- updatedAt?: Date;- type?: string;- metadata: FirecrawlDocumentMetadataV0;- childrenLinks?: string[];- provider?: string;- warning?: string;- index?: number;+ metadata?: FirecrawlDocumentMetadata;}/*** Parameters for scraping operations.* Defines the options and configurations available for scraping web content.*/export interface ScrapeParams {- formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "extract")[];- formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "full@scrennshot")[];++ formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "extract" | "full@scrennshot")[];headers?: Record<string, string>;includeTags?: string[];excludeTags?: string[];onlyMainContent?: boolean;- screenshotMode?: "desktop" | "full-desktop" | "mobile" | "full-mobile";waitFor?: number;timeout?: number;+ extract?: {+ prompt?: string;+ schema?: z.ZodSchema | any;+ systemPrompt?: string;+ };}- /**- * Parameters for scraping operations on v0.- * Includes page and extractor options specific to API version v0.- */- export interface ScrapeParamsV0 {- pageOptions?: {- headers?: Record<string, string>;- includeHtml?: boolean;- includeRawHtml?: boolean;- onlyIncludeTags?: string[];- onlyMainContent?: boolean;- removeTags?: string[];- replaceAllPathsWithAbsolutePaths?: boolean;- screenshot?: boolean;- fullPageScreenshot?: boolean;- waitFor?: number;- };- extractorOptions?: {- mode?: "markdown" | "llm-extraction" | "llm-extraction-from-raw-html" | "llm-extraction-from-markdown";- extractionPrompt?: string;- extractionSchema?: Record<string, any> | z.ZodSchema | any;- };- timeout?: number;- }/*** Response interface for scraping operations.* Defines the structure of the response received after a scraping operation.diff --cc apps/python-sdk/example.pyindex 9d439a3b9,efb139391..02c062884--- a/apps/python-sdk/example.py+++ b/apps/python-sdk/example.py@@@ -15,62 -33,97 +33,94 @@@ print(crawl_status# LLM Extraction:# Define schema to extract contents into using pydantic-# from pydantic import BaseModel, Field-# from typing import List--# class ArticleSchema(BaseModel):-# title: str-# points: int-# by: str-# commentsURL: str--# class TopArticlesSchema(BaseModel):-# top: List[ArticleSchema] = Field(..., max_items=5, description="Top 5 stories")--# llm_extraction_result = app.scrape_url('https://news.ycombinator.com', {-# 'extractorOptions': {-# 'extractionSchema': TopArticlesSchema.model_json_schema(),-# 'mode': 'llm-extraction'-# },-# 'pageOptions':{-# 'onlyMainContent': True-# }-# })+from pydantic import BaseModel, Field+from typing import List-# print(llm_extraction_result['llm_extraction'])+class ArticleSchema(BaseModel):+ title: str+ points: int+ by: str+ commentsURL: str++class TopArticlesSchema(BaseModel):+ top: List[ArticleSchema] = Field(..., max_items=5, description="Top 5 stories")++llm_extraction_result = app.scrape_url('https://news.ycombinator.com', {+ 'formats': ['extract'],+ 'extract': {+ 'schema': TopArticlesSchema.model_json_schema()+ }+})++print(llm_extraction_result['extract'])# # Define schema to extract contents into using json schema-# json_schema = {-# "type": "object",-# "properties": {-# "top": {-# "type": "array",-# "items": {-# "type": "object",-# "properties": {-# "title": {"type": "string"},-# "points": {"type": "number"},-# "by": {"type": "string"},-# "commentsURL": {"type": "string"}-# },-# "required": ["title", "points", "by", "commentsURL"]-# },-# "minItems": 5,-# "maxItems": 5,-# "description": "Top 5 stories on Hacker News"-# }-# },-# "required": ["top"]-# }--# llm_extraction_result = app.scrape_url('https://news.ycombinator.com', {-# 'extractorOptions': {-# 'extractionSchema': json_schema,-# 'mode': 'llm-extraction'-# },-# 'pageOptions':{-# 'onlyMainContent': True-# }-# })+json_schema = {+ "type": "object",+ "properties": {+ "top": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "title": {"type": "string"},+ "points": {"type": "number"},+ "by": {"type": "string"},+ "commentsURL": {"type": "string"}+ },+ "required": ["title", "points", "by", "commentsURL"]+ },+ "minItems": 5,+ "maxItems": 5,+ "description": "Top 5 stories on Hacker News"+ }+ },+ "required": ["top"]+}++app2 = FirecrawlApp(api_key="fc-", version="v0")+++llm_extraction_result = app2.scrape_url('https://news.ycombinator.com', {+ 'extractorOptions': {+ 'extractionSchema': json_schema,+ 'mode': 'llm-extraction'+ },+ 'pageOptions':{+ 'onlyMainContent': True+ }+})- print(llm_extraction_result['llm_extraction'])+ # print(llm_extraction_result['llm_extraction'])+++ # Map a website:+ map_result = app.map_url('https://firecrawl.dev', { 'search': 'blog' })+ print(map_result)++ # Crawl a website with WebSockets:+ # inside an async function...+ nest_asyncio.apply()++ # Define event handlers+ def on_document(detail):+ print("DOC", detail)++ def on_error(detail):+ print("ERR", detail['error'])++ def on_done(detail):+ print("DONE", detail['status'])++ # Function to start the crawl and watch process+ async def start_crawl_and_watch():+ # Initiate the crawl job and get the watcher+ watcher = app.crawl_url_and_watch('firecrawl.dev', { 'excludePaths': ['blog/*'], 'limit': 5 })++ # Add event listeners+ watcher.add_event_listener("document", on_document)+ watcher.add_event_listener("error", on_error)+ watcher.add_event_listener("done", on_done)++ # Start the watcher+ await watcher.connect()--# Run the event loop-await start_crawl_and_watch()diff --cc apps/python-sdk/firecrawl/firecrawl.pyindex 4e9a7daba,b7a0bff62..7a7ff5f57--- a/apps/python-sdk/firecrawl/firecrawl.py+++ b/apps/python-sdk/firecrawl/firecrawl.py@@@ -58,33 -59,23 +59,33 @@@ class FirecrawlApp# If there are additional params, process themif params:- # Initialize extractorOptions if present- extractor_options = params.get('extractorOptions', {})- # Check and convert the extractionSchema if it's a Pydantic model- if 'extractionSchema' in extractor_options:- if hasattr(extractor_options['extractionSchema'], 'schema'):- extractor_options['extractionSchema'] = extractor_options['extractionSchema'].schema()- # Ensure 'mode' is set, defaulting to 'llm-extraction' if not explicitly provided- extractor_options['mode'] = extractor_options.get('mode', 'llm-extraction')- # Update the scrape_params with the processed extractorOptions- scrape_params['extractorOptions'] = extractor_options-- # Include any other params directly at the top level of scrape_params- for key, value in params.items():- if key != 'extractorOptions':- scrape_params[key] = value+ if self.version == 'v0':+ # Handle extractorOptions (for v0 compatibility)+ extractor_options = params.get('extractorOptions', {})+ if extractor_options:+ if 'extractionSchema' in extractor_options and hasattr(extractor_options['extractionSchema'], 'schema'):+ extractor_options['extractionSchema'] = extractor_options['extractionSchema'].schema()+ extractor_options['mode'] = extractor_options.get('mode', 'llm-extraction')+ scrape_params['extractorOptions'] = extractor_options++ # Include any other params directly at the top level of scrape_params+ for key, value in params.items():+ if key not in ['extractorOptions']:+ scrape_params[key] = value+ elif self.version == 'v1':+ # Handle extract (for v1)+ extract = params.get('extract', {})+ if extract:+ if 'schema' in extract and hasattr(extract['schema'], 'schema'):+ extract['schema'] = extract['schema'].schema()+ scrape_params['extract'] = extract++ # Include any other params directly at the top level of scrape_params+ for key, value in params.items():+ if key not in ['extract']:+ scrape_params[key] = value- endpoint = f'/{self.version}/scrape'+ endpoint = f'/v1/scrape'# Make the POST request with the prepared headers and JSON dataresponse = requests.post(f'{self.api_url}{endpoint}',