Getting JSON back
Get validated JSON from any model without response_format, with a precise system prompt, pydantic or zod, one retry and test results per model.
Many integrations need structured data: the fields of an invoice for the bookkeeping, a category for a support ticket, the dates in a contract.
PeakPrivacy drops response_format (Differences from the OpenAI API). The request succeeds, but nothing enforces JSON. In our tests, mistral-small-swiss with {"type": "json_object"} and gpt-4.1 with a strict json_schema both answered in prose. SDK helpers that depend on it, such as client.chat.completions.parse(), then fail with a validation error.
What works instead:
- A system prompt that names every field with its type and format, and shows one example.
temperatureset to0.- Validation of the answer with pydantic or zod.
- One retry that shows the model its error.
All examples were run against the live API on 11.11.2026.
The system prompt
Save this as system-prompt.txt:
You extract data from supplier invoices.
Reply with one JSON object and nothing else: no Markdown, no code fences, no comments.
Fields:
- invoice_number: string
- supplier: string, the company name only
- invoice_date: string, YYYY-MM-DD
- due_date: string, YYYY-MM-DD. If only payment terms are given, add them to invoice_date.
- currency: string, ISO code such as "CHF"
- total_excl_vat: number
- vat_amount: number
- total: number
- iban: string without spaces, or null
Use null for anything the invoice doesn't state. Never guess.
Example:
{"invoice_number": "R-1001", "supplier": "Muster AG", "invoice_date": "2026-01-15", "due_date": "2026-02-14", "currency": "CHF", "total_excl_vat": 100.0, "vat_amount": 8.1, "total": 108.1, "iban": null}Each part has a job:
- "One JSON object and nothing else" keeps out code fences and explanations. Most models follow it. Your code should still cope when one doesn't.
- One line per field, with type and format. Ask for dates as
YYYY-MM-DDand amounts as numbers, so that your code never has to parseCHF 1'234.50. - A rule for derived values. The invoice below only says "zahlbar innert 30 Tagen". Before we added the rule to
due_date, some runs calculated the date and others returnednull. nullinstead of guesses. Missing data should be visible, not invented.- An example shows the exact shape. Use made-up values, so that they can't leak into real answers.
Extract invoice fields
Save the invoice text as invoice.txt. To work with a PDF, upload it and use its extracted text, see Files.
Druckerei Säntis AG, Bahnhofstrasse 12, 9000 St. Gallen
Rechnung Nr. 2026-0412
An: Alpenblick Treuhand AG, Seefeldstrasse 123, 8008 Zürich
Datum: 03.11.2026, zahlbar innert 30 Tagen
500 Visitenkarten, 4-farbig CHF 240.00
Versand CHF 9.50
Total exkl. MWST CHF 249.50
MWST 8.1 % CHF 20.21
Total CHF 269.71
IBAN CH44 3199 9123 0008 8901 2Uses jq to build the request body from both files:
jq -n --rawfile system system-prompt.txt --rawfile invoice invoice.txt '{
model: "gpt-swiss",
temperature: 0,
messages: [
{role: "system", content: $system},
{role: "user", content: $invoice}
]
}' |
curl -s https://api.peakprivacy.ch/v1/ai/chat/completions \
-H "Authorization: Bearer $PEAKPRIVACY_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d @- |
jq -r '.choices[0].message.content'{"invoice_number":"2026-0412","supplier":"Druckerei Säntis AG","invoice_date":"2026-11-03","due_date":"2026-12-03","currency":"CHF","total_excl_vat":249.5,"vat_amount":20.21,"total":269.71,"iban":"CH4431999123000889012"}Validate and retry
The Python and JavaScript versions guard the answer in three steps:
- Cut out the JSON.
json_partandjsonPartkeep only what lies between the first{and the last}. In our tests,glm5once wrapped its JSON in a code fence despite the instruction. - Validate it. The schema checks required fields, types and date formats, not only the syntax. pydantic also turns dates into
dateand amounts intoDecimal. - Retry once. On failure, the code sends the model its own answer plus the validation error and asks again. We tested this path by replacing the first answer with broken JSON, and the second answer was valid. If the second attempt fails too, log the answer and route the document to a person.
The loop only handles invalid content. The SDKs already retry 429 and 5xx responses, see Retries.
Validation can't tell whether a value is right. Add checks your business knows, for example that total_excl_vat plus vat_amount equals total.
Tip: to keep prompt and validator in sync, generate the field list from your schema with Invoice.model_json_schema() in pydantic or z.toJSONSchema(Invoice) in zod, and put it into the system prompt.
Which model to use
We ran the invoice above repeatedly through each model at temperature 0. "Valid JSON" counts answers that parsed as JSON without cutting, over three versions of the prompt. "All fields right" counts runs with the final prompt.
| Model | Level | Valid JSON | All fields right | Notes |
|---|---|---|---|---|
gpt-swiss | Schweiz | 9 of 9 | 3 of 3 | 2 to 3.5 seconds per call. Used in the examples above. |
deepseek-v4-flash | Schweiz | 9 of 9 | 3 of 3 | 1.5 to 10 seconds per call. |
glm5 | Schweiz | 8 of 9 | 3 of 3 | Wrapped the JSON in a code fence once; json_part handles that. |
mistral-small-swiss | Schweiz | 9 of 9 | 1 of 3 | Shortened the supplier name in 2 of 3 runs. With an earlier prompt, it skipped the calculated due date in 2 of 3. Fine for copying values, weak at deriving them. |
qwen-3-fast | EU | 4 of 4 | 2 of 2 | |
gpt-4.1 | Extern | 4 of 4 | 2 of 2 | Not better than the Swiss models on this task. |
Start with gpt-swiss or deepseek-v4-flash. This is a small test with one document, so run your own documents through your chosen model before you rely on it.
Alternative: a tool definition
You can also describe the fields as a function in tools. The model then returns them as JSON in tool_calls[].function.arguments. In our tests, gpt-swiss, deepseek-v4-flash and mistral-small-swiss each called the tool with valid arguments.
PeakPrivacy drops tool_choice, so you can't force the call. Check for tool_calls, fall back to the prompt approach, and validate the arguments like any other answer.
import json
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
base_url="https://api.peakprivacy.ch/v1/ai",
api_key=os.environ["PEAKPRIVACY_API_KEY"],
)
record_invoice = {
"type": "function",
"function": {
"name": "record_invoice",
"description": "Store the fields of a supplier invoice.",
"parameters": {
"type": "object",
"properties": {
"invoice_number": {"type": "string"},
"supplier": {"type": "string"},
"invoice_date": {"type": "string", "description": "YYYY-MM-DD"},
"currency": {"type": "string"},
"total": {"type": "number"},
},
"required": ["invoice_number", "supplier", "invoice_date", "currency", "total"],
},
},
}
completion = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Record this invoice:\n" + Path("invoice.txt").read_text()}],
tools=[record_invoice],
)
message = completion.choices[0].message
if message.tool_calls:
print(json.loads(message.tool_calls[0].function.arguments))
else:
print("No tool call:", message.content) # fall back to the prompt approach{'invoice_number': '2026-0412', 'supplier': 'Druckerei Säntis AG', 'invoice_date': '2026-11-03', 'currency': 'CHF', 'total': 269.71}Pitfalls
temperature0 isn't repeatable. Two runs of the same request can still differ. Validate every answer.- Cut-off answers. If
finish_reasonislength, the JSON is incomplete. Retrying with the same input won't help. Split the document instead. ßbecomesss. PeakPrivacy replacesßin chat completion answers, also inside JSON values. A supplier on theHauptstraßecomes back on theHauptstrasse. Keep that in mind when you match names against your own records.- Reasoning models. Their reasoning arrives in
reasoning_content. Parse onlycontent. - Don't stream extraction. You can only validate the complete answer, see Streaming.
- Personal data. Invoices and contracts often contain it. Choose the model by its security level, see Models.