Skip to content

注意

Ollamaクラウドは現在、構造化出力をサポートしていません。

構造化出力を使用すると、モデルのレスポンスにJSONスキーマを適用できるため、構造化データの確実な抽出、画像の説明、またはすべてのレスポンスの一貫性を維持することができます。

構造化JSONの生成

cURL

shell
curl -X POST http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "gpt-oss",
  "messages": [{"role": "user", "content": "Tell me about Canada in one line"}],
  "stream": false,
  "format": "json"
}'

Python

python
from ollama import chat

response = chat(
  model='gpt-oss',
  messages=[{'role': 'user', 'content': 'Tell me about Canada.'}],
  format='json'
)
print(response.message.content)

JavaScript

javascript
import ollama from 'ollama'

const response = await ollama.chat({
  model: 'gpt-oss',
  messages: [{ role: 'user', content: 'Tell me about Canada.' }],
  format: 'json'
})
console.log(response.message.content)

スキーマを使用した構造化JSONの生成

formatフィールドにJSONスキーマを指定します。

注意

モデルのレスポンスをスキーマに基づかせるため、プロンプト内にJSONスキーマを文字列として渡すことも推奨されます。

cURL

shell
curl -X POST http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "gpt-oss",
  "messages": [{"role": "user", "content": "Tell me about Canada."}],
  "stream": false,
  "format": {
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "capital": {"type": "string"},
      "languages": {
        "type": "array",
        "items": {"type": "string"}
      }
    },
    "required": ["name", "capital", "languages"]
  }
}'

Python

Pydanticモデルを使用し、model_json_schema()formatに渡してレスポンスを検証します:

python
from ollama import chat
from pydantic import BaseModel

class Country(BaseModel):
  name: str
  capital: str
  languages: list[str]

response = chat(
  model='gpt-oss',
  messages=[{'role': 'user', 'content': 'Tell me about Canada.'}],
  format=Country.model_json_schema(),
)

country = Country.model_validate_json(response.message.content)
print(country)

JavaScript

Zodスキーマをz.toJSONSchema()でシリアライズし、構造化レスポンスを解析します:

javascript
import ollama from 'ollama'
import * as z from 'zod'

const Country = z.object({
  name: z.string(),
  capital: z.string(),
  languages: z.array(z.string()),
})

const response = await ollama.chat({
  model: 'gpt-oss',
  messages: [{ role: 'user', content: 'Tell me about Canada.' }],
  format: z.toJSONSchema(Country),
})

const country = Country.parse(JSON.parse(response.message.content))
console.log(country)

例:構造化データの抽出

返却したいオブジェクトを定義し、モデルにフィールドに入力させます:

python
from ollama import chat
from pydantic import BaseModel

class Pet(BaseModel):
  name: str
  animal: str
  age: int
  color: str | None
  favorite_toy: str | None

class PetList(BaseModel):
  pets: list[Pet]

response = chat(
  model='gpt-oss',
  messages=[{'role': 'user', 'content': 'I have two cats named Luna and Loki...'}],
  format=PetList.model_json_schema(),
)

pets = PetList.model_validate_json(response.message.content)
print(pets)

例:構造化出力を使用したビジョン

ビジョンモデルは同じformatパラメータを受け付けるため、画像の決定的な説明が可能になります:

python
from ollama import chat
from pydantic import BaseModel
from typing import Literal, Optional

class Object(BaseModel):
  name: str
  confidence: float
  attributes: str

class ImageDescription(BaseModel):
  summary: str
  objects: list[Object]
  scene: str
  colors: list[str]
  time_of_day: Literal['Morning', 'Afternoon', 'Evening', 'Night']
  setting: Literal['Indoor', 'Outdoor', 'Unknown']
  text_content: Optional[str] = None

response = chat(
  model='gemma4',
  messages=[{
    'role': 'user',
    'content': 'Describe this photo and list the objects you detect.',
    'images': ['path/to/image.jpg'],
  }],
  format=ImageDescription.model_json_schema(),
  options={'temperature': 0},
)

image_description = ImageDescription.model_validate_json(response.message.content)
print(image_description)

信頼性の高い構造化出力のためのヒント

  • Pydantic(Python)またはZod(JavaScript)でスキーマを定義することで、検証のために再利用できるようにします。
  • より決定的な生成を行うために、temperature(例:0に設定)を下げます。
  • 構造化出力は、OpenAI互換APIを介してresponse_formatで動作します