Preloader
Getting Reliable Structured Outputs from LLMs: Validation, Retries and Constrained Decoding
Getting your Trinity Audio player ready...

In this article, you will learn how to get reliable structured outputs from large language models by validating them against a contract and the source text, retrying only when it helps, and constraining generation.

Structured output is a standard feature now. OpenAI’s Responses API takes a JSON schema or a Pydantic model and promises a response that fits it, vLLM does the same on a local server with xgrammar behind it, and the Python SDKs hand you a parsed object instead of a string. Most tutorials stop at the moment the JSON parses. That’s the wrong place to stop, and here’s the whole problem in four lines of invoice:

Ask a model for the invoice id, the currency, the total in cents and the line it took the total from, and you might get this back:

It’s valid JSON, every key is present, the types are right, EUR is in the allowed set, and the quoted line really is in the invoice. The total is 12,500 cents, which is 125 euros, for an invoice that says 1,250. No parser catches that and no schema catches it, because 12500 is a perfectly good integer. The only thing that catches it is a comparison with the source text, and your application has to make that comparison itself.

Source: Machine Learning Mastery — Read the full article on the original site ↗

Get the best of this topic in your inbox

Join the newsletter. A short, useful digest, no spam.