AI State of the Art
Fundamentals/LLM: Understanding Large Language Models/24 min
Section 61

Structured Output: JSON Mode, Function Calling, Grammars

Listen as a podcast →

The Need for Structure

LLMs produce free-form text by nature. That is perfect for conversation, and catastrophic as soon as you want a program to read the answer. Ask a model to extract the sentiment and entities from a customer review: it might answer "The sentiment is positive and the mentioned entities are Paris and the Eiffel Tower," or "Positive. Entities: Paris, Eiffel Tower," or wrap it all in a paragraph of explanation. No program handles all three.

Structured output covers the techniques that constrain an LLM's output to a predefined format that a program can parse: JSON (JavaScript Object Notation, a text format for representing structured data, now the standard exchange format on the web), XML (eXtensible Markup Language, an older tag-based format), function calls, or any other schema.

It is an essential building block for reliable applications. Without it, every call to the model can break your processing chain because the shape of the answer changed.

JSON Mode

The Principle

JSON mode is the most common form of structured output. The model is constrained to produce output that is valid JSON, optionally conforming to a predefined schema.

{
  "sentiment": "positive",
  "confidence": 0.92,
  "entities": ["Paris", "Eiffel Tower"],
  "summary": "The text describes a positive tourist visit to Paris."
}

API-side Implementation

Major providers offer a native JSON mode through their API (Application Programming Interface, the set of requests a program can send to the service). This is fundamentally different from "asking for JSON in the prompt": the model is constrained at the generation level itself.

Three families of approach, bearing in mind that the exact API parameters change regularly and that you should always check the provider's documentation before writing code:

  • constraint via an API parameter: you send a schema along with the request and the service enforces it. This is what OpenAI's response_format parameter does, with a json_object mode for arbitrary JSON and a json_schema mode for JSON conforming to a given schema;
  • constraint via prompt and prefill: you describe the expected format in the instructions and seed the model's answer with an opening brace, so it cannot start with a preamble. Less robust, but usable anywhere;
  • local constraint: with a model you host yourself, libraries such as outlines, guidance or lm-format-enforcer constrain the generation directly. That is the mechanism explained in detail below.
JSON Schema vs Free JSON

Basic JSON mode guarantees that the output is syntactically valid JSON, but not its internal structure. The model could return {"foo": 42} when you expect {"sentiment": "positive"}. JSON schema mode goes further: it guarantees the JSON follows a precise schema, the right field names, the right types (string, number, boolean), values from an allowed set (enum). It's the difference between "any JSON" and "exactly the JSON my code expects." In production, this is essential.

The Pitfalls of JSON by Prompting

Before native JSON modes existed, you simply asked the model to respond in JSON in the prompt. Common problems:

  • The model adds explanatory text before or after the JSON
  • Trailing commas make the JSON invalid
  • Quotes aren't properly escaped in strings
  • The model "forgets" to close braces or brackets
  • Types aren't respected (a number returned as a string)

Native JSON mode eliminates most of these problems by constraining generation at the decoder level.

Function Calling

The Concept

Function calling (or tool use) is perhaps the most important advance for production LLM applications. The principle: instead of simply generating text, the model can decide to call a function defined by the developer, generating a structured call with the right arguments.

This is what enables an LLM to do concrete things in the real world: search the web, query a database, send an email, trigger an action. The developer defines a set of functions with their signatures:

{
  "name": "get_weather",
  "description": "Gets the weather for a city",
  "parameters": {
    "type": "object",
    "properties": {
      "city": { "type": "string", "description": "City name" },
      "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
    },
    "required": ["city"]
  }
}

When the user asks "What's the weather like in Lyon?", the model generates:

{ "name": "get_weather", "arguments": { "city": "Lyon", "unit": "celsius" } }
The LLM as an Intelligent Router

Function calling turns the LLM into a router: it understands the request stated in ordinary language and translates it into a structured call to the right function with the right parameters. This is the foundation of agents and of RAG (Retrieval-Augmented Generation) systems.

The Complete Workflow

  1. The user sends their request
  2. The LLM decides whether to call a function (and which one)
  3. The LLM generates the call arguments
  4. The application executes the function and gets the result
  5. The result is sent back to the LLM
  6. The LLM formulates a response in natural language

Multiple and Parallel Calls

Recent models support:

  • Sequential calls: the result of one call informs the next
  • Parallel calls: multiple functions called simultaneously
  • Dynamic choice: the model decides not to call a function if it can answer directly

Constrained Generation

The Fundamental Problem

Reminder: an LLM produces its tokens one by one, drawing at each step from a probability distribution over its whole vocabulary, 32,000 to 128,000 possible tokens depending on the model. Before that distribution, the network produces one raw score per token, called a logit; it is the softmax function that then turns those scores into probabilities.

To guarantee structured output, it is enough to intervene between the two. At each step you work out which tokens are "legal" given the expected format, and set the logit of all the others to minus infinity: after the softmax their probability is exactly zero. This is constrained decoding.

