Structured JSON Outputs

Force reliable JSON from local models using the format flag and a JSON Schema for exact shapes.

TL;DR

  1. Pass format: json to force a valid JSON object.
  2. Constrain shape by passing a full JSON Schema in format.
  3. Describe the exact keys you expect in the SYSTEM prompt.

JSON Mode

    format json

    Force the response to be a valid JSON object.

    curl http://localhost:11434/api/generate -d '{
      "model": "llama3.1",
      "prompt": "List 2 colors as JSON",
      "format": "json",
      "stream": false
    }'
    Prompt For Keys

    Name the exact keys you want in the prompt.

    "prompt": "Return name and age as JSON"
    Parse Safely

    The whole response body parses as JSON.

    # response text is valid JSON to parse

Schema-Constrained Output

    format Schema

    Pass a JSON Schema object in the format field.

    "format": { "type": "object", ... }
    type object

    Define the top-level type and properties.

    { "type": "object",
      "properties": { } }
    required

    List required keys the model must include.

    "required": ["name", "age"]

Python Example

    Pass format

    Send a schema in the chat request's format.

    ollama.chat(model="llama3.1",
      messages=msgs, format=schema)
    Pydantic Schema

    Generate a schema from a Pydantic model.

    schema = Person.model_json_schema()
    Validate

    Parse the reply back into your model.

    Person.model_validate_json(reply)

Determinism

    temperature 0

    Zero temperature removes sampling randomness.

    # options: { "temperature": 0 }
    Fixed seed

    A set seed repeats output for a prompt.

    # options: { "seed": 42 }
    Schema + temp 0

    Combine both for repeatable structured output.

    # fixed shape + deterministic values

Tips

  1. Pass a JSON Schema in format to pin exact keys and types, which is stricter and safer than plain format: "json" alone.
  2. Also name the required fields in the prompt, since telling the model what to produce plus a schema yields the most reliable output.

Warnings

  1. Plain format: "json" guarantees valid JSON but not your shape; pass a JSON Schema when specific keys are required.
  2. Ollama constrains output with a JSON Schema, not GBNF grammar files; put the schema in the format field, not a grammar.

In Practice

FAQ