# Document classification

> File each incoming document by its type from your backend, and send only the ones decisio is unsure about to a person.

Source: https://opendecisio.com/docs/use-cases/document-classification/

The script asks for the document’s type and files it only on a [certified answer](https://opendecisio.com/docs/glossary/#certified-answer):

 

[Figure: The model judges the input; your code chooses the action. Input: A document. Question: What type of document is this?. Typed answer: A document-type key and probabilities. Your code: File a certified classification; send the rest to review..]

 

## TL;DR

 

Save the [complete caller](https://opendecisio.com/examples/recipes/document-classification.py) as `document-classification.py` and run it with Python 3.12 or later. Set `DECISIO_BASE_URL` to your server, or leave the local default. Until you register and certify this [question](https://opendecisio.com/docs/glossary/#question), the caller sends answers to review.

 python

```
import json
import os
import urllib.error
import urllib.request

QUESTION = {
    "type": "choice",
    "instructions": "What type of document is this?",
    "criteria": {
        "invoice": "A bill asking for payment",
        "contract": "An agreement between parties",
        "purchase_order": "An order placed with a supplier",
        "receipt": "A proof of payment",
        "other": "Anything else"
    }
}
BASE_URL = os.environ.get("DECISIO_BASE_URL", "http://127.0.0.1:8000").rstrip("/")
TIMEOUT = 15
REVIEW = "to a person"

def route(text):
    request = urllib.request.Request(
        BASE_URL + "/v1/systemone",
        data=json.dumps({"state": text, "questions": {"type": QUESTION}}).encode(),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
            answer = json.load(response)["answers"]["type"]
        if not isinstance(answer, dict) or answer.get("type") != QUESTION["type"]:
            return REVIEW
        if not (answer.get("choice") in QUESTION["criteria"]):
            return REVIEW
        # A gold certificate is about correctness; agreement alone is insufficient.
        if (answer.get("certified") is True
                and answer.get("certificate_kind") == "gold"
                and isinstance(answer.get("certificate"), str)
                and answer["certificate"]):
            return f"file as {answer['choice']}"
        return "to a person"
    except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError, TypeError):
        return REVIEW

if __name__ == "__main__":
    print(route("INVOICE No. 2026-117. Amount due: 1,240.00 EUR by 30 November."))
```

 Output

```
to a person
```

 

## Is it a good fit?

 

Good fit

- A fixed set of document types, and past documents sorted into them.
- Documents whose text fits the server’s length, or whose first pages decide the type.

Not a good fit

- Documents whose type depends on images or layout more than on their text.
- Very long documents read whole: the first read grows with the length ([Scale](https://opendecisio.com/docs/scale/#plan-for-the-first-read)).

 

## 1 Write the question

 

One `choice` question, with a description for each type and an `other` type. Send the document’s text, or its first pages, as the text.

 

## 2 Teach it and certify it

 

Teach the question from past documents and certify it at your [error target](https://opendecisio.com/docs/glossary/#error-target).

 

Send at least 118 labelled documents. The server holds back half to certify, and a 5% certificate needs 59 of those. More examples certify a larger share.

 

Prepare `document-classification-labels.jsonl` with one JSON object per line, containing `state` and `answer`. Use real inputs and labels chosen by a person; each answer is one of the question’s [option](https://opendecisio.com/docs/glossary/#option) keys. The code below builds complete requests using the same question as the caller.

 python

```
import json
import os
import urllib.request

QUESTION = {
    "type": "choice",
    "instructions": "What type of document is this?",
    "criteria": {
        "invoice": "A bill asking for payment",
        "contract": "An agreement between parties",
        "purchase_order": "An order placed with a supplier",
        "receipt": "A proof of payment",
        "other": "Anything else"
    }
}
# One JSON object per line: state and the answer chosen by a person.
with open("document-classification-labels.jsonl", encoding="utf-8") as source:
    rows = [json.loads(line) for line in source if line.strip()]
examples = [
    {"request": {"state": row["state"], "questions": {"type": QUESTION}},
     "answer": row["answer"]}
    for row in rows
]
body = {"id": "document-classification", "examples": examples, "certify": {"alpha": 0.05}}
base_url = os.environ.get("DECISIO_BASE_URL", "http://127.0.0.1:8000").rstrip("/")
request = urllib.request.Request(
    base_url + "/v1/tasks", data=json.dumps(body).encode(),
    headers={"Content-Type": "application/json"},
)
# Registration reads all your examples; allow more time than an ordinary decision.
with urllib.request.urlopen(request, timeout=300) as response:
    record = json.load(response)
print(json.dumps(record.get("certificate"), indent=2))
```

 

Needs the reader’s own human-labelled JSONL file.

 

Save the [registration script](https://opendecisio.com/examples/recipes/document-classification-register.py) beside the labels file and run it with Python. Registration replaces a [task](https://opendecisio.com/docs/glossary/#task) of the same id. Check the returned certificate: a `null` [threshold](https://opendecisio.com/docs/glossary/#threshold) means no answer can be certified.

 

[Certify answers](https://opendecisio.com/docs/tasks/certify/#2-teach-the-task-with-a-certificate) runs this call on a server, with its answer.

 

## 3 Route on the certificate

 

The caller acts only when `certified` is `true` and `certificate_kind` is `gold`, with a certificate id. A learned table’s `agreement` certificate measures agreement with the model, so it goes to review in this recipe.

 

- A certified answer files the document by its type.
- Everything else goes to a person.
- When a new kind of document arrives, certification is suspended until you certify again ([Watch for drift](https://opendecisio.com/docs/tasks/drift/)).

 

## What it did

 

- A recipe: decisio is measured on short texts, such as the intent sets of the support inbox; no run on long documents is published.

 

 

## Limits

 

- An HTTP error, timeout or invalid response goes to the review path, like an uncertified answer ([Handle review and service failures](https://opendecisio.com/docs/use-cases/#handle-review-and-service-failures)).
- Keep the question and options stable after registration, and certify again after changing the task or [serving setup](https://opendecisio.com/docs/glossary/#serving-setup) ([Keep a certificate valid](https://opendecisio.com/docs/production/#keep-a-certificate-valid)).

 

## What next

 

- [Scale](https://opendecisio.com/docs/scale/): long texts, and what the first read costs.
- [Requirements and limits](https://opendecisio.com/docs/limits/): how long a text each model reads.
- [Use cases](https://opendecisio.com/docs/use-cases/): the other recipes.
