跳过至正文
结构化输出允许您对模型响应强制执行 JSON 模式,以便可靠地提取结构化数据、描述图像或保持回复的一致性。

生成结构化 JSON

curl -X POST https://: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"
}'

使用模式生成结构化 JSON

format 字段提供一个 JSON 模式。
最好同时在提示词中以字符串形式传递 JSON 模式,以锚定模型的响应。
curl -X POST https://: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"]
  }
}'

示例:提取结构化数据

定义您想要返回的对象,并让模型填充字段
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 参数,从而实现对图像的确定性描述
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='gemma3',
  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) 定义模式,以便它们可以被重用于验证。
  • 降低温度(例如,将其设置为 0)以获得更具确定性的补全。
  • 结构化输出通过 response_format 在兼容 OpenAI 的 API 中运行