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

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

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 解説本文です。元記事全文の転載・翻訳ではありません。This AI explainer is generated from the summaries and collected metadata, not from a reproduction 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文法による制約とも思想を共有していると考えられる。

OllamaでローカルLLMを動かす際に、structured outputを使ってJSONスキーマに厳密に準拠したレスポンスを得る方法を解説した開発記録。
🏠 Local LLM / Open Models · 本記事のポイント

同様の発想は他社サービスにも広がっている。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 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.
🏠 Local LLM / Open Models · Key takeaway

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.

  • 出典SourceZenn LLMコミュニティCommunity
  • 直近30件の平均重要度Avg importance, last 301=Info · 2=Medium · 3=High
  • 配信形式FormatブログBlog
  • 重要度Importance重要度 MediumMedium priority(Local LLM / Open Models 230件中、同等以上 207件)(207 of 230 Local LLM / Open Models entries are equal or higher)
  • 情報の寿命Half-life📘 中期 (チュートリアル)Medium-term (tutorial)
  • 原文言語Source languageJA
  • 収集日時Collected2026/07/20 05:01

本ページの本文と要約は 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).

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