Skip to content

Clairic extraction

Read, compute or predict typed values from text and images with Clairic, through the Extraction API.

Updated

Clairic is Cloudflare’s extraction model. You send an input, which Cloudflare calls the state, and a set of typed fields, and it returns one value per field. A value can be read straight from the input, computed from it or predicted from it. When the input doesn’t determine a value, the value is null.

Use Clairic when you can’t list the answers in advance, such as an invoice total or a due date. To choose among options you define, use Clef.

Laravel AI has no extraction API, so the package adds Extraction. It’s built like Classification, and it works on every supported laravel/ai version.

Extract values

You don’t need extra config. Your workers-ai provider entry works on both the direct route and the gateway route.

use Meirdick\WorkersAi\Extraction;
use Meirdick\WorkersAi\Extraction\DateField;
use Meirdick\WorkersAi\Extraction\Estimate;
use Meirdick\WorkersAi\Extraction\ListField;
use Meirdick\WorkersAi\Extraction\Number;
use Meirdick\WorkersAi\Extraction\Text;

$text = 'Invoice INV-2291 from Northwind Supply, issued 2026-09-02, net 30. '
    .'4 pallets at $250.00 each, shipping $80.00. Contact: Dana Ruiz, Priya Shah.';

$invoice = Extraction::of($text)
    ->fields([
        'invoice_number' => new Text,
        'due_date' => DateField::date('Issue date plus the net payment days'),
        'total' => new Number(
            instructions: 'Amount due including shipping',
            decimals: 2,
            unit: 'USD',
        ),
        'contacts' => ListField::of('text'),
        'po_number' => new Text(instructions: 'Purchase order number'),
        'days_to_pay' => new Estimate(
            min: 0,
            max: 120,
            step: 1,
            instructions: 'Days after issue until this invoice is paid',
        ),
    ])
    ->extract();

Read the answers

$invoice['invoice_number']->value();  // 'INV-2291'
$invoice['invoice_number']->span();   // [8, 16], offsets into the state
$invoice['due_date']->value();        // '2026-10-02'
$invoice['total']->value();           // 1080
$invoice['contacts']->value();        // ['Dana Ruiz', 'Priya Shah']
$invoice['po_number']->value();       // null, the invoice has none
$invoice['days_to_pay']->median();    // 30
Method Returns
value() The answer, or null when the input does not determine it.
isNull() True when value() is null.
isPresent($threshold = 0.5) True when there is a value and pNull() is at or below the threshold.
pNull() Probability that the input does not determine the value.
guess() The model’s best value, even when value() is null.
confidence() How sure the model is of the guess.
span() [start, end] character offsets of a text answer.
spans() The offsets of each item in a list answer.
median(), mean(), p10(), p90() The figures of an estimate. p10 to p90 is an 80% interval.
pBelow(), pAbove() Probability that an estimate is outside min to max.
steps() One array of estimate figures for each forecast step.
type(), toArray() The answer type, and Cloudflare’s whole answer.

On the response, $invoice->truncated is true when the state was too long and Clairic cut it. $invoice->usage has the token counts.

These figures tell you which answers are safe to act on:

$total = $invoice['total'];

if ($total->isPresent(0.1) && $total->confidence() >= 0.9) {
    $order->update(['total' => $total->value()]);
} else {
    ReviewQueue::push($order);
}

Field types

Class Asks for Options
Text A span of the state. instructions, nullThreshold
Number A number. instructions, unit, integer, decimals, nullThreshold
DateField::date() An ISO date. Also time(), dateTime() and duration(). instructions. duration() also takes unit and integer.
ListField::of('text') A list of text, number or date items. instructions, unit, decimals, nullThreshold
Estimate A median, a mean and an 80% interval. Requires min and max. Also step, scale, unit, instructions.
Forecast One estimate per step. Requires min, max, horizon and interval.

Estimate works best when the input has evidence to go on, such as history or comparable items. Forecasting is basic, and it doesn’t replace a time-series model.

On a forecast answer, value(), median(), p10() and p90() return a list with one item per step. steps() returns the same figures grouped by step.

Read a PDF

Clairic reads only text and images. For a PDF or a Word file, convert it to text first with Markdown::of().

Set the reference date

Clairic needs a reference date to resolve a date written without a year, or a field that depends on today’s date. Set it with referenceDate():

Extraction::of($text)->fields($fields)->referenceDate('2026-11-05')->extract();

Send images

You can send up to 4 JPEG, PNG or WebP images, and the state can be blank when you do. Cloudflare allows 4 MiB per image and 8 MiB in total.

use Laravel\Ai\Files\Image;

Extraction::of('', [Image::fromPath(storage_path('app/receipt.jpg'))])
    ->field('total', new Number(unit: 'USD'))
    ->extract();

Change the call

Each of these methods returns the pending extraction, so you can chain them:

Extraction::of($text)
    ->fields($fields)
    ->when($needsPo, fn ($pending) => $pending->field('po', new Text))
    ->timeout(60)
    ->withProviderOptions(['options' => ['return_state_text' => true]])
    ->extract(provider: 'workers-ai', model: '@cf/cloudflare/clairic');
  • Provider options cannot replace model, state, fields or images.
  • With return_state_text, the text Clairic read is on $invoice->stateText.
  • withHeaders() adds headers for one call, on laravel/ai 1.x. On earlier versions, use the headers config key.
  • With no provider:, the package uses ai.default if that is a Workers AI provider, otherwise the workers-ai entry.
  • Set your default model in models.extraction.default. If you name a model that isn’t Clairic, the package throws before it sends the request.

Fail over

Add a second provider entry to config/ai.php, such as another Workers AI account:

'workers-ai-backup' => [
    'driver'     => 'workers-ai',
    'key'        => env('CLOUDFLARE_BACKUP_AI_API_TOKEN'),
    'account_id' => env('CLOUDFLARE_BACKUP_ACCOUNT_ID'),
],

Then pass a list of providers. The package tries the next provider when a call fails in a way a different provider could avoid, such as HTTP 429 or 503.

->extract(provider: ['workers-ai', 'workers-ai-backup']);

Test your code

Extraction::fake() replaces the request, so nothing reaches Cloudflare. Map each field name to the value you want back. A field you leave out is null, with pNull() at 1.0.

use Meirdick\WorkersAi\Extraction;
use Meirdick\WorkersAi\Prompts\ExtractionPrompt;

Extraction::fake([['total' => 1080]]);

// run your code, then:
Extraction::assertExtracted(fn (ExtractionPrompt $prompt) => $prompt->asks('total'));
Extraction::assertNotExtracted(fn (ExtractionPrompt $prompt) => $prompt->contains('secret'));
Extraction::assertNothingExtracted();

fake() also accepts a closure that receives the prompt, and a fake response can be a whole ExtractionResponse.

Events

The package dispatches Extracting, Extracted and ExtractionFailed, in Meirdick\WorkersAi\Events. Each has invocationId, provider, model and prompt. Extracted adds response, and ExtractionFailed adds exception.

Errors

Clairic fails in the same ways as Clef. On top of that, a blank state with no image, or a call with no fields, throws InvalidArgumentException before the request is sent.

Cost

Cloudflare charges for input tokens only. Read the count from $invoice->usage: inputTokens on laravel/ai 1.x, promptTokens on earlier versions. The WorkersAiUsageReported event also reports the neuron figure. See the Workers AI pricing page.

Type to search…

↑↓ navigate↵ selectEsc close