Module 1 · Core principles

Precisely specifying the output format

5 min read

"Answer in JSON" is not a specification. Lesson 1.2 showed it: with that instruction alone, the model produces valid JSON that no program can use. Specifying a format means fixing names, types, units, allowed values, and what to do when information is missing. This lesson details that work, then presents the ultimate weapon of recent models: guaranteed structured outputs.

What to specify

Quill's specification, used by prompt V2:

SPEC = """Réponds uniquement par un objet JSON avec exactement ces clés :
- "fournisseur" : la raison sociale du fournisseur, telle qu'écrite dans le document ;
- "montant_ht" : le montant hors taxes, en nombre décimal (12450.5), sans symbole ni séparateur de milliers ;
- "devise" : le code ISO de la devise du montant : "EUR", "USD" ou "CHF" ;
- "echeance" : la date limite de paiement au format AAAA-MM-JJ ;
- "penalites_retard" : true si le document prévoit des pénalités de retard, sinon false."""

(Answer only with a JSON object with exactly these keys: the supplier's company name as written; the amount before tax as a decimal number without symbol or thousands separator; the ISO currency code among EUR, USD and CHF; the due date in YYYY-MM-DD format; true if the document provides for late-payment penalties.) Each line answers a question the model would have asked itself — and, without a specification, answered at random:

QuestionWithout specification (V1, observed)With specification
Which key name?montant_hors_taxes, date_echeancemontant_ht, echeance
Which type?79200 or "79 200 CHF"decimal number
Which unit, which code?"francs suisses""CHF"
Which date format?"3 mai 2026""2026-05-03"
Which possible values?freea closed list
What if it is missing?an invention(to be specified: null? a default value?)

The last point is actually missing from Quill's specification, and it is a real weakness: faced with a purchase order without a date, the model will invent a plausible date. A good specification always says what to do when the information is not in the document — null, an explicit value like "unknown", or a warning field.

The errors a specification does not fix

With V2, the formal fields are almost perfect (due date 97%, currency 92%, supplier 97%). The remaining errors are comprehension errors:

  • the amount before tax confused with the VAT, when the document mentions both;
  • "23.700 EUR" read as 23.7 instead of 23,700 (the dot is a thousands separator here);
  • a flat fee "of €40" that suggests euros in an order denominated in dollars.

A specification says what to produce; it does not say how to read an ambiguous document. For that, you add examples that cover the traps (lesson 1.2: 55% → 89%), or a targeted instruction ("the amount before tax is the one before VAT; ignore the VAT amount").

Guaranteed structured outputs

Current Claude models offer better than an instruction: an output constrained by a schema. Generation is guided server-side so that the answer is always conforming JSON. With the Python SDK, a Pydantic model is enough:

class Commande(BaseModel):
    model_config = ConfigDict(extra="forbid")

    fournisseur: str = Field(description="Raison sociale du fournisseur, telle qu'écrite dans le document")
    montant_ht: float = Field(description="Montant hors taxes, nombre décimal sans symbole")
    devise: Literal["EUR", "USD", "CHF"]
    echeance: date = Field(description="Date limite de paiement, format AAAA-MM-JJ")
    penalites_retard: bool
def extract_order(document: str) -> Commande:
    """Sortie structurée garantie : la réponse est un objet Commande validé, ou une exception."""
    response = client().messages.parse(
        model=config.CLAUDE_MODEL,
        max_tokens=2000,
        system="Tu extrais les informations clés des bons de commande pour qu'un programme les enregistre.",
        messages=[{"role": "user", "content": f"<bon_de_commande>\n{document}\n</bon_de_commande>"}],
        output_format=Commande,
    )
    return response.parsed_output

The field descriptions (Field(description=…)) are part of the schema sent: they play the role of the written specification. Literal closes the list of possible values; extra="forbid" forbids invented keys.

Two important clarifications:

  • The guarantee covers form, not substance. Conforming JSON can contain a wrong amount. Examples and comprehension instructions remain necessary.
  • Prefilling no longer exists. An old technique consisted of starting the model's answer yourself (a last assistant message containing {) to force JSON. On current Claude models, a last assistant message returns a 400 error: structured outputs replace that trick.

Choosing a format

FormatWhen to use it
JSON with schemaOutput read by a program: the default rule
XML tags (<reponse>, <raisonnement>)Separating several parts of a free-text answer (reasoning then answer, lesson 2.1)
MarkdownOutput read by a human: headings, lists, tables
Constrained text ("one sentence", "50 words")Summaries, messages; to be checked, lengths are approximate

Key takeaways

  • Specify names, types, units, formats, allowed values — and the behavior when information is missing.
  • A specification fixes form errors; comprehension errors need examples or targeted instructions.
  • With Claude, structured outputs (messages.parse, output_config.format) guarantee JSON conforming to the schema.
  • The guarantee covers form: always validate the substance.
  • Prefilling the answer returns an error on current Claude models: use structured outputs.

Practice

  1. Add a rule for missing fields to the specification, then test it on a purchase order without a due date.
  2. Add the instruction "the amount before tax is the one before VAT" to V2 and measure the montant_ht field.
  3. With an API key, call claude.extract_order on ten purchase orders and compare with the ground truth.

Resources