If you need machine-readable output from a model, you have three options on an OpenAI-compatible API: structured outputs vs JSON mode vs plain tool calling. They look similar in code and fail very differently in production. This post compares the three on what each one actually guarantees, what each costs in tokens, and how to use them safely when a gateway sits between your app and the model.
It is written by AtmoRouter, so we will be explicit about one limit up front: a gateway forwards these parameters, it does not invent guarantees the underlying model lacks. Everything below assumes you still validate the output in your own code.
What each mode actually guarantees
The vendor docs are clearer than most blog posts on this, so start there.
JSON mode (response_format: {"type": "json_object"}) asks the model for valid JSON. OpenAI's Structured Outputs guide is blunt about its limits: it ensures the output parses, but it "will not guarantee the output matches any specific schema". You must also tell the model to produce JSON somewhere in the conversation. OpenAI's API rejects the request if the string "JSON" never appears in the context, because without the instruction the model may emit whitespace until it hits the token limit.
Structured outputs (response_format: {"type": "json_schema", "json_schema": {..., "strict": true}}) constrain decoding to your JSON Schema. OpenAI calls it "the evolution of JSON mode" and recommends it whenever it is available. Anthropic has the same idea under a different field: JSON outputs via `output_config.format` with type: "json_schema".
Tool calling (tools=[...]) is for when the model should ask your code to do something. Arguments arrive as a JSON string in tool_calls. With strict: true on the function definition, OpenAI's function calling guide says arguments "reliably adhere to the function schema, instead of being best effort"; Anthropic offers strict tool use with the same flag.
| | JSON mode | Structured outputs (strict) | Tool calling (strict) | |---|---|---|---| | Valid JSON | Yes, except edge cases | Yes | Yes (arguments) | | Matches your schema | No | Yes, within supported subset | Yes, within supported subset | | Best for | Legacy models, loose shapes | Final answers your code parses | Actions your code executes | | Extra prompt needed | Must mention "JSON" | No | Tool descriptions |
Schema rules that bite in strict mode
Strict mode only supports a subset of JSON Schema, and the rules are stricter than many Pydantic models you already have. From OpenAI's docs:
- Every field must be listed in
required. Emulate optional fields with a union such as"type": ["string", "null"]. additionalProperties: falsemust be set on every object.- Limits: up to 5,000 object properties total, 10 levels of nesting, and 1,000 enum values.
Anthropic documents its own complexity limits, including a cap of 16 parameters using union types across all strict schemas, and returns a 400 ("Schema is too complex for compilation") when a schema is too large. Both vendors note that the first request with a new schema has extra latency while it is processed; Anthropic caches the compiled grammar for 24 hours from last use.
Even strict output can be incomplete. If the model refuses or runs out of max_tokens, you get a refusal or a truncated response, not a schema-valid object. Check finish_reason (or stop_reason on Anthropic) before you parse.
The token cost of structure
None of these modes is free in tokens. A JSON Schema or tool definition is sent as input on every request, and the output itself is often longer than prose because of keys and quotes.
Illustrative math, using AtmoRouter "from" prices at the time of writing (USD per million input / output tokens; rates refresh, and the model page is authoritative):
| Model ID | From price (input / output) | 400-token schema × 100,000 requests (40M input tokens) | |---|---|---| | zai/glm-5.3 | $0.0035 / $0.011 | $0.14 | | cx/gpt-6.2-sol | $0.10 / $0.50 | $4.00 | | cc/claude-sonnet-4-6 | $0.5175 / $2.5875 | $20.70 |
Two things change that picture more than the mode itself:
- 1.Caching. The schema is an identical prefix on every call, so it is an ideal cache candidate. On AtmoRouter, cached input is billed at 10% of the input rate where the model supports caching.
- 2.Retries. JSON mode has no schema guarantee, so you need a validate-and-retry loop. If 3% of responses fail validation, you pay for roughly 3% more full requests, input and output, plus the added latency. Strict mode usually removes that loop, but only on models that actually enforce it.
"From" prices are the cheapest listed tier, so treat these numbers as a lower bound, not a quote.
Working code: strict schema with a safe fallback
On AtmoRouter, response_format, strict schemas, and tool choice are model-dependent: the gateway forwards them, but it cannot guarantee a given model enforces them. So the pattern below asks for a strict schema, falls back to JSON mode if the model rejects it, and validates either way.
pythonimport json
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.environ["ATMOROUTER_API_KEY"],
base_url="https://atmorouter.dev/v1",
)
MODEL = "cx/gpt-6.2-sol" # exact catalogue ID; check atmorouter.dev/models
SCHEMA = {
"type": "object",
"properties": {
"sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
"summary": {"type": "string"},
"ticket_id": {"type": ["string", "null"]},
},
"required": ["sentiment", "summary", "ticket_id"],
"additionalProperties": False,
}
MESSAGES = [
{"role": "system", "content": "Classify the support message. Reply in JSON only."},
{"role": "user", "content": "Ticket 4821: the export finally works, thanks!"},
]
def validate(obj: dict) -> dict:
if obj.get("sentiment") not in {"positive", "neutral", "negative"}:
raise ValueError("bad sentiment")
if not isinstance(obj.get("summary"), str):
raise ValueError("bad summary")
if obj.get("ticket_id") is not None and not isinstance(obj["ticket_id"], str):
raise ValueError("bad ticket_id")
return obj
def classify() -> dict:
strict_format = {
"type": "json_schema",
"json_schema": {"name": "ticket", "strict": True, "schema": SCHEMA},
}
try:
resp = client.chat.completions.create(
model=MODEL, messages=MESSAGES, response_format=strict_format, max_tokens=300
)
except BadRequestError:
# Model does not accept json_schema: fall back to JSON mode.
resp = client.chat.completions.create(
model=MODEL, messages=MESSAGES,
response_format={"type": "json_object"}, max_tokens=300,
)
choice = resp.choices[0]
if choice.finish_reason != "stop":
raise RuntimeError(f"incomplete output: {choice.finish_reason}")
return validate(json.loads(choice.message.content))
if __name__ == "__main__":
print(classify())Notes on the code:
- The system message mentions JSON, which keeps the JSON mode fallback valid.
ticket_idis nullable instead of optional, which is how strict mode expresses "may be missing".- The local
validate()runs even on the strict path. It costs nothing and catches models that accept the parameter but do not enforce it.
Which one to pick
- Your code parses the model's final answer (classification, extraction, UI payloads): structured outputs with
strict: true, plus local validation. - The model triggers actions in your system (search, database writes, API calls): tool calling with strict schemas. Validate arguments before executing anything, and never evaluate model-generated code.
- The model or route does not support schemas: JSON mode, an explicit "JSON" instruction, a validator, and a bounded retry (one or two attempts, not a loop).
- You switch models often through one gateway: write to the strictest common denominator, keep the fallback path, and test each model ID you put in production instead of assuming parity.
FAQ
Is JSON mode deprecated?
Not removed, but OpenAI recommends structured outputs instead "when possible". JSON mode remains useful for older models and routes that do not accept json_schema.
Does structured output work with every model on AtmoRouter?
No. response_format, strict schemas, and tool choice depend on the model. AtmoRouter forwards the parameter; whether it is enforced depends on the model behind the ID. Test the exact ID and keep local validation.
Do schemas count toward my token bill?
Yes. Schemas and tool definitions are input tokens on every request. Keep them short, reuse the same schema so it caches, and move long explanations out of field descriptions.
Strict mode or tool calling for data extraction?
OpenAI's guidance: use function calling when the model connects to your tools or data, and a structured response format when you want to shape the model's reply. For pure extraction, a response format is simpler.
Next step
Pick one model ID, run the script above against it, and log how often the fallback path fires. Compare live rates on the models page, read the tool calling and JSON docs, or create a key at atmorouter.dev to try it with a prepaid balance and no seat fees.