Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping support for 3.10

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, deliberately. It comes with the httpx2 switch (S5, #17): httpx2 declares requires-python >=3.11 (2.18.0 on PyPI), so it can't be installed on 3.10. Python 3.10 also reached end of life in October 2026, and python-jev already targets 3.11–3.14.

Keeping 3.10 would mean staying on httpx 0.28.1, which has had no stable release since December 2024, or supporting both clients side by side. Neither seemed worth it before the 1.0 API freeze.

The PR description lists this under breaking changes, and the 0.2.0 release notes will say it too. CI now runs 3.11–3.14, plus a job on 3.11 with the lowest allowed dependency versions.

🤖 Claude Code

python-version: ["3.11", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
Expand All @@ -22,3 +22,13 @@ jobs:
- run: uv run ruff check
- run: uv run pyright
- run: uv run pytest

lowest-dependencies:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
with:
python-version: "3.11"
- run: uv sync --resolution lowest-direct
- run: uv run pytest
49 changes: 25 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ that model.
pip install clairic
```

Python 3.10 or later. The client reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`, or takes
Python 3.11 or later. The client reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`, or takes
them as arguments with `Clairic(account_id="...", api_token="...")`. Create the token in the
Cloudflare dashboard with access to Workers AI.

Expand Down Expand Up @@ -71,8 +71,7 @@ invoice.total.confidence # 0.99995
invoice.contacts.value # ['Dana Ruiz', 'Priya Shah']

invoice.po_number.value # None
invoice.po_number.p_null # 0.9999994, the probability that the PO number is absent
invoice.po_number.guess # 'INV-2291', the best candidate
invoice.po_number.p_null # 0.9996, the probability that the PO number is absent
```

### Estimates
Expand Down Expand Up @@ -135,12 +134,12 @@ Each field of the extraction model has an answer type, which sets the Clairic fi

| Answer type | Clairic type | Spec (options) |
|---|---|---|
| `TextAnswer` | `text`: a span of the input | `Text(unit, null_threshold)` |
| `NumberAnswer[float]`, `NumberAnswer[int]` | `number` (`int` requests whole numbers) | `Number(unit, null_threshold, decimals)` |
| `TextAnswer` | `text` | `Text()`, no options |
| `NumberAnswer[float]`, `NumberAnswer[int]` | `number` (`int` requests whole numbers) | `Number(unit, decimals)` |
| `DateAnswer`, `TimeAnswer`, `DatetimeAnswer` | `date`, `time`, `datetime` | `Date(null_threshold)`, `Time(...)`, `Datetime(...)` |
| `DurationAnswer[float]`, `DurationAnswer[int]` | `duration` | `Duration(unit, null_threshold, decimals)`, unit defaults to seconds |
| `TextListAnswer` | `list` of text spans | `List(unit, decimals)` |
| `ListAnswer[int]`, `ListAnswer[float]`, `ListAnswer[date]` | `list` of numbers or dates | `List(unit, decimals)` |
| `TextListAnswer` | `list` of texts | `List(unit)` |
| `ListAnswer[int]`, `ListAnswer[float]`, `ListAnswer[date]` | `list` of numbers or dates | `List(unit, decimals)`, decimals for numbers only |
| `EstimateAnswer[int]`, `EstimateAnswer[float]` | `estimate` with number bounds | `Estimate(min, max, step, scale, unit)`, required |
| `DateEstimateAnswer` | `estimate` with date bounds | `Estimate(min=date, max=date, step="month")`, required |
| `ForecastAnswer` | `forecast` of a series | `Forecast(min, max, horizon, interval, step, scale, unit)`, required |
Expand All @@ -161,16 +160,16 @@ Every answer holds a `value` and the metadata Clairic attaches to it, all typed

| Answers | Attributes |
|---|---|
| Single values (`text`, `number`, `date`, `time`, `datetime`, `duration`) | `value`, `guess`, `confidence`, `p_null` |
| Text | `span`, end-exclusive offsets into the input (`text[span.start:span.end]`). Text lists carry `spans` |
| Single values (`text`, `number`, `date`, `time`, `datetime`, `duration`) | `value`, `confidence`, `p_null`. Dates, times, datetimes and durations also carry `guess` |
| Text | `span`, end-exclusive offsets into the input (`text[span.start:span.end]`). Text lists carry `spans`. A span is `None` when the value occurs more than once in the input |
| Number and date lists | `confidences`, one per item |
| Estimates | `value` (the mean rounded to the `step` grid), `mean`, `median`, `p10`, `p90`. With number bounds, `p_below` and `p_above` hold the probability mass below `min` and above `max` |
| Forecasts | Per-step lists `value`, `median`, `p10`, `p90`, and `steps` with the full estimate of each step |

`value` turns to `None` when `p_null` exceeds the field's `null_threshold`, 0.5 by default, and
`guess` keeps the best candidate. On "can be reached at +33 6 12 34 56 78 or at
firstname.name@gmail.com", Clairic returned the phone number with a confidence of 1.0, and for the
email a `p_null` of 0.66 with the address in `guess`.
Text and number answers are generated: Clairic writes the value, or null when the input does not
determine it, and `confidence` is the probability of what it wrote. Date, time, datetime and
duration answers are scored: `value` turns to `None` when `p_null` exceeds the field's
`null_threshold`, 0.5 by default, and `guess` keeps the best candidate.

The p10 to p90 range is an 80% interval. Cloudflare publishes calibration measurements, and
intervals can come out too narrow on new kinds of data.
Expand Down Expand Up @@ -201,27 +200,29 @@ async with AsyncClairic() as clairic:
| `ClairicConfigurationError` | The account id or token is missing. |
| `AuthenticationError` | HTTP 401: invalid token or unknown account. |
| `InvalidRequestError` | HTTP 400 or 422: Cloudflare rejected the request content. |
| `ContextWindowExceededError` | HTTP 413: the input exceeds the 65,536-token context window. |
| `ContextWindowExceededError` | HTTP 413: the input and field definitions exceed Clairic's 65,273-token limit. |
| `APIError` | Any other error response, or answers outside the model's shape. Base class of the API errors. |
| `APIConnectionError`, `APITimeoutError` | Cloudflare was unreachable, or the timeout expired (30 seconds by default). |

API errors carry `status_code`, the Cloudflare error `code`, `message` and `request_id`. When
Clairic reports a truncated input, the client emits `ClairicTruncationWarning` and sets
`result.truncated`.
API errors carry `status_code`, the Cloudflare error `code`, `message` and `request_id`.

When a generated answer comes back invalid, for example a value Clairic could not normalize, its
`value` is `None` and Clairic reports `truncated: true`. The client then sets `result.truncated` and
emits `ClairicInvalidAnswerWarning` naming the fields. Turn it into an error with
`warnings.simplefilter("error", ClairicInvalidAnswerWarning)`.

## Cost

Clairic bills input tokens, at $0.10 per million at the time of writing. It packs fields next to
the input in 8,192-token passes and runs extra passes in parallel when they overflow. Each pass
reads the whole input, and `result.usage.input_tokens` counts it once per pass. The full invoice
extraction above took 655 input tokens over 3 passes.
Cloudflare prices Clairic per input token, at $0.10 per million at the time of writing.
`result.usage.input_tokens` counts every prompt token, retries included, and `output_tokens` the
tokens Clairic generates for text, number and list answers. In December 2026 the full invoice
extraction above took 1,823 input tokens over 9 decode steps (`usage.passes`).

## Preview status

Clairic is a preview model. Cloudflare provides it as is and may withdraw it at any time. Field
options can change too, and a weekly CI job compares Cloudflare's published schemas with the ones
vendored here. The cause of `truncated: true` is under investigation in
[#15](https://github.com/VianneyMI/clairic/issues/15).
options and answers can change too, as they did in November 2026, and a weekly CI job compares
Cloudflare's published schemas with the ones vendored here.

## Going further

Expand Down
4 changes: 2 additions & 2 deletions examples/invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ def main() -> None:
print(f"Invoice number: {number.value} (confidence {number.confidence:.4f})")
print(f"Due date: {data.due_date.value}")
print(f"Total: {data.total.value} USD")
print(f"PO number: {po.value} (p_null {po.p_null:.4f}, best guess {po.guess!r})")

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why removing guess ?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Cloudflare's November update, Clairic no longer returns a guess for text (or number) answers. They are now generated answers: Clairic writes the value, or null, and checks it, so there's no separate best candidate.

guess is only returned for typed answers (date, time, datetime, duration, compute). The new output schema says so: "guess: Typed answers only". The re-recorded invoice response confirms it: po_number comes back with value: null and no guess key.

In 0.2, TextAnswer.guess stays for compatibility but is always None. With the line kept, the example printed best guess None, which is misleading. 0.3 (#24) removes the attribute from text and number answers altogether.

🤖 Claude Code

print(f"PO number: {po.value} (p_null {po.p_null:.4f})")
print(f"Days to pay: {estimate.value} (80% interval {estimate.p10} to {estimate.p90})")
print(f"Input tokens: {result.usage.input_tokens} over {result.usage.passes} passes")
print(f"Input tokens: {result.usage.input_tokens} over {result.usage.passes} decode steps")

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

passes = decode steps ?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's how the new output schema defines it: usage.passes, "Sequential decode steps."

At launch, passes counted the parallel 8,192-token passes fields were split into. Now Clairic decodes its generated answers step by step, and passes counts those steps. The invoice example takes 9 for 6 fields.

The SDK keeps the API's field name, usage.passes, and only the wording around it changes. Cloudflare's model page still describes passes the old way, so the schema is the only source for the new meaning.

If you prefer, the example could print {passes} passes (decode steps) to keep the API's word visible.

🤖 Claude Code

print()
print(result.values_as(Invoice))

Expand Down
10 changes: 4 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,22 @@ description = "Unofficial typed Python SDK for Cloudflare's Clairic extraction m
readme = "README.md"
authors = [{ name = "Vianney Mixtur", email = "vianney@consio.ai" }]
license = { file = "LICENSE" }
requires-python = ">=3.10"
requires-python = ">=3.11"
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Typing :: Typed",
]
dependencies = [
"httpx>=0.27",
"httpx2>=2.16",
"pydantic>=2.7",
"typing-extensions>=4.12",
]

[project.urls]
Expand Down Expand Up @@ -55,7 +53,7 @@ include = ["/src", "/LICENSE", "/NOTICE", "/README.md", "/pyproject.toml"]

[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py311"

[tool.ruff.lint]
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "D"]
Expand All @@ -74,7 +72,7 @@ convention = "google"

[tool.pyright]
include = ["src", "tests", "scripts", "examples"]
pythonVersion = "3.10"
pythonVersion = "3.11"
typeCheckingMode = "strict"
extraPaths = ["scripts"]

Expand Down
6 changes: 4 additions & 2 deletions scripts/check_schema_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from pathlib import Path
from typing import Any, Literal, cast

import httpx
import httpx2

SCHEMAS = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "schemas"
BASE_URL = "https://developers.cloudflare.com/workers-ai/models/clairic"
Expand Down Expand Up @@ -233,7 +233,9 @@ def main(argv: list[str]) -> int:
sections: list[str] = []
line_diffs: list[str] = []
for name in NAMES:
published = _normalized(httpx.get(f"{BASE_URL}/{name}", timeout=30).raise_for_status().text)
published = _normalized(
httpx2.get(f"{BASE_URL}/{name}", timeout=30).raise_for_status().text
)
vendored_path = SCHEMAS / name
vendored = _normalized(vendored_path.read_text())
if published == vendored:
Expand Down
4 changes: 2 additions & 2 deletions src/clairic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
AuthenticationError,
ClairicConfigurationError,
ClairicError,
ClairicTruncationWarning,
ClairicInvalidAnswerWarning,
ContextWindowExceededError,
InvalidRequestError,
ModelDefinitionError,
Expand Down Expand Up @@ -64,7 +64,7 @@
"Clairic",
"ClairicConfigurationError",
"ClairicError",
"ClairicTruncationWarning",
"ClairicInvalidAnswerWarning",
"ContextWindowExceededError",
"Date",
"DateAnswer",
Expand Down
63 changes: 38 additions & 25 deletions src/clairic/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@
import os
import warnings
from types import TracebackType
from typing import Any, TypeVar
from typing import Any, Self, TypeVar, cast

import httpx
import httpx2
from pydantic import BaseModel, ValidationError
from typing_extensions import Self

from clairic._compile import build_data, fields_payload
from clairic._version import __version__
Expand All @@ -20,7 +19,7 @@
APITimeoutError,
AuthenticationError,
ClairicConfigurationError,
ClairicTruncationWarning,
ClairicInvalidAnswerWarning,
ContextWindowExceededError,
InvalidRequestError,
)
Expand Down Expand Up @@ -74,7 +73,7 @@ def _body(state: str, model: type[BaseModel], reference_date: dt.date | None) ->
return body

@staticmethod
def _parse(response: httpx.Response, model: type[M]) -> Result[M]:
def _parse(response: httpx2.Response, model: type[M]) -> Result[M]:
status_code = response.status_code
request_id = response.headers.get("cf-ai-req-id")
try:
Expand All @@ -99,9 +98,7 @@ def _parse(response: httpx.Response, model: type[M]) -> Result[M]:
) from error
if result.truncated:
warnings.warn(
"Clairic truncated the input: the answers were computed on part of it",
ClairicTruncationWarning,
stacklevel=3,
_invalid_answers_message(result.answers), ClairicInvalidAnswerWarning, stacklevel=3
)
return Result[model](
data=data,
Expand Down Expand Up @@ -134,6 +131,22 @@ class _ResultBody(BaseModel):
model: str


def _invalid_answers_message(answers: dict[str, Any]) -> str:
"""Name the fields whose raw answer Clairic marks invalid or incomplete."""
invalid = [name for name, answer in answers.items() if _is_invalid(answer)]
if not invalid:
return "Clairic reported truncated: true"
noun = "answer" if len(invalid) == 1 else "answers"
return f"Clairic returned {len(invalid)} invalid {noun}: {', '.join(invalid)}"


def _is_invalid(answer: Any) -> bool:
if not isinstance(answer, dict):
return False
fields = cast("dict[str, Any]", answer)
return fields.get("valid") is False or fields.get("complete") is False


def _api_error(status_code: int, envelope: _Envelope, request_id: str | None) -> APIError:
first = envelope.errors[0] if envelope.errors else _ErrorItem()
message = first.message or f"HTTP {status_code}"
Expand Down Expand Up @@ -166,9 +179,9 @@ class Clairic(_ClientBase):
Cloudflare API token.
base_url: str
Cloudflare API root, to route requests through a proxy.
timeout: float | httpx.Timeout
timeout: float | httpx2.Timeout
Seconds to wait for a response. Ignored when `http_client` is given.
http_client: httpx.Client | None
http_client: httpx2.Client | None
HTTP client to send requests with, for custom transports or proxies. The caller
closes it.

Expand All @@ -183,26 +196,26 @@ def __init__(
account_id: str | None = None,
api_token: str | None = None,
base_url: str = DEFAULT_BASE_URL,
timeout: float | httpx.Timeout = DEFAULT_TIMEOUT,
http_client: httpx.Client | None = None,
timeout: float | httpx2.Timeout = DEFAULT_TIMEOUT,
http_client: httpx2.Client | None = None,
) -> None:
super().__init__(account_id=account_id, api_token=api_token, base_url=base_url)
self._owns_http_client = http_client is None
self._http_client = http_client or httpx.Client(timeout=timeout)
self._http_client = http_client or httpx2.Client(timeout=timeout)

def extract(
self, state: str, model: type[M], *, reference_date: dt.date | None = None
) -> Result[M]:
"""Extract the fields of `model` from `state`.

Clairic answers every field in a single pass without generating text, usually in under
a second. Each field of `model` declares its Clairic type through its answer type, its
Each field of `model` declares its Clairic type through its answer type, its
options through an `Annotated` spec, and its instructions through
`Field(description=...)`.

Args:
state: str
Text to read, up to Clairic's 65,536-token context window.
Text to read. With the field definitions, each prompt must fit in 65,273
tokens.
model: type[M]
Extraction model whose fields are answer types.
reference_date: date | None
Expand All @@ -229,9 +242,9 @@ def extract(
body = self._body(state, model, reference_date)
try:
response = self._http_client.post(self._url, json=body, headers=self._headers())
except httpx.TimeoutException as error:
except httpx2.TimeoutException as error:
raise APITimeoutError(f"Clairic did not answer in time: {error}") from error
except httpx.TransportError as error:
except httpx2.TransportError as error:
raise APIConnectionError(f"Could not reach Cloudflare: {error}") from error
return self._parse(response, model)

Expand Down Expand Up @@ -269,9 +282,9 @@ class AsyncClairic(_ClientBase):
Cloudflare API token.
base_url: str
Cloudflare API root, to route requests through a proxy.
timeout: float | httpx.Timeout
timeout: float | httpx2.Timeout
Seconds to wait for a response. Ignored when `http_client` is given.
http_client: httpx.AsyncClient | None
http_client: httpx2.AsyncClient | None
HTTP client to send requests with. The caller closes it.

Raises:
Expand All @@ -285,12 +298,12 @@ def __init__(
account_id: str | None = None,
api_token: str | None = None,
base_url: str = DEFAULT_BASE_URL,
timeout: float | httpx.Timeout = DEFAULT_TIMEOUT,
http_client: httpx.AsyncClient | None = None,
timeout: float | httpx2.Timeout = DEFAULT_TIMEOUT,
http_client: httpx2.AsyncClient | None = None,
) -> None:
super().__init__(account_id=account_id, api_token=api_token, base_url=base_url)
self._owns_http_client = http_client is None
self._http_client = http_client or httpx.AsyncClient(timeout=timeout)
self._http_client = http_client or httpx2.AsyncClient(timeout=timeout)

async def extract(
self, state: str, model: type[M], *, reference_date: dt.date | None = None
Expand All @@ -299,9 +312,9 @@ async def extract(
body = self._body(state, model, reference_date)
try:
response = await self._http_client.post(self._url, json=body, headers=self._headers())
except httpx.TimeoutException as error:
except httpx2.TimeoutException as error:
raise APITimeoutError(f"Clairic did not answer in time: {error}") from error
except httpx.TransportError as error:
except httpx2.TransportError as error:
raise APIConnectionError(f"Could not reach Cloudflare: {error}") from error
return self._parse(response, model)

Expand Down
Loading
Loading