# Getting JSON back (/docs/entwickler/json-output)

> 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](/docs/entwickler#differences)). 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:

1. A system prompt that names every field with its type and format, and shows one example.
2. `temperature` set to `0`.
3. Validation of the answer with pydantic or zod.
4. 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`:

```text
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-DD` and amounts as numbers, so that your code never has to parse `CHF 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 returned `null`.
- **`null` instead 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](/docs/entwickler/files#completions).

```text
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 2
```

**curl**

Uses `jq` to build the request body from both files:

```bash
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'
```

```json
{"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"}
```

**Python**

```python
# Python 3.10 or later, pip install openai pydantic
import os
from datetime import date
from decimal import Decimal
from pathlib import Path

from openai import OpenAI
from pydantic import BaseModel, ValidationError

client = OpenAI(
    base_url="https://api.peakprivacy.ch/v1/ai",
    api_key=os.environ["PEAKPRIVACY_API_KEY"],
)
SYSTEM_PROMPT = Path("system-prompt.txt").read_text()

class Invoice(BaseModel):
    invoice_number: str
    supplier: str
    invoice_date: date
    due_date: date | None
    currency: str
    total_excl_vat: Decimal
    vat_amount: Decimal
    total: Decimal
    iban: str | None

def json_part(text):
    # Cut away anything around the outermost {...}, such as code fences.
    start, end = text.find("{"), text.rfind("}")
    return text[start : end + 1] if start != -1 else text

def extract_invoice(text, attempts=2):
    messages = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": text},
    ]
    for _ in range(attempts):
        completion = client.chat.completions.create(
            model="gpt-swiss", messages=messages, temperature=0
        )
        answer = completion.choices[0].message.content or ""
        try:
            return Invoice.model_validate_json(json_part(answer))
        except ValidationError as error:
            # Show the model its answer and what is wrong with it, then ask again.
            messages.append({"role": "assistant", "content": answer})
            messages.append({
                "role": "user",
                "content": f"That is not valid:\n{error}\nReply with the corrected JSON object only.",
            })
    raise ValueError(f"No valid invoice after {attempts} attempts")

invoice = extract_invoice(Path("invoice.txt").read_text())
print(invoice)
```

```text
invoice_number='2026-0412' supplier='Druckerei Säntis AG' invoice_date=datetime.date(2026, 11, 3) due_date=datetime.date(2026, 12, 3) currency='CHF' total_excl_vat=Decimal('249.5') vat_amount=Decimal('20.21') total=Decimal('269.71') iban='CH4431999123000889012'
```

**JavaScript**

```js
// npm install openai zod — run as an ES module
import { readFile } from "node:fs/promises";
import OpenAI from "openai";
import { z } from "zod";

const client = new OpenAI({
  baseURL: "https://api.peakprivacy.ch/v1/ai",
  apiKey: process.env.PEAKPRIVACY_API_KEY,
});
const SYSTEM_PROMPT = await readFile("system-prompt.txt", "utf8");

const Invoice = z.object({
  invoice_number: z.string(),
  supplier: z.string(),
  invoice_date: z.iso.date(),
  due_date: z.iso.date().nullable(),
  currency: z.string().length(3),
  total_excl_vat: z.number(),
  vat_amount: z.number(),
  total: z.number(),
  iban: z.string().nullable(),
});

// Cut away anything around the outermost {...}, such as code fences.
function jsonPart(text) {
  const start = text.indexOf("{");
  const end = text.lastIndexOf("}");
  return start === -1 ? text : text.slice(start, end + 1);
}

async function extractInvoice(text, attempts = 2) {
  const messages = [
    { role: "system", content: SYSTEM_PROMPT },
    { role: "user", content: text },
  ];
  for (let i = 0; i < attempts; i++) {
    const completion = await client.chat.completions.create({ model: "gpt-swiss", messages, temperature: 0 });
    const answer = completion.choices[0].message.content ?? "";

    let problem;
    try {
      const result = Invoice.safeParse(JSON.parse(jsonPart(answer)));
      if (result.success) return result.data;
      problem = z.prettifyError(result.error);
    } catch (error) {
      problem = error.message; // not JSON at all
    }
    // Show the model its answer and what is wrong with it, then ask again.
    messages.push(
      { role: "assistant", content: answer },
      { role: "user", content: `That is not valid:\n${problem}\nReply with the corrected JSON object only.` },
    );
  }
  throw new Error(`No valid invoice after ${attempts} attempts`);
}

const invoice = await extractInvoice(await readFile("invoice.txt", "utf8"));
console.log(invoice);
```

```text
{
  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_part` and `jsonPart` keep only what lies between the first `{` and the last `}`. In our tests, `glm5` once 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 `date` and amounts into `Decimal`.
- **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](/docs/entwickler/errors#retry).

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.

```python
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
```

```text
{'invoice_number': '2026-0412', 'supplier': 'Druckerei Säntis AG', 'invoice_date': '2026-11-03', 'currency': 'CHF', 'total': 269.71}
```

## Pitfalls
- **`temperature` 0 isn't repeatable.** Two runs of the same request can still differ. Validate every answer.
- **Cut-off answers.** If `finish_reason` is `length`, the JSON is incomplete. Retrying with the same input won't help. Split the document instead.
- **`ß` becomes `ss`.** PeakPrivacy replaces `ß` in chat completion answers, also inside JSON values. A supplier on the `Hauptstraße` comes back on the `Hauptstrasse`. Keep that in mind when you match names against your own records.
- **Reasoning models.** Their reasoning arrives in `reasoning_content`. Parse only `content`.
- **Don't stream extraction.** You can only validate the complete answer, see [Streaming](/docs/entwickler/streaming).
- **Personal data.** Invoices and contracts often contain it. Choose the model by its security level, see [Models](/docs/entwickler/models#tiers).

## See also
- [Conversations and system prompts](/docs/entwickler/conversations#system-prompt)
- [Chat completions](/docs/entwickler/chat-completions#fields)
- [Files](/docs/entwickler/files#completions)
- [Errors and limits](/docs/entwickler/errors)
