Enterprise integrations receive many kinds of documents: invoices, receipts, identity documents, statements, forms, and organization-specific records. Depending on the task, a workflow may need to identify a document type, extract predefined fields, recognize the words on a page, or preserve a table’s row-and-column structure. OCI Document Understanding provides different operations for these different jobs; there is no single operation that reliably turns every document into every business field.
For an Oracle Integration 3 (OIC) engineer, the design challenge is deciding where extraction ends and deterministic validation, human correction, and downstream commitment begin. A small supported document may suit a synchronous request; larger or decoupled workloads often need a recoverable Processor Job flow and Object Storage result reconciliation. In either case, preserving source references and page-level evidence helps explain a result later.
This tutorial demonstrates the native OIC Document Understanding action and the signed REST API route. A fictional supplier invoice is the detailed worked example for key-value and line-item extraction, while classification, text extraction, table extraction, batch processing, and custom models show how to build a broader document-processing workflow. Runtime output is not treated as business truth, approval, or proof that a target-system transaction should be committed.
1. What You Will Build
The detailed fixture is a fictional procurement invoice, NIS-2026-117.pdf, stored in an Object Storage input bucket. OIC will extract invoice header fields and line items, retain page and geometry references, compare the result with a trusted purchase-order record, and route unresolved cases to review. This invoice is a worked example, not a claim that Document Understanding is limited to invoices or that every document type supports the same fields.
Practical outcome
- Process one supported document synchronously through the native OCI Document Understanding action and the REST API; use invoice extraction as the detailed example.
- Inspect extracted fields, confidence scores, line items, page numbers, and bounding polygons where the selected operation returns them.
- Classify an unknown document when useful, then route only to an operation/model that supports that document type.
- Use text extraction when you need recognized words and lines, and table extraction when you need row-and-column structure.
- Submit a batch Processor Job, poll its lifecycle, retrieve output artifacts, reconcile failures, and prevent duplicate business processing.
- Choose a pretrained or custom model based on documented capability, region availability, and a labeled evaluation—not on a demo alone.
Quick map: choose the operation by the result you need
Start with the output your business process actually needs. A document type, a field value, recognized text, and table cells are different outputs, so do not choose an operation only because the input file happens to be a PDF.
| Your goal | Start with | Important boundary |
|---|---|---|
| Decide what kind of document arrived | Document classification | The pretrained classifier returns candidate types and confidence scores. Use policy and review for ambiguous or unsupported files. |
| Extract known fields from a supported document type | The matching pretrained key-value model, or a custom model for a measured gap | Do not send an arbitrary document to the invoice model and assume its field schema applies. |
| Get recognized words, lines, and source locations | Text extraction | Recognized text does not identify the business meaning of a number or approve a transaction. |
| Preserve a table’s cells and columns | Table extraction | The documented table-extraction feature is English-only; cell structure still needs business validation. |
| Process many or longer documents asynchronously | Processor Job with Object Storage input and output | Store the job ID, poll a bounded lifecycle, retrieve the actual output objects, and reconcile every input. |
| Extract organization-specific fields or categories | Evaluate a custom key-value or classification model | Check model type, supported region, permissions, and held-out test accuracy before adopting it. |
A useful beginner mental model is: Document Understanding produces observations; OIC moves and maps them; trusted business systems and deterministic rules decide what those observations mean; people review uncertainty. The native OIC action and REST API can implement similar business outcomes, but their request/response schemas and identity configuration are different.
The main implementation boundary is explicit: the article supplies a reproducible processing pattern and synthetic fixtures, but no OIC tenant, Object Storage bucket, procurement endpoint, or executed run was supplied. Therefore, all runtime outputs below are illustrative and all tests are marked Not executed. Completion means the reader can configure the documented route and inspect the stated evidence—not that a fictional deployment has already run.
2. In This Post
- Before You Begin — Shared Setup
- Worked example: invoice key-value extraction, validation, and human review
- Document classification and routing
- OCR and text extraction with source geometry
- Table extraction and line-item reconciliation
- Batch Processor Jobs: submit, poll, retrieve, reconcile
- Custom classic versus generative models
- Combine the completed paths
- Completion checklist and next steps
- Five useful FAQs
- References checked
- Finally — Summary
3. Before You Begin — Shared Setup
3.1 Confirm the actual product boundary
OCI Document Understanding is the OCI service. The OCI Document Understanding action in OIC is a separate, native orchestration feature that invokes supported service capabilities. A REST Adapter call is a third implementation path. The three can share a business contract, but their configuration schemas and response envelopes are not interchangeable.
Oracle's currently published OIC documentation describes native actions for pretrained models, custom models, and Processor Job create/status/cancel operations. The published OIC AI action documentation also states that these OCI AI actions are available only in the commercial realm (OC1); verify your tenant's realm and the action's current availability before designing around it. OIC's current public documentation is the baseline used here as of 28 October 2026; no tenant release or patch was supplied, so do not interpret this as a statement about your specific instance. See the OIC Document Understanding action guide and OIC AI feature availability.
3.2 Identity and permissions: native action versus REST Adapter
For the native OIC action, Oracle documents an identity-domain tenancy, a dynamic group matching the OAuth application client ID for the OIC instance, and a policy granting access to the Document Understanding resource family. The matching-rule pattern is resource.id = '<OIC_OAUTH_CLIENT_ID>'. Oracle's OIC prerequisite guide gives this policy pattern: Allow dynamic-group <dynamic_group> to manage ai-service-document-family in compartment <compartment_name>. In that OIC guide, the compartment placeholder refers to the compartment where the Oracle Integration instance is located. Create the policy according to the current OIC AI-service prerequisites; do not replace this with a REST-signing user's policy or infer scope from the Object Storage bucket alone.
For an OIC REST Adapter connection, configure the invoke connection with the OCI Signature Version 1 security policy. That route signs requests with the OCI API-signing identity configured in the connection; it is not automatically the same identity as the native action's dynamic group. For a REST caller, Oracle's Document Understanding IAM guide shows this broad API-access example: Allow group <signing_group> to manage ai-service-document-family in tenancy. The guide says to create Document Understanding user-access policies at the tenancy root. Treat this as Oracle's documented broad example, not an automatic production least-privilege recommendation. The REST Adapter guide specifies an RSA API-signing key in PKCS1 format; a key downloaded as PKCS8 must be converted if required by the adapter. It also states that private endpoints are not supported with this security policy, so verify network reachability and endpoint design before selecting this route. Follow the OCI Signature Version 1 REST Adapter guide, connection prerequisites, and Document Understanding IAM policy guide.
Object Storage input and output require separate access decisions. Oracle's Document Understanding IAM guide gives a broad same-tenancy input example, Allow group <signing_group> to manage object-family in tenancy, and documents an output policy scoped to the compartment containing the output bucket. The input policy is broad; do not copy it blindly into production. Confirm the exact same-tenancy or cross-tenancy pattern, the identity that reads source objects, and the identity/service path writing results. Narrow permissions only to a supported policy model and verify them with denied-access tests. Permission to invoke Document Understanding does not, by itself, prove permission to read source objects or write results.
3.3 Endpoint, API version, file limits, and language checks
Use the regional Document Understanding endpoint, for example https://document.aiservice.<region>.oci.oraclecloud.com. The REST resource path in this tutorial uses API version 20221109. This is the OCI API version, not an OIC release number or a document-model version. Resolve the actual endpoint for the service region and realm from the OCI API reference and endpoints before use.
| Document Understanding limit | Published value to design against | Engineering implication |
|---|---|---|
| File types | JPEG, PNG, PDF, TIFF | Reject unsupported extensions/content before invocation; verify that the bytes match the declared media type. |
| Synchronous document | 8 MB maximum; five pages or fewer | Use for small, latency-sensitive documents only; avoid passing an oversized PDF to the synchronous path. |
| Asynchronous inline | 8 MB maximum; five pages or fewer | Async does not remove the inline size/page restriction. |
| Asynchronous Object Storage | 500 MB per document; up to 2,000 pages per document; at most 2,000 documents per job or a request body of 500 KB or less | Prefer object references for batches; check both the document/job-count and request-body limits before building the manifest. |
| Image geometry | 32 × 32 minimum and 10,000 × 10,000 maximum; minimum text height 15 pixels | A syntactically valid image can still be unreadable because of low resolution, skew, blur, or compression. |
The values above come from Oracle's Document Understanding limits page. They are service-level limits, not a guarantee that every native OIC action or adapter accepts every listed file format; the OIC action guide generally describes PDF, PNG, and JPEG inputs. Confirm the selected action’s current input contract before using TIFF or relying on any route-specific file behavior. Quotas, tenant configuration, OIC message constraints, and downstream target limits are separate. Check each one before sizing throughput. Do not interpret an asynchronous limit as a promise of completion time.
Language support is model- and operation-specific. The current Getting Started table lists Version 2 multilingual options for OCR and invoice/receipt key-value extraction, while the standalone OCR feature page still says OCR is limited to English. These two Oracle pages are not fully aligned. Treat this as an operation/version-specific documentation discrepancy: confirm the selected model version, language parameter, region, and tenant behavior before processing non-English invoices. Table extraction is documented as English-only. Do not transfer a service-wide language list to every model.
3.4 Shared learning fixture and audit contract
Create two private Object Storage buckets in the intended region: procure-invoices-in for source documents and procure-invoices-out for generated results. Upload synthetic PDFs named incoming/NIS-2026-117.pdf and incoming/NIS-2026-118.pdf. Use your own Object Storage namespace, compartment OCID, and region; the names in this article are illustrative. Do not store real supplier bank details or customer PII in a learning fixture.
Use this minimal inbound OIC business contract for the synchronous path:
{
"documentId": "DOC-0001",
"objectName": "incoming/NIS-2026-117.pdf",
"purchaseOrderNumber": "PO-450018",
"legalEntity": "ACME-INDIA"
}
The purchaseOrderNumber and legalEntity values are lookup keys for the trusted procurement system, not facts that Document Understanding should invent. The source object name is the stable link back to the uploaded document. A production audit record should also capture the source version/ETag or a source checksum where available, the request or job ID, the model/version returned, extraction values and geometry, validation outcomes, reviewer corrections, timestamps, and downstream correlation ID. Keep raw invoice text and sensitive fields out of ordinary logs and fault emails.
4. Worked Example — Invoice Key-Value Extraction, Validation, and Review
4.1 Purpose, first principles, and suitability
Invoice key-value extraction applies a pretrained invoice model to identify a documented set of header fields and line-item values. For example, the service can return invoice ID, invoice date, vendor name, purchase order, subtotal, tax, invoice total, amount due, and item fields such as description, quantity, unit price, product code, and line amount. See Oracle's supported invoice fields and response example.
Kid-friendly analogy
Imagine a student copying the invoice number and total from a paper into a worksheet. The teacher can check where the student found each value, but must still compare the total with the class purchase record before approving it.
In this OCI AI integration, this means: The model extracts field values and source geometry; OIC validates them against trusted purchase-order and supplier data before any consequential write.
An invoice PDF may contain selectable text or be a scan. The same document can still be processed, but a scan is more sensitive to blur, skew, faint print, and small characters. Image quality and format eligibility do not guarantee correct extraction. The model returns evidence and confidence signals; the procurement system remains authoritative for supplier status, PO existence, approved prices, allowed currency, tax treatment, tolerances, and duplicate detection.
4.2 Native OIC route — configure and map the invoice action
- Add the activity. In an OIC integration, add OCI Document Understanding, choose category Pre-trained Models, then choose Analyze document (with confidence score) if the workflow needs field-level confidence for review decisions. Use Analyze document only when the confidence-score variant is not part of the contract you need. These are native OIC action labels documented in the native action guide.
- Set the service region and compartment. Choose the region containing the model/service you intend to call and the permitted OCI compartment. The native action supports a region override at runtime through its generated
Region Idtarget element; do not dynamically override it unless that region has been validated and the identity can access it. - Choose the document type. Select Invoice. This enables the predefined invoice key-value model. The selected type is reflected in the generated mapper schema; it is a configuration choice rather than a field extracted from the document.
- Choose the source. Select Object storage and configure the input bucket and namespace, or choose Inline for a document passed in the request. Object Storage is used in the main example because it avoids carrying document bytes in an OIC JSON payload and supports the separate batch route. With Object Storage, map the file name to the mapper's generated Document → Object Name target. Map Bucket Name and Namespace Name only if you intend to override wizard values.
- Finish and configure the request mapper. In the generated request wrapper, map the source
objectNamevalue toDocument/Object Name. Check the generated target schema rather than inventing REST fields such asdocument.objectNamein the OIC action mapper. OIC's native wrapper is connector-generated and is not the literal REST JSON envelope. - Configure the response mapper. Preserve the document ID and object name alongside the extracted results. Map or transform the document field label/name, extracted value text, field confidence, page number, bounding polygon vertices, and any word indexes exposed in the generated response schema. Preserve the repeatable page/field/item arrays; do not flatten line items into one uncorrelated string.
- Add deterministic branches. After the action, validate required fields and compare the extracted purchase-order value with the inbound/trusted PO record. Route mismatches or missing key fields to a review outcome. Do not add a downstream payment or invoice-posting action until those controls and idempotency are implemented.
For an inline document, the OIC guide documents the mapper function oraext:encodeReferenceToBase64(...) applied to the source Stream Reference and mapped to the target Document → Data field. Do this only when the source is an OIC stream reference; don't base64-encode an already encoded string a second time. The exact stream-reference XPath depends on the trigger schema, so use the expression builder's generated source path, not a copied path from an unrelated integration. Oracle's action guide contains the documented example and the Object Storage mapper procedure.
4.3 REST equivalent — synchronous AnalyzeDocument
The synchronous operation is AnalyzeDocument, API version 20221109, HTTP POST, path /20221109/actions/analyzeDocument. Use the regional endpoint pattern described in Section 3. The request uses the API model AnalyzeDocumentDetails: compartmentId, document, features, and the applicable documentType. The official SDK model reference documents these fields; the example below uses an Object Storage document so it contains no document bytes.
Request headers: OCI Signature Version 1 signed request; Content-Type: application/json; Accept: application/json. A plain bearer token or an unsigned curl request is not a valid substitute for the required OCI request signing.
Minimal invoice request JSON:
{
"compartmentId": "ocid1.compartment.oc1..exampleuniqueID",
"document": {
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-117.pdf"
},
"features": [
{
"featureType": "KEY_VALUE_EXTRACTION"
}
],
"documentType": "INVOICE"
}
Replace ocid1.compartment.oc1..exampleuniqueID and your_object_storage_namespace with actual values. Bucket and object names are synthetic fixture values. Do not add a processorConfig or inputLocation wrapper to this synchronous request; those belong to the asynchronous Processor Job contract, shown in Section 8. For inline input, the document object instead uses "source": "INLINE" and a "data" property containing the document bytes as a base64 string. The API SDK model documents InlineDocumentDetails.data as base64-encoded raw document data.
Important: the CLI arguments are not the complete REST request body. The REST body above is for the HTTP POST operation. The current OCI CLI contract takes the document and features as separate parameters; it does not define an --analyze-document-details option. Create these two files for the CLI example.
document.json — only the DocumentDetails object:
{
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-117.pdf"
}
features.json — the feature array:
[{"featureType":"KEY_VALUE_EXTRACTION"}]
Run from a configured OCI CLI profile: replace the quoted compartment and region placeholders with real values; do not include the angle brackets.
oci ai-document analyze-document-result analyze-document --document file://document.json --features file://features.json --compartment-id "<compartment-ocid>" --document-type INVOICE --region "<region-identifier>"
For a raw HTTP call, issue POST to https://document.aiservice.<region>.oci.oraclecloud.com/20221109/actions/analyzeDocument with the full JSON body shown above, Content-Type: application/json, and OCI Signature Version 1 signing. The AnalyzeDocumentDetails model reference, API guide, and specific OCI CLI analyze-document command reference document these different contracts.
4.4 Implement the REST route inside OIC with the REST Adapter
- Create an invoke REST Adapter connection whose connection URL is the regional host, for example
https://document.aiservice.<region>.oci.oraclecloud.com, and select OCI Signature Version 1. Configure the tenancy OCID, user OCID, fingerprint, RSA private key in the format required by the adapter, and passphrase if applicable. Grant that signing identity permission to call the operation. Do not copy the native action's dynamic-group policy and assume it authorizes the REST Adapter's signing user. - Configure the invoke resource as HTTP
POST, relative URI/20221109/actions/analyzeDocument, request content typeapplication/json, and a JSON request schema matching the valid request above. If the wizard accepts a JSON sample to infer the schema, use a valid sample with all required fields and the same case-sensitive names. - In the request mapper, map the inbound
compartmentId,namespaceName,bucketName, andobjectNameto the identical REST fields. Setdocument.sourceto the constantOBJECT_STORAGEanddocumentTypetoINVOICE; set thefeaturesarray to oneKEY_VALUE_EXTRACTIONentry for the first exercise. - In the response mapper, keep
documentMetadata,pages,documentFields, detected/processing errors, and model version fields that are available in the response schema. Add your validation scope and response contract after the invoke. Verify the actual request and response in OIC's activity stream without logging raw invoice contents.
The REST Adapter supports consuming OCI REST APIs with the OCI Signature Version 1 policy. See Oracle's REST Adapter authentication types and OCI REST API support guide.
4.5 Correlate business fields, REST fields, and OIC mapper nodes
| Business meaning | REST request/result element | Native OIC mapper meaning | Control |
|---|---|---|---|
| Source document | document.source, namespaceName, bucketName, objectName | Generated Document / Object Name / bucket / namespace targets | Retain the original object reference and source version/ETag where available. |
| Model selection | features[].featureType and documentType | Chosen in the wizard and reflected by the generated schema; some input values are configured, not runtime-supplied | Use KEY_VALUE_EXTRACTION plus INVOICE for the pretrained invoice model. |
| Header field | pages[].documentFields[].fieldLabel.name, fieldValue.text, fieldLabel.confidence | Corresponding generated response nodes; exact namespaces/wrappers depend on the OIC action schema | Preserve values and confidence with their page and geometry evidence. |
| Source coordinates | fieldValue.boundingPolygon.normalizedVertices, wordIndexes, pageNumber | Map the returned page/field/geometry array nodes if exposed by the generated schema | Geometry is source evidence, not proof that the extracted value is business-correct. |
The native action's request/response wrapper is not the same as the REST API body. Use the exact node names visible in the generated mapper for the selected action. The documented OIC mapper steps specifically distinguish Document/Data for inline input from Document/Object Name for Object Storage input.
4.6 Worked input, output, and interpretation
The synthetic invoice fixture contains supplier Northwind Industrial Supplies, invoice NIS-2026-117, PO PO-450018, date 2026-10-14, two invoice lines, subtotal USD 245.00, tax USD 19.60, and total USD 264.60. Example line items are 3 units × USD 60.00 and 5 units × USD 13.00. These values define the test fixture, not a claimed service response.
A representative subset of the response structure, using illustrative values and omitting unrelated fields, looks like this:
{
"documentMetadata": { "pageCount": 1, "mimeType": "application/pdf" },
"pages": [
{
"pageNumber": 1,
"documentFields": [
{
"fieldType": "KEY_VALUE",
"fieldLabel": { "name": "InvoiceId", "confidence": 0.97 },
"fieldValue": {
"valueType": "STRING",
"text": "NIS-2026-117",
"boundingPolygon": {
"normalizedVertices": [
{ "x": 0.68, "y": 0.09 },
{ "x": 0.88, "y": 0.09 },
{ "x": 0.88, "y": 0.12 },
{ "x": 0.68, "y": 0.12 }
]
}
}
},
{
"fieldType": "LINE_ITEM_GROUP",
"fieldLabel": { "name": "Items" },
"fieldValue": {
"valueType": "ARRAY",
"items": [
{
"fieldType": "LINE_ITEM",
"fieldValue": {
"valueType": "ARRAY",
"text": "Bearing Kit 3 60.00 180.00",
"items": [
{
"fieldType": "LINE_ITEM_FIELD",
"fieldLabel": { "name": "Description", "confidence": 0.96 },
"fieldValue": { "valueType": "STRING", "text": "Bearing Kit", "value": "Bearing Kit" }
},
{
"fieldType": "LINE_ITEM_FIELD",
"fieldLabel": { "name": "Quantity", "confidence": 0.98 },
"fieldValue": { "valueType": "NUMBER", "text": "3", "value": 3 }
},
{
"fieldType": "LINE_ITEM_FIELD",
"fieldLabel": { "name": "UnitPrice", "confidence": 0.95 },
"fieldValue": { "valueType": "NUMBER", "text": "60.00", "value": 60.0 }
},
{
"fieldType": "LINE_ITEM_FIELD",
"fieldLabel": { "name": "Amount", "confidence": 0.94 },
"fieldValue": { "valueType": "NUMBER", "text": "180.00", "value": 180.0 }
}
]
}
}
]
}
}
]
}
]
}
This is an illustrative structure using the synthetic Bearing Kit fixture, not a claimed service response; the confidence values and field values are examples. Its nesting follows Oracle's documented pattern: LINE_ITEM_GROUP contains LINE_ITEM entries, each containing LINE_ITEM_FIELD members such as Quantity. The full response can also include field geometry and word indexes; preserve those fields whenever returned. Do not flatten nested items into one uncorrelated string.
A normalized polygon coordinate is relative to the page dimensions and usually ranges from 0 to 1. To display a field highlight, multiply normalized x values by page width and y values by page height in the coordinate system returned by the service. Retain pageNumber because the same normalized coordinate on a different page is a different source location. Do not interpret confidence as a calibrated probability of business correctness; calibrate review rules against labeled invoices and the cost of accepting a wrong field.
4.7 Validate extracted values before business consumption
Kid-friendly analogy
A shopping list says five boxes were ordered, but the classroom order says three. Even if the handwriting is easy to read, the mismatch still needs checking. The list helps explain the claim; the approved order decides what was allowed.
In this OCI AI integration, this means: Cross-check extracted values against the supplier master, purchase order, receiving facts, contract, and deterministic arithmetic; send conflicts to review instead of treating OCR confidence as approval.
Implement these validations after extraction. Use a decimal-safe numeric type for financial arithmetic; do not use binary floating point for currency totals. Define tolerances through the finance/procurement policy and currency precision, not through a sample threshold invented in the integration.
- Supplier: resolve the extracted vendor name/identifier to an enabled supplier in the target system. If the model extracts only a name, use name matching as a candidate lookup, not as the authorization identity.
- Purchase order: compare extracted
PurchaseOrderwith the expected PO, confirm that the PO belongs to the legal entity and supplier, and check open/approved status and available quantity/value using the procurement source of truth. - Duplicate invoice: enforce a unique business key appropriate to the organization, typically supplier + legal entity + normalized invoice ID, with a documented policy for credit notes and corrected invoices. A duplicate check followed by a write is not sufficient by itself under concurrency; enforce uniqueness or idempotency at the persistence/target boundary.
- Line items: check each item quantity × unit price against line amount, match product/service/PO lines where possible, and reconcile page-spanning line items. Missing, repeated, or contradictory line items must not be silently dropped.
- Subtotal, tax, freight, discount, and total: reconcile components according to the applicable invoice and tax rules. The invoice's formula can differ by jurisdiction or document type; use an explicit business rule rather than blindly assuming subtotal + tax equals total in every case.
- Currency: the documented pretrained invoice field list includes amounts but does not define a dedicated currency-code field. Do not assume the API returns a reliable currency property. Derive/validate currency from the printed source content and trusted PO/vendor configuration, or define a supported custom field; never treat an ambiguous
$symbol as a unique currency. - Human review: route missing required fields, low-quality images, contradictory totals, supplier/PO mismatch, suspicious duplicates, uncertain currency, and low-evidence fields to a review state. Store the original value, correction, reviewer, timestamp, reason, and source geometry in the audit record.
4.8 Tests, troubleshooting, and checkpoint
| Case | Expected behavior | Evidence to inspect |
|---|---|---|
| Clear invoice with PO match | Extract fields, reconcile header/line arithmetic, pass only if supplier/PO rules pass. | Original object reference, documentFields, confidence/geometry, validator result and business-key record. |
| Missing invoice ID or PO | Mark required field missing and route to review; do not create a payable from an incomplete record. | Missing field in response, deterministic validation fault/route, review record. |
| Blurred or skewed scan | Quality failure or uncertain extraction becomes reviewable; no silent approval. | Page metadata, absent/poor fields, confidence distribution, preserved source image. |
| PO or supplier mismatch | Deterministic mismatch route even if extracted fields have high confidence. | Trusted PO/supplier response and validation reason. |
| Duplicate supplier invoice ID | Return existing processing state or duplicate-review outcome; do not post a second invoice. | Unique key/idempotency record and downstream acknowledgement. |
| REST caller lacks permission | Fail closed and correct the signer identity/policy; do not retry an authorization fault indefinitely. | HTTP status/error body, signer identity, opc-request-id, OIC activity stream with sensitive data redacted. |
Troubleshooting by layer: 400-class validation errors usually call for checking JSON casing/types, source values, file eligibility, and required fields; 401/403 calls for checking the signing identity and IAM permissions; missing-object errors call for checking namespace, bucket, object name, region, and read access. Check the actual returned error contract rather than assuming every status has the same cause. Retest after fixing the input/permission, and capture request IDs for diagnosis.
Completion checkpoint: You can run the native action and the equivalent signed REST operation for a fixture invoice; retain the extracted header and nested line-item records with source object, page, geometry and confidence; and prove that a PO mismatch or duplicate cannot flow to the downstream business action. All execution tests remain Not executed in this article.
5. Capability 2 — Document Classification and Routing
5.1 Purpose, concept, and supported scope
Use document classification when the incoming file type is not trusted or known. The pretrained classifier returns candidate document types and confidence scores. Oracle documents candidates including Invoice, Receipt, Resume/CV, Tax Form, Driver's License, Passport, Bank Statement, Check, Payslip, and Other. Classification is useful for routing to an invoice extractor, receipt extractor, review queue, or an unsupported-document path; it is not a substitute for validating the document's business meaning.
Kid-friendly analogy
Imagine a school office sorting papers into homework, permission slips, and lunch forms. If a paper could belong in two folders, the clerk checks it rather than automatically sending it to the wrong teacher.
In this OCI AI integration, this means: Treat detectedDocumentTypes as ranked candidates; route to a model only when the classification policy is satisfied and send ambiguous/Other cases to review.
5.2 Native OIC implementation
- Add OCI Document Understanding → Pre-trained Models → Document classification.
- Set the intended service region and compartment. Select inline or Object Storage. Use Object Storage for the sample fixture and map
objectNameto the generated Document → Object Name node. For inline input, use the documented base64 stream-reference mapping described in Section 4.2. - Map the returned candidate document type(s), score(s), and page/source metadata from the generated response schema. Keep the candidate list; do not keep only the first label before reviewing the scores and policy.
- Use a Switch/decision branch: route
INVOICEto the invoice action,RECEIPTto receipt-specific processing if in scope, and unsupported/ambiguous candidates to review. Thresholds are application policy and must be calibrated with labeled samples, not copied from this example.
5.3 REST equivalent — classify a document
Use the same synchronous operation, API version and signed endpoint as Section 4.3. Only the feature changes to DOCUMENT_CLASSIFICATION. maxResults is a documented feature option; the service response can include more than one candidate. The following is a valid illustrative request with a maximum of five candidates:
{
"compartmentId": "ocid1.compartment.oc1..exampleuniqueID",
"document": {
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-117.pdf"
},
"features": [
{
"featureType": "DOCUMENT_CLASSIFICATION",
"maxResults": 5
}
]
}
For a raw REST call, use POST /20221109/actions/analyzeDocument with Content-Type: application/json and OCI Signature Version 1. For OCI CLI, reuse document.json from Section 4.3 and set features.json to [{"featureType":"DOCUMENT_CLASSIFICATION","maxResults":5}]. Run oci ai-document analyze-document-result analyze-document --document file://document.json --features file://features.json --compartment-id "<compartment-ocid>" --region "<region-identifier>". Do not pass the complete REST body as the CLI's --document value.
5.4 Response, mapping correlation, tests, and checkpoint
The REST response includes page information and detected document-type candidates (for example, pages[].detectedDocumentTypes[].documentType and confidence). The native OIC response schema is generated by the action wizard; map the corresponding label and confidence nodes without assuming its wrapper path is a literal REST path.
| Case | Expected behavior | Evidence |
|---|---|---|
| Clear invoice | Invoice route is selected only after the configured classification policy passes. | Candidate array, chosen route, original document reference. |
| Receipt or bank statement | Use the appropriate supported path or review; do not force invoice extraction. | Returned document-type candidates and routing log. |
| Ambiguous candidates / Other | Hold for review or apply a labeled, tested disambiguation policy. | Candidate list, confidence values, review case. |
| Unsupported file or unreadable scan | Reject or review with a controlled fault, not an invoice post. | Input-validation fault and activity/request ID. |
Troubleshooting: if the top candidate is plausible but wrong, inspect the full candidate list and source quality; if Other appears, don't silently map it to Invoice; if a native action returns a wrapper unfamiliar from the REST response, inspect the generated OIC response schema and activity stream. The official classification guide documents candidate categories and confidence semantics.
Completion checkpoint: Both native and REST routes classify the same source fixture, preserve the candidate list, and route a non-invoice/ambiguous result without accidentally invoking invoice business processing. Tests: Not executed.
6. Capability 3 — OCR and Text Extraction with Source Geometry
6.1 When text extraction is the right operation
Text extraction recognizes document text and returns word-level/line-level content and spatial information. Choose it when the downstream process needs searchable text, a source-linked transcript of the page, or a text-based classification/pre-processing stage. It is not the same as invoice key-value extraction: OCR can return the characters 264.60, but it does not establish that this number is the invoice total rather than a line amount or prior balance.
Kid-friendly analogy
A librarian can copy every word from a page and note where each word sits. That makes the page searchable, but it does not tell the librarian which sentence is the book's title or which number should be used on a bill.
In this OCI AI integration, this means: Use TEXT_EXTRACTION for words, lines, and geometry; use the invoice model or deterministic business logic when a field's meaning matters.
6.2 Native OIC implementation
- Add OCI Document Understanding → Pre-trained Models → Text extraction.
- Choose the service region and compartment; select inline or Object Storage. For Object Storage, map the object name to the generated target
Document/Object Name. For inline input, map the source stream through the documentedoraext:encodeReferenceToBase64(...)function intoDocument/Data. - Map the response's pages, text lines, words, confidence, and polygons where exposed. Preserve page number and word/line sequence. Do not log full invoice text by default.
- Use OCR output for search, text quality checks, or an evidence layer; continue to the invoice action for structured invoice fields rather than parsing a generic text blob with fragile string offsets unless that is a deliberate tested design.
6.3 REST equivalent — request text extraction
Use POST /20221109/actions/analyzeDocument, Content-Type: application/json, and OCI Signature Version 1. The field names below follow the documented AnalyzeDocumentDetails shape and the DocumentTextExtractionFeature option. The default path needs only the feature type; add optional supported properties only when required and validated.
{
"compartmentId": "ocid1.compartment.oc1..exampleuniqueID",
"document": {
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-117.pdf"
},
"features": [
{
"featureType": "TEXT_EXTRACTION"
}
]
}
For OCI CLI, reuse document.json from Section 4.3 and set features.json to [{"featureType":"TEXT_EXTRACTION"}], then run oci ai-document analyze-document-result analyze-document --document file://document.json --features file://features.json --compartment-id "<compartment-ocid>" --region "<region-identifier>". To request a searchable PDF, set the feature's documented generateSearchablePdf property to true and supply the documented output location (for the CLI, --output-location file://output-location.json, where that file contains namespaceName, bucketName, and prefix). Confirm output-bucket permissions and inspect the result object; a synchronous analysis response does not itself mean a searchable PDF has been retrieved.
6.4 Response interpretation, language boundary, and tests
The result's pages array contains page metadata and text-related structures; the model documentation lists textExtractionModelVersion and possible errors. Word and line records include text and page geometry so the application can highlight a source region or show the reviewer where a recognized token came from. Scores closer to 1 indicate higher model confidence for that text grouping; they do not prove the word was understood in the right business context.
Language qualification matters. The current general Getting Started table lists model-version-specific OCR languages, but the standalone OCR page says OCR is limited to English. Until the selected version's UI/API contract is confirmed for your region, treat non-English OCR as an availability/quality check rather than a guaranteed path. Text extraction is also not translation: it does not change the language into another language.
| Case | Expected behavior | Evidence to inspect |
|---|---|---|
| Searchable digital PDF | Return text and source geometry as supported. | Pages, lines, words, geometry, page count. |
| Blurred scan / very small print | Recognized text may be missing or uncertain; invoke a quality/review route. | Missing lines, low-confidence groups, original file and dimensions. |
| Non-English content | Verify support for the exact model version and operation; don't assume support from a different model. | Selected model version, request outcome, current language table. |
| Missing document/object | Fail clearly; do not treat an empty result as a valid no-text document. | Request error, object metadata, source permission. |
Troubleshooting: check whether a digital PDF contains selectable text, but don't assume that eliminates all OCR error; check resolution/skew and file limits; inspect the response's errors; and verify the request did not accidentally choose an unsupported language/model combination. The official OCR guide and versioned supported-language table should be revisited before production adoption.
Completion checkpoint: Run the native and REST text extraction variants on the same source object; retain word/line/page geometry; and show that generic recognized text is not directly treated as a validated invoice field. Tests: Not executed.
7. Capability 4 — Table Extraction and Line-Item Reconciliation
7.1 What a table result does and does not mean
Table extraction recognizes tables and returns row/column relationships, cell text, confidence, and source geometry. Oracle documents tables with and without borders and shows rowCount, columnCount, bodyRows, and cells containing rowIndex, columnIndex, text, confidence, and boundingPolygon. The documented table extraction feature is English-only. See the table extraction guide.
Kid-friendly analogy
A classroom chart has names in one column, quantities in another, and prices in a third. Copying the words without preserving the columns could attach the wrong price to the wrong item.
In this OCI AI integration, this means: Preserve each cell's row and column indexes, header context, page, and geometry when normalizing a table; never reconcile a table after flattening all cells into one text string.
7.2 Native OIC implementation
- Add OCI Document Understanding → Pre-trained Models → Table extraction.
- Select the service region and compartment, then choose inline or Object Storage input. Map the generated
Document/Object Namefor the Object Storage route, or map the stream reference throughoraext:encodeReferenceToBase64(...)toDocument/Datafor inline input. - Map the returned pages/tables and repeatable cell arrays. Preserve
rowCount,columnCount, any header-row information present, row/column indexes, cell text, confidence, polygon, and page number where the generated schema exposes them. - Normalize the table into a business list only after verifying the column heading and row relationships. If a row wraps across pages or the table repeats its header, use a deterministic reconciliation rule or send the row to review; do not assume the service has merged continuation rows into a single business item.
7.3 REST equivalent — TABLE_EXTRACTION
For a synchronous request, use the same AnalyzeDocument endpoint and document structure as Section 4.3, changing the feature type to TABLE_EXTRACTION:
{
"compartmentId": "ocid1.compartment.oc1..exampleuniqueID",
"document": {
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-117.pdf"
},
"features": [
{
"featureType": "TABLE_EXTRACTION"
}
]
}
Invoke POST /20221109/actions/analyzeDocument with JSON content type and OCI Signature Version 1. For OCI CLI, reuse document.json from Section 4.3 and set features.json to [{"featureType":"TABLE_EXTRACTION"}], then run oci ai-document analyze-document-result analyze-document --document file://document.json --features file://features.json --compartment-id "<compartment-ocid>" --region "<region-identifier>". Do not use the unsupported --analyze-document-details parameter. The minimal REST table example does not include documentType because the selected feature is explicit and the example only demonstrates generic table extraction.
7.4 Normalize tables without losing evidence
A representative response fragment is:
{
"pages": [
{
"pageNumber": 1,
"tables": [
{
"rowCount": 1,
"columnCount": 4,
"bodyRows": [
{
"cells": [
{ "text": "Bearing Kit", "rowIndex": 0, "columnIndex": 0, "confidence": 0.96 },
{ "text": "3", "rowIndex": 0, "columnIndex": 1, "confidence": 0.98 },
{ "text": "60.00", "rowIndex": 0, "columnIndex": 2, "confidence": 0.95 },
{ "text": "180.00", "rowIndex": 0, "columnIndex": 3, "confidence": 0.94 }
]
}
]
}
]
}
]
}
The snippet is an illustrative one-row table, not a claimed service response. The first displayed row uses zero-based index 0, consistent with Oracle's example; the complete cell contract may include geometry and word references. Treat rowIndex and columnIndex as structural coordinates, not business IDs. Merged cells, blank cells, repeated headers, and page-spanning rows require deliberate mapping rules. A bounding polygon can support a reviewer display, but does not prove the cell belongs to the correct line item. If the task is invoice field extraction, use the pretrained invoice KEY_VALUE_EXTRACTION result as the primary line-item source and add generic TABLE_EXTRACTION when the invoice layout needs it, validating duplicates and disagreements between the two views.
7.5 Tests, troubleshooting, and checkpoint
| Case | Expected behavior | Evidence |
|---|---|---|
| Simple bordered table | Rows/cells are represented with their indexes and text. | Table row/column counts, cells, confidence, geometry. |
| Borderless or low-quality table | Inspect column assignment and send structurally uncertain rows to review. | Cell positions and rendered-source comparison. |
| Table continues to page 2 | Reconcile with page-aware continuation logic; no assumed auto-merge. | Page number, repeated headers, item sequence, duplicate detection. |
| Non-English table | Do not rely on the documented table extractor without confirming language support. | Selected operation/version and current language guide. |
Troubleshooting: if table rows shift columns, check row/column indexes and the source rendering; if rows are duplicated across pages, compare the business line key and source geometry; if cell text is missing, inspect image quality and language support. Avoid silently dropping any cell that doesn't fit the expected schema.
Completion checkpoint: Both routes return a structured table result; OIC preserves cell coordinates; the normalization logic explicitly handles missing/merged cells and multi-page continuation instead of assuming the model has solved invoice reconciliation. Tests: Not executed.
8. Capability 5 — Batch Processor Jobs, Recovery, and Result Retrieval
8.1 Lifecycle and choice of processing mode
A Processor Job is the asynchronous route for processing documents in Object Storage and writing analysis results to a configured Object Storage output location. Its lifecycle separates job acceptance from actual processing and from business completion. OCI exposes create, get, and cancel operations. The lifecycle can include ACCEPTED, IN_PROGRESS, SUCCEEDED, FAILED, CANCELING, and CANCELED; the job can also report PARTIALLY_SUCCEEDED or COMPLETELY_FAILED as lifecycle details. A SUCCEEDED job is not by itself proof that every extracted field passed procurement validation.
Kid-friendly analogy
Submitting a class set of papers is like receiving a ticket from the school office. The ticket proves the work was accepted into the queue, not that every paper has been checked, graded, or returned.
In this OCI AI integration, this means: Persist the job ID and input manifest, poll until a terminal lifecycle state, retrieve the output artifacts, inspect per-document errors, and reconcile each result before marking an invoice complete.
Use synchronous AnalyzeDocument for a small document that fits the current synchronous constraints. Use Processor Jobs when a set of files, larger document, or decoupled processing lifecycle makes Object Storage-based submission and retrieval more appropriate. Do not convert a slow synchronous call into a blind retry loop.
8.2 Native OIC route — create, poll, cancel, and retrieve output
- Create job action: add OCI Document Understanding → Processor Job → Create a processor job. Choose region and compartment, then set the output bucket and namespace. In the request mapper, populate the feature type(s) and document type for the intended analysis, the input Object Storage location(s), and the output prefix. Oracle documents the required mapper values as at least
Feature Type,Input Locationbucket/namespace, andOutput Locationprefix, with the source file/object mapped in the request wrapper. Follow the generated schema to add each repeatedFeatures/Object Locationsentry supported by the action. - Persist the job handle: map the create response's
IdandPercent Complete/status fields into the integration's tracking record with the inbound run ID and input manifest. Save before the integration returns or continues asynchronously; a job ID is the correlation key required for status polling. - Poll status: add Get a processor job status and map the create action's returned
idto the targetProcessor Job Id. Use a bounded wait/poll design and a maximum age/attempt count. Do not build an unbounded, tight loop that consumes OIC execution capacity. - Handle terminal states:
ACCEPTED/IN_PROGRESSmeans wait and poll again within the policy;SUCCEEDEDmeans retrieve results and reconcile;FAILED/CANCELEDmeans stop the normal path and record recovery status. TreatPARTIALLY_SUCCEEDED/COMPLETELY_FAILEDlifecycle details as a prompt to inspect result objects and per-document errors, not as an all-or-nothing status. - Cancel only when appropriate: use Cancel a processor job with the existing job ID when cancellation is permitted and the job is in progress. Cancellation can be asynchronous; inspect the returned/current state rather than assuming that the request has immediately halted processing.
- Retrieve output objects: the native Processor Job action sends results to Object Storage; it does not eliminate the need to read those result files. Use an OIC Object Storage-capable connection or REST Adapter calls to list objects under the configured output prefix and retrieve each result object. The published job guide does not establish a universal filename convention for every run; list the actual objects and correlate their contents to the input manifest rather than constructing a guessed object key.
For Object Storage retrieval through REST, the list operation uses the Object Storage resource path /n/<namespace>/b/<bucket>/o with the prefix query parameter; an individual object is retrieved through /n/<namespace>/b/<bucket>/o/<objectName>. Use the Object Storage regional endpoint and OCI Signature Version 1, and URL-encode object-name path values correctly. The output bucket needs its own appropriate permissions. If your tenant uses a supported Object Storage adapter operation for listing/getting objects, configure its documented contract instead of treating that adapter's schema as the raw REST schema.
8.3 REST equivalent — CreateProcessorJob, GetProcessorJob, CancelProcessorJob
The batch path uses a different body from synchronous AnalyzeDocument. The create operation is HTTP POST on /20221109/processorJobs; status is HTTP GET on /20221109/processorJobs/<processorJobId>; cancellation is HTTP POST on /20221109/processorJobs/<processorJobId>/actions/cancel. Use the regional host described in Section 3 and OCI Signature Version 1. Send Content-Type: application/json for the create request; a GET does not need a request body.
Complete illustrative two-document batch request:
{
"compartmentId": "ocid1.compartment.oc1..exampleuniqueID",
"displayName": "procurement-invoice-batch-demo",
"processorConfig": {
"processorType": "GENERAL",
"features": [
{ "featureType": "KEY_VALUE_EXTRACTION" },
{ "featureType": "TABLE_EXTRACTION" }
],
"documentType": "INVOICE"
},
"inputLocation": {
"sourceType": "OBJECT_STORAGE_LOCATIONS",
"objectLocations": [
{
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-117.pdf"
},
{
"source": "OBJECT_STORAGE",
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-in",
"objectName": "incoming/NIS-2026-118.pdf"
}
]
},
"outputLocation": {
"namespaceName": "your_object_storage_namespace",
"bucketName": "procure-invoices-out",
"prefix": "runs/demo-run-001"
}
}
The bucket names, object names, display name, namespace, and compartment value are placeholders/fixtures. The feature list illustrates invoice key-value extraction plus table extraction; verify the actual configured operation/model compatibility in the target region before relying on combined features. The request uses only Object Storage locations as required for the batch pattern, not inline base64 document content.
OCI CLI create/status/cancel commands: save the inputLocation, outputLocation, and processorConfig objects into separate valid JSON files (input-location.json, output-location.json, processor-config.json) and the compartment OCID into a shell variable. The CLI uses the same documented API but structures its command arguments separately.
export COMPARTMENT_ID='ocid1.compartment.oc1..exampleuniqueID'
export REGION_ID='<region-identifier>'
JOB_ID=$(oci ai-document processor-job create \
--compartment-id "$COMPARTMENT_ID" \
--input-location file://input-location.json \
--output-location file://output-location.json \
--processor-config file://processor-config.json \
--display-name procurement-invoice-batch-demo \
--region "$REGION_ID" \
--query 'data.id' --raw-output)
echo "$JOB_ID"
oci ai-document processor-job get \
--processor-job-id "$JOB_ID" \
--region "$REGION_ID"
# Use only for a job that should be canceled and is still cancellable.
oci ai-document processor-job cancel \
--processor-job-id "$JOB_ID" \
--region "$REGION_ID"
This is an OCI CLI example, not a literal HTTP body. Oracle's create command guide, get command, and Document Understanding command index (includes Processor Job cancel) document the required options. For raw REST, use the create JSON above and the operation paths, with OCI Signature Version 1. The API's create/get response includes the job ID, lifecycle state, progress, and output location; preserve the entire state record rather than only the percent value.
8.4 Polling, artifact retrieval, partial failures, and reconciliation
Use a persisted state machine rather than a single in-memory loop:
- Record
submissionPending, the input manifest, a unique run ID, and a deterministic output prefix before calling create. - Submit once. Persist the returned processor-job ID immediately. When the create call times out and the outcome is uncertain, reconcile job records/tracking before creating another job; don't assume the request failed just because the caller timed out.
- Poll with a bounded interval and maximum elapsed time. Continue only for known nonterminal lifecycle states. Use a scheduled continuation or durable orchestration pattern if the processing duration could exceed a reasonable synchronous OIC execution window.
- When the job is terminal, list objects under the output prefix and retrieve the actual result JSON artifacts. Parse each result; inspect job-level
lifecycleDetails, per-document errors, page count, document metadata, and extraction errors. A successful job with a failed document item still needs a review/retry decision. - Reconcile every input manifest entry with one business outcome: extracted and validated, review required, processing failed, or canceled. Do not mark the batch complete until every source document has a tracked outcome.
- Keep source files, job metadata, and output artifacts under the retention policy. Deleting or canceling a job should not be assumed to delete input or output objects; perform explicit retention/cleanup operations in Object Storage.
A basic Object Storage CLI inspection after the job finishes is:
oci os object list \
--namespace-name 'your_object_storage_namespace' \
--bucket-name 'procure-invoices-out' \
--prefix 'runs/demo-run-001' \
--region '<region-identifier>'
# Replace <actual-object-name-from-list> with a name returned by the list call.
oci os object get \
--namespace-name 'your_object_storage_namespace' \
--bucket-name 'procure-invoices-out' \
--name '<actual-object-name-from-list>' \
--file result.json \
--region '<region-identifier>'
The result filename in the second command is deliberately not guessed. Use the actual object name returned by Object Storage listing, then correlate the result JSON to the input object manifest based on the result metadata and content. If the output structure doesn't contain enough stable information to unambiguously map a result to its source, treat that as an integration design gap that must be tested and resolved before production.
8.5 Batch tests, troubleshooting, and checkpoint
| Case | Expected behavior | Evidence to inspect |
|---|---|---|
| Two valid documents | One batch job is tracked and each source gets a reconciled result. | Job ID/state, output prefix/object list, source-to-result reconciliation table. |
| One corrupt/unsupported document | The other results are retained; failed item is classified and not silently dropped. | Lifecycle details, errors, available result artifacts, input manifest. |
| Output bucket permission denied | Job failure/partial failure is recorded; do not repeatedly create jobs without correcting access. | Job state, error details, Object Storage policy and target bucket region. |
| Status remains nonterminal past policy limit | Move to a monitored waiting/escalation state; do not loop indefinitely. | lifecycleState, progress, accepted/started timestamps, last poll and request ID. |
| Create timeout / uncertain outcome | Reconcile the submission before retrying; avoid duplicate expensive jobs and duplicate business writes. | Tracking record, output prefix, recent jobs, request IDs, source manifest. |
| Cancel while processing | Check cancellation eligibility and confirm the terminal state; still reconcile any artifacts already produced. | Job state transition, result object list and input manifest. |
Troubleshooting: no output objects may mean the job is not terminal, the output location/prefix is wrong, or result writing failed; don't assume one cause. A PARTIALLY_SUCCEEDED detail means you must inspect per-item outcomes. A successful GetProcessorJob call only confirms status retrieval worked, not that the result object was fetched or business validation passed. Retry only documented retryable failures with bounded attempts and duplicate prevention.
Completion checkpoint: You can submit the batch through the native OIC action and REST API, persist the job ID, poll with bounded control, cancel where allowed, list/retrieve actual output objects, inspect item-level errors, and reconcile every source to a terminal business outcome. Tests: Not executed.
9. Capability 6 — Choose a Custom Classic or Custom Generative Model
9.1 Decision framework
Use a custom model when the pretrained field set, classification categories, or extraction behavior do not meet a measured requirement. Document Understanding's classic custom key-value models require a labeled training dataset. The newer custom generative key-value model (V2.0) uses a JSON array of field definitions and natural-language descriptions instead of requiring the same labeled training process. The two approaches have different prerequisites and availability; neither should be selected based only on a demo.
Kid-friendly analogy
A teacher can train a class helper using many marked-up examples of the same worksheet, or give the helper a clear set of written rules for a variety of worksheets. The first needs prepared examples; the second needs careful instructions and testing. Neither removes the need to check answers.
In this OCI AI integration, this means: Prefer a classic model when you have representative labeled documents and a stable task; evaluate generative extraction when formats and requested fields vary and the supported region is available, then validate the actual output against a labeled test set.
| Choice | When it fits | Cost and limitation to evaluate |
|---|---|---|
| Pretrained invoice model | Standard invoice fields and line-item concepts cover the required scope. | Fixed supported fields; no dedicated currency-code field in the documented list; language/format support is model-specific. |
| Custom classic key-value model | A repeatable field task with enough labeled representative examples; custom labels/fields are required. | Requires dataset curation, annotations, training, evaluation, and model lifecycle management. Oracle documents a minimum of five labeled documents for each custom key-value label. |
| Custom generative key-value model V2.0 | Fields or document layouts vary and you need a schema described with natural-language field definitions. | Custom model management is documented only in sa-saopaulo-1, ap-osaka-1, uk-london-1, and us-chicago-1; verify inference/region and OIC action support for your tenant. |
Oracle's custom-model overview describes the classic and generative approaches. The V2.0 generative extraction guide specifies the region list and field-definition structure. A model's management region availability should not be inferred from the broader availability of pretrained Document Understanding across OCI regions.
9.2 Define the generative custom field schema
For generative key-value extraction, the documented configuration is a JSON array of objects; each field definition requires key and description, with optional dataType. Documented data types include string, date, number, currency, and phone. This file is a service-specific field-definition array, not a general JSON Schema document.
[
{
"key": "SupplierTaxRegistrationId",
"dataType": "string",
"description": "Supplier tax registration identifier printed on this invoice. Extract the supplier's own identifier, not the customer's identifier. Preserve letters, digits, and separators exactly as printed."
},
{
"key": "CurrencyCode",
"dataType": "string",
"description": "Explicit three-letter currency code printed on the invoice near the totals. Do not infer the code from an ambiguous currency symbol. If no explicit code is present, leave the value missing for business validation."
},
{
"key": "DeliveryReference",
"dataType": "string",
"description": "Supplier delivery-note reference associated with this invoice, usually printed near the purchase order or shipping information. Do not return the purchase-order number as the delivery reference."
}
]
Save the field-definition JSON in an Object Storage bucket and follow the V2.0 model-creation instructions for the target region/project. Descriptions should distinguish confusing identifiers, describe location/context when useful, state acceptable formats, and tell the extractor what not to return. Then evaluate the custom model using separately held-out invoices, with the expected field values and source evidence manually labeled. A model that follows the schema syntactically can still extract the wrong value.
9.3 Call a custom model through native OIC and REST
For OIC, choose OCI Document Understanding → Custom models and select the model created in the OCI Console. Oracle's action guide documents Analyze document and Analyze document (with confidence score) variants for custom models; it also explains that the wizard's region, compartment, model, and input source are configuration choices, with source object name mapped in the mapper. Select the region where the intended model is available and verify that the specific model version appears in the tenant's action wizard before building dependent integrations.
For the REST equivalent, use the same synchronous AnalyzeDocument path and request envelope as Section 4.3, but set the custom model's modelId inside the applicable feature object. The OCI SDK model reference explicitly documents modelId as a feature-level field for custom inference. For example, the feature fragment is:
"features": [
{
"featureType": "KEY_VALUE_EXTRACTION",
"modelId": "ocid1.documentmodel.oc1..replaceWithYourModelOCID"
}
]
This is the feature fragment to replace in the full synchronous request—not a complete JSON request by itself. Use the actual model OCID returned by your own OCI Console/API, not the illustrative text. For batch inference, use the Processor Job schema from Section 8 and place the custom model reference in the feature configuration supported by the selected processor/model version. Verify this exact custom-model combination with the current API reference/target region before production; do not assume that every model type exposes identical parameters through every native action.
9.4 Model acceptance tests and checkpoint
| Case | Expected behavior | Evidence |
|---|---|---|
| Known layout, labeled sample | Evaluate field accuracy against a labeled ground-truth set. | Per-field precision/recall or error review, document/page coverage, model version. |
| New supplier layout | Observe generalization and route uncertain/missing critical fields to review. | Field-level comparison, page/source evidence, review outcomes. |
| Confusing IDs/totals | Description and schema reduce mistakes, but validators still catch conflicts. | Confusion cases, false positives, missed fields and deterministic checks. |
| Model not available in selected region | Deployment is blocked pending supported model/region selection; don't guess an endpoint. | Console model availability, region-specific API result, OIC action wizard. |
Use a representative, held-out evaluation set and include hard negatives (similar-looking identifiers, missing labels, unusual layouts, page continuations, and nonstandard totals). A small sample is a learning exercise, not production accuracy certification. The relevant operating cost is not only model invocation; account for annotation work, review rates, reprocessing, and downstream exception handling without inventing a cost estimate.
Completion checkpoint: You can explain why the selected model matches the field/layout problem, confirm region and OIC/API compatibility, invoke it through a supported route, and evaluate critical fields against labeled evidence. Tests: Not executed.
10. Combine the Completed Paths into a Multi-Document Workflow
The combined design uses only operations already explained:
- Register the source. Ingest the PDF/image into a private input bucket, assign a business
documentId, and persist the source object name plus version/ETag/checksum metadata available to the design. - Choose an execution mode. For a small request within the documented synchronous limits, invoke the operation that matches the known document type and required output—for example, invoice key-value extraction for the invoice branch. For a batch, create a Processor Job and persist its job ID/output prefix immediately.
- Classify when type is unknown. Route only known/approved document categories to their associated extraction operation. Ambiguous/unsupported files go to review.
- Extract and preserve evidence. Keep header fields, line-item arrays, page number, geometry, confidence, error details, and model version. Use table/text extraction only where it adds needed structure or source evidence.
- Validate deterministically. For the invoice branch, compare supplier, PO, legal entity, invoice identifier, quantity, price, currency, tax, and totals with trusted procurement/business data. For other document types, define the corresponding checks against their own system of record. A missing field must not be guessed from a confidence score; send unresolved critical fields to review.
- Review and correct. Present the original source page and detected polygon with the extracted value. Store the original output and human correction separately. Preserve reviewer identity, timestamp, reason, and state transition.
- Commit through controlled consumption. Only validated/approved records may proceed. Apply a unique business key or idempotency mechanism and reconcile uncertain target-write outcomes before retrying. The model and extraction action do not grant payment authority.
Control boundary
Keep authorization, duplicate prevention, human approval, financial limits, and target-system writes in deterministic identity/integration/business controls. Extracted text, uploaded documents, retrieved content, confidence scores, and the model's fields are untrusted input. A high confidence score is not approval, and a completed service job is not invoice acceptance.
10.1 End-to-end verification matrix
| End-to-end case | Expected behavior | Evidence to retain |
|---|---|---|
| Supported document with matching source-of-truth record | The correct operation is selected, then all document-specific validations and approval policy run. | Source reference, classification/route decision, extraction evidence, validation result, approval and target correlation ID. |
| Extracted total differs from line/tax arithmetic | Review outcome; no automatic downstream commit. | Original totals/line values, reconciliation calculation, source polygons and review reason. |
| Duplicate document or business transaction | The duplicate is blocked or routed according to the target business process and correction policy. | Source/document key, idempotency record, target lookup and response. |
| Partial batch failure | Successful items remain reconciled; failed items are individually tracked for retry/review. | Job lifecycle/detail, per-document errors, output object names, complete input manifest. |
| Target write times out after submit | Reconcile whether the target accepted the write before retrying. | Target business key, request/correlation ID, lookup result, retry ledger. |
A small labeled evaluation suite should track field-level errors (missing/incorrect values), page/source evidence quality, route decisions, human review rate, and downstream business correctness separately. Measure the common failure categories—wrong supplier/PO, missed invoice number, amount/currency confusion, duplicate rows, and partial batch results—before relaxing any review policy. All tests in this article are Not executed; run the same fixture through both supported routes and record actual outputs in your own tenant.
11. Completion Checklist and What Comes Next
- [ ] Native OIC invoice action is configured with correct model type, region, compartment, and input source; mapper retains header fields, line items, confidence, page, geometry, and the source reference.
- [ ] The same source is processable through the signed REST API using
AnalyzeDocumentDetails; the request body uses the synchronous schema, not a Processor Job payload. - [ ] A REST Adapter implementation uses OCI Signature Version 1 and an authorized caller identity; it does not rely on an unsigned call or generic bearer token.
- [ ] Classification, OCR/text extraction, and table extraction have been exercised locally where required, with their limits and language/model-version constraints understood.
- [ ] Supplier/PO/identifier/currency/tax/total validation and duplicate prevention are deterministic and reject or review inconsistent facts.
- [ ] Batch processing persists the job ID and manifest, polls with bounded control, handles cancellation/partial failure, lists and retrieves result artifacts, and reconciles every source object.
- [ ] Human correction retains the original model result, source evidence, reviewer, timestamp, reason, and final corrected value.
- [ ] Logs and alerts avoid raw sensitive document content; input/output retention and cleanup are explicitly configured.
A genuinely deferred follow-up is the target-specific invoice creation/posting integration and its approval, concurrency, and uncertain-outcome recovery controls. Those depend on the actual ERP/Payables API and finance policy; they should be implemented as a separate, tested boundary rather than implied by successful extraction. Custom-model training is likewise outside the pretrained invoice path unless labeled requirements show the built-in field set is insufficient.
12. Five Useful FAQs
1. If the PDF is digitally generated, can I skip OCR?
Not automatically. The service can extract text from a PDF that already contains text, but layout, embedded fonts, scanning artifacts, and the chosen operation still matter. Choose the operation based on the required result and compare it with the source; do not assume digital origin proves complete or correctly classified text.
2. Does an invoice confidence score of 0.95 mean the field is 95% correct?
No. It is the service's confidence signal for that returned element, not a guarantee of calibrated correctness on your invoice population. Establish review policy from labeled examples and the business cost of accepting an incorrect supplier, identifier, tax value, or total.
3. Why does the REST invoice payload look different from the batch payload?
AnalyzeDocument is synchronous and accepts document plus features. CreateProcessorJob is asynchronous and accepts processorConfig, inputLocation, and outputLocation. Both are Document Understanding APIs, but their request schemas serve different lifecycles and must not be mixed.
4. Can a Processor Job marked SUCCEEDED be consumed as a valid invoice batch?
Not without retrieving and validating the output artifacts. Inspect lifecycle details, per-document errors, the source-to-output reconciliation, field/line quality, and deterministic business validations. Service completion and business acceptance are separate statuses.
5. When should I create a custom model?
Only when a documented gap in the pretrained capability is demonstrated by a representative labeled evaluation set. Classic custom models require labeled training examples; generative custom key-value models use a field-definition JSON and have their own region and model-lifecycle constraints. In either case, keep independent validation and human review for high-impact fields.
13. References Checked
The official Oracle documentation below was checked against the operation contracts, limits, IAM guidance, and native OIC mapper behavior described in this post. Oracle blog posts are secondary release/implementation context, not substitutes for the API schema. Link checks here are browser/documentation checks, not an automated HTTP status crawl of every URL from every network.
- OIC — Extract Document Information with a Document Understanding Action. Native categories/actions, regional and compartment configuration, inline/Object Storage mapper steps, custom-model configuration, and Processor Job create/status/cancel mapping.
- OIC — OCI AI service prerequisites. Identity-domain prerequisite, OIC OAuth application client ID, dynamic-group matching rule, and service policy examples.
- OIC — AI feature availability. Public availability boundary for native OIC AI actions.
- OCI Document Understanding — Service Overview. Supported pretrained model families and synchronous/batch processing concepts.
- OCI Document Understanding — Analyzing with the API.
AnalyzeDocument,CreateProcessorJob,GetProcessorJob, andCancelProcessorJoboverview. - OCI SDK — AnalyzeDocumentDetails model. Synchronous request fields, document type values, and feature list contract.
- OCI Document Understanding — Invoice key-value extraction. Supported invoice header and line-item fields, response nesting, confidence, word indexes, and geometry example.
- OCI Document Understanding — Document classification. Candidate document types and confidence outputs.
- OCI Document Understanding — OCR and Table extraction. Text geometry, table rows/cells, confidence, and documented language limits.
- OCI Document Understanding — Limits. File formats, size/page limits, dimensions, pending jobs, and service quota values.
- OCI Document Understanding — IAM Policies. Document Understanding permission and Object Storage access examples.
- OCI Document Understanding — Custom Models and Custom Generative Model V2.0. Classic-versus-generative approach, field schema, and limited model-management regions.
- OCI CLI — synchronous analyze-document command, plus Processor Job create, get, and Document Understanding command index (includes Processor Job cancel). The synchronous command takes separate
--documentand--featuresarguments; the Processor Job commands take their own distinct parameters. - OIC REST Adapter — Authentication Types and OCI Signature Version 1 security policy. Authentication path for the REST Adapter route.
- Oracle APEX blog — Invoice handling with OCI Document Understanding. Practical REST integration context; used as secondary context, while the current SDK/API model references govern the payloads above.
- Oracle Integration blog — OIC 26.01 adapter and AI-action enhancements. Oracle Integration 26.01 release context for native Document Understanding custom-model key/value support; verify the actual tenant, model region, and action wizard before relying on it.
Finally — Summary
OCI Document Understanding can classify supported document types and extract predefined fields, recognized text, and table structure. A useful OIC design keeps that extraction layer separate from deterministic business validation. Choose the operation that matches the output you need, verify the selected model’s document-type, language, and region limits, and treat the invoice path in this tutorial as one concrete worked example rather than the universal schema for all documents.
The implementation choice matters. AnalyzeDocument is the synchronous request contract; Processor Jobs use a distinct asynchronous schema and require lifecycle tracking plus Object Storage result retrieval. Preserve source references, page geometry, confidence, model/version information when returned, errors, and review corrections so that the business record remains auditable. Validate extracted values against trusted systems before downstream consumption. Treat confidence and job completion as evidence—not as authorization or business correctness. A well-designed workflow can explain, review, recover, and reconcile results, including failures, without claiming that this illustrative tutorial has been executed in a tenant.

Comments
Post a Comment