diff --git a/docs/web-tests/py/test_firecrawl.py b/docs/web-tests/py/test_firecrawl.py new file mode 100644 index 000000000..70594539d --- /dev/null +++ b/docs/web-tests/py/test_firecrawl.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import os + +import pytest + + +def require_env(var_name: str) -> str: + """Skip the test unless the required environment variable is provided.""" + value = os.environ.get(var_name) + if not value: + pytest.skip(f"Set {var_name} to run this integration snippet") + return value + + +def test_firecrawl_crawl_and_search() -> None: + require_env("FIRECRAWL_API_KEY") + pytest.importorskip("firecrawl") + pytest.importorskip("sentence_transformers") + + # --8<-- [start:firecrawl_crawl] + import os + + from firecrawl import Firecrawl + + firecrawl = Firecrawl(api_key=os.environ["FIRECRAWL_API_KEY"]) + + crawl = firecrawl.crawl( + "https://docs.lancedb.com/enterprise/v1-14-0/integrations", + limit=10, + scrape_options={"formats": ["markdown"], "only_main_content": True}, + integration="_lancedb", + ) + pages = [page for page in crawl.data if page.markdown] + print(f"Crawled {len(pages)} pages") + # --8<-- [end:firecrawl_crawl] + + assert pages + + # --8<-- [start:firecrawl_chunk] + def chunk_markdown(markdown: str, max_chars: int = 1000) -> list[str]: + chunks, current = [], "" + for paragraph in markdown.split("\n\n"): + if current and len(current) + len(paragraph) > max_chars: + chunks.append(current.strip()) + current = "" + current += paragraph + "\n\n" + if current.strip(): + chunks.append(current.strip()) + return chunks + + # --8<-- [end:firecrawl_chunk] + + # --8<-- [start:firecrawl_table] + import tempfile + + import lancedb + from lancedb.embeddings import get_registry + from lancedb.pydantic import LanceModel, Vector + + embedder = ( + get_registry().get("sentence-transformers").create(name="all-MiniLM-L6-v2") + ) + + class WebChunk(LanceModel): + text: str = embedder.SourceField() + vector: Vector(embedder.ndims()) = embedder.VectorField() + source_url: str + title: str + + rows = [ + { + "text": chunk, + "source_url": page.metadata.source_url, + "title": page.metadata.title or "", + } + for page in pages + for chunk in chunk_markdown(page.markdown) + ] + + db = lancedb.connect(tempfile.mkdtemp(prefix="lancedb-firecrawl-")) + table = db.create_table("firecrawl_docs", schema=WebChunk) + table.add(rows) + print(f"Added {table.count_rows()} chunks") + # --8<-- [end:firecrawl_table] + + assert table.count_rows() == len(rows) > 0 + + # --8<-- [start:firecrawl_query] + results = ( + table.search("How do I query a LanceDB table with SQL?") + .select(["title", "source_url", "text", "_distance"]) + .limit(3) + .to_list() + ) + for row in results: + print(f"{row['_distance']:.3f}", row["source_url"]) + # --8<-- [end:firecrawl_query] + + assert len(results) == 3 + assert all(row["source_url"].startswith("https://") for row in results) + + # --8<-- [start:firecrawl_web_search] + search = firecrawl.search( + "lancedb hybrid search reranking", + limit=5, + scrape_options={"formats": ["markdown"], "only_main_content": True}, + integration="_lancedb", + ) + table.add( + [ + { + "text": chunk, + "source_url": result.metadata.source_url, + "title": result.metadata.title or "", + } + for result in search.web or [] + if getattr(result, "markdown", None) + for chunk in chunk_markdown(result.markdown) + ] + ) + print(f"Table now holds {table.count_rows()} chunks") + # --8<-- [end:firecrawl_web_search] + + assert table.count_rows() > len(rows) + + +def test_firecrawl_search_with_mixed_results(monkeypatch: pytest.MonkeyPatch) -> None: + """Run the examples on canned responses where search mixes plain and scraped results.""" + firecrawl = pytest.importorskip("firecrawl") + pytest.importorskip("sentence_transformers") + from firecrawl.v2.types import ( + CrawlJob, + Document, + DocumentMetadata, + SearchData, + SearchResultWeb, + ) + + def page(url: str, title: str, markdown: str) -> Document: + return Document( + markdown=markdown, + metadata=DocumentMetadata(source_url=url, title=title), + ) + + class FakeFirecrawl: + def __init__(self, api_key: str) -> None: + pass + + def crawl(self, url: str, **kwargs) -> CrawlJob: + return CrawlJob( + status="completed", + total=3, + completed=3, + data=[ + page( + f"https://docs.lancedb.com/{slug}", + slug.title(), + f"# {slug.title()}\n\nLanceDB {slug} guide.", + ) + for slug in ("sql", "search", "indexing") + ], + ) + + def search(self, query: str, **kwargs) -> SearchData: + return SearchData( + web=[ + SearchResultWeb( + url="https://example.com/unscraped", + title="Unscraped result", + ), + page( + "https://example.com/hybrid-search", + "Hybrid search", + "# Hybrid search\n\nReranking LanceDB results.", + ), + ] + ) + + import lancedb + + connections = [] + connect = lancedb.connect + + def recording_connect(*args, **kwargs): + connections.append(connect(*args, **kwargs)) + return connections[-1] + + monkeypatch.setenv("FIRECRAWL_API_KEY", "fc-test") + monkeypatch.setattr(firecrawl, "Firecrawl", FakeFirecrawl) + monkeypatch.setattr(lancedb, "connect", recording_connect) + + test_firecrawl_crawl_and_search() + + source_urls = ( + connections[0].open_table("firecrawl_docs").to_pandas()["source_url"].tolist() + ) + assert len(source_urls) == 4 + assert source_urls.count("https://example.com/hybrid-search") == 1 + assert "https://example.com/unscraped" not in source_urls diff --git a/docs/web/docs.json b/docs/web/docs.json index f74ea17b2..623fe7ab1 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -665,7 +665,8 @@ "integrations/data/pandas_and_pyarrow", "integrations/data/polars_arrow", "integrations/data/dlt", - "integrations/data/voxel51" + "integrations/data/voxel51", + "integrations/data/firecrawl" ] }, { diff --git a/docs/web/integrations/data/firecrawl.mdx b/docs/web/integrations/data/firecrawl.mdx new file mode 100644 index 000000000..958fdb65c --- /dev/null +++ b/docs/web/integrations/data/firecrawl.mdx @@ -0,0 +1,101 @@ +--- +title: "Firecrawl" +sidebarTitle: "Firecrawl" +description: "Crawl or search the web with Firecrawl, store the pages as Markdown chunks in a LanceDB table with an embedding function, and search them by meaning." +keywords: ["firecrawl", "web crawling", "web search", "markdown", "rag", "ingestion"] +--- + +import { + PyFirecrawlChunk, + PyFirecrawlCrawl, + PyFirecrawlQuery, + PyFirecrawlTable, + PyFirecrawlWebSearch, +} from '/snippets/firecrawl.mdx'; + +[Firecrawl](https://www.firecrawl.dev) is a web data API that turns websites into clean +Markdown. It can crawl a whole site, scrape a single page, or run a web search and return the +content of each result. That makes it a convenient source for a LanceDB table: Firecrawl +fetches and cleans the pages, and LanceDB embeds, stores, and searches them. + +This page builds a small retrieval pipeline in Python. It crawls a documentation site, splits +each page into chunks, stores the chunks with their source URL in a LanceDB table that embeds +them with a local Sentence Transformers model, and then searches the table. A last step adds +web search results to the same table. + +## Install {#install} + +```bash +pip install lancedb firecrawl-py sentence-transformers +``` + +The examples use `firecrawl-py` 4.3.3 or later. Create an API key in the +[Firecrawl dashboard](https://www.firecrawl.dev/app/api-keys) and export it: + +```bash +export FIRECRAWL_API_KEY="fc-..." +``` + +The embedding model, `all-MiniLM-L6-v2`, runs locally, so no other API key is needed. + +## Crawl a site {#crawl-a-site} + +`crawl` starts at a URL, follows links below it, and waits until the job finishes. `limit` +caps the number of pages, and `formats` asks for each page as Markdown. The `integration` +argument labels the requests as coming from this guide; you can leave it out. + + + {PyFirecrawlCrawl} + + +Each item in `crawl.data` has the page's `markdown` and a `metadata` object with fields +such as `source_url` and `title`. To fetch a single page instead of a site, call +`firecrawl.scrape(url, formats=["markdown"])`, which returns one such item. + +## Split pages into chunks {#split-pages-into-chunks} + +A crawled page is often longer than an embedding model reads in one pass. Split the Markdown on +blank lines and group paragraphs into chunks of about 1,000 characters, so each row covers one +topic: + + + {PyFirecrawlChunk} + + +## Store the chunks in LanceDB {#store-the-chunks-in-lancedb} + +Get the Sentence Transformers embedding function from the +[embedding registry](/embedding) and declare a schema with `LanceModel`. The `text` field is +the source field, so LanceDB fills in `vector` from it as rows are added. Keep `source_url` +and `title` beside each chunk so search results can point back to the page they came from. +The database goes in a new temporary directory, so each run of this step starts from an empty +database and never overwrites a table you built earlier, including the web search results +added in the last step. + + + {PyFirecrawlTable} + + +## Search the pages {#search-the-pages} + +The table stores its embedding function, so a text query is embedded with the same model as +the rows: + + + {PyFirecrawlQuery} + + +## Add web search results {#add-web-search-results} + +`search` runs a web search. With `formats` set to Markdown, Firecrawl also scrapes each +result, so the results can go into the same table as the crawled pages: + + + {PyFirecrawlWebSearch} + + +## Learn more {#learn-more} + +- [Firecrawl documentation](https://docs.firecrawl.dev) +- [Firecrawl Python SDK](https://docs.firecrawl.dev/sdks/python) +- [Embedding functions in LanceDB](/embedding) diff --git a/docs/web/snippets/firecrawl.mdx b/docs/web/snippets/firecrawl.mdx new file mode 100644 index 000000000..dd66f6146 --- /dev/null +++ b/docs/web/snippets/firecrawl.mdx @@ -0,0 +1,12 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const PyFirecrawlChunk = "def chunk_markdown(markdown: str, max_chars: int = 1000) -> list[str]:\n chunks, current = [], \"\"\n for paragraph in markdown.split(\"\\n\\n\"):\n if current and len(current) + len(paragraph) > max_chars:\n chunks.append(current.strip())\n current = \"\"\n current += paragraph + \"\\n\\n\"\n if current.strip():\n chunks.append(current.strip())\n return chunks\n"; + +export const PyFirecrawlCrawl = "import os\n\nfrom firecrawl import Firecrawl\n\nfirecrawl = Firecrawl(api_key=os.environ[\"FIRECRAWL_API_KEY\"])\n\ncrawl = firecrawl.crawl(\n \"https://docs.lancedb.com/enterprise/v1-14-0/integrations\",\n limit=10,\n scrape_options={\"formats\": [\"markdown\"], \"only_main_content\": True},\n integration=\"_lancedb\",\n)\npages = [page for page in crawl.data if page.markdown]\nprint(f\"Crawled {len(pages)} pages\")\n"; + +export const PyFirecrawlQuery = "results = (\n table.search(\"How do I query a LanceDB table with SQL?\")\n .select([\"title\", \"source_url\", \"text\", \"_distance\"])\n .limit(3)\n .to_list()\n)\nfor row in results:\n print(f\"{row['_distance']:.3f}\", row[\"source_url\"])\n"; + +export const PyFirecrawlTable = "import tempfile\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\nembedder = (\n get_registry().get(\"sentence-transformers\").create(name=\"all-MiniLM-L6-v2\")\n)\n\nclass WebChunk(LanceModel):\n text: str = embedder.SourceField()\n vector: Vector(embedder.ndims()) = embedder.VectorField()\n source_url: str\n title: str\n\nrows = [\n {\n \"text\": chunk,\n \"source_url\": page.metadata.source_url,\n \"title\": page.metadata.title or \"\",\n }\n for page in pages\n for chunk in chunk_markdown(page.markdown)\n]\n\ndb = lancedb.connect(tempfile.mkdtemp(prefix=\"lancedb-firecrawl-\"))\ntable = db.create_table(\"firecrawl_docs\", schema=WebChunk)\ntable.add(rows)\nprint(f\"Added {table.count_rows()} chunks\")\n"; + +export const PyFirecrawlWebSearch = "search = firecrawl.search(\n \"lancedb hybrid search reranking\",\n limit=5,\n scrape_options={\"formats\": [\"markdown\"], \"only_main_content\": True},\n integration=\"_lancedb\",\n)\ntable.add(\n [\n {\n \"text\": chunk,\n \"source_url\": result.metadata.source_url,\n \"title\": result.metadata.title or \"\",\n }\n for result in search.web or []\n if getattr(result, \"markdown\", None)\n for chunk in chunk_markdown(result.markdown)\n ]\n)\nprint(f\"Table now holds {table.count_rows()} chunks\")\n"; +