LLM Features
Selectors are fast and free, but they need a known layout. When pages vary, or when you want
answers rather than fields, a language model helps. PAM Crawl’s Pam\Crawl\Llm namespace adds:
- LLM extraction into your own PHP classes or a JSON Schema;
- question answering over a page, with numbered citations;
- learn-once schemas: the model writes CSS selectors once per site layout, and every later page is extracted with plain selectors and no LLM call;
- table extraction for messy HTML tables;
- content filtering that asks a model to clean a page into Markdown;
- embeddings for semantic clustering and adaptive crawling.
The same provider strings work everywhere, and a local model through Ollama needs no API key.
Configuring a provider
Section titled “Configuring a provider”Every feature takes a Pam\Crawl\Llm\Config. Its first argument is a provider string in the
Crawl4AI / LiteLLM form vendor/model:
use Pam\Crawl\Llm\Config;
$llm = new Config('ollama/qwen2.5:7b', temperature: 0.0);ollama pull qwen2.5:7buse Pam\Crawl\Llm\Config;
$llm = new Config('openai/gpt-4o-mini'); // token from OPENAI_API_KEYuse Pam\Crawl\Llm\Config;
$llm = new Config('anthropic'); // vendor default model, token from ANTHROPIC_API_KEYuse Pam\Crawl\Llm\Config;
$llm = new Config('gemini/gemini-2.5-flash'); // token from GEMINI_API_KEY or GOOGLE_API_KEYA bare vendor ('anthropic') picks that vendor’s default model. The API token can be passed
literally, as 'env:VARIABLE', or omitted, in which case it is read from the vendor’s usual
environment variable:
| Vendor | Environment variable | Endpoint |
|---|---|---|
openai |
OPENAI_API_KEY |
api.openai.com |
anthropic |
ANTHROPIC_API_KEY |
api.anthropic.com |
gemini, google |
GEMINI_API_KEY |
generativelanguage.googleapis.com |
groq |
GROQ_API_KEY |
api.groq.com |
openrouter |
OPENROUTER_API_KEY |
openrouter.ai |
deepseek |
DEEPSEEK_API_KEY |
api.deepseek.com |
mistral |
MISTRAL_API_KEY |
api.mistral.ai |
together |
TOGETHER_API_KEY |
api.together.xyz |
xai |
XAI_API_KEY |
api.x.ai |
fireworks |
FIREWORKS_API_KEY |
api.fireworks.ai |
ollama |
none | localhost:11434 |
lmstudio |
none | localhost:1234 |
vllm |
none | localhost:8000 |
Any other vendor works with an OpenAI-compatible endpoint when you pass baseUrl:
$llm = new Config('acme/my-model', apiToken: 'env:ACME_KEY', baseUrl: 'http://10.0.0.5:9000/v1');Config also accepts temperature, maxTokens, topP, stop, timeout (120 s),
connectTimeout (10 s), retry back-off settings (backoffBaseDelay, backoffMaxAttempts,
backoffFactor), extra HTTP headers and extra request-body fields. Rate limits (429), server
errors (5xx) and network errors are retried with exponential back-off, honoring Retry-After.
The CLI, HTTP API and
MCP server read their default provider from CRAWL_LLM_PROVIDER and
CRAWL_LLM_TOKEN (or pam crawl config set DEFAULT_LLM_PROVIDER ...). In PHP code you always pass
a Config explicitly.
LLM extraction
Section titled “LLM extraction”LlmExtraction ports Crawl4AI’s LLMExtractionStrategy. Give it a PHP class and it derives a JSON
Schema from the class constructor, sends the page to the model, and hydrates the JSON answer back
into objects:
use Pam\Crawl\Crawl;use Pam\Crawl\Llm\Config;use Pam\Crawl\Llm\LlmException;use Pam\Crawl\Llm\LlmExtraction;
final readonly class Book{ public function __construct( public string $title, public float $price, public string $currency, public bool $inStock, ) {}}
$page = Crawl::url('https://books.toscrape.com/catalogue/category/books/poetry_23/index.html') ->target('ol.row') // send only the product list to the model ->withoutImages() ->get();
$extraction = new LlmExtraction( new Config('ollama/qwen2.5:7b', temperature: 0.0), instruction: 'Extract every book in the list.', schema: Book::class,);
try { $books = $extraction->extract($page); // list<Book>} catch (LlmException $e) { // missing API key, unreachable endpoint, or an invalid response}
$usage = $extraction->usage; // requests, promptTokens, completionTokens, totalTokensNarrow what you send with target(), selector() and exclude() (see
Markdown & Content). Less input means
lower cost and better answers.
Long pages are split into chunks (about 2,048 tokens each, with 10% overlap) and the chunks are sent in parallel. The main options:
| Option | Description |
|---|---|
schema |
A DTO class name, a JSON Schema array, or a JSON Schema string. |
instruction |
What to extract, in plain language. |
type |
'schema' (default) or 'block', which returns semantic blocks: index, tags, content. |
input |
What the model reads: Input::Markdown (default), FitMarkdown, Html, CleanedHtml, FitHtml or Text. |
chunkTokenThreshold, overlapRate, applyChunking |
Chunking. |
concurrency |
Parallel requests per extraction (default 4). |
Providers that support it receive the schema as a native JSON Schema response format; the others are prompted for JSON.
Question answering
Section titled “Question answering”Ask answers a question from a page’s content. The Markdown is cut into passages, the passages
most relevant to the question (BM25) are numbered and sent as context, and the model answers
citing them as ⟨n⟩:
use Pam\Crawl\Crawl;use Pam\Crawl\Llm\Ask;use Pam\Crawl\Llm\Config;
$page = Crawl::url('https://en.wikipedia.org/wiki/Web_crawler')->get();
$answer = (new Ask(new Config('ollama/qwen2.5:7b'), topK: 5, passageWords: 120)) ->ask($page, 'How does a crawler avoid overloading the web servers it visits?');
echo $answer->text, "\n"; // ... a politeness policy ⟨2⟩ ...
foreach ($answer->citations as $citation) { echo "⟨{$citation['n']}⟩ {$citation['text']}\n";}Answer has text, citations, the context passages that were sent, token usage and the
page url. ask() also accepts a Markdown string instead of a page. The defaults are topK: 6 and
passageWords: 150.
Learn once, extract for free
Section titled “Learn once, extract for free”Asking an LLM about every page is slow and costs money. When many pages share a layout (product pages, search results, listings), let the model write the selectors once and run them everywhere else.
Schema generation
Section titled “Schema generation”SchemaGenerator ports Crawl4AI’s generate_schema. The model writes a CSS (or XPath) schema from
a sample page; PAM Crawl validates it by running it on that page and asks the model to refine it
(up to three rounds) while fields come back empty:
use Pam\Crawl\Crawl;use Pam\Crawl\Llm\Config;use Pam\Crawl\Llm\SchemaGenerator;
$generator = new SchemaGenerator(new Config('ollama/qwen2.5:7b'), cacheDir: __DIR__.'/storage/schemas');
$schema = $generator->generate( Crawl::url('https://quotes.toscrape.com/page/1/')->get(), query: 'each quote: text, author name and the link to the author page', example: ['text' => '“A quote.”', 'author' => 'Some Author', 'author_url' => '/author/Some-Author'],);
echo $schema->toJson();
// The same layout elsewhere: plain selectors, no LLM call.foreach (Crawl::urls(['https://quotes.toscrape.com/page/2/', 'https://quotes.toscrape.com/page/3/'])->stream() as $page) { $rows = $schema->extract($page);}With a cacheDir, the schema is stored per domain, query and layout, so later runs make no LLM
call at all. The result is a regular JSON schema: you
can review it, commit it, or turn it into a DTO with toPhpClass().
Typed learn-once extraction
Section titled “Typed learn-once extraction”Learn does the same for a DTO without selector attributes. Fields that already carry #[Css],
#[XPath] or #[Regex] keep their selectors; the model fills in the rest:
use Pam\Crawl\Llm\Config;use Pam\Crawl\Llm\Learn;
final readonly class Product{ public function __construct( public string $name, public ?float $price = null, public ?string $url = null, ) {}}
$products = Learn::extract($page, Product::class, new Config('openai/gpt-4o-mini'), __DIR__.'/storage/learn');Learned schemas are cached in memory and, with a cache directory, on disk, keyed by domain, DTO
shape and layout. A cached schema that stops matching is relearned once. Learn::one() returns a
single object and Learn::schema() returns the learned schema.
Tables
Section titled “Tables”LlmTableExtraction turns messy HTML tables (merged cells, nested tables, missing headers) into
clean headers, rows, caption, summary and metadata. Large tables are split into row
chunks with the header repeated, processed in parallel and merged back:
use Pam\Crawl\Llm\LlmTableExtraction;
$tables = (new LlmTableExtraction($llm, selector: 'main'))->extract($page);For well-formed tables, the free $page->tables is usually enough (see
Markdown & Content).
Content filtering
Section titled “Content filtering”LlmContentFilter asks the model to convert a page’s cleaned HTML into relevant Markdown. Use it
as any other content filter, with an optional instruction:
use Pam\Crawl\Llm\LlmContentFilter;
$filter = new LlmContentFilter($llm, instruction: 'Keep only the installation steps.');
$markdown = $page->markdown(filter: $filter);It is the most expensive way to get Markdown; try $page->content and
markdown(focus: ...) first.
Embeddings
Section titled “Embeddings”Embeddings calls OpenAI-compatible /embeddings endpoints (OpenAI, Ollama, LM Studio, vLLM,
Mistral, Together, OpenRouter…) and Gemini. Inputs are batched, batches run in parallel, and vectors
are kept in a bounded in-memory cache so repeated texts are embedded once per process:
use Pam\Crawl\Llm\Config;use Pam\Crawl\Llm\Embeddings;
$embeddings = new Embeddings(new Config('ollama/nomic-embed-text'));// or 'openai/text-embedding-3-small', 'gemini/text-embedding-004'
[$a, $b] = $embeddings->embedMany(['cats purr', 'kittens meow']);
echo Embeddings::cosine($a, $b);Anthropic has no embeddings endpoint. Embeddings power semantic clustering and embedding-based adaptive crawling.
Adaptive crawling with embeddings
Section titled “Adaptive crawling with embeddings”The adaptive crawler can measure coverage
semantically, like Crawl4AI’s EmbeddingStrategy: a chat model expands the query into variations,
pages are embedded, links are ranked by how much they close the remaining gaps, and the crawl stops
on irrelevance or a validated plateau:
use Pam\Crawl\Adaptive\AdaptiveCrawler;use Pam\Crawl\Adaptive\Config;use Pam\Crawl\Llm\Config as Llm;
$adaptive = new AdaptiveCrawler(new Config( strategy: 'embedding', maxPages: 15, embeddingLlmConfig: new Llm('ollama/nomic-embed-text'), queryLlmConfig: new Llm('ollama/qwen2.5:3b'),));
$state = $adaptive->digest('https://docs.python.org/3/library/asyncio.html', 'task cancellation timeout');
echo $adaptive->confidence(), ' ', $state->metrics['stopped_reason'] ?? '', "\n";Responsible use
Section titled “Responsible use”Sending page content to a hosted model sends it to a third party. Check the site’s terms and your provider’s data policy before you do, and prefer a local model for private or sensitive content. See Responsible Use.
Next steps
Section titled “Next steps”- Start with free, selector-based Extraction where layouts allow it.
- Give AI assistants crawling tools through the MCP server.
This product includes software developed by UncleCode (https://x.com/unclecode) as part of the Crawl4AI project (https://github.com/unclecode/crawl4ai). The LLM prompts are adapted from Crawl4AI.