For example, if the JSON being generated is {"sentiment": "posi, the only legal tokens are those that could continue a JSON string. The token } would be blocked (the string isn't closed), but tive" would be allowed.

Formal Grammars

To constrain generation, you first have to write the rules of the format down somewhere. That is what a formal grammar is for: a short text that spells out everything the format allows, and nothing else.

The closest analogy is a strictly codified legal document. At any point in the reading, only certain continuations are admissible: after the heading you expect an article, not a signature. A grammar writes those expectations down in a form a machine can enforce.

How to read a grammar

Here are the rules for JSON, written in the notation most commonly used for this purpose, BNF (Backus-Naur Form, named after its two inventors). Three symbols are enough to decipher it: ::= reads "consists of", the vertical bar reads "or", and the star * means "repeated zero or more times". Anything in quotes must be written literally.

root   ::= object
object ::= "{" pair ("," pair)* "}"
pair   ::= string ":" value
value  ::= string | number | object | array | "true" | "false" | "null"

Line by line: a document is an object; an object is an opening brace, one pair, optionally more pairs separated by commas, then a closing brace; a pair is a string, a colon, and a value; and a value can be a string, a number, another object, an array, or one of the three words true, false, null.

Look at the last line: a value can be an object, which contains pairs, which contain values. The rule refers back to itself. That is how four lines can describe nested documents of any depth.

What "the parser state" actually means

A parser is simply a program that reads text while following the grammar. At every moment it knows where it stands in the rules, and therefore what may legally come next. That is its state: the set of continuations admissible at that precise instant.

Let us walk through a generation, character by character:

Text produced so farWhere the parser standsWhat is allowed next
(nothing)at the start of object{ and nothing else
{waiting for a pair", which opens a string
{"sentiment"has read the string of the pair: and nothing else
{"sentiment":waiting for a value", a digit, {, [, or the start of true / false / null
{"sentiment": "posiin the middle of a stringany character, or " to close it

Notice the second and fourth rows: at some moments exactly one character is possible, at others several are. The parser state is therefore not a position in the text, it is a set of possibilities.

The masking itself

At each step the model produces one score per token in its vocabulary, say 130,000 scores. The decoder queries the parser, gets the list of tokens compatible with the current state, and sets the score of every other token to minus infinity. Once converted to probabilities, those tokens are exactly zero. Sampling then happens only among what is left.

Hence the guarantee, and this is the point worth keeping: the model cannot produce invalid JSON, not because it learned to be disciplined, but because the offending tokens are physically not drawable. The constraint is mechanical, not statistical. That is the whole difference from politely asking for the right format in the prompt.

The Outlines Library

Outlines is a Python library that implements grammar-constrained generation for models you host yourself. Its technical idea: compile the grammar into a finite automaton, a table that, for each parser state, directly gives the list of admissible tokens. The expensive work is done once, at compile time, rather than at every generated token.

The authors present the method as adding only negligible decoding overhead, which is consistent with the mechanism: at run time all that remains is a table lookup and setting some logits to minus infinity.

Efficient Guided Generation for Large Language Models (Willard and Louf, 2023)

Regular Expressions as Constraints

For simpler formats, a regular expression (often shortened to regex, a pattern describing the set of acceptable strings) is enough:

# Guarantee a date format
pattern = r"\d{4}-\d{2}-\d{2}"

# Guarantee a yes/no answer
pattern = r"(yes|no)"

# Guarantee an email
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"

JSON Schemas as Constraints

A JSON schema can be compiled into a formal grammar. This is what native JSON schema API modes do: the schema is converted into generation constraints that guarantee conformance.

Trade-offs and Limitations

Content Quality vs Structure

A crucial point that beginners often forget: constraining the structure absolutely does not guarantee the quality of the content. A perfectly valid JSON, conforming to the schema, with the right types everywhere, can contain completely wrong, hallucinated, or incoherent values. Structure is necessary but not sufficient for reliability. It's like having a well-filled form with false information.

Valid Structure != Correct Content

A model constrained to respond in JSON with a "sentiment" field of type enum ["positive", "negative", "neutral"] will always produce one of these three values. But the chosen value may be incorrect. Constrained generation solves the form problem, not the substance problem.

Impact on Generation

Structural constraints can slightly affect the quality of free text inside structured fields. The model must "plan" its generation while accounting for upcoming constraints, which can limit its creativity or fluency.

Latency

Constrained generation adds one extra computation at each step: working out the list of admissible tokens. When the grammar is precompiled into an automaton, as Outlines does, that overhead is negligible in practice, it is a table lookup. It can become noticeable again with very complex grammars, where the parser state does not reduce to a simple position.

We give no percentage: it depends entirely on the grammar, the model and the implementation.

Practical Applications

Information Extraction

This is the most widespread use case: extracting structured data from free text (emails, reports, articles, customer reviews) by defining a precise JSON schema. For example, automatically extracting the name, address, and amount from each invoice received by email.

Agents and Tools

Function calling is the foundation of agents: systems that use an LLM to decide which actions to take. The model receives a request, decides whether to search the web, query a database or send a message, then produces the matching function call. Without reliable structured output, agents would be impractical, a single malformed call breaks the chain.

Data Pipelines

LLMs can be integrated into data processing pipelines where each step expects a specific input format and produces a specific output format. Structured output guarantees that the LLM's output is compatible with the next pipeline step, whether it's a database, an API, or another model.

Validation and Robustness

In production, constrained generation lets you guarantee that the output is always parseable, eliminating an entire category of bugs (the infamous "JSON parse errors" at 3 AM). Combined with semantic validation (checking that values make sense), it forms the foundation of reliable, deployable LLM applications.

The Golden Rule in Production

Never trust an LLM's free-form output. Always use some form of structured output (JSON schema, function calling, grammar) and validate the result in code before using it.

And remember the distinction from the previous section: the constraint guarantees the form, never the substance.

Another route has existed since September 2026: models that generate no text at all and directly return probabilities over options defined in advance. See Jev and « System One » models.

Check your understanding0 / 4

1. An API's json_object mode guarantees the output is syntactically valid JSON. What else does it guarantee?

2. How does constrained decoding mechanically guarantee a valid format?

3. A model constrained to a positive / negative / neutral enum returns positive. What do you know?

4. In function calling, who actually executes the function?