Skip to main content

OCI AI Services: Integrate OCI Document Understanding for Automated Document Extraction

Calculating read time…

A supplier invoice may arrive as a searchable PDF, a scanned image, or a low-quality phone capture. The procurement workflow still needs the same dependable facts: supplier, invoice number, purchase order, tax, currency, totals, and line items. A field that looks plausible is not necessarily a field that is correct, and a successful extraction call does not authorize a payment.

Invoice workflow: extraction, validation, and approval

StageResponsibility
1. RegisterOIC records the source object, document ID, and processing state.
2. ExtractOCI Document Understanding returns model results and the evidence exposed by the selected API or native action.
3. Validate and reviewOIC and trusted business systems check supplier, PO, arithmetic, currency, and duplicates. A reviewer resolves exceptions.
4. Approve and commitThe approval policy and target system control acceptance; idempotency prevents duplicate processing.

For custom extraction, classic models use labeled training data; generative models use field definitions and descriptions. Both need evaluation.

For an OIC engineer, the practical question is not simply how to read a PDF. It is where to place the boundary between document extraction, deterministic business validation, human correction, and downstream commitment—and how to preserve the page-level evidence needed to explain a result later. A synchronous request is attractive for a small invoice, while a large inbox needs recoverable batch processing and result reconciliation.

This tutorial builds those paths with OCI Document Understanding and Oracle Integration. It distinguishes what the service extracts from what procurement rules must prove, demonstrates both the native OIC action and the REST API route, and treats a document as traceable source evidence rather than an unquestioned record.

1. What You Will Build

The running example is a fictional procurement invoice, NIS-2026-117.pdf, stored in an Object Storage input bucket. OIC will extract the invoice header and line items, retain page and geometry references where exposed by the selected route, compare the result with a trusted purchase-order record, and route unresolved cases to review instead of treating extraction as approval.

Practical outcome

  1. Process one invoice synchronously with the native OCI Document Understanding action and the documented REST API.
  2. Inspect field confidence, line-item structure, page numbers, and bounding polygons.
  3. Validate supplier, purchase order, identifiers, arithmetic, tax, and currency using trusted business data.
  4. Classify unknown documents and use OCR/text or table extraction where that is the appropriate operation.
  5. Submit a batch Processor Job, poll its lifecycle, retrieve output artifacts, reconcile partial failures, and avoid duplicate business processing.
  6. Choose between a pretrained invoice model, a custom classic model, and a custom generative model based on evidence and availability.

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

  1. Before You Begin — Shared Setup
  2. Invoice key-value extraction, validation, and human review
  3. Document classification and routing
  4. OCR and text extraction with source geometry
  5. Table extraction and line-item reconciliation
  6. Batch Processor Jobs: submit, poll, retrieve, reconcile
  7. Custom classic versus generative models
  8. Combine the completed paths
  9. Completion checklist and next steps
  10. Five useful FAQs
  11. References checked
  12. 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 native orchestration feature that invokes supported service capabilities. This article also demonstrates a REST Adapter route. Each route has its own request/response wrapper. Native OCI AI actions are documented for the commercial realm (OC1), and AI feature eligibility depends on the OIC edition; confirm OIC AI feature availability and the target service region before configuration.

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. 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 limitPublished value to design againstEngineering implication
File typesJPEG, PNG, PDF, TIFFReject unsupported extensions/content before invocation; verify that the bytes match the declared media type.
Synchronous document8 MB maximum; five pages or fewerUse for small, latency-sensitive documents only; avoid passing an oversized PDF to the synchronous path.
Asynchronous inline8 MB maximum; five pages or fewerAsync does not remove the inline size/page restriction.
Asynchronous Object Storage500 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 lessPrefer object references for batches; check both the document/job-count and request-body limits before building the manifest.
Image geometry32 × 32 minimum and 10,000 × 10,000 maximum; minimum text height 15 pixelsA syntactically valid image can still be unreadable because of low resolution, skew, blur, or compression.

The values above referred from Oracle's Document Understanding limits page. 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. 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 namespace, bucket, and object name identify the source location. An object name alone is not immutable: prevent overwrites or bind processing to a controlled source copy/version so the reviewed bytes are the bytes analyzed. 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. Capability 1 — 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

  1. 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.
  2. 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 Id target element; do not dynamically override it unless that region has been validated and the identity can access it.
  3. 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.
  4. 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.
  5. Finish and configure the request mapper. In the generated request wrapper, map the source objectName value to Document/Object Name. Check the generated target schema rather than inventing REST fields such as document.objectName in the OIC action mapper. OIC's native wrapper is connector-generated and is not the literal REST JSON envelope.
  6. Configure the response mapper. Preserve the document ID and source object reference. Map the extracted values, confidence fields, and repeatable item structures that the generated schema exposes. Check page numbers, bounding polygons, and word indexes separately: the native action guide does not guarantee that every REST evidence field is exposed by every action variant. If required audit evidence is unavailable in the native response, use the documented REST response or Processor Job output for that evidence; never synthesize missing geometry.
  7. 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

  1. 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 PKCS1 format, and the passphrase required by Oracle’s connection prerequisites. Convert a downloaded PKCS8 key when necessary. Oracle documents that private endpoints are not supported with this security policy. 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.
  2. Configure the invoke resource as HTTP POST, relative URI /20221109/actions/analyzeDocument, request content type application/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.
  3. In the request mapper, obtain compartmentId, namespaceName, and bucketName from authorized integration configuration; these are not fields in the minimal inbound fixture in Section 3.4. Map the inbound objectName to document.objectName. Set document.source to OBJECT_STORAGE, documentType to INVOICE, and the feature type to KEY_VALUE_EXTRACTION.
  4. 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 meaningREST request/result elementNative OIC mapper meaningControl
Source documentdocument.source, namespaceName, bucketName, objectNameGenerated Document / Object Name / bucket / namespace targetsRetain the original object reference and source version/ETag where available.
Model selectionfeatures[].featureType and documentTypeChosen in the wizard and reflected by the generated schema; some input values are configured, not runtime-suppliedUse KEY_VALUE_EXTRACTION plus INVOICE for the pretrained invoice model.
Header fieldpages[].documentFields[].fieldLabel.name, fieldValue.text, fieldLabel.confidence, fieldValue.confidenceCorresponding generated response nodes; exact namespaces/wrappers depend on the OIC action schemaPreserve values and confidence with their page and geometry evidence.
Source coordinatesfieldValue.boundingPolygon.normalizedVertices, wordIndexes, pageNumberMap the returned page/field/geometry array nodes if exposed by the generated schemaGeometry 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.

Keep confidence fields distinct. fieldLabel.confidence accompanies the field label; fieldValue.confidence accompanies the extracted value. Preserve both when returned, and bind each validation threshold to the intended field. A label score alone does not establish that the extracted value is correct. See the FieldValue model and FieldLabel model.

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": 2,
    "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
                }
              ]
            },
            "confidence": 0.95
          }
        },
        {
          "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",
                        "confidence": 0.94
                      }
                    },
                    {
                      "fieldType": "LINE_ITEM_FIELD",
                      "fieldLabel": {
                        "name": "Quantity",
                        "confidence": 0.98
                      },
                      "fieldValue": {
                        "valueType": "NUMBER",
                        "text": "3",
                        "value": 3,
                        "confidence": 0.96
                      }
                    },
                    {
                      "fieldType": "LINE_ITEM_FIELD",
                      "fieldLabel": {
                        "name": "UnitPrice",
                        "confidence": 0.95
                      },
                      "fieldValue": {
                        "valueType": "NUMBER",
                        "text": "60.00",
                        "value": 60.0,
                        "confidence": 0.93
                      }
                    },
                    {
                      "fieldType": "LINE_ITEM_FIELD",
                      "fieldLabel": {
                        "name": "Amount",
                        "confidence": 0.94
                      },
                      "fieldValue": {
                        "valueType": "NUMBER",
                        "text": "180.00",
                        "value": 180.0,
                        "confidence": 0.92
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  ]
}

This is an illustrative structure using the synthetic Bearing Kit fixture, not a claimed service response; the label-confidence scores, value-confidence scores, and field values are independently illustrative. This is a partial projection, so required model members not relevant to the illustration are omitted; it is not a complete response fixture. 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 the displayed page width and y values by the displayed page height. Apply the same page rotation, crop, and scaling as the reviewer image; otherwise the highlight can move away from the detected field. 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 PurchaseOrder with 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

CaseExpected behaviorEvidence to inspect
Clear invoice with PO matchExtract 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 POMark 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 scanQuality failure or uncertain extraction becomes reviewable; no silent approval.Page metadata, absent/poor fields, confidence distribution, preserved source image.
PO or supplier mismatchDeterministic mismatch route even if extracted fields have high confidence.Trusted PO/supplier response and validation reason.
Duplicate supplier invoice IDReturn existing processing state or duplicate-review outcome; do not post a second invoice.Unique key/idempotency record and downstream acknowledgement.
REST caller lacks permissionFail 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 header and nested line-item records, verify evidence availability for each route, and obtain required page/geometry evidence through REST/job output when the native schema omits it; 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 candidates to compare by confidence; do not assume array order is a contractual ranking. Route only when the classification policy passes, and send ambiguous or Other results to review. The current API enum uses OTHERS for the Other category.

5.2 Native OIC implementation

  1. Add OCI Document Understanding → Pre-trained Models → Document classification.
  2. Set the intended service region and compartment. Select inline or Object Storage. Use Object Storage for the sample fixture and map objectName to the generated Document → Object Name node. For inline input, use the documented base64 stream-reference mapping described in Section 4.2.
  3. 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.
  4. Use a Switch/decision branch: route INVOICE to the invoice action, RECEIPT to 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.

CaseExpected behaviorEvidence
Clear invoiceInvoice route is selected only after the configured classification policy passes.Candidate array, chosen route, original document reference.
Receipt or bank statementUse the appropriate supported path or review; do not force invoice extraction.Returned document-type candidates and routing log.
Ambiguous candidates / OtherHold for review or apply a labeled, tested disambiguation policy.Candidate list, confidence values, review case.
Unsupported file or unreadable scanReject 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

  1. Add OCI Document Understanding → Pre-trained Models → Text extraction.
  2. 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 documented oraext:encodeReferenceToBase64(...) function into Document/Data.
  3. 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.
  4. 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.

CaseExpected behaviorEvidence to inspect
Searchable digital PDFReturn text and source geometry as supported.Pages, lines, words, geometry, page count.
Blurred scan / very small printRecognized text may be missing or uncertain; invoke a quality/review route.Missing lines, low-confidence groups, original file and dimensions.
Non-English contentVerify 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/objectFail 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

  1. Add OCI Document Understanding → Pre-trained Models → Table extraction.
  2. Select the service region and compartment, then choose inline or Object Storage input. Map the generated Document/Object Name for the Object Storage route, or map the stream reference through oraext:encodeReferenceToBase64(...) to Document/Data for inline input.
  3. 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.
  4. 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": 3,
          "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 illustrative and abbreviated: only one representative body row is shown even though the sample table reports three rows. 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

CaseExpected behaviorEvidence
Simple bordered tableRows/cells are represented with their indexes and text.Table row/column counts, cells, confidence, geometry.
Borderless or low-quality tableInspect column assignment and send structurally uncertain rows to review.Cell positions and rendered-source comparison.
Table continues to page 2Reconcile with page-aware continuation logic; no assumed auto-merge.Page number, repeated headers, item sequence, duplicate detection.
Non-English tableDo 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

  1. 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 Location bucket/namespace, and Output Location prefix, with the source file/object mapped in the request wrapper. Follow the generated schema to add each repeated Features/Object Locations entry supported by the action.
  2. Persist the job handle: map the create response's Id and Percent 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.
  3. Poll status: add Get a processor job status and map the create action's returned id to the target Processor 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.
  4. Handle lifecycle states: ACCEPTED and IN_PROGRESS require bounded polling. CANCELING is also nonterminal: keep checking until cancellation or another terminal result is observed. SUCCEEDED requires output retrieval and reconciliation; FAILED and CANCELED stop normal consumption and require recovery accounting. Inspect lifecycleDetails separately for PARTIALLY_SUCCEEDED or COMPLETELY_FAILED; these are detail values, not additional lifecycle states. Retain any artifacts produced before failure or cancellation.
  5. 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. The cancel API has no response-body job record; call GetProcessorJob to inspect the subsequent state instead of expecting cancel to return it.
  6. 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. Follow every listing page: use the response’s nextStartWith value as the next request’s start parameter until it is absent. A first page alone cannot reconcile a large batch. 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": [
      {
        "namespaceName": "your_object_storage_namespace",
        "bucketName": "procure-invoices-in",
        "objectName": "incoming/NIS-2026-117.pdf"
      },
      {
        "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. This multi-line script uses Bash syntax; run it in Bash or OCI Cloud Shell, not unchanged in PowerShell. Check the create command’s exit status and persist a nonempty job ID before issuing status calls. The CLI uses the same documented API but structures its command arguments separately.

set -euo pipefail

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)

[ -n "$JOB_ID" ] && [ "$JOB_ID" != "null" ] || { echo "No processor job ID returned; reconcile the submission." >&2; exit 1; }
echo "$JOB_ID"
oci ai-document processor-job get \
  --processor-job-id "$JOB_ID" \
  --region "$REGION_ID"

# Optional manual cancellation: uncomment only when cancellation is intended.
# 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 cancel command 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:

  1. Record submissionPending, the input manifest, a unique run ID, and a deterministic output prefix before calling create.
  2. Persist the returned processor-job ID immediately. For direct REST submission, generate and retain one opc-retry-token for the logical create request before sending it; reuse that token and the same request when retrying within its validity period. Oracle documents retry-token support for CreateProcessorJob. Do not assume the native OIC action exposes that header: inspect its generated contract, or use a REST route when explicit retry-token control is required. A timeout leaves the outcome uncertain; do not create a fresh logical submission blindly. The current public Document Understanding client does not expose ListProcessorJobs, so a “list recent jobs” recovery call must not be invented.
  3. 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.
  4. 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.
  5. 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.
  6. Keep source files, job metadata, and output artifacts under the retention policy. Removing a local tracking record 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/' \
  --all \
  --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

CaseExpected behaviorEvidence to inspect
Two valid documentsOne 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 documentThe other results are retained; failed item is classified and not silently dropped.Lifecycle details, errors, available result artifacts, input manifest.
Output bucket permission deniedJob 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 limitMove to a monitored waiting/escalation state; do not loop indefinitely.lifecycleState, progress, accepted/started timestamps, last poll and request ID.
Create timeout / uncertain outcomeReconcile the submission before retrying; avoid duplicate expensive jobs and duplicate business writes.Persisted submission/retry-token record, output prefix, captured job ID if available, request IDs, source manifest.
Cancel while processingCheck 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.

ChoiceWhen it fitsCost and limitation to evaluate
Pretrained invoice modelStandard 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 modelA 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.0Fields 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. Natural-language instructions such as “leave missing” are guidance, not enforced validators; OIC must independently check identifier ownership, explicit currency codes, required fields, and acceptable missing-value handling.

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

CaseExpected behaviorEvidence
Known layout, labeled sampleEvaluate field accuracy against a labeled ground-truth set.Per-field precision/recall or error review, document/page coverage, model version.
New supplier layoutObserve generalization and route uncertain/missing critical fields to review.Field-level comparison, page/source evidence, review outcomes.
Confusing IDs/totalsDescription and schema reduce mistakes, but validators still catch conflicts.Confusion cases, false positives, missed fields and deterministic checks.
Model not available in selected regionDeployment 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 an Invoice Workflow

The combined design uses only operations already explained:

  1. 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.
  2. Choose an execution mode. For a small request within the documented synchronous limits, invoke invoice key-value extraction. For a batch, create a Processor Job and persist its job ID/output prefix immediately.
  3. Classify when type is unknown. Route only known/approved document categories to their associated extraction operation. Ambiguous/unsupported files go to review.
  4. 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.
  5. Validate deterministically. Compare supplier, PO, legal entity, invoice key, quantity, price, currency, tax, and totals with trusted procurement/business data. A missing currency field cannot be guessed from the score; if currency cannot be established, review is required.
  6. 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.
  7. 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 caseExpected behaviorEvidence to retain
Valid invoice / matching POExtraction is followed by all configured deterministic validations and approval policy.Source reference, extraction evidence, PO lookup result, validation decision, approval and target correlation ID.
Extracted total differs from line/tax arithmeticReview outcome; no automatic downstream commit.Original totals/line values, reconciliation calculation, source polygons and review reason.
Supplier invoice already processedDuplicate is blocked or routed according to credit/correction policy.Unique key lookup, idempotency record, target response.
Partial batch failureSuccessful 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 submitReconcile 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 exposed header fields, line items, confidence, and the source reference; required page/geometry evidence is confirmed in the actual native schema or obtained through REST/job output.
  • [ ] 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. Additional References

  1. 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.
  2. OIC — OCI AI service prerequisites. Identity-domain prerequisite, OIC OAuth application client ID, dynamic-group matching rule, and service policy examples.
  3. OIC — AI feature availability. Public availability boundary for native OIC AI actions.
  4. OCI Document Understanding — Service Overview. Supported pretrained model families and synchronous/batch processing concepts.
  5. OCI Document Understanding — Analyzing with the API. AnalyzeDocument, CreateProcessorJob, GetProcessorJob, and CancelProcessorJob overview.
  6. OCI SDK — AnalyzeDocumentDetails model. Synchronous request fields, document type values, and feature list contract.
  7. OCI Document Understanding — Invoice key-value extraction. Supported invoice header and line-item fields, response nesting, confidence, word indexes, and geometry example.
  8. OCI Document Understanding — Document classification. Candidate document types and confidence outputs.
  9. OCI Document Understanding — OCR and Table extraction. Text geometry, table rows/cells, confidence, and documented language limits.
  10. OCI Document Understanding — Limits. File formats, size/page limits, dimensions, pending jobs, and service quota values.
  11. OCI Document Understanding — IAM Policies. Document Understanding permission and Object Storage access examples.
  12. OCI Document Understanding — Custom Models and Custom Generative Model V2.0. Classic-versus-generative approach, field schema, and limited model-management regions.
  13. OCI CLI — synchronous analyze-document command, plus Processor Job create, get, and cancel. The synchronous command takes separate --document and --features arguments; the Processor Job commands take their own distinct parameters.
  14. OIC REST Adapter — Authentication Types and OCI Signature Version 1 security policy. Authentication path for the REST Adapter route.
  15. 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.
  16. 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.
  17. OCI SDK — ObjectLocation. Documented properties for each batch input object; this type has no source discriminator.
  18. OCI SDK — FieldValue. Extracted-value confidence, text, geometry, and word references.
  19. OCI SDK — FieldLabel. Label name and label confidence, kept distinct from value confidence.
  20. OCI SDK — ProcessorJob. Lifecycle states and separate lifecycle details.
  21. OCI SDK — AIServiceDocumentClient. Create retry-token support, operation inventory, and cancellation response contract.
  22. OCI CLI — Object Storage object list. The --all option retrieves every listing page.
  23. OCI SDK — ListObjects. nextStartWith continuation for Object Storage listing.
  24. OCI SDK — DocumentKeyValueExtractionFeature. Feature-level modelId for custom key-value inference.
  25. OCI SDK — DocumentTextExtractionFeature. TEXT_EXTRACTION and generateSearchablePdf feature settings.

Finally — Summary

OCI Document Understanding can turn invoices and related documents into structured fields, line items, tables, and page-linked text. A useful OIC design keeps that extraction layer separate from deterministic business validation. Pretrained invoice extraction provides a practical starting point, while classification, OCR/text extraction, and table extraction solve different input and structure problems; use each where its documented behavior fits.

The implementation choice matters. AnalyzeDocument is the synchronous request contract; Processor Jobs use a distinct asynchronous schema and require status tracking plus Object Storage result retrieval. Preserve source references, page geometry, confidence, model version, errors, and review corrections so that the business record remains auditable. Validate supplier, PO, identifiers, currency, tax, arithmetic, and duplicates against trusted systems before downstream consumption. Finally, treat confidence and job completion as evidence—not as authorization or business correctness. A production-ready workflow is one that can explain, review, recover, and reconcile its results, including failures.

Comments