> ## Documentation Index
> Fetch the complete documentation index at: https://developer.box.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get consistent output across many documents with a document extraction schema

> Pull the same fields out of thousands of PDFs without the output format drifting. Use a Box metadata template as your document extraction schema, much like a JSON schema, and the Box Extract API returns the template's keys and types for every file.

To get an LLM to pull the same fields out of 50,000 PDFs without the output format drifting from one document to the next, define the fields once in a document extraction schema, much like a JSON schema, and extract every PDF against that one schema. In Box, that schema is a metadata template, which names each field and sets its type. The Box Extract API (`POST /2.0/ai/extract_structured`) returns every answer under the template's field keys, with `date` fields as RFC 3339 timestamps and `float` fields as numbers.

Box runs OCR, layout parsing, and extraction for you. You can attach a Custom Extract Agent to a folder without writing code, or call the API once per file from a script like the one in this guide. The examples use PDFs, but the API accepts other file formats too.

## How a metadata template prevents format drift

Format drift is when the same field comes back with a different name, type, or format from one document to the next. For example, one answer has `total: "$1,050.00"` and the next has `amount_due: 2480.5`. A metadata template prevents this in three ways:

* **One definition.** Each request references the template by its key, so you don't copy field definitions into every prompt.
* **Fixed keys and types.** Box AI returns values under the template's field keys, with dates as RFC 3339 timestamps and numbers as JSON numbers.
* **A typed store.** When you save an answer as metadata on the file, Box returns `400 Bad Request` for any value that doesn't fit its field. Examples are text in a `float` field, an `enum` value that isn't one of the options, or a key that isn't in the template.

Box AI also reads each field's description, so put the expected format there, for example "The three-letter ISO 4217 currency code".

With the template in this guide, Box AI returned these values from five invoice layouts, one of them scanned:

| Printed in the PDF | Returned by Box AI |
| - | - |
| `Date: 02/13/2026` | `"issueDate": "2026-02-13T00:00:00Z"` |
| `Issued 13 March 2026` | `"issueDate": "2026-03-13T00:00:00Z"` |
| `Date of issue: 1st April 2026` | `"issueDate": "2026-04-01T00:00:00Z"` |
| `Total due: $1,050.00` | `"totalAmount": 1050`, `"currency": "USD"` |
| `Amount payable: 2.480,50 €` | `"totalAmount": 2480.5`, `"currency": "EUR"` |
| `TOTAL (USD) 1,397.96` on a scanned page | `"totalAmount": 1397.96`, `"currency": "USD"` |

Outputs can still vary between runs, and Box AI leaves out fields it can't find. The script in this guide validates each answer before saving it.

## Map a JSON schema to a metadata template

If you already have a JSON schema, map each property to a template field type:

| JSON schema property | Template field type | Notes |
| - | - | - |
| `"type": "string"` | `string` | Accepts any text. The metadata write doesn't check its format. |
| `"type": "number"` or `"type": "integer"` | `float` | Returned as a JSON number. |
| `"type": "string"` with `"format": "date"` or `"date-time"` | `date` | Returned and stored as an RFC 3339 timestamp, for example `2026-03-13T00:00:00Z`. |
| `"enum"` | `enum` | List the allowed values as `options`. |
| `"type": "array"` with `enum` items | `multiSelect` | List the allowed values as `options`. Returned as a JSON array. |
| `"type": "boolean"` | `enum` | Use options such as `Yes` and `No`. |
| `"type": "object"`, or an array of objects | None | See [Nested fields and line items](#nested-fields-and-line-items). |

Two JSON schema keywords work differently:

* `required` has no template equivalent. Box AI leaves out fields it can't find, so check for required fields in your code.
* `additionalProperties: false` needs no setting. The metadata write rejects keys that aren't in the template.

For values from a known list, such as document types or vendor names you already have, use an `enum` field instead of `string`. Box then rejects any other value when you save it.

## Choose between a Custom Extract Agent and the API

Both options run OCR, layout parsing, and extraction in Box. They differ in who runs the loop over your files.

| | Custom Extract Agent | Box Extract API |
| - | - | - |
| You set up | A metadata template and an agent in the Box web app | A metadata template and a script that calls the API once per file |
| Box handles | Extracting every file in up to 10 folders, including files already there and files uploaded later, and saving the values as metadata | OCR, layout parsing, and extraction against the template for each request |
| You handle | Checking results in the agent's Run History and in Box Preview | Listing files, pacing requests, validating answers, and saving them |
| Plan | Enterprise Advanced | Business and above, or a free developer account for testing |

A Custom Extract Agent uses one metadata template, and Box locks the template when you attach a source folder. Every file in the agent's folders uses the same schema. Box Extract processes at most 500 extractions per minute per user and 700 per minute per enterprise. See [About Box Extract](https://docs.box.com/en/box-extract/about-box-extract) and [Using Box Extract](https://docs.box.com/en/box-extract/using-box-extract).

The rest of this guide uses the Box Extract API.

## Before you start

* Store the PDFs in a Box folder. To upload a local folder tree, see Recursively upload a folder with Python.
* Create a Client Credentials Grant app with the **Read and write all files and folders stored in Box** and **Manage AI** scopes, and have an admin authorize it in the Admin Console. See Get started with Box AI.
* Invite the app's service account to the folder as an **Editor**, so it can read the PDFs and write metadata.
* Get an admin to create the metadata template if you can't. Only admins, and co-admins with permission to create and edit metadata templates, can create templates.
* Plan for AI Units. Each extract call consumes AI Units, and confidence scores consume more. Before a large run, request an allowance increase and tell your Box account team. See the [Box AI Units consumption table](https://cloud.box.com/v/box-ai-units-consumption-table).
* Install Python 3.11 or later and the Box Python SDK 10.5 or later:

  ```bash theme={null}
  python3 -m pip install "boxsdk~=10.5"
  ```

  If the deprecated `box-sdk-gen` package is installed in the same environment, uninstall it first. Both packages install the `box_sdk_gen` module, so having both can break the script's imports.

## Define the document extraction schema

Create a metadata template with one field per value, and put the expected format in each field's `description`:

```bash theme={null}
curl -X POST "https://api.box.com/2.0/metadata_templates/schema" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "scope": "enterprise",
    "templateKey": "invoiceExtraction",
    "displayName": "Invoice extraction",
    "fields": [
      {"type": "string", "key": "vendorName", "displayName": "Vendor name", "description": "The legal name of the company that issued the document"},
      {"type": "string", "key": "documentNumber", "displayName": "Document number", "description": "The invoice or credit note number exactly as printed, including any prefix"},
      {"type": "enum", "key": "documentType", "displayName": "Document type", "description": "Whether the document is an invoice or a credit note", "options": [{"key": "Invoice"}, {"key": "Credit note"}]},
      {"type": "date", "key": "issueDate", "displayName": "Issue date", "description": "The date the document was issued"},
      {"type": "date", "key": "dueDate", "displayName": "Due date", "description": "The date payment is due"},
      {"type": "float", "key": "totalAmount", "displayName": "Total amount", "description": "The total including tax, as a number without a currency symbol or thousands separators"},
      {"type": "string", "key": "currency", "displayName": "Currency", "description": "The three-letter ISO 4217 currency code, for example USD, EUR, or GBP"}
    ]
  }'
```

Admins can also create templates in the Admin Console. See Create a metadata template.

## Test the schema on a sample of PDFs

Before a full run, extract a sample that covers your layouts, including scanned files and documents with missing fields. Pass the template instead of a list of fields:

```bash theme={null}
curl -X POST "https://api.box.com/2.0/ai/extract_structured" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "items": [{"id": "<FILE_ID>", "type": "file"}],
    "metadata_template": {
      "template_key": "invoiceExtraction",
      "type": "metadata_template",
      "scope": "enterprise"
    }
  }'
```

The `answer` object uses the template's field keys. This invoice has no due date, so `answer` leaves out `dueDate`:

```json theme={null}
{
  "answer": {
    "vendorName": "Thames Print Ltd",
    "documentNumber": "7781",
    "documentType": "Invoice",
    "issueDate": "2026-04-01T00:00:00Z",
    "totalAmount": 640,
    "currency": "GBP"
  },
  "ai_agent_info": {
    "processor": "basic_text",
    "models": [
      {
        "name": "google__gemini_3_1_flash_lite",
        "provider": "google"
      }
    ]
  },
  "created_at": "2026-11-30T06:04:54.224-08:00",
  "completion_reason": "done"
}
```

`ai_agent_info` shows the model that handled the request.

To get a confidence score for each field, add `"include_confidence_score": true` to the request. The response then has a `confidence_score` object with entries such as `"totalAmount": {"level": "HIGH", "score": 1}`. A score of 0.90 or higher is high, 0.70 to 0.89 is medium, and below 0.70 is low. Confidence scores work only with Gemini models, which the default Extract Agent and the Enhanced Extract Agent use.

If a value comes back in the wrong form, refine the field's description and test again. For multi-column layouts, scanned files, or dense tables, add `"ai_agent": {"type": "ai_agent_id", "id": "enhanced_extract_agent"}` to the request to use the Enhanced Extract Agent.

## Run the extraction across a folder

There is no batch extract endpoint. A request can include up to 25 files, but Box AI returns one combined answer for all of them. Send one file per request and run requests in parallel.

The following script extracts every PDF in a folder, checks each answer against the template's field types, and saves valid answers as metadata on the file. Save it as `extract_invoices.py`.

> [accordion] extract\_invoices.py
>
> ```python theme={null}
> import json
> import os
> import time
> from concurrent.futures import ThreadPoolExecutor
> from datetime import datetime
> from functools import partial
>
> from box_sdk_gen import (
>     AiItemBase,
>     BoxAPIError,
>     BoxCCGAuth,
>     BoxClient,
>     CCGConfig,
>     CreateAiExtractStructuredMetadataTemplate,
>     CreateAiExtractStructuredMetadataTemplateTypeField,
>     CreateFileMetadataByIdScope,
>     GetFileMetadataByIdScope,
>     GetMetadataTemplateScope,
>     TimeoutConfig,
> )
>
> TEMPLATE_KEY = os.environ["BOX_TEMPLATE_KEY"]
> FOLDER_ID = os.environ["BOX_FOLDER_ID"]
> WORKERS = 8
> REVIEW_BELOW = 0.90
>
>
> def get_client() -> BoxClient:
>     auth = BoxCCGAuth(
>         config=CCGConfig(
>             client_id=os.environ["BOX_CLIENT_ID"],
>             client_secret=os.environ["BOX_CLIENT_SECRET"],
>             enterprise_id=os.environ["BOX_ENTERPRISE_ID"],
>         )
>     )
>     return BoxClient(auth=auth).with_timeouts(TimeoutConfig(read_timeout_ms=120_000))
>
>
> def list_pdfs(client: BoxClient, folder_id: str):
>     marker = None
>     while True:
>         page = client.folders.get_folder_items(
>             folder_id, fields=["name"], usemarker=True, marker=marker, limit=1000
>         )
>         for item in page.entries:
>             if item.type == "file" and item.name.lower().endswith(".pdf"):
>                 yield item.id
>         marker = page.next_marker
>         if not marker:
>             return
>
>
> def has_metadata(client: BoxClient, file_id: str) -> bool:
>     try:
>         client.file_metadata.get_file_metadata_by_id(
>             file_id, GetFileMetadataByIdScope.ENTERPRISE, TEMPLATE_KEY
>         )
>         return True
>     except BoxAPIError as error:
>         if error.response_info.status_code == 404:
>             return False
>         raise
>
>
> def extract(client: BoxClient, file_id: str) -> dict:
>     for attempt in range(5):
>         try:
>             response = client.ai.create_ai_extract_structured(
>                 [AiItemBase(id=file_id)],
>                 metadata_template=CreateAiExtractStructuredMetadataTemplate(
>                     template_key=TEMPLATE_KEY,
>                     type=CreateAiExtractStructuredMetadataTemplateTypeField.METADATA_TEMPLATE,
>                     scope="enterprise",
>                 ),
>                 include_confidence_score=True,
>             )
>             return response.to_dict()
>         except BoxAPIError as error:
>             if error.response_info.status_code != 412 or attempt == 4:
>                 raise
>             time.sleep(30 * 2**attempt)
>
>
> def matches_type(value, field) -> bool:
>     if field.type == "float":
>         return isinstance(value, (int, float)) and not isinstance(value, bool)
>     if field.type == "date":
>         try:
>             datetime.fromisoformat(value)
>         except (TypeError, ValueError):
>             return False
>         return "T" in value
>     options = {option.key for option in field.options or []}
>     if field.type == "enum":
>         return value in options
>     if field.type == "multiSelect":
>         return isinstance(value, list) and set(value) <= options
>     return isinstance(value, str)
>
>
> def process(client: BoxClient, fields: dict, file_id: str) -> dict:
>     record = {"file_id": file_id}
>     try:
>         if has_metadata(client, file_id):
>             return {**record, "status": "skipped"}
>
>         result = extract(client, file_id)
>         answer = result.get("answer", {})
>         record["models"] = sorted({m["name"] for m in result["ai_agent_info"]["models"]})
>         if not answer:
>             return {**record, "status": "empty"}
>
>         invalid = [k for k, v in answer.items() if k not in fields or not matches_type(v, fields[k])]
>         if invalid:
>             return {**record, "status": "invalid", "fields": invalid, "answer": answer}
>
>         missing = sorted(fields.keys() - answer.keys())
>         scores = result.get("confidence_score", {})
>         low_confidence = sorted(k for k, c in scores.items() if c["score"] < REVIEW_BELOW)
>
>         client.file_metadata.create_file_metadata_by_id(
>             file_id, CreateFileMetadataByIdScope.ENTERPRISE, TEMPLATE_KEY, answer
>         )
>         if missing or low_confidence:
>             return {**record, "status": "review", "missing": missing, "low_confidence": low_confidence}
>         return {**record, "status": "saved"}
>     except BoxAPIError as error:
>         info = error.response_info
>         return {**record, "status": "error", "code": info.status_code, "reason": info.code}
>
>
> def main():
>     client = get_client()
>     template = client.metadata_templates.get_metadata_template(
>         GetMetadataTemplateScope.ENTERPRISE, TEMPLATE_KEY
>     )
>     fields = {field.key: field for field in template.fields}
>
>     with ThreadPoolExecutor(max_workers=WORKERS) as pool, open("extraction-log.jsonl", "a") as log:
>         for record in pool.map(partial(process, client, fields), list_pdfs(client, FOLDER_ID)):
>             line = json.dumps(record)
>             log.write(line + "\n")
>             print(line)
>
>
> if __name__ == "__main__":
>     main()
> ```

Set your app credentials, the template key, and the folder ID, then run the script:

```bash theme={null}
export BOX_CLIENT_ID="<CLIENT_ID>"
export BOX_CLIENT_SECRET="<CLIENT_SECRET>"
export BOX_ENTERPRISE_ID="<ENTERPRISE_ID>"
export BOX_TEMPLATE_KEY="invoiceExtraction"
export BOX_FOLDER_ID="<FOLDER_ID>"
python3 extract_invoices.py
```

For each file, the script prints a JSON record and appends it to `extraction-log.jsonl`:

```json theme={null}
{"file_id": "12345", "models": ["google__gemini_3_1_flash_lite"], "status": "review", "missing": ["dueDate"], "low_confidence": []}
```

The script:

* Reads the field definitions from the template once and checks every answer against them. If the answer is empty or a value doesn't fit its field, the script saves nothing for that file.
* Skips files that already have an instance of the template, so you can stop and rerun it.
* Runs 8 workers with a 120-second read timeout. The Box Python SDK retries `429` and `5xx` responses, and the script retries `412` responses, starting with a 30-second wait and doubling it each time.
* Logs the models from `ai_agent_info` for each extracted file.

The script reads only the top level of the folder. For PDFs in subfolders, run it for each subfolder. It also picks up only files that end in `.pdf`. To process other supported formats, change the extension check in `list_pdfs`. Start with a small batch, then raise `WORKERS`. For pacing guidance, see Best practices for the Extract Structured API.

## Review the results

Each record in `extraction-log.jsonl` has a `status`:

| Status | Saved to Box | What it means |
| - | - | - |
| `saved` | Yes | Every template field came back, and none scored below 0.90. |
| `review` | Yes | Box AI didn't find the fields in `missing`, and the fields in `low_confidence` scored below 0.90. Check them against the PDF and update the metadata instance if needed. |
| `empty` | No | Box AI found none of the template's fields. The file is often a different kind of document, such as a contract in a folder of invoices. |
| `invalid` | No | A value didn't fit its field. The record includes the full answer. Refine the field description or try the Enhanced Extract Agent. |
| `error` | No | The API returned an error. The record includes the HTTP status code in `code` and Box's error code in `reason`. |
| `skipped` | Already has metadata from this template | The file already had metadata. |

The next run retries `empty`, `invalid`, and `error` files. Move files that aren't the right kind of document out of the folder, so later runs don't use AI Units on them.

## Keep the schema stable during a run

Don't change the template mid-run. Template changes apply to every file that already has an instance of the template, and files extracted before a description change used the old description.

Box updates the default models on a regular basis and announces changes in the developer changelog. Use the models in the log to find files that a different model extracted. To keep a run on one configuration, see AI agent configuration versioning.

## Nested fields and line items

Metadata templates have no field type for nested objects or repeating rows, such as invoice line items. For those, use inline `fields` with the `struct` or `table` type. A request takes either `metadata_template` or `fields`, not both, so extract line items in a separate request or define every field inline.

To keep inline fields consistent, define the list once in your code and send the same list with every request. Store the results in your own database, because a metadata template can't hold them. See `struct` and `table` field types and the supplier agreement tutorial.

**RELATED GUIDES**

**RELATED APIS**
