API reference¶
nirmala.pipeline
¶
Extraction + decisions in one call, sync or async, one document or many.
Pipeline
¶
An :class:Extractor followed by a :class:DecisionEngine.
pipe = Pipeline(rules=[...], gate=Gate(field=80, average=90)) result = pipe.run("policy.pdf", Policy) result.data, result.verdict.decision
arun_many(sources, schema, *, concurrency=4)
async
¶
Run many documents concurrently; failures are returned, not raised.
extract(source, schema, *, llm=None, rules=(), gate=None, judge=None, **options)
¶
One-call API: extract schema from source; verify when rules or gate are given.
aextract(source, schema, *, llm=None, rules=(), gate=None, judge=None, **options)
async
¶
Async :func:extract.
nirmala.extract
¶
PDF -> typed Pydantic model, grounded in the document text.
ExtractionResult
dataclass
¶
Bases: Generic[T]
What :meth:Extractor.extract returns.
data is the validated model (None only if validation failed for a
required field; see validation_errors). values holds the grounded,
normalized values before validation and raw the model's reply as parsed.
Extractor
¶
Configurable extraction engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LLMClient | None
|
Any :class: |
None
|
vision_llm
|
LLMClient | None
|
Client/model used when a PDF has no text layer (defaults to llm). |
None
|
vision_model
|
str | None
|
Model id passed to the vision client, if different. |
None
|
max_pages
|
int
|
Text pages shown to the model (later pages are pulled in
only for missing field |
6
|
max_chars
|
int
|
Character budget of the document text in the prompt. |
30000
|
vision
|
bool
|
Render scanned PDFs to images instead of failing. |
True
|
vision_pages
|
int
|
Pages rendered for the vision path. |
5
|
passwords
|
PasswordSource
|
Candidate passwords (list, callable or
:class: |
None
|
normalizers
|
Normalizers | None
|
:class: |
None
|
postprocessors
|
Sequence[PostProcessor]
|
|
()
|
instructions
|
str | None
|
Extra prompt rules applied to every extraction. |
None
|
events
|
EventTarget
|
Event sink or callable receiving progress events. |
None
|
extract(source, schema, *, instructions=None)
¶
Extract schema from one document (path, bytes, file or :class:Document).
aextract(source, schema, *, instructions=None)
async
¶
Async :meth:extract; document parsing runs in a worker thread.
extract_best(sources, schema, *, target=None, instructions=None)
¶
Dedupe sources, pick the one that is the target document, extract it.
target describes the document you want ("the insurance policy
schedule", "the final invoice"); it defaults to the schema's docstring.
Raises :class:ExtractionError when the selector is unsure.
select(documents, target)
¶
Ask the model which of documents is target; None when uncertain.
ground(raw, specs, document_text)
¶
Apply choices, verbatim snapping and normalizers to a raw reply.
parse_json_object(text)
¶
The first JSON object in a model reply (markdown fences tolerated).
nirmala.schema
¶
Schemas are plain Pydantic models; :func:field adds extraction hints.
.. code-block:: python
from pydantic import BaseModel
from nirmala import field
class Invoice(BaseModel):
number: str = field("Invoice number as printed", verbatim=True)
total: Decimal | None = field("Grand total including tax")
currency: str | None = field("ISO currency", choices=["INR", "USD", "EUR"])
FieldSpec
dataclass
¶
Everything nirmala knows about one schema field.
field(description='', *, default=None, verbatim=False, prefixes=(), choices=None, hint=None, normalize=None, critical=False, instructions=None, **kwargs)
¶
A Pydantic Field carrying nirmala's extraction options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
str
|
What the model should extract (goes into the prompt). |
''
|
verbatim
|
bool
|
Snap the value to the exact printed text. |
False
|
prefixes
|
Sequence[str]
|
Printed prefixes to keep when snapping (e.g. honorifics). |
()
|
choices
|
Sequence[str] | None
|
Allowed values; answers are snapped to one or set to |
None
|
hint
|
str | None
|
Regex for a page that carries this field (see |
None
|
normalize
|
Callable[..., Any] | None
|
|
None
|
critical
|
bool
|
Must be present and confidently verified for auto-approval. |
False
|
instructions
|
str | None
|
Extra per-field rules for the model. |
None
|
build_prompt(schema, *, instructions=None, document_text=None)
¶
The extraction prompt for schema: one line per field plus the document.
nirmala.documents
¶
Document intake: open, decrypt, dedupe, read text, pick pages, render images.
Page
dataclass
¶
One page of extracted text (1-based number).
Document
dataclass
¶
A PDF held in memory.
Build one with :meth:Document.open (path, bytes or file object).
metadata is yours: put ids, filenames or anything your
:class:~nirmala.providers.PasswordProvider needs.
is_encrypted()
¶
True when the PDF needs a user password to open.
unlock(passwords=None)
¶
Return self once opened, trying each candidate password.
Raises :class:PasswordRequired when the file is encrypted and no
candidate works. An unencrypted file is returned unchanged.
broken_reason()
¶
Why this file cannot be a readable PDF, or None when it looks fine.
pages(max_text_pages=None, max_chars=None)
¶
Extract text page by page, releasing each page as it goes.
With max_text_pages a scanned file (no text on its first
:data:SCANNED_PROBE_PAGES pages) stops early, and at most
2 * max_text_pages pages are examined.
render_jpeg(max_pages=5, *, max_dim=1568, quality=70)
¶
Render the first pages to base64 JPEGs (for vision models).
dedupe(documents)
¶
Drop byte-identical documents, keeping the first of each.
select_pages(pages, *, max_pages=6, hints=(), extra_pages=2)
¶
Keep the first max_pages text pages, then pull in later pages for missing hints.
Each hint is a regex for something the schema needs (a totals table, a
signature block...). When no kept page matches a hint, the first later
page that does is added (up to extra_pages in total), in page order.
join_pages(pages, max_chars=30000)
¶
The text shown to the model: --- PAGE n --- blocks, truncated.
nirmala.grounding
¶
Grounding: keep extracted values faithful to what the document actually prints.
- :func:
verbatim_matchsnaps an LLM-normalized string back to the exact printed span (case, spacing and punctuation preserved). - :func:
parse_number, :func:parse_dateand :func:snap_choiceare the default normalizers. Replace any of them per field or per type through :class:Normalizers.
Normalizers
¶
Which normalizer runs for each field.
Resolution order for a field: by_field[name] -> the field's own
nirmala_field(normalize=...) -> by_type[annotation] -> unchanged.
Pass None as a value to switch a default off.
norms = Normalizers(by_field={"policy_no": str.upper}, by_type={date: my_date_parser})
verbatim_match(value, text)
¶
Return the exact span of text that matches value.
Matching ignores case, whitespace and punctuation but requires word
boundaries, so "SON" never matches inside "PERSON".
verbatim_with_prefixes(value, text, prefixes=())
¶
Like :func:verbatim_match, but prefer a printed form that starts with one of prefixes.
Useful for honorifics: with prefixes=("MR.", "DR.") a model answer of
"Kapil Mittal" becomes the printed "MR. KAPIL MITTAL".
parse_number(value)
¶
Parse a printed amount: "₹ 1,23,456.00" -> Decimal("123456.00").
Strips currency symbols/codes, grouping commas and spaces, the Indian
/- suffix, and reads (1,200) as negative. Returns None when
nothing numeric remains.
parse_date(value, *, dayfirst=True)
¶
Parse common printed dates; None when unrecognised.
Handles ISO (2026-05-01, with or without time), 01/05/2026,
01-05-26 (dayfirst decides day/month order), 1 May 2026,
May 1, 2026 and 01-May-2026.
date_spellings(value)
¶
Ways a document may print value (for evidence checks).
snap_choice(value, choices, *, cutoff=0.85)
¶
Map value onto one of choices (case-insensitive, then fuzzy); else None.
call_normalizer(fn, value, ctx)
¶
Call fn as fn(value, ctx) or, for one-argument callables like str.upper, fn(value).
nirmala.decisions.engine
¶
The decisions engine: rules + per-field confidence + a gate -> one Verdict.
Gate
dataclass
¶
Auto-approval thresholds (0-100).
Every critical field must score at least field; the mean over all
scored fields must reach average. critical=None uses the fields
marked field(..., critical=True) in the schema.
DecisionEngine
¶
Evaluates an extraction and returns a :class:Verdict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rules
|
Iterable[Rule]
|
Any mix of |
()
|
gate
|
Gate | None
|
Confidence thresholds; |
None
|
judge
|
Judge | None
|
Model judge for NL rules and confidence (OpenCode by default). |
None
|
trust_code_evidence
|
bool
|
A value visibly printed in the document scores 100 without asking the judge. |
True
|
ignore
|
Iterable[str]
|
Fields never scored (e.g. ones that are not applicable). |
()
|
Decision: any failed reject rule -> reject; otherwise any failed
block rule, gate miss or judge failure -> review; else approve.
evaluate(result=None, *, values=None, document_text=None, critical=())
¶
Evaluate an :class:~nirmala.ExtractionResult (or raw values + document_text).
nirmala.decisions.rules
¶
Rules: Python decorators, natural-language checks and declarative YAML.
All three produce :class:~nirmala.decisions.RuleOutcome objects and can be
mixed freely in one :class:~nirmala.decisions.DecisionEngine.
RuleContext
dataclass
¶
What every rule sees.
printed(value)
¶
True when value (string, number or date) appears in the document.
Rule
¶
Base class. Subclass and implement :meth:check, or use :func:rule.
NLRule
¶
Bases: Rule
A rule written in plain language and checked by the judge model.
NLRule("The premium equals the base premium plus GST", field="premium")
All natural-language rules of one evaluation go to the judge in one call.
evidence_for(value, text)
¶
Code-level support check: is value visibly printed in text?
rule(fn=None, *, name=None, field=None, severity='block', when=None, message=None)
¶
Decorator turning a function into a :class:Rule.
.. code-block:: python
@rule(field="total", when="currency == 'INR'")
def total_is_printed(ctx):
"Total must be printed on the document"
return ctx.printed(ctx["total"])
compile_expr(source, functions=None)
¶
Compile a small, side-effect-free expression over field names.
Supports arithmetic, comparisons, and/or/not, in, literals, lists
and the functions in :data:SAFE_FUNCTIONS (present(x),
diff(a, b), matches(x, '^[A-Z]')...). printed(x) checks the
value appears in the document. Unknown names evaluate to None.
rules_from_config(items)
¶
Build rules from dicts (the YAML format).
.. code-block:: yaml
- name: idv_for_motor
when: insurance_type == 'Motor'
require: idv > 0
field: idv
severity: block # reject | block | warn
message: Motor policies must print an IDV
- name: premium_math
judge: The total premium equals the base premium plus GST.
field: total_premium
load_rules(source)
¶
Load rules from a YAML file path or YAML text (needs pip install nirmala[yaml]).
nirmala.decisions.judge
¶
The judge: typed questions answered by a model, failing closed.
A decision request is a state (the evidence: document text and the
extracted values) plus a map of typed questions::
{
"premium_ok": {"type": "boolean", "prompt": "Is premium = base + GST?"},
"conf.total": {"type": "number", "min": 0, "max": 100, "prompt": "..."},
"doc_kind": {"type": "choice", "choices": ["invoice", "receipt"], "prompt": "..."}
}
:meth:Judge.decide returns only answers that match their declared type.
Any failure (backend down, unparseable reply, wrong type) leaves that answer
out, and callers treat a missing answer as "not verified" — no error path can
ever produce an approval.
Decision
dataclass
¶
A judge reply.
Judge
¶
Answers typed questions with any :class:~nirmala.llm.LLMClient.
Defaults to :class:~nirmala.llm.OpenCodeClient, so the judge can run on a
different (often stronger) model than extraction: Judge(model="opencode-go/qwen4-max").
coerce_answer(value, spec)
¶
value if it matches the question's type, else None (= unanswered).
nirmala.decisions.verdict
¶
Results produced by the decisions engine.
nirmala.llm.opencode
¶
OpenCode backend: drive a local opencode serve (v2 API) as the model gateway.
OpenCode gives you every provider you have signed in to (OpenCode Go/Zen, GitHub Copilot, OpenAI, Anthropic, local models...) behind one local server, so nirmala never handles provider API keys itself.
- Text prompts use the stateless
POST /api/experimental/generate. - Prompts with images open a short-lived session with every tool permission denied, send the images as file attachments, wait, read the reply and delete the session.
When no server URL is given, :class:OpenCodeClient starts opencode
serve on a free localhost port in an empty temporary directory and stops it
on :meth:close (or at interpreter exit).
OpenCodeClient
¶
:class:~nirmala.llm.LLMClient backed by OpenCode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
|
None
|
base_url
|
str | None
|
A running server ( |
None
|
password
|
str | None
|
The server password ( |
None
|
timeout
|
float
|
Default per-request timeout in seconds. |
120.0
|
parse_model(model)
¶
"provider/model[#variant]" -> OpenCode Model.Ref.
find_opencode_binary(explicit=None)
¶
Locate the real opencode executable (npm shims resolved on Windows).
nirmala.llm.openai_compat
¶
Direct OpenAI-compatible backend (OpenRouter, vLLM, Ollama, LM Studio...).
For environments where running opencode serve is not possible (serverless
functions, locked-down containers). Standard library only.
OpenAICompatibleClient
¶
POSTs to {base_url}/v1/chat/completions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Model id understood by the endpoint. |
required |
base_url
|
str | None
|
API root ( |
None
|
api_key
|
str | None
|
Bearer token ( |
None
|
retries
|
int
|
Extra attempts on timeouts and retryable HTTP statuses. |
1
|
extra_body
|
dict[str, Any] | None
|
Merged into every request (e.g. |
None
|
nirmala.providers
¶
Extension points: plug your own infrastructure and domain logic into nirmala.
Every hook is a small :class:typing.Protocol or a plain callable, so an
application can supply a class, a function or a lambda. nirmala never imports
your storage, CRM or cloud SDK — you hand it these objects instead.
===================== ==========================================================
Hook Called for
===================== ==========================================================
PasswordProvider candidate passwords for an encrypted PDF
EventSink progress events (stage started / finished / warning)
Normalizer turning a raw LLM value into the value you store
PostProcessor whole-record fixes after extraction (derived fields etc.)
===================== ==========================================================
PasswordProvider
¶
Bases: Protocol
Yields candidate passwords for an encrypted document.
document is the :class:nirmala.Document being opened; use its
name, sha256 or metadata to look passwords up.
EventSink
¶
Bases: Protocol
Receives pipeline events: emit("extract.started", {...}).
NormalizeContext
¶
What a :data:Normalizer may look at besides the raw value.
resolve_passwords(source, document)
¶
Return the candidate list from any accepted source shape.
emit(target, event, **data)
¶
Send event to target; a failing sink never breaks extraction.
nirmala.testing
¶
Test helpers: a scripted LLM so your tests never call a real model.
FakeLLM
¶
An :class:~nirmala.llm.LLMClient that replies from a script.
replies may be strings, dicts (sent as JSON) or a callable
(prompt, images) -> str | dict. Every call is recorded in calls.
llm = FakeLLM([{"number": "INV-1"}])