[Bug]: llm_strategy returns empty extracted_content
crawl4ai version
0.6.3
Expected Behavior
It is expected that the extracted_content to be populated with the content an LLM extracted.
Current Behavior
It returns an empty extracted_content. This is what it returns:
[{'index': 0, 'error': True, 'tags': ['error'], 'content': "'str' object has no attribute 'choices'"}]
def get_browser_config() -> BrowserConfig:
"""
Returns the browser configuration for the crawler.
Returns:
BrowserConfig: The configuration settings for the browser.
"""
# https://docs.crawl4ai.com/core/browser-crawler-config/
return BrowserConfig(
browser_type="chromium", # Type of browser to simulate
headless=True, # Whether to run in headless mode (no GUI)
verbose=True, # Enable verbose logging
)
def get_llm_strategy() -> LLMExtractionStrategy:
"""
Returns the configuration for the language model extraction strategy.
Returns:
LLMExtractionStrategy: The settings for how to extract data using LLM.
"""
# https://docs.crawl4ai.com/api/strategies/#llmextractionstrategy
return LLMExtractionStrategy(
llm_config=LLMConfig(provider='ollama/qwen3:14b'),
schema=model.model_json_schema(), # JSON schema of the data model
extraction_type="schema", # Type of extraction to perform
instruction=(
"some instructions."
), # Instructions for the LLM
input_format="markdown", # Format of the input content
verbose=True, # Enable verbose logging
)
browser_config = get_browser_config()
llm_strategy = get_llm_strategy()
session_id = "crawl_session"
async with AsyncWebCrawler(config=browser_config) as crawler:
while True:
# Fetch and process data from the current page
venues, no_results_found = await fetch_and_process_page(
crawler,
page_number,
BASE_URL,
CSS_SELECTOR,
llm_strategy,
session_id,
REQUIRED_KEYS,
seen_names,
)
async def fetch_and_process_page(
crawler: AsyncWebCrawler,
page_number: int,
base_url: str,
css_selector: str,
llm_strategy: LLMExtractionStrategy,
session_id: str,
required_keys: List[str],
seen_names: Set[str],
) -> Tuple[List[dict], bool]:
"""
Fetches and processes a single page of venue data.
Args:
crawler (AsyncWebCrawler): The web crawler instance.
page_number (int): The page number to fetch.
base_url (str): The base URL of the website.
css_selector (str): The CSS selector to target the content.
llm_strategy (LLMExtractionStrategy): The LLM extraction strategy.
session_id (str): The session identifier.
required_keys (List[str]): List of required keys in the venue data.
seen_names (Set[str]): Set of venue names that have already been seen.
Returns:
Tuple[List[dict], bool]:
- List[dict]: A list of processed venues from the page.
- bool: A flag indicating if the "No Results Found" message was encountered.
"""
if page_number ==1:
url = f"{base_url}"
else:
url = f"{base_url}?page={page_number}"
print(f"Loading page {page_number}...")
# Check if "No Results Found" message is present
no_results = await check_no_results(crawler, url, session_id)
if no_results:
return [], True # No more results, signal to stop crawling
# Fetch page content with the extraction strategy
result = await crawler.arun(
url=url,
config=CrawlerRunConfig(
cache_mode=CacheMode.BYPASS, # Do not use cached data
extraction_strategy=llm_strategy, # Strategy for data extraction
css_selector=css_selector, # Target specific content on the page
session_id=session_id, # Unique session ID for the crawl
),
)
if not (result.success and result.extracted_content):
print(f"Error fetching page {page_number}: {result.error_message}")
return [], False
# Parse extracted content
extracted_data = json.loads(result.extracted_content)
if not extracted_data:
print(f"No venues found on page {page_number}.")
return [], False
# After parsing extracted content
print("Extracted data:", extracted_data)
Is this reproducible?
Yes
Inputs Causing the Bug
Steps to Reproduce
Code snippets
OS
Linux
Python version
3.11.10
Browser
No response
Browser version
No response
Error logs & Screenshots (if applicable)
No response
I've experienced something similar. Here's what happened in my case, which might be helpful:
-
Initially, I directly inserted the
LLMExtractionStrategyintoAsyncWebCrawler. After wrapping it insideCrawlerRunConfig, the issue whereresult.extracted_contentwasNonewas resolved, although some error messages persisted. -
Changing the LLM provider helped. I was initially using Gemini 2.5, but when I downgraded to a model officially supported in the documentation, the extraction worked perfectly without any error messages.
@pnsafari can you check on this branch 2025-MAY-2 if you still face with the error ([{'index': 0, 'error': True, 'tags': ['error'], 'content': "'str' object has no attribute 'choices'"}]) ?
from crawl4ai import LLMConfig from crawl4ai import AsyncWebCrawler, LLMExtractionStrategy import asyncio import os import json from pydantic import BaseModel, Field
url = "https://openai.com/api/pricing/"
class OpenAIModelFee(BaseModel): model_name: str = Field(..., description="Name of the OpenAI model.") input_fee: str = Field(..., description="Fee for input token for the OpenAI model.") output_fee: str = Field( ..., description="Fee for output token for the OpenAI model." ) async def main(): # Use AsyncWebCrawler async with AsyncWebCrawler() as crawler: result = await crawler.arun( url=url, word_count_threshold=1, extraction_strategy=LLMExtractionStrategy( # provider= "openai/gpt-4o", api_token = os.getenv('OPENAI_API_KEY'), llm_config=LLMConfig(provider="deepseek/deepseek-r1", api_token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"), schema=OpenAIModelFee.model_json_schema(), extraction_type="schema", instruction="From the crawled content, extract all mentioned model names along with their ", ), ) print("Success:", result.success) print(result.extracted_content)
model_fees = json.loads(result.extracted_content)
print(len(model_fees))
print(result.extracted_content)
with open(".data/data.json", "w", encoding="utf-8") as f:
f.write(result.extracted_content)
asyncio.run(main())
I meet question same
@vesttt Could you please try the code below? Just replace the LLM provider with your own.
import asyncio
from pydantic import BaseModel, Field
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, LLMConfig, BrowserConfig, CacheMode
from crawl4ai.extraction_strategy import LLMExtractionStrategy
from typing import Dict
import os
class OpenAIModelFee(BaseModel):
model_name: str = Field(..., description="Name of the OpenAI model.")
input_fee: str = Field(..., description="Fee for input token for the OpenAI model.")
output_fee: str = Field(..., description="Fee for output token for the OpenAI model.")
async def extract_structured_data_using_llm(provider: str, api_token: str = None, extra_headers: Dict[str, str] = None):
print(f"\n--- Extracting Structured Data with {provider} ---")
if api_token is None and provider != "ollama":
print(f"API token is required for {provider}. Skipping this example.")
return
browser_config = BrowserConfig(headless=True)
extra_args = {"temperature": 0, "top_p": 0.9, "max_tokens": 2000}
if extra_headers:
extra_args["extra_headers"] = extra_headers
crawler_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
word_count_threshold=1,
page_timeout=80000,
extraction_strategy=LLMExtractionStrategy(
llm_config=LLMConfig(provider=provider, api_token=api_token),
schema=OpenAIModelFee.model_json_schema(),
extraction_type="schema",
instruction="""From the crawled content, extract all mentioned model names along with their fees for input and output tokens.
Do not miss any models in the entire content.""",
extra_args=extra_args,
),
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(
url="https://openai.com/api/pricing/",
config=crawler_config
)
print(result.extracted_content)
if __name__ == "__main__":
asyncio.run(
extract_structured_data_using_llm(
provider="openai/gpt-4o", api_token=os.getenv("OPENAI_API_KEY")
)
)
@fleem82 I originally tried qwen3 but now I changed to llama3 and it does not produce an empty (with error) output but it does not work as expected. It should scrape 30 entries but returns only 4.
I've experienced something similar. Here's what happened in my case, which might be helpful:
- Initially, I directly inserted the
LLMExtractionStrategyintoAsyncWebCrawler. After wrapping it insideCrawlerRunConfig, the issue whereresult.extracted_contentwasNonewas resolved, although some error messages persisted.- Changing the LLM provider helped. I was initially using Gemini 2.5, but when I downgraded to a model officially supported in the documentation, the extraction worked perfectly without any error messages.
@ntohidi I changed to the branch you mentioned and it returns no error, but it does not work as expected. Out of 30 entries on the page it only scrapes 4.
@pnsafari can you check on this branch
2025-MAY-2if you still face with the error ([{'index': 0, 'error': True, 'tags': ['error'], 'content': "'str' object has no attribute 'choices'"}]) ?
用deepseek/deepseek:7b的api没有问题,用本地ollama/deepseek:7b会出现这个问题
I have a same problem
import os import json import asyncio from typing import Dict from pydantic import BaseModel, Field from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, LLMConfig, BrowserConfig, CacheMode from crawl4ai.extraction_strategy import LLMExtractionStrategy
class ProductInfo(BaseModel): product_name: str = Field(..., description="Name of the product.") retail_price: str = Field(..., description="Retail price of the product.") description: str = Field(..., description="Short description of the product.") trade_price: str = Field(..., description="Trade price of the product.") price_excl_vat: str = Field(..., description="Price excluding VAT.") product_code: str = Field(..., description="Unique product code.")
async def extract_structured_data_using_llm( provider: str, api_token: str = None, extra_headers: Dict[str, str] = None ): print(f"\n--- Extracting Structured Data with {provider} ---")
if api_token is None and not provider.startswith("ollama"):
print(f"API token is required for {provider}. Skipping this example.")
return
browser_config = BrowserConfig(headless=True)
extra_args = {"temperature": 0, "top_p": 0.9, "max_tokens": 2000}
if extra_headers:
extra_args["extra_headers"] = extra_headers
crawler_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
word_count_threshold=1,
page_timeout=80000,
extraction_strategy=LLMExtractionStrategy(
llm_config=LLMConfig(provider=provider, api_token=api_token),
schema=ProductInfo.model_json_schema(),
extraction_type="schema",
instruction="""
From the crawled content, extract all product entries including:
product name, retail price, description, trade price, price excluding VAT, and product code.
Ensure all products mentioned are included in the result.
""",
extra_args=extra_args,
)
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(
url="https://www.travisperkins.co.uk/product/timber-and-sheet-materials/sawn-timber/treated-timber/c"
"/1500002/", config=crawler_config
)
print(result.extracted_content)
if name == "main": asyncio.run( extract_structured_data_using_llm( provider="groq/deepseek-r1-distill-llama-70b", api_token=#your_token' ) )
--- Extracting Structured Data with groq/deepseek-r1-distill-llama-70b --- [INIT].... → Crawl4AI 0.6.3 [FETCH]... ↓ https://www.travisperkins.co.uk/product/timber-a...-materials/sawn-timber/treat ed-timber/c/1500002/ | ✓ | ⏱: 9.83s [SCRAPE].. ◆ https://www.travisperkins.co.uk/product/timber-a...-materials/sawn-timber/treat ed-timber/c/1500002/ | ✓ | ⏱: 0.10s [EXTRACT]. ■ Completed for https://www.travisperkins.co.uk/product/timber-and... | Time: 15.463947299998836s [COMPLETE] ● https://www.travisperkins.co.uk/product/timber-a...-materials/sawn-timber/treat ed-timber/c/1500002/ | ✓ | ⏱: 25.41s [ { "index": 0, "error": true, "tags": [ "error" ], "content": "'str' object has no attribute 'choices'" } ]
any solution pls??
@TemiShols You are using an outdated version of the library. Please update it to the latest version, which is currently 0.7.4.
This issue is already fixed in 0.7.4