Skip to content

DocsExamples

4 min read · updated

Document classification

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

The script asks for the document’s type and files it only on a certified answer:

Figure · How to use it

The model judges the input; your code chooses the action.

  1. InputA document
  2. QuestionWhat type of document is this?
  3. Typed answerA document-type key and probabilities
  4. Your codeFile a certified classification; send the rest to review.

The answer is under answers.type. Check the certificate required by your application before automating the action.

Source: this recipe’s question and application policy. No model result is illustrated here.

Save the complete caller 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, 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

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).

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.

Teach the question from past documents and certify it at your 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 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 beside the labels file and run it with Python. Registration replaces a task of the same id. Check the returned certificate: a null threshold means no answer can be certified.

Certify answers runs this call on a server, with its answer.

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).
  • A recipe: decisio is measured on short texts, such as the intent sets of the support inbox; no run on long documents is published.