This example extracts information from an invoice — the value of the service and the CNPJ (a Brazilian tax identification number).
File uploads belong in a Page: the uploaded bytes arrive in-memory as file["content"] and you persist them with get_persistent_dir(). The AI extracts more reliably from text than from a raw document, so we extract_text first and prompt on the resulting string.
from pathlib import Path
from abstra.pages import register_function
from abstra.common import get_persistent_dir
from abstra.ai import extract_text, prompt
@register_function
def analyze(file: dict):
# The upload arrives as {"filename", "content_type", "content"}; persist the bytes.
dest = get_persistent_dir() / "uploads" / Path(file["filename"]).name
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(file["content"])
# Extract the text first, then prompt on the text
text = extract_text(dest)
answer = prompt(
["Here is an invoice", text],
format={
"value": {"type": "number", "description": "Value of the service in dollars"},
"CNPJ": {"type": "string"},
},
)
return {"value": answer["value"], "cnpj": answer["CNPJ"]}
@register_function
def __render__():
return """
<link rel="stylesheet" href="https://design.abstra.io/v0/abstra-ds.css">
<script type="module" src="https://design.abstra.io/v0/abstra-ds.js"></script>
<ab-stack gap="4">
<ab-upload id="invoice" label="Invoice" accept=".pdf,.jpg,.jpeg,.png"></ab-upload>
<ab-cluster justify="end"><ab-button id="go" variant="primary">Read invoice</ab-button></ab-cluster>
<ab-code id="out" language="json" hidden></ab-code>
</ab-stack>
<script type="module">
const button = document.getElementById('go');
const out = document.getElementById('out');
button.addEventListener('click', async () => {
const file = document.getElementById('invoice').files[0];
if (!file) return abToast('Choose a file first', { tone: 'warn' });
button.loading = true;
try {
const result = await analyze(file); // pass the File directly
out.code = JSON.stringify(result, null, 2);
out.hidden = false;
} catch (error) {
abToast(await abErrorMessage(error), { tone: 'danger' });
} finally {
button.loading = false;
}
});
</script>
"""