Skip to content
Go back

Structured Output and JSON Mode: APIs and Local LLMs

By KingPin 13 min read
Structured Output and JSON Mode: APIs and Local LLMs
Contents

The Appeal: Guaranteed JSON

Structured output (JSON mode) promises: “The model will always output valid JSON, never unstructured text.”

Sounds great. But there’s a catch: forcing structure sometimes makes the model dumber.

How JSON Mode Works

Most LLM APIs let you specify output format:

from openai import OpenAI
import json
client = OpenAI()
message = client.chat.completions.create(
model="gpt-5-mini",
max_tokens=1024,
response_format={"type": "json_object"},
messages=[
{"role": "user", "content": "Extract names and ages from: 'Alice is 30, Bob is 25'"}
]
)
# Response is guaranteed valid JSON
result = json.loads(message.choices[0].message.content)

Ollama also supports this:

Terminal window
curl http://localhost:11434/api/generate -d '{
"model": "mistral",
"prompt": "Extract JSON: {\"name\": \"...\", \"age\": ...} from: Alice is 30",
"format": "json",
"stream": false
}'

The model’s output will be valid JSON, not “name: Alice, age: 30” or other variations.

When JSON Mode Saves You

Use JSON mode when:

  1. Extraction from unstructured text
  1. Form filling / structured categorization
  1. Data pipeline integrations
# Example: Extract structured data from free text
prompt = """
Extract the following fields from this support ticket:
- issue: What's the problem?
- priority: critical/high/medium/low
- component: backend/frontend/database/infrastructure
- action_required: A brief next step
Ticket: "The login page is broken. Users can't sign in. This is blocking our launch."
"""
# With JSON mode, you get valid JSON guaranteed
# Without it, you might get: "issue: The login page is broken\npriority: critical"

When JSON Mode Hurts

JSON mode constraints the model’s reasoning. Some models perform worse when forced into JSON.

Consider:

User: "Explain why OAuth is better than basic auth"
With JSON mode:
- Model is constrained to structure
- May oversimplify to fit the schema
- Loses nuance
Without JSON mode:
- Model can write naturally, include caveats
- Can say "it depends" with explanation

Real example:

Terminal window
# Without JSON mode
$ curl http://localhost:11434/api/generate -d '{
"model": "mistral",
"prompt": "What are the tradeoffs of microservices?",
"stream": false
}'
# Output: "Microservices offer scalability and independence, but they add complexity..."
# (Clear, nuanced, well-reasoned)
# With JSON mode
curl http://localhost:11434/api/generate -d '{
"model": "mistral",
"prompt": "What are the tradeoffs of microservices? Output as JSON: {\"pros\": [...], \"cons\": [...]}",
"format": "json",
"stream": false
}'
# Output: {"pros": ["Scalability", "Independence"], "cons": ["Complexity", "Cost"]}
# (Oversimplified, loses explanation)

Decision Tree

Use JSON mode if:

Skip JSON mode if:

Hybrid Approach: JSON + Explanation

Get the best of both worlds:

prompt = """
Analyze this code for security issues. Output as JSON:
{
"vulnerability": "name of issue",
"severity": "critical/high/medium/low",
"explanation": "why this is a problem",
"fix": "how to fix it"
}
Code:
```python
import os
password = os.getenv("DB_PASSWORD") # Hardcoded in logs

"""

Model can explain fully within the “explanation” field

while still outputting valid JSON

