Home›Local LLM / Open Models›ローカルLLM(Ollama)にJSONを厳密に返させる — 自分専用ニュースbot開発記 #1
ローカルLLM(Ollama)にJSONを厳密に返させる — 自分専用ニュースbot開発記 #1

ローカルLLM(Ollama)にJSONを厳密に返させる — 自分専用ニュースbot開発記 #1This article explains how to enforce strict JSON output from a local LLM…

元記事を読むRead original articlezenn.dev(新しいタブで開きます)(opens in a new tab)
AI2 点サマリ2 key points
  • OllamaでローカルLLMを動かす際に、structured outputを使ってJSONスキーマに厳密に準拠したレスポンスを得る方法を解説した開発記録。
  • プロンプト工夫だけでは不安定だった出力を安定させる実践的な知見を共有している。
  • This article explains how to enforce strict JSON output from a local LLM running on Ollama using structured output schemas, solving the instability that comes from prompt-engineering alone.
  • It serves as the first entry in a series building a personal news bot.

本ページの本文と要約は AI による自動生成です。日本語版と英語版は言語ごとに独立して生成されるため、表現や詳しさが異なる場合があります。正確性は元記事 (zenn.dev) をご確認ください。The body and summaries are AI-generated independently for each language, so wording and detail may differ. Verify accuracy at the original source (zenn.dev).

要約と収集メタデータに基づく AI 解説。元記事全文の転載・翻訳ではありません。AI explainer based on the summaries and collected metadata, not a copy or translation of the full source article.

ローカルで動く大規模言語モデル(LLM)をツールや自動化に組み込む際、最大の障壁のひとつが「出力の不安定さ」だ。個人開発者による連載「自分専用ニュースbot開発記」の第1回は、Ollama上で動かすローカルLLMに、JSONスキーマへ厳密に準拠したレスポンスを返させる手法を実践的にまとめている。

Ollamaは、LlamaやMistralといったオープンなモデルをローカル環境で手軽に実行できるツールとして普及が進んでいる。クラウドAPIに依存しないためコストやプライバシーの面で利点がある一方、扱うモデルの規模がクラウド上の最上位モデルより小さいこともあり、指示への追従性が課題になりやすい。

記事が指摘するのは、プロンプトの工夫だけでJSONを返させようとすると出力が安定しないという問題だ。「JSONだけを返して」と指示しても、前後に説明文が付いたり、キーが欠けたり、カンマの位置が崩れたりして、プログラムでパースする際にエラーになりやすい。こうした揺れは、ニュースbotのように出力を機械的に処理する用途では致命的になりうる。

解決策として紹介されているのが、Ollamaのstructured output(構造化出力)機能である。あらかじめJSON Schemaで期待する構造を定義し、モデルの生成時にその形式へ制約をかけることで、スキーマに沿った出力を得やすくする仕組みだ。内部的には生成トークンを文法で縛るアプローチに近いと見られ、llama.cppのGBNF文法による制約とも思想を共有していると考えられる。

同様の発想は他社サービスにも広がっている。OpenAIはStructured Outputsやfunction calling、GoogleやAnthropicもツール利用のためのスキーマ指定に対応しており、LLMの出力を確実に構造化することは業界全体の共通課題となっている。ローカルLLMでも同水準の信頼性を確保できれば、外部APIに頼らない自動化の幅が広がる可能性がある。

本連載は今後、この構造化出力を土台に、ニュース収集や要約を自動化するbotを組み上げていく構成とみられる。プロンプト設計に頼りきらず、スキーマで出力を保証するという設計思想は、個人開発に限らず参考になりそうだ。

Running large language models locally has become increasingly practical, and Ollama is one of the most popular tools for doing so. Yet anyone who tries to build an automated pipeline on top of a local model quickly runs into a familiar obstacle: coaxing the model into returning clean, machine-readable JSON that a downstream program can parse without breaking. This article, the first in a series documenting the construction of a personal news bot, describes how to enforce strict JSON output using Ollama's structured output feature rather than relying on prompt wording alone.

The core issue is that instruction-tuned models are trained to be conversational. Even when a prompt explicitly asks for JSON, a model may wrap the response in Markdown code fences, prepend a sentence such as "Here is the JSON you requested," omit a required field, or emit subtly invalid syntax like trailing commas or unescaped quotes. For a one-off interaction a human can clean this up by hand, but for an unattended bot that runs on a schedule, a single malformed response can halt the entire pipeline. Prompt engineering lowers the failure rate but rarely eliminates it, and the failures tend to appear unpredictably, which makes them hard to test against.

Structured output addresses this at the decoding level rather than the prompting level. Ollama exposes a format parameter in its API that accepts a JSON Schema object describing the exact shape of the expected response: the field names, their data types, and which fields are required. When this schema is supplied, the runtime constrains token generation so that only tokens consistent with the schema can be produced. In practice this is implemented through constrained or grammar-based sampling, a technique that llama.cpp, the inference engine underpinning Ollama, supports through GBNF grammars. Because invalid tokens are masked out during generation, the model is prevented from producing output that violates the declared structure. That is a considerably stronger guarantee than asking the model politely and hoping it complies.

In a typical workflow, a developer defines the schema, often generated automatically from a Pydantic model in Python or a Zod schema in TypeScript, and passes it in the request alongside the prompt. The response then arrives as a string that reliably parses into the expected object. It is worth noting that constraining the format does not guarantee the content is correct; the model can still populate a valid field with an inaccurate value or a hallucinated summary. Structured output solves the parsing problem, not the reasoning problem, so validation of the actual values still matters. It also appears that smaller local models benefit especially from this approach, since they are more prone to formatting drift than larger hosted models.

This capability sits within a broader industry movement toward reliable structured generation. OpenAI introduced its Structured Outputs feature in 2024, offering a similar schema-adherence guarantee for its hosted models, and earlier JSON mode options provided a weaker version of the same idea. In the open-source ecosystem, libraries such as Outlines, Guidance, and Instructor tackle the problem from different angles, ranging from grammar enforcement to automatic retries and validation against a schema. Ollama's built-in support means that developers no longer need to bolt on an external library for basic cases, which lowers the barrier for local-first projects that prioritize privacy or offline operation.

For the news bot use case, this reliability is the foundation everything else depends on. The bot is likely to fetch articles, ask the model to extract fields such as a title, a concise summary, a category, and a sentiment label, and then store or route those results. Any of those steps that assumes well-formed JSON would be fragile without a hard structural guarantee. By moving the constraint into the model's decoding process, the pipeline can treat the LLM more like a predictable component and less like an unpredictable text generator.

Readers considering a similar build should keep a few prerequisites in mind. A working knowledge of JSON Schema helps, since overly strict or ambiguous schemas can occasionally reduce output quality or cause the model to stall. Choosing a model that handles structured generation well is also worth testing, as behavior varies across model families and sizes. Subsequent entries in the series are expected to cover the surrounding components, such as source ingestion, scheduling, and delivery, building on this structured-output groundwork.

ポコとTECHガイドPoko & TECH Guide

ポコと当サイトのTECHガイドが、記事の要約と収集した情報から読みどころを語るAI生成の対話です。Poko and TECH Dashboard's own TECH Guide discuss the article's highlights in an AI-generated conversation based on its summary and collected source details.

  1. ポコPokoプロンプトで「JSONで返して」と頼むだけじゃ不安定なの? structured outputって何?Isn’t asking “reply in JSON” in the prompt enough? What exactly is structured output?
  2. TECHガイドTECH Guide記事によれば、プロンプトの工夫だけでは出力が安定しなかったそうじゃ。structured outputは、返答を決めたJSONスキーマの形に従わせる仕組みじゃよ。According to the article, prompt tweaks alone produced unstable results. Structured output makes responses follow a predefined JSON schema—a fixed structure for the data.
  3. ポコPoko形が毎回そろうと、ニュースbotには何が嬉しいの?What does consistent formatting actually do for the news bot?
  4. TECHガイドTECH Guide簡単に言うとじゃな、決めた項目どおりの返答を得やすくなり、後の処理を安定させられるんじゃ。記事ではOllamaで厳密なJSON出力を得る方法を扱っておる。Simply put, predictable fields make later processing more reliable. The article shows how to get strict JSON responses from a local LLM running through Ollama.
  5. ポコPokoなるほど! 言葉でお願いするだけでなく、JSONの型を指定して出力を安定させるんだね。Got it! Instead of relying only on instructions, you specify the JSON structure to keep the output stable.
  6. TECHガイドTECH Guideその理解でよいぞ。これは自分専用ニュースbot開発の第1回なので、この安定した出力が自動収集・要約・通知にどうつながるかが見どころじゃな。Exactly. Since this is part one of a personal news bot series, the next thing to watch is how this stable output supports automated collection, summarization, and notifications.
記事情報・収集記録Article details & collection record
出典Source
Zenn LLMコミュニティCommunity
公開日時 (JST)Published (JST)
収集日時 (JST)Collected (JST)
配信形式Format
ブログBlog
原文言語Source language
JA
重要度の位置づけImportance in this lane
MediumMedium priority(Local LLM / Open Models 238件中、同等以上 191件)(191 of 238 Local LLM / Open Models entries are equal or higher)
出典の平均重要度(掲載直近 30 件・最大 30 件)Source average (last 30 listed, up to 30)
2.1 / 31=情報 · 2=中 · 3=高1=Info · 2=Medium · 3=High
情報の寿命Half-life
中期 (チュートリアル)Medium-term (tutorial)

🏠Local LLM / Open Models の他の記事More from Local LLM / Open Modelsもっと見る →View more →

ページ上部へScroll to top