Skip to content

Structured LLM Output: From JSON to Strict Schemas

Cover: Structured LLM Output: From JSON to Strict Schemas LLMs naturally generate text, but for integration into software systems, structured data such as JSON, YAML, or XML is required. Without format control, model responses are unpredictable: extra explanations, invalid JSON, missing fields. In this article, I will discuss methods for obtaining strict structured output, their advantages, and limitations.

Why Simply Asking for JSON Isn't Enough

Even if the prompt explicitly states to return JSON, the model may: - Add text before or after the JSON; - Use single quotes instead of double quotes; - Insert comments; - Forget required fields. Example of an invalid response:

Here is the result:
{
  'name': 'Alice',  // name
  age: 30
}
Such output breaks json.loads(). Systematic methods of control are needed.

Methods for Structured Output

1. Prompt Engineering

The simplest way is to provide a detailed schema description in the prompt. Suitable for prototypes but does not guarantee validity.

Return JSON with the following fields:
- name: string
- age: integer
- email: string

Example: {"name": "Alice", "age": 30, "email": "alice@example.com"}

2. Function Calling

APIs like OpenAI and others support tools — descriptions of functions that the model can call. The response comes in strict JSON format.

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Extract user data"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "extract_user",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"},
                    "email": {"type": "string"}
                },
                "required": ["name", "age", "email"]
            }
        }
    }],
    tool_choice="auto"
)

3. Grammar-Constrained Generation

The most reliable method is to limit generation at the decoding level. Libraries like outlines, guidance, llama.cpp support grammars (e.g., GBNF). Example with outlines:

import outlines

model = outlines.models.transformers("mistralai/Mistral-7B-v0.1")

def extract_user(name: str, age: int, email: str):
    """Extract user data"""
    return {"name": name, "age": age, "email": email}

generator = outlines.generate.json(model, extract_user)
result = generator("Extract data: Ivan, 25, ivan@example.com")
print(result)

4. Structured Decoding in vLLM

vLLM supports guided_json and guided_grammar for server-side inference.

from vllm import LLM, SamplingParams

llm = LLM(model="meta-llama/Llama-3.1-8B-Instruct")

json_schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"}
    },
    "required": ["name", "age"]
}

params = SamplingParams(guided_json=json_schema)
output = llm.generate(["Extract data"], params)
print(output[0].outputs[0].text)

Comparison of Methods

Method Guarantee of Validity Speed Complexity of Implementation
Prompt Engineering No High Low
Function Calling Partial High Medium
Grammar Constraints Full Medium High
Structured Decoding Full Medium Medium
## Practical Recommendations
1. For production, use grammar constraints or structured decoding. Leave prompt engineering for prototypes.
2. Always validate the output even when using strict methods — in case of model errors.
3. Use Pydantic for schema definition and validation.
Example with Pydantic:
from pydantic import BaseModel, ValidationError

class User(BaseModel):
    name: str
    age: int
    email: str

try:
    user = User.model_validate_json(response_text)
except ValidationError as e:
    print(e)
4. Test on different models. Strict methods do not work equally well on all architectures.
## Conclusion
Structured output is a mandatory component of production systems on LLMs. The choice of method depends on reliability and speed requirements. For most tasks, Function Calling is sufficient, but for critical scenarios, use grammar constraints. Don't forget validation and error handling.
Additional recommendations include studying the glossary on structured output, guide on function calling, and MCP practice.