This works because JSON allows text fields. The model can be verbose and nuanced, but the output is still machine-parseable.
## Local Models: llama.cpp, Ollama, and vLLM
Everything above works the same on a local stack, with a few sharp edges of its own. The runtime applies the constraint, not the model, so any model you already run supports it.
### How constrained decoding works
A grammar tracks where you are in the output and marks which tokens are legal next. Illegal tokens get probability zero before sampling. After `{"sentiment": ` the only legal tokens are the opening quote of your allowed strings, so the model cannot write "Sure! Here's your JSON:".
Two consequences matter. The model gets no smarter, only fenced in: if it had no idea what the right value was, the fence still forces a value of the right type. And the model usually does not see your schema. llama.cpp uses the schema only to build the constraint, so describe the structure in your prompt too. That is the number one cause of "valid JSON, garbage values".
### JSON mode versus schema mode
| | What it enforces | Your keys |
|---|---|---|
| Plain JSON mode (Ollama `format: "json"`, `response_format: {"type": "json_object"}`) | Output parses as a JSON object | Not enforced |
| Schema mode (Ollama `format: {...schema...}`, llama.cpp `json_schema`) | Output matches the schema's shape | Enforced |
Plain JSON mode gives you `{"answer": "yes"}` today and `{"result": {"verdict": true}}` tomorrow. Both parse. Neither matches what your code expects. Use schema mode.
### llama.cpp: schema in, grammar out
`llama-server` converts a subset of JSON Schema to a GBNF grammar for you. On the OpenAI-style chat endpoint, pass the schema inside `response_format`:
```bash frame="terminal"
curl -s http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "system", "content": "Extract the receipt. Reply with JSON: vendor (string), total (number, or null if absent)."},
{"role": "user", "content": "ACME HARDWARE\n2x bolts 3.00\n1x drill 45.00"}
],
"temperature": 0,
"max_tokens": 300,
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "receipt",
"schema": {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"total": {"type": ["number", "null"]}
},
"required": ["vendor", "total"]
}
}
}
}' | jq -r '.choices[0].message.content'

The system prompt repeats the structure in plain words because the grammar will not. On the native /completion endpoint the field is json_schema at the top level, and the same endpoint accepts a raw grammar field. Write GBNF yourself for output that is not JSON, such as a closed list of labels:

root ::= "{" ws "\"sentiment\"" ws ":" ws ("\"positive\"" | "\"negative\"" | "\"neutral\"") ws "}"
ws ::= " "?

Bound that ws rule. A classic mistake is ws ::= [ \t\n]*, which lets a stuck model spend its whole token budget on spaces and newlines.

llama.cpp skips unsupported schema features silently. Your schema loads, and the constraint is looser than you think. The documented gaps include:

Also, additionalProperties defaults to false in llama.cpp, the opposite of the JSON Schema spec. Set it to true if you rely on extra keys. Test each schema once with a few deliberately wrong outputs. For handwritten GBNF, a llama.cpp build with tests produces a test-gbnf-validator binary that checks strings against a grammar file. Run it once per schema, not once per outage.

Ollama: format takes a string or a schema

Ollama’s chat and generate endpoints have one format field. The string "json" gives plain JSON mode. A JSON schema object gives schema mode:

Terminal window
curl -s http://localhost:11434/api/chat -d '{
"model": "qwen3.6:35b",
"stream": false,
"messages": [
{"role": "user", "content": "Extract the receipt as JSON with vendor and total (number or null):\nACME HARDWARE\n2x bolts 3.00\n1x drill 45.00"}
],
"options": {"temperature": 0, "num_predict": 300},
"format": {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"total": {"type": ["number", "null"]}
},
"required": ["vendor", "total"]
}
}' | jq -r '.message.content'

Ollama’s API docs warn that plain JSON mode needs an instruction in the prompt, or the model may emit large amounts of whitespace. Schema mode reduces that risk, and a prompt that names the structure removes most of the rest.

vLLM, briefly

vLLM builds structured outputs into its OpenAI-compatible server, with xgrammar and guidance as backends. The --structured-outputs-config.backend flag on vllm serve picks one, and auto chooses per request. The standard response_format with json_schema works as shown above. vLLM’s own fields go inside extra_body={"structured_outputs": {"json": schema}}. The older guided_json family of fields was removed in v0.12.0, so 2024 tutorials fail on a current install.

Local gotchas after the first demo

Pydantic and retry: the mask is not a judge

Constrained decoding guarantees syntax, not truth. A model forced to emit {"total": <number>} will pick a number even when the receipt has no total, which is how a $48 receipt becomes $48,000 in Postgres with zero parse errors. Write the schema once as a Pydantic model, generate the JSON schema from it, and validate every reply with validators that know something about your data. When validation fails, feed the error back:

extract.py
from ollama import chat
from pydantic import BaseModel, ValidationError, model_validator
class Receipt(BaseModel):
reasoning: str
vendor: str
total: float | None
@model_validator(mode="after")
def total_is_sane(self):
if self.total is not None and not (0 < self.total < 100_000):
raise ValueError("total out of range")
return self
def extract(text: str, attempts: int = 3) -> Receipt:
messages = [
{"role": "system", "content": "Extract the receipt as JSON: reasoning (short), vendor, total (number, or null if no total is printed)."},
{"role": "user", "content": text},
]
last_error = None
for _ in range(attempts):
resp = chat(
model="qwen3.6:35b",
messages=messages,
format=Receipt.model_json_schema(),
options={"temperature": 0.3, "num_predict": 400},
)
raw = resp.message.content
try:
return Receipt.model_validate_json(raw)
except ValidationError as e:
last_error = e
messages += [
{"role": "assistant", "content": raw},
{"role": "user", "content": f"That failed validation: {e}. Fix it and reply with JSON only."},
]
raise RuntimeError(f"gave up after {attempts} tries: {last_error}")

Retries at temperature 0 tend to repeat themselves, so nudge it up a little. A schema alone cannot tell a right total from a wrong one, so add checks that tie fields together: totals equal the sum of line items, dates fall in the expected range, IDs exist in your database. Nested Pydantic models emit $ref, which llama.cpp handles poorly, so flatten deep models for it.

Against llama-server you use the standard openai client, because the server speaks the OpenAI chat API. Pass the same Receipt schema through response_format:

extract_llamacpp.py
from openai import OpenAI
from extract import Receipt # the model from extract.py above
client = OpenAI(base_url="http://localhost:8080/v1", api_key="not-needed")
resp = client.chat.completions.create(
model="local", # llama-server serves the model it loaded
messages=[
{"role": "system", "content": "Extract the receipt as JSON: reasoning, vendor, total."},
{"role": "user", "content": "ACME HARDWARE\n1x drill 45.00"},
],
temperature=0,
max_tokens=400,
response_format={
"type": "json_schema",
"json_schema": {"name": "receipt", "schema": Receipt.model_json_schema()},
},
)
receipt = Receipt.model_validate_json(resp.choices[0].message.content)

Testing: Before and After

Always benchmark JSON mode vs. free form:

#!/bin/bash
# Test both modes on the same prompt
prompt="Extract: name, email, age from 'John Doe (john@example.com) is 35 years old'"
echo "=== Without JSON mode ==="
curl -s http://localhost:11434/api/generate -d "{
\"model\": \"mistral\",
\"prompt\": \"$prompt\",
\"stream\": false
}" | jq '.response'
echo ""
echo "=== With JSON mode ==="
curl -s http://localhost:11434/api/generate -d "{
\"model\": \"mistral\",
\"prompt\": \"$prompt\nOutput as valid JSON: {\\\"name\\\": ..., \\\"email\\\": ..., \\\"age\\\": ...}\",
\"format\": \"json\",
\"stream\": false
}" | jq '.response'
# Compare:
# - Which is easier to parse?
# - Which is more accurate?
# - Does quality differ?

The Real Cost

JSON mode adds computational overhead. The model has to track syntax, ensure quotes match, etc. This makes inference slightly slower and can degrade quality on complex reasoning tasks.

For simple extraction? The overhead is negligible and the safety gain is huge.

For “explain this concept”? You’re paying a real penalty for no benefit.

Bottom Line

JSON mode is a power tool for extraction and data pipelines. Use it there. Don’t use it for explanation, analysis, or anything where nuance matters.

When in doubt, let the model write freely, then parse the output with a simple regex or JSON.loads(). Your model will thank you with better output.

On local models, use schema mode, describe the structure in the prompt too, put reasoning before the answer, and validate every reply on the client. Constrained decoding is a seatbelt. It keeps the output on the road. It does not drive.

Common Questions

Does Ollama structured output work with every model?

Yes for text models in practice, because the Ollama runtime applies the constraint during sampling, not the model. Quality still varies: small models follow field descriptions worse, so they fill valid fields with weaker values. Test your schema on the exact model tag you deploy.

Why does my local model return valid JSON with wrong values?

Grammar-constrained decoding only restricts which tokens are legal, so the model must emit something of the right type even when it lacks the information. Fix it with field descriptions in the prompt, nullable fields for missing data, enums for closed sets, and Pydantic validators that cross-check values.

Does llama.cpp validate my JSON Schema?

No. The llama.cpp schema converter skips unsupported keywords silently, so a schema can load without errors and still constrain less than you expect. Test the schema with a few deliberately wrong outputs, and validate replies on the client with Pydantic.

Should I use GBNF grammars or JSON schema in llama-server?

Use JSON schema for JSON output, since llama-server converts it to GBNF for you. Write raw GBNF when the output is not JSON, such as a closed list of labels or a custom line format. Bound whitespace rules in handwritten grammars so a stuck model cannot loop on spaces.


Share this post on:

Send a Webmention

Written about this post on your own site? Send a webmention and it'll show up above once verified.


Previous Post
AMD Lemonade: Local LLM Serving for AMD GPUs
Next Post
Browser GPU Acceleration on Linux in 2026

Discussion

Powered by Garrul . Sign in with GitHub or Google, or post anonymously.

Related Posts