json_schema: two fields without a schema, six with it, five invoices

Without json_schema, our five invoices returned valid JSON, but it only contained due_date and currency. With the schema, the same model returned vendor, number, total, currency, due date and line items, five times out of five, for $0.0003 in total. This tutorial builds that extractor: paste an email or invoice text, and you get back a JSON object that follows the schema.
Instead of asking for JSON in the prompt, you describe the contract (the fields, their types) and the model sticks to it. That is the response_format parameter of type json_schema, which OpenAI's documentation describes as a constraint on the output. The usual case: invoices that arrive by email, each in its own format.
What you need
- Python 3.11, and the
openai==2.8.1SDK in a venv. - A
cdm_key, created in API → Keys. When you create it, you choose Credits or Prepaid. - A model whose sheet shows the Structured output chip. We used
deepseek-v4-flash, a private model at $0.0759 / $0.151 per million tokens at the time of the test. On that day, 124 models out of 432 carried this chip.


Step 1: install the SDK and point it at Carpe Diem
python3 -m venv .venv
.venv/bin/pip install openai==2.8.1
export OPENAI_API_KEY=cdm_your_key_here
The base URL ends with /v1: https://carpe-diem.xyz/api/operator/v1. The SDK appends /chat/completions on its own. It is the same wiring as in the OpenAI Python SDK tutorial.
Step 2: describe the JSON you want, then extract
The script holds five deliberately mixed invoices (English, French, euros, Swiss francs, dollars), the schema, then the extraction loop. Without a schema, the model stuck to the two details given in the prompt (due_date, currency) and dropped the rest. OpenAI says the same: the schema is the contract; valid JSON on its own is not one.
import json
import os
from openai import OpenAI
MODEL = "deepseek-v4-flash"
INVOICES = [
{
"id": "acme",
"text": (
"From: billing@acme-corp.example\n"
"Subject: Invoice 1042 — please pay by 1 Dec\n\n"
"Hi,\nplease find invoice #1042 for ACME Corp.\n"
"Total due: 1,250.00 EUR by 2026-12-01.\n"
"Lines:\n- Hosting Q4 900.00\n- Support pack 350.00\n"
"Thanks,\nACME billing"
),
},
{
"id": "nord",
"text": (
"FACTURE N° F-2026-0881\n"
"Émetteur : Nord Papier SAS\n"
"Date d'échéance : 15/12/2026\n"
"Montant TTC : 3 480,50 €\n"
"Détail : ramettes A4 (2 100,00) ; enveloppes kraft (1 380,50)"
),
},
{
"id": "harbor",
"text": (
"Harbor Freight LLC / INV-7781 / net 30\n"
"Due December 20 2026\n"
"Pallet jacks x2 @ 410 USD = 820\n"
"Freight 65.40\n"
"Amount due $885.40 — wire to Chase ****4412"
),
},
{
"id": "atelier",
"text": (
"Bonjour, ci-joint le relevé Atelier Lumière.\n"
"Ref interne AL-441. À régler avant le 8 janvier 2027.\n"
"Prestation photo 1 200 CHF + retouches 180 CHF = 1 380 CHF TTC.\n"
"Pas de TVA suisse sur cette ligne."
),
},
{
"id": "orbit",
"text": (
"ORBIT CLOUD\nInvoice: OC-19-B\nBill to: Luna Labs\n"
"Period: Nov 2026\nGPU hours 142 @ 0.42 = 59.64\n"
"Egress 12 GB = 1.20\nTOTAL USD 60.84 due 2026-12-05"
),
},
]
SCHEMA = {
"name": "invoice",
"strict": True,
"schema": {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"invoice_number": {"type": "string"},
"total": {"type": "number"},
"currency": {"type": "string"},
"due_date": {"type": "string"},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"amount": {"type": "number"},
},
"required": ["description", "amount"],
"additionalProperties": False,
},
},
},
"required": [
"vendor",
"invoice_number",
"total",
"currency",
"due_date",
"line_items",
],
"additionalProperties": False,
},
}
PROMPT = (
"Extract the invoice fields from the message. "
"due_date as YYYY-MM-DD. currency as a 3-letter code."
)
client = OpenAI(
base_url="https://carpe-diem.xyz/api/operator/v1",
api_key=os.environ["OPENAI_API_KEY"],
)
total_micro = 0
ok = 0
for inv in INVOICES:
raw = client.chat.completions.with_raw_response.create(
model=MODEL,
messages=[{"role": "user", "content": f"{PROMPT}\n\n{inv['text']}"}],
response_format={"type": "json_schema", "json_schema": SCHEMA},
extra_body={
"venice_parameters": {"include_venice_system_prompt": False},
},
)
micro = int(raw.headers.get("x-carpe-cost-usdc-micro") or "0")
total_micro += micro
text = raw.parse().choices[0].message.content
try:
data = json.loads(text)
ok += 1
status = "ok"
except json.JSONDecodeError as e:
data = {"error": str(e), "raw": (text or "")[:400]}
status = "parse_error"
print(f"=== {inv['id']} {status} cost_usd={micro / 1_000_000:.6f} ===")
print(json.dumps(data, ensure_ascii=False, indent=2))
print(
f"SUMMARY valid={ok}/{len(INVOICES)} "
f"total_usd={total_micro / 1_000_000:.6f} model={MODEL}"
)
The venice_parameters.include_venice_system_prompt: false field avoids paying Venice's system prompt (about 1,700 tokens per call). As for cost, it is read from the X-Carpe-Cost-Usdc-Micro header, not from a calculation based on the per-million price.
Step 3: read what comes out
The first invoice is a slightly noisy ACME email. Here is what the script pulls out:
{
"vendor": "ACME Corp",
"invoice_number": "1042",
"total": 1250.0,
"currency": "EUR",
"due_date": "2026-12-01",
"line_items": [
{"description": "Hosting Q4", "amount": 900.0},
{"description": "Support pack", "amount": 350.0}
]
}
The other four followed: Nord Papier (3,480.50 EUR, two lines), Harbor Freight (885.40 USD), Atelier Lumière (1,380 CHF, due 2027-01-08, invoice_number taken from the internal ref AL-441) and Orbit Cloud (60.84 USD). Dates in French format or in words came out as YYYY-MM-DD, and json.loads never failed. The last printed line is SUMMARY valid=5/5 total_usd=0.000328 model=deepseek-v4-flash.
The same prompt, without response_format, gave parseable JSON five times, but with only the keys currency and due_date. Nothing breaks, but four fields out of six are missing.
If it does not work
llama-3.3-70bwithjson_schema. Its sheet does not show the Structured output chip, and the call answered400VENICE_BAD_REQUEST(Invalid request parameters). Look for the chip on the model sheet before you pick one.- Key refused. A
401means an invalid key. Create a new one in API → Keys. - Insufficient balance. Top up Credits or Prepaid in API → Balance.
- JSON still incomplete. You probably left
response_formatout. Use an id that carries the Structured output chip.
What it cost
The five extractions with a schema cost $0.000328 in total, read from the headers: between $0.000054 and $0.000084 per invoice. The five calls without a schema cost $0.000134, cheaper, but with no vendor, number, total or lines.
Method: test on 19 November 2026 with deepseek-v4-flash on the /v1 route, one run per variant, text only; invoice images were not tested.
Going further
The extraction recipe in the docs goes through the router with an Idempotency-Key: a retry replays the first answer instead of billing twice. For invoices as images, the image API was not wired in here. Create a key, paste the script, then check that json.loads holds on your own emails: API → Keys.