ollama - 💡(How to fix) Fix gemma4:e4b thinking failing with structured output [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
ollama/ollama#15416Fetched 2026-04-09 07:51:25
View on GitHub
Comments
0
Participants
1
Timeline
3
Reactions
0
Author
Participants
Timeline (top)
closed ×1cross-referenced ×1labeled ×1

Error Message

import ollama from pydantic import BaseModel, ValidationError

class TestModel(BaseModel): name: str age: int

def test_llm_client(): client = ollama.Client() system = "You are a helpful assistant that generates JSON objects with name and age." prompt = "Generate a JSON object with name and age." try: response = client.chat( model="gemma4:e4b", messages=[ {"role": "system", "content": system}, {"role": "user", "content": prompt}, ], format=TestModel.model_json_schema(), think="low", options={ "temperature": 1.0, "top_p": 0.95, "top_k": 64, }, ) content = response.message.content or "" print("LLM Response:", content) result = TestModel.model_validate_json(content) print("Parsed Result:", result) except ValidationError as ve: print("Validation Error:", ve) except Exception as e: print("Error:", e)

if name == "main": test_llm_client()

Code Example

import ollama
from pydantic import BaseModel, ValidationError

class TestModel(BaseModel):
    name: str
    age: int

def test_llm_client():
    client = ollama.Client()
    system = "You are a helpful assistant that generates JSON objects with name and age."
    prompt = "Generate a JSON object with name and age."
    try:
        response = client.chat(
            model="gemma4:e4b",
            messages=[
                    {"role": "system", "content": system},
                    {"role": "user",   "content": prompt},
                ],
                format=TestModel.model_json_schema(),
                think="low",
                options={
                    "temperature": 1.0,
                    "top_p": 0.95,
                    "top_k": 64,
                },
            )
        content = response.message.content or ""
        print("LLM Response:", content)
        result = TestModel.model_validate_json(content)
        print("Parsed Result:", result)
    except ValidationError as ve:
        print("Validation Error:", ve)
    except Exception as e:
        print("Error:", e)

if __name__ == "__main__":
    test_llm_client()

---

LLM Response: 
{
  "name": "Alice",
  "age": 30
}

Validation Error: 1 validation error for TestModel
  Invalid JSON: expected value at line 1 column 1 [type=json_invalid, input_value='\n{\n  "name": "A...",\n  "age": 30\n}\n', input_type=str]
    For further information visit https://errors.pydantic.dev/2.12/v/json_invalid
RAW_BUFFERClick to expand / collapse

What is the issue?

llm client calls produce output with json fences when thinking is not set to False. using package ollama 0.6.1

Reproducible code:

import ollama
from pydantic import BaseModel, ValidationError

class TestModel(BaseModel):
    name: str
    age: int

def test_llm_client():
    client = ollama.Client()
    system = "You are a helpful assistant that generates JSON objects with name and age."
    prompt = "Generate a JSON object with name and age."
    try:
        response = client.chat(
            model="gemma4:e4b",
            messages=[
                    {"role": "system", "content": system},
                    {"role": "user",   "content": prompt},
                ],
                format=TestModel.model_json_schema(),
                think="low",
                options={
                    "temperature": 1.0,
                    "top_p": 0.95,
                    "top_k": 64,
                },
            )
        content = response.message.content or ""
        print("LLM Response:", content)
        result = TestModel.model_validate_json(content)
        print("Parsed Result:", result)
    except ValidationError as ve:
        print("Validation Error:", ve)
    except Exception as e:
        print("Error:", e)

if __name__ == "__main__":
    test_llm_client()

Relevant log output

LLM Response: 
{
  "name": "Alice",
  "age": 30
}

Validation Error: 1 validation error for TestModel
  Invalid JSON: expected value at line 1 column 1 [type=json_invalid, input_value='\n{\n  "name": "A...",\n  "age": 30\n}\n', input_type=str]
    For further information visit https://errors.pydantic.dev/2.12/v/json_invalid

OS

Windows

GPU

Nvidia

CPU

Intel

Ollama version

0.20.3

extent analysis

TL;DR

Setting thinking to False in the client.chat method may resolve the issue with JSON fences in the output.

Guidance

  • Verify that the thinking parameter is set to False in the client.chat method to prevent JSON fences in the output.
  • Check the ollama package documentation to ensure that the thinking parameter is supported in version 0.6.1.
  • Review the TestModel.model_validate_json method to ensure it can handle the JSON output from the LLM client.
  • Consider updating the ollama package to the latest version (0.20.3) to ensure compatibility and potential bug fixes.

Example

response = client.chat(
    model="gemma4:e4b",
    messages=[
            {"role": "system", "content": system},
            {"role": "user",   "content": prompt},
        ],
        format=TestModel.model_json_schema(),
        think=False,  # Set thinking to False
        options={
            "temperature": 1.0,
            "top_p": 0.95,
            "top_k": 64,
        },
    )

Notes

The issue may be specific to the ollama package version 0.6.1, and updating to the latest version (0.20.3) may resolve the issue. However, without further information, it is unclear if this is the root cause.

Recommendation

Apply workaround: Set thinking to False in the client.chat method, as this is the most likely cause of the issue with JSON fences in the output.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING