crawl4ai icon indicating copy to clipboard operation
crawl4ai copied to clipboard

[Bug]: LLMExtractionStrategy not applied when CrawlerRunConfig.cache_mode=ENABLED

Open fraank opened this issue 1 year ago • 3 comments

crawl4ai version

0.7.4

Expected Behavior

When using cache_mode=CacheMode.ENABLED on CrawlerRunConfig and a previously crawled and cached URL the result.extracted_content is filled with freshly generated output of LLM.

Current Behavior

When using cache_mode=CacheMode.ENABLED on CrawlerRunConfig and a previously crawled and cached URL the result.extracted_content is empty.

Is this reproducible?

Yes

Code snippets

import os
import asyncio
import json
from pydantic import BaseModel, Field
from typing import List
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode, LLMConfig
from crawl4ai import LLMExtractionStrategy

class Product(BaseModel):
    name: str
    price: str

async def main():
    # 1. Define the LLM extraction strategy
    llm_strategy = LLMExtractionStrategy(
        llm_config = LLMConfig(provider="openai/gpt-4o-mini", api_token=os.getenv('OPENAI_API_KEY')),
        schema=Product.schema_json(), # Or use model_json_schema()
        extraction_type="schema",
        instruction="Extract all product objects with 'name' and 'price' from the content.",
        chunk_token_threshold=1000,
        overlap_rate=0.0,
        apply_chunking=True,
        input_format="markdown",   # or "html", "fit_markdown"
        extra_args={"temperature": 0.0, "max_tokens": 800}
    )

    # 2. Build the crawler config
    crawl_config = CrawlerRunConfig(
        extraction_strategy=llm_strategy,
        cache_mode=CacheMode.ENABLED # (!!) BYPASS is working
    )

    # 3. Create a browser config if needed
    browser_cfg = BrowserConfig(headless=True)

    async with AsyncWebCrawler(config=browser_cfg) as crawler:
        # 4. Let's say we want to crawl a single page
        result = await crawler.arun(
            url="https://example.com/products",
            config=crawl_config
        )

        if result.success:
            # 5. The extracted content is presumably JSON
            data = json.loads(result.extracted_content)
            print("Extracted items:", data)

            # 6. Show usage stats
            llm_strategy.show_usage()  # prints token usage
        else:
            print("Error:", result.error_message)

The Code Example is taken from the LLM Strategies Documentation

OS

macOS

Python version

3.11.4

Browser

No response

Browser version

No response

Error logs & Screenshots (if applicable)

No response

fraank avatar Aug 29 '25 09:08 fraank

Hey, thanks for the raising this issue. I managed to reproduce it on crawl4ai v0.7.4.

Root cause Analysis

When cache_mode=CacheMode.ENABLED and a cache hit occurs, AsyncWebCrawler.arun returns the cached CrawlResult early and never invokes the processing pipeline (aprocess_html). The extraction pipeline (where LLMExtractionStrategy runs) only executes inside the fresh-fetch branch.

  • Code path on cache hit (early return without processing):
else:
    self.logger.url_status(..., tag="COMPLETE")
    cached_result.success = bool(html)
    cached_result.session_id = getattr(config, "session_id", None)
    cached_result.redirected_url = cached_result.redirected_url or url
    return CrawlResultContainer(cached_result)
  • Processing/extraction runs only on fresh fetch:
crawl_result: CrawlResult = await self.aprocess_html(
    url=url,
    html=html,
    extracted_content=extracted_content,
    config=config,
    ...
)
...
return CrawlResultContainer(crawl_result)
  • Cache read/write includes extracted_content:
    • Read: aget_cached_url(...) hydrates CrawlResult (lines ~288+)
    • Write: acache_url(...) persists extracted_content (lines ~381–409), but only when we take the fresh path.

Impact: If the original cached entry was created without an extraction strategy (or extraction was empty/"[]"), subsequent runs with an extraction strategy still return the cached result unchanged, leaving result.extracted_content empty.

Proposed fixes

  • Minimal/low risk: On cache hit, if config.extraction_strategy is present and cached extracted_content is empty (or strategy signature differs), call aprocess_html using the cached HTML, then update the cache if allowed. This avoids re-fetches and keeps current behavior otherwise.
  • Opt-in flag: Add force_extraction_on_cache_hit to CrawlerRunConfig; when true, always run extraction on cached HTML and write back if allowed.
  • Longer-term: Store a strategy/config signature alongside the cache entry and re-run extraction when signatures differ or output is missing.

SohamKukreti avatar Sep 09 '25 12:09 SohamKukreti

Fix submitted in PR #1866.

Root cause (as identified by @SohamKukreti): the cache-hit path in arun() (line 652 of async_webcrawler.py) returned cached_result directly without calling aprocess_html(), so extraction strategies were never applied to cached content.

Fix: on cache hit, if config.extraction_strategy is set, the processing pipeline now runs on the cached HTML. Cache hits without an extraction strategy continue to return immediately (no behavior change).

@fraank to test before it's merged:

pip install git+https://github.com/hafezparast/crawl4ai.git@fix/maysam-cache-extraction-strategy-1455

Please give it a try with your LLMExtractionStrategy + cache_mode=CacheMode.ENABLED setup and let us know if it works!

hafezparast avatar Mar 24 '26 23:03 hafezparast

Another symptom of the same root cause, in the Docker server's /md endpoint: crawl4ai 0.9.5 (the current release), image unclecode/crawl4ai:latest (sha256:0b05666882bfb67f45d559a5b827839c54127b74aedd723f8ab338a3571b5fc9), default config.yml, API token set.

With "c": "1" (read the cache), /md returns empty markdown and "success": true for the fit and bm25 filters. The same request with "c": "0" returns the filtered markdown, and raw works from the cache:

POST /md body, url https://quotes.toscrape.com/ markdown length
"f": "fit", "c": "0" 3,663
"f": "fit", "c": "1" (twice) 0
"f": "bm25", "q": "world thinking", "c": "0" 246
"f": "bm25", "q": "world thinking", "c": "1" (twice) 0
"f": "raw", "c": "0" 4,375
"f": "raw", "c": "1" (twice) 4,375

Every response has "success": true, so a client cannot tell this from a page without content. Wikipedia pages show the same pattern (f=fit: 74,636 characters fresh, empty from the cache).

Why (line numbers from the 0.9.5 image):

  1. deploy/docker/api.py, handle_markdown_request: c == "1" maps to CacheMode.ENABLED and anything else to WRITE_ONLY (line 381), and the endpoint returns result.markdown.fit_markdown for every filter except raw (lines 404-406).
  2. crawl4ai/async_webcrawler.py, arun(): on a cache hit, the else branch at lines 690-705 returns CrawlResultContainer(cached_result) without calling aprocess_html, so the request's markdown_generator and its content filter never run. This is the code path described in the root-cause comment above for extraction_strategy.
  3. crawl4ai/async_database.py: the cache stores the whole MarkdownGenerationResult as JSON (lines 495-498), but reading it back keeps only raw_markdown (lines 361-363) and rebuilds the result with fit_markdown="" (lines 350-355). A cached result therefore never carries fit markdown, whatever filter wrote it.

Scope for #1866: it re-runs the processing on a cache hit only when config.extraction_strategy is set. /md sets only markdown_generator (with a content filter), so this case stays broken with that change. Re-running markdown generation on the cached HTML whenever the request's markdown_generator has a content filter would cover it. Returning a stored fit_markdown instead would be wrong when the stored entry was written with a different filter or query.

ar27111994 avatar Oct 19 '26 18:10 ar27111994