API reference¶
This page is auto-generated from the source code's docstrings via mkdocstrings. If you're reading the rendered site, the symbols below expand on click.
Top-level¶
idp
¶
py-idp: General-purpose, AI-enabled Intelligent Document Processing framework.
A six-stage pipeline: parse -> classify -> extract -> assess -> validate -> HITL. Each stage is a pure function over a Document, pluggable, and independently testable.
Design draws from
- aws-solutions-library-samples/accelerated-intelligent-document-processing-on-aws (pipeline shape, HITL, confidence assessment)
- docling-project/docling (parser: PDF, tables, reading order)
- run-llama/llama_cloud_services (Pydantic-schema-driven extraction API)
- Unstructured-IO/unstructured (chunking + multi-format ingest)
Document
dataclass
¶
A document flowing through the IDP pipeline.
Stages mutate this in-place by setting the corresponding attribute (parsed_pages, classification, extraction, confidence, validation).
Source code in src/idp/core/document.py
parser_used
¶
Pipeline
¶
Compose the six stages. Each stage can be skipped via flags.
Template support: pass a :class:idp.templates.Template (or a
string name resolved against a registry) and the template's
Markdown body is prepended to every LLM extraction call as
document-type-specific guidance. See idp/templates.py.
Source code in src/idp/pipeline/pipeline.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
arun
async
¶
arun(doc: Document) -> PipelineResult
Async variant of run() — runs the blocking pipeline in a
worker thread so the FastAPI event loop stays responsive.
Without this, Pipeline.run() (which calls sync LLM clients and
on Nanonets runs torch inference) blocks the event loop for
5–15 s per request, freezing the entire server. arun uses
asyncio.to_thread to dispatch the blocking work to the default
thread pool, freeing the event loop to handle health checks,
other concurrent requests, etc.
Performance note: this trades parallelism-on-the-loop for one
blocking operation per request. For sustained throughput you still
want a separate worker process; arun is the minimum-viable
fix to keep the HTTP tier responsive when Nanonets (or any
synchronous backend) is the chosen LLM.
Source code in src/idp/pipeline/pipeline.py
set_template_registry
¶
Attach a TemplateRegistry for resolving string template names.
Usage::
from idp.templates import TemplateRegistry
registry = TemplateRegistry.load("./templates")
pipeline = Pipeline(backend="mock", template="invoice")
pipeline.set_template_registry(registry)
result = pipeline.run(doc)
The registry is consulted at run() time, so calls benefit from
hot-reload if watch=True was passed when loading.
Source code in src/idp/pipeline/pipeline.py
discover_schema
¶
discover_schema(source: str | Path | Document, *, hint: str = _DEFAULT_HINT, backend: Backend | None = None, page_limit: int = 4) -> DiscoveryResult
Infer a Pydantic schema from a PDF + natural-language hint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | Document
|
PDF path or a pre-parsed |
required |
hint
|
str
|
Natural-language description of fields to extract. Example: "extract vendor_name, total_amount, and line items". Pass an empty string to let the LLM infer fields from the document alone. |
_DEFAULT_HINT
|
backend
|
Backend | None
|
Multimodal backend to use. Defaults to NanonetsVLBackend
(gated by |
None
|
page_limit
|
int
|
Max pages to render for the prompt. Default 4 keeps the prompt under most models' context budgets. |
4
|
Returns:
| Type | Description |
|---|---|
DiscoveryResult
|
|
DiscoveryResult
|
raw |
DiscoveryResult
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
if the source path doesn't exist. |
ValueError
|
if the LLM's output isn't valid JSON Schema. |
RuntimeError
|
if the backend fails. |
Source code in src/idp/discover.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
Pipeline¶
pipeline
¶
Pipeline orchestrator.
Composes the six stages: parse -> classify -> extract -> assess -> validate.
Each stage is a pure function that mutates a Document. The pipeline
adds structured logging and timing, and returns a PipelineResult with
both the document and a per-stage timing/cost breakdown.
Pipeline
¶
Compose the six stages. Each stage can be skipped via flags.
Template support: pass a :class:idp.templates.Template (or a
string name resolved against a registry) and the template's
Markdown body is prepended to every LLM extraction call as
document-type-specific guidance. See idp/templates.py.
Source code in src/idp/pipeline/pipeline.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
arun
async
¶
arun(doc: Document) -> PipelineResult
Async variant of run() — runs the blocking pipeline in a
worker thread so the FastAPI event loop stays responsive.
Without this, Pipeline.run() (which calls sync LLM clients and
on Nanonets runs torch inference) blocks the event loop for
5–15 s per request, freezing the entire server. arun uses
asyncio.to_thread to dispatch the blocking work to the default
thread pool, freeing the event loop to handle health checks,
other concurrent requests, etc.
Performance note: this trades parallelism-on-the-loop for one
blocking operation per request. For sustained throughput you still
want a separate worker process; arun is the minimum-viable
fix to keep the HTTP tier responsive when Nanonets (or any
synchronous backend) is the chosen LLM.
Source code in src/idp/pipeline/pipeline.py
set_template_registry
¶
Attach a TemplateRegistry for resolving string template names.
Usage::
from idp.templates import TemplateRegistry
registry = TemplateRegistry.load("./templates")
pipeline = Pipeline(backend="mock", template="invoice")
pipeline.set_template_registry(registry)
result = pipeline.run(doc)
The registry is consulted at run() time, so calls benefit from
hot-reload if watch=True was passed when loading.
Source code in src/idp/pipeline/pipeline.py
PipelineResult
dataclass
¶
Source code in src/idp/pipeline/pipeline.py
save_result
¶
save_result(result: PipelineResult, output_path: str | Path) -> None
Backends¶
backend
¶
LLM backend abstraction.
All stages call Backend.complete() and get back a string. Backends
handle their own deps lazily (openai/anthropic/ollama) so the framework
runs without any of them installed.
A MockBackend ships for tests + reproducible eval, when the user
has no API keys / hardware.
Adding a new backend¶
Subclass Backend and decorate it with register_backend("name").
name becomes the canonical lookup key for get_backend("name"),
and the class is then listed by list_backends(). Aliases for
backward compatibility go in _REGISTRY_ALIASES.
Backend
¶
Bases: ABC
Pluggable LLM backend.
Backends implement :meth:complete (sync). For async use, backends
also expose :meth:acomplete, which by default delegates to
:meth:complete via :func:asyncio.to_thread so every existing
backend transparently supports await. Backends with a native
async HTTP client (e.g. openai.AsyncOpenAI,
anthropic.AsyncAnthropic) can override :meth:acomplete for
better performance.
Source code in src/idp/llm/backend.py
json_complete
¶
Complete + parse JSON. Never raises.
On parse failure returns {"_error": ..., "_raw": ...} so the
caller can decide whether the empty dict is acceptable or whether
it should route to an error path.
Source code in src/idp/llm/backend.py
acomplete
async
¶
Async version of :meth:complete.
Default implementation runs the sync :meth:complete in a
worker thread via :func:asyncio.to_thread so every existing
backend automatically supports async. Backends with a native
async client (anthropic, openai) can override this for better
performance.
Source code in src/idp/llm/backend.py
get_backend
¶
get_backend(name: str = 'auto', **kwargs: Any) -> Backend
Resolve a backend by name.
'auto' picks in this order: env override -> anthropic -> openai -> ollama -> mock.
Recognized names
mock | mock-ideal | mock-random | mock-omits (no API key needed) openai | ollama | vllm | compat | anthropic (international) intl:groq | intl:mistral | intl:together | (international providers) intl:cohere | intl:fireworks china:deepseek | china:qwen | china:zhipu | (China providers) china:moonshot | china:yi | china:doubao | china:hunyuan | china:baichuan nanonets (gated, self-hosted OCR) unlimited-ocr (gated, self-hosted OCR, v0.6) slowmock (load-test only)
For China providers you can pass multimodal=True to switch to the
provider's vision model if it has one. Pass api_key= or set the
provider's env var.
The slowmock backend is only enabled when IDP_ENABLE_SLOWMOCK=1
is set in the environment. Production deployments never set this; it's
intended for load-testing only.
To register a new backend without editing this file, use
@register_backend("name") (see module docstring).
Source code in src/idp/llm/backend.py
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 | |
Schemas¶
schemas
¶
Built-in example schemas that ship with py-idp.
Users can supply their own Pydantic models; these are reference implementations.
SCHEMA_REGISTRY
module-attribute
¶
SCHEMA_REGISTRY: dict[str, type[BaseModel]] = {'Invoice': Invoice, 'Contract': Contract, 'BankStatement': BankStatement, 'Receipt': Receipt, 'W2': W2, 'IDCard': IDCard, 'MedicalClaim': MedicalClaim}
Invoice
¶
Bases: BaseModel
Standard invoice extraction schema.
Minimal required fields chosen from real-world IDP requirements: an invoice that lacks an ID, vendor identity, or a total isn't an invoice we can route or pay. Everything else is optional because partial extractions from weaker LLMs are still useful.
Source code in src/idp/core/schemas.py
Contract
¶
Bases: BaseModel
Basic contract extraction schema.
Title is required: a contract without a title is unidentifiable. Parties and effective dates are optional — partial extraction still surfaces what was found for downstream HITL review.
Source code in src/idp/core/schemas.py
BankStatement
¶
Bases: BaseModel
Bank statement extraction schema.
Account holder is required — a statement without an identified account holder is unactionable. Transactions and balances are optional and may be partially extracted.
Source code in src/idp/core/schemas.py
BankTransaction
¶
Receipt
¶
Bases: BaseModel
Receipt extraction schema (CORD: Consolidated Receipt Dataset shape).
merchant_name is required (a receipt without an identified merchant
is unactionable). Other fields are optional and may be partially
extracted — handwritten or faded receipts often miss subtotals, tips,
or tax.
Source code in src/idp/core/schemas.py
LineItem
¶
HITL¶
store
¶
Storage interface.
Keeps the framework decoupled from any specific database / object store. Default in-memory implementation supports tests + single-node demos. Swap in Postgres + S3 (or whatever) for production.
JsonFileStorage
¶
Bases: Storage
Line-delimited JSON store on disk. Trivially inspectable, zero-deps.
Memory profile: keeps an in-memory cache of the file's parsed
StoredResults. Cache is invalidated on put() and
mark_reviewed(). For a file with N entries, peak memory is
roughly 2-3× the on-disk JSON size (raw dicts + StoredResult
objects + the cache dict itself).
For workloads with >10k stored results, switch to SqlStorage
instead — JSONL doesn't index either and the full-file cache
becomes the dominant cost.
Source code in src/idp/storage/store.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
StoredResult
dataclass
¶
A pipeline run, persisted.