> For the complete documentation index, see [llms.txt](https://typless.gitbook.io/typlessapi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://typless.gitbook.io/typlessapi/automation-use-cases/custom-pretrained-document.md). Agents can also search and read this documentation through its [MCP server](https://typless.gitbook.io/typlessapi/~gitbook/mcp).

# Custom pretrained document

Building your own pretrained document type with field descriptions and presets, with examples in Python and Node.

### Overview

Pretrained models are not limited to invoices. This guide shows how to build a document type for your own kind of document, an **order confirmation** from your suppliers, by describing its fields in plain language. There is no training: once the descriptions are right, the model extracts the first document of every supplier.\
You will extract the following fields:

* Supplier name
* Confirmation number and date
* Your purchase order number
* Confirmed delivery date
* Total amount
* Ordered items: code, description, quantity and unit price

**This guide shows you how to**

1. [Create a custom pretrained document type](#id-1.-create-a-new-document-type)
2. [Write field descriptions](#id-2.-write-field-descriptions)
3. [Extract data from documents](#id-3.-extract-data-from-documents)
4. [Extract an extra field for one request](#id-4.-extract-an-extra-field-for-one-request)

## Get your API Key

The *Authorization* header for your API key is: `Token YOUR-API-KEY` ([Login](https://app.typless.com/login/?redirect=https://docs.typless.com/) if you do not see one).\
You can also obtain the **API key** by visiting the [API Keys page](https://app.typless.com/settings/api-keys).

<figure><img src="https://2174127710-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FePXqOCeLb4FOuZhmYG8X%2Fuploads%2Fgit-blob-05bd0b7a3f05edcaa4e7e94708a8c16da9596015%2Fimage.png?alt=media" alt=""><figcaption><p>Getting your API key</p></figcaption></figure>

## 1. Create a new document type

Navigate to the [Document types page](https://app.typless.com) and click on the ***New document type*** button. Click ***Select Pretrained*** and then ***Start Building*** on ***Build Custom Document Type***.

In ***Basic info***, enter:

* ***Name***: **order-confirmation**
* ***Description***: *Order confirmations that suppliers send after we place a purchase order.*

The form already has the `supplier_name` field, which every document type needs; edit its description. Then add the other fields with ***Add field***. Where a [preset](https://typless.gitbook.io/typlessapi/typless/document-type/descriptions-and-presets.md#presets) fits, choose it first: it fills in the name, data type and a description, and lets Typless clean up the value. Change the name and description where your documents need it.

| Field name         | Data type | Preset           | Description                                                     |
| ------------------ | --------- | ---------------- | --------------------------------------------------------------- |
| `supplier_name`    | Supplier  | Supplier Name    | Name of the supplier that confirms the order.                   |
| `document_number`  | String    | Document Number  | Number of the order confirmation.                               |
| `document_date`    | Date      | Document Date    | Date the order confirmation was issued. Use YYYY-MM-DD format.  |
| `purchasing_order` | String    | Purchasing Order | Our purchase order number that this confirmation refers to.     |
| `delivery_date`    | Date      | –                | Delivery date confirmed by the supplier. Use YYYY-MM-DD format. |
| `total_amount`     | Number    | Total Amount     | Total amount of the order. Use float format with dot separator. |

If your subscription includes line items, add these ***Line item fields*** with ***Add line item field***:

| Field name         | Data type | Preset           | Description                                          |
| ------------------ | --------- | ---------------- | ---------------------------------------------------- |
| `item_code`        | String    | Item Code        | Supplier's item code.                                |
| `item_description` | String    | Item Description | Line item description.                               |
| `quantity`         | Number    | Quantity         | Ordered quantity.                                    |
| `unit_net`         | Number    | Unit Net         | Price per unit. Use float format with dot separator. |

If you added line item fields, fill in ***Description for line item fields*** above them, for example *Ordered items listed in the order confirmation table.* Click ***Create document type***.

## 2. Write field descriptions

The descriptions are the instructions the pretrained model follows, so most of your tuning happens here:

* **Name the value, not the position.** *Our purchase order number that this confirmation refers to.* works for every supplier; *The number in the top right corner* only for some.
* **Resolve ambiguity.** An order confirmation often has several dates. *Delivery date confirmed by the supplier* tells the model which one you want.
* **Say the format.** Keep *Use YYYY-MM-DD format.* for dates and *Use float format with dot separator.* for numbers.
* **Keep supplier quirks out.** If one supplier labels the delivery date differently, write a [supplier description](https://typless.gitbook.io/typlessapi/automation-use-cases/supplier-descriptions.md) instead of making the field description longer.

You can change descriptions and presets of existing fields at any time in ***Edit***; the change applies to the next extraction. See [Descriptions and presets](https://typless.gitbook.io/typlessapi/typless/document-type/descriptions-and-presets.md).

## 3. Extract data from documents

Extract a document with [asynchronous extraction](https://typless.gitbook.io/typlessapi/typless/data-extraction/asynchronous-extraction.md), as in the [Pretrained invoice](https://typless.gitbook.io/typlessapi/automation-use-cases/pretrained-invoice.md) guide, with `"document_type_name": "order-confirmation"`. The result has one entry per field in `extracted_fields` and one row per ordered item in `line_items`.

## 4. Extract an extra field for one request

Sometimes you need a value only for some documents, for example the delivery terms for an import order. Instead of adding a field to the document type, send it with the request in `additional_extraction_fields`, with a `name`, a `type` and a `description`. It is extracted for this document only and returned like any other field.

<details>

<summary><strong>1 Define the extra field</strong> <em><mark style="color:green;">(Lines 14-20)</mark></em></summary>

The name must not be one of the document type's field names.

</details>

<details>

<summary><strong>2 Start the extraction and poll for the result</strong> <em><mark style="color:green;">(Lines 23-31)</mark></em></summary>

The same as any asynchronous extraction.

</details>

{% tabs %}
{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
import base64
import time

import requests

file_name = 'order-confirmation.pdf'
with open(file_name, 'rb') as file:
    base64_data = base64.b64encode(file.read()).decode('utf-8')

payload = {
    "file": base64_data,
    "file_name": file_name,
    "document_type_name": "order-confirmation",
    "additional_extraction_fields": [
        {
            "name": "incoterms",
            "type": "STRING",
            "description": "Incoterms delivery term and place, for example DAP Ljubljana."
        }
    ]
}
headers = {"Authorization": "<<apiKey>>"}
response = requests.post("https://developers.typless.com/api/v1/extract-data-async", json=payload, headers=headers)
extraction_id = response.json()["extraction_id"]

url = "https://developers.typless.com/api/v2/get-extraction-data"
while True:
    result = requests.get(url, headers=headers, params={"extraction_id": extraction_id}).json()
    if result["status"] != "IN_PROGRESS":
        break
    time.sleep(5)

for field in result["result"]["extracted_fields"]:
    print(field["name"], field["values"][0]["value"])
```

{% endcode %}
{% endtab %}

{% tab title="Node" %}

```javascript
// Node.js 18 or newer (built-in fetch)
const fs = require('fs');

const fileName = 'order-confirmation.pdf';
const headers = { 'Content-Type': 'application/json', 'Authorization': '<<apiKey>>' };

async function main() {
  const start = await fetch('https://developers.typless.com/api/v1/extract-data-async', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({
      file: fs.readFileSync(fileName, {encoding: 'base64'}),
      file_name: fileName,
      document_type_name: 'order-confirmation',
      additional_extraction_fields: [
        {
          name: 'incoterms',
          type: 'STRING',
          description: 'Incoterms delivery term and place, for example DAP Ljubljana.'
        }
      ]
    })
  });
  const { extraction_id } = await start.json();

  let result;
  do {
    await new Promise(resolve => setTimeout(resolve, 5000));
    const url = `https://developers.typless.com/api/v2/get-extraction-data?extraction_id=${extraction_id}`;
    result = await (await fetch(url, { headers })).json();
  } while (result.status === 'IN_PROGRESS');

  result.result.extracted_fields.forEach(field => console.log(`${field.name}: ${field.values[0].value}`));
}

main().catch(err => console.error('error:' + err));
```

{% endtab %}
{% endtabs %}

Response (shortened to three fields and without line items):

{% tabs %}
{% tab title="JSON" %}

```json
{
  "status": "SUCCESS",
  "error": {},
  "result": {
    "object_id": "177a2723638d2a1b3e3dd7b49e597e171fbdf8a4",
    "file_name": "order-confirmation-oc-88412.pdf",
    "customer": null,
    "extracted_fields": [
      {
        "name": "document_number",
        "data_type": "STRING",
        "values": [
          {
            "x": 121,
            "y": 464,
            "width": 473,
            "height": 39,
            "page_number": 0,
            "value": "OC-88412",
            "confidence_score": 0.95
          }
        ],
        "multiple_values": false
      },
      {
        "name": "delivery_date",
        "data_type": "DATE",
        "values": [
          {
            "x": -1,
            "y": -1,
            "width": -1,
            "height": -1,
            "page_number": -1,
            "value": "2026-11-17",
            "confidence_score": 0.95
          }
        ],
        "multiple_values": false
      },
      {
        "name": "incoterms",
        "data_type": "STRING",
        "values": [
          {
            "x": -1,
            "y": -1,
            "width": -1,
            "height": -1,
            "page_number": -1,
            "value": "DAP Ljubljana",
            "confidence_score": 0.95
          }
        ],
        "multiple_values": false
      }
    ],
    "line_items": [],
    "vat_rates": [],
    "number_of_pages": 1,
    "markdown_content": null,
    "text_blocks": null,
    "adjusted_s3_url": null,
    "supplier_id": null
  }
}
```

{% endtab %}
{% endtabs %}

The extra field `incoterms` is returned next to the fields of the document type. `delivery_date` has no preset, so its position on the page is `-1`; the value is still extracted.

## Running Typless live

The only thing that you need to do to automate your manual data entry is to integrate those simple API calls into your system.

{% hint style="success" %}
Have any questions, or do you need some help? Contact us via email <mark style="color:green;">**<support@typless.com>**</mark>**.**
{% endhint %}
