How to get Reliable JSON Output from LLMs

The backbone of modern AI agents

Johnny Zhou

4 min read

It took four years to get reliable JSON output from frontier language models.

Back in 2020 when GPT-3 beta got announced, natural language text was all you could get from the models. If you wanted JSON, you had to prompt for it. But as you can imagine, it was painfully unreliable and hallucinated a lot.

People continued to experiment on how to take a messy string of words and wrestle it into a predictable format. Because if we could achieve this, then we could use the structured output in our applications, and treat it like any other regular REST API. This idea became the genesis of AI agents.

This table shows the timeline of how valid structured output came into existence.

MethodWhen it became availableHow it works
1. Ask for JSON in the promptJune 2020 with GPT‑3’s API beta. The same prompting technique carried over to Claude and Gemini in 2023.Ask for JSON as ordinary text. Your app parses and validates it.
2. Function callingJune 2023 for OpenAI function calling, followed by December 2023 for Gemini function calling and April 2024 for Claude’s tool-use beta.The model supplies a function name and arguments. Your app can use those arguments as the final result.
3. JSON modeNovember 2023 for OpenAI JSON mode, followed by April 2024 for Gemini JSON mode.Enforces valid JSON syntax. Keys and types can still vary.
4. Schema-enforced output (reply or tool arguments)May 2024 for Gemini 1.5 Pro schema-enforced replies. August 2024 for OpenAI strict replies and tool arguments. Claude introduced structured outputs for replies and tools in beta in November 2025.The API constrains the final reply or the tool arguments to match a supplied schema.

JSON Mode

Since pure prompting was so unreliable, JSON mode got introduced in November 2023. JSON mode made sure the text output from the model was in a JSON structure.

You simply pass response_format={"type": "json_object"} in the Chat Completion API.

Request
// POST /v1/chat/completions
{
  "model": "gpt-4o-2024-08-06",
  "messages": [
    { "role": "system", "content": "Return valid JSON." },
    { "role": "user", "content": "Extract the invoice total in cents as amount: ..." }
  ],
  "response_format": { "type": "json_object" }
}

While this gave you the correct JSON structure, the actual types that you wanted could still be wrong. E.g. getting a string amount instead of an int: "amount": 2000 vs "amount": "2000". JSON mode also still required you to ask for JSON as part of your prompt too.

JSON mode is still available, but it is recommended to structured output instead.

Structured output

To solve the field mismatch issue, OpenAI introduced structured output in August 2024. You set strict: true and it made sure the field type that you wanted is what you got.

Compared to JSON mode, structured output allowed for different output schemas (JSON being one) and no longer required mentioning JSON as part of your prompt.

You could have structured output in two ways: 1) on the model's text output or 2) on the function tool call.

Structured text output

Setting strict on the model's text means the text output will conform to the type defined in the schema.

Request
// POST /v1/chat/completions
{
  "model": "gpt-5.5",
  "messages": [
    { "role": "system", "content": "You extract structured data from financial documents." },
    { "role": "user", "content": "Extract the invoice total in cents as amount: ..." }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "invoice",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": { "amount": { "type": "integer" } },
        "required": ["amount"],
        "additionalProperties": false
      }
    }
  }
}
Response
// choices[0].message
{
  "role": "assistant",
  "content": "{\"amount\":2000}"
}

Structured tool call output

Function tool calls were first introduced on June 2023, while strict wasn't available until August 2024. That's 14 months where the type could have been wrong, and we had to return an error or do a retry.

But thankfully now with strict: true, the input arguments into your function will respect the type you define.

Request
// POST /v1/chat/completions
{
  "model": "gpt-5.5",
  "messages": [
    { "role": "system", "content": "You extract structured data from financial documents." },
    { "role": "user", "content": "Extract the invoice total in cents as amount: ..." }
  ],
  "tool_choice": "required",
  "tools": [{
    "type": "function",
    "function": {
      "name": "extract_invoice",
      "strict": true,
      "parameters": {
        "type": "object",
        "properties": { "amount": { "type": "integer" } },
        "required": ["amount"],
        "additionalProperties": false
      }
    }
  }]
}

Note: tool_choice: required here forces the model to select the tool.

Then the response looks like this:

Response
// choices[0].message
{
  "role": "assistant",
  "content": null,
  "tool_calls": [{
    "id": "call_123",
    "type": "function",
    "function": {
      "name": "extract_invoice",
      "arguments": "{\"amount\":2000}" // input into your function
    }
  }]
}

The combination of both structured output (specifically JSON structure) and strict: true (field types must match) allows us to get reliable JSON from LLMs.

Structured outputs with Agent frameworks

Many AI engineers won't need to worry about reliable JSON output since it'll be handled under the hood if you use one of the many agent frameworks (LangChain, Pydantic AI, etc.) out there.

You just need to define the output object structure you want.

OpenAI Agents SDK
from agents import Agent, Runner
from pydantic import BaseModel
 
class Ticket(BaseModel):
    ticket_id: int
 
agent = Agent(name="Ticket extractor", output_type=Ticket)
ticket = Runner.run_sync(agent, "Ticket #4812 is closed.").final_output
print(ticket.ticket_id)  # 4812

Conclusion

If you're going to create your own custom framework (which I believe everyone should know how to do), then it's important to understand how to configure valid structured output: specify the output schema and use strict: true.

The examples given here were using the OpenAI API, but it's more or less the same across other models such as Claude or Gemini.

Lastly, while we can reliably get structured output and JSON from LLMs, this doesn't mean the answer is correct. The values themselves could still be wrong due to hallucinations, so it's important to know how to engineer your AI system to cross the reliability chasm.


The Stack Instinct newsletter

Get practical insights on AI engineering and how to apply AI in businesses.

For engineers, founders and leaders.

Free. Unsubscribe anytime.