[Bug]: LLMExtractionStrategy not applied when CrawlerRunConfig.cache_mode=ENABLED
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
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(...)hydratesCrawlResult(lines ~288+) - Write:
acache_url(...)persistsextracted_content(lines ~381–409), but only when we take the fresh path.
- Read:
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_strategyis present and cachedextracted_contentis empty (or strategy signature differs), callaprocess_htmlusing 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_hittoCrawlerRunConfig; 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.
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!
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):
deploy/docker/api.py,handle_markdown_request:c == "1"maps toCacheMode.ENABLEDand anything else toWRITE_ONLY(line 381), and the endpoint returnsresult.markdown.fit_markdownfor every filter exceptraw(lines 404-406).crawl4ai/async_webcrawler.py,arun(): on a cache hit, theelsebranch at lines 690-705 returnsCrawlResultContainer(cached_result)without callingaprocess_html, so the request'smarkdown_generatorand its content filter never run. This is the code path described in the root-cause comment above forextraction_strategy.crawl4ai/async_database.py: the cache stores the wholeMarkdownGenerationResultas JSON (lines 495-498), but reading it back keeps onlyraw_markdown(lines 361-363) and rebuilds the result withfit_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.