In this recipe you turn messy invoice text into clean, validated records. The model is forced to return JSON that matches your schema, so there is no cleanup code and no "please return valid JSON" prompting.
What you need
- A Spro API key. See API keys.
- Python 3.9 or newer, and two packages:
pip install openai pydantic.
export SPRO_API_KEY="YOUR_SPRO_API_KEY"The code
Save this as extract_invoices.py.
import os
from openai import OpenAIfrom pydantic import BaseModel
client = OpenAI( base_url="https://spro.hridaai.com/v1", api_key=os.environ["SPRO_API_KEY"],)
class Invoice(BaseModel): vendor: str invoice_number: str currency: str total: float paid: bool
# The same shape as the model above, written as a JSON Schema for the API.INVOICE_SCHEMA = { "type": "object", "properties": { "vendor": {"type": "string"}, "invoice_number": {"type": "string"}, "currency": {"type": "string", "description": "Three letter code, e.g. USD"}, "total": {"type": "number"}, "paid": {"type": "boolean"}, }, "required": ["vendor", "invoice_number", "currency", "total", "paid"], "additionalProperties": False,}
INVOICES = [ "Invoice INV-2041 from Northwind Traders. Amount due: $1,240.50. Status: PAID on 3 March.", "Hi, this is Lumen Studio. Our invoice number is 88-A for EUR 312.00. We haven't received payment yet.",]
def extract(text: str) -> Invoice: response = client.chat.completions.create( model="gpt-oss-20b", messages=[ {"role": "system", "content": "Extract the invoice details from the text."}, {"role": "user", "content": text}, ], response_format={ "type": "json_schema", "json_schema": {"name": "invoice", "strict": True, "schema": INVOICE_SCHEMA}, }, ) # The output is JSON that matches the schema. Pydantic checks it and gives you a typed object. return Invoice.model_validate_json(response.choices[0].message.content)
for text in INVOICES: invoice = extract(text) print(invoice)Run it
python extract_invoices.pyvendor='Northwind Traders' invoice_number='INV-2041' currency='USD' total=1240.5 paid=Truevendor='Lumen Studio' invoice_number='88-A' currency='EUR' total=312.0 paid=FalseYour exact output can differ slightly, because it comes from a model.
How it works
- The schema.
response_formatwithtype: "json_schema"andstrict: Trueconstrains the model to your schema. See Structured outputs. - Validation.
Invoice.model_validate_jsonchecks the result a second time and gives you a typed object. If a field is missing or has the wrong type, it raises an error instead of letting bad data through. - Any provider. Spro normalizes the format, so the same code works whichever provider serves the model.
Make it safer
Invoices often carry bank account numbers and personal details. Turn on the Sensitive Information Disclosure guardrail with redact to mask them before they reach the provider, but note that masked values can't be extracted afterwards. If you need the full values, use log and pair it with Zero Data Retention, so the text isn't shown in your workspace's logs. See Guardrails.
Ideas to extend it
- Add line items as a list in the schema. Keep schemas simple, since not every model supports every schema feature.
- Read the invoice text from files in a folder and write the results to a CSV.
