Skip to content

Note

Hiện tại, Ollama Cloud không hỗ trợ đầu ra có cấu trúc.

Đầu ra có cấu trúc cho phép bạn áp dụng lược đồ JSON lên phản hồi của mô hình, giúp bạn trích xuất dữ liệu có cấu trúc một cách đáng tin cậy, mô tả hình ảnh hoặc giữ cho mọi phản hồi nhất quán.

Tạo JSON có cấu trúc

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)
```

Tạo JSON có cấu trúc với lược đồ

Cung cấp lược đồ JSON cho trường format.

Note

Lý tưởng nhất là bạn cũng truyền lược đồ JSON dưới dạng chuỗi trong lời nhắc để làm cơ sở cho phản hồi của mô hình.

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

Sử dụng các mô hình Pydantic và truyền `model_json_schema()` vào trường `format`, sau đó xác thực phản hồi:

```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

Tuần tự hóa lược đồ Zod bằng `z.toJSONSchema()` và phân tích cú pháp phản hồi có cấu trúc:

```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)
```

Ví dụ: Trích xuất dữ liệu có cấu trúc

Xác định các đối tượng bạn muốn nhận được và để mô hình điền giá trị vào các trường:

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)

Ví dụ: Thị giác với đầu ra có cấu trúc

Các mô hình thị giác chấp nhận tham số format tương tự, cho phép tạo các mô tả hình ảnh xác định:

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)

Mẹo để tạo đầu ra có cấu trúc đáng tin cậy

  • Xác định lược đồ bằng Pydantic (Python) hoặc Zod (JavaScript) để có thể tái sử dụng cho việc xác thực.
  • Giảm temperature (ví dụ: đặt thành 0) để có kết quả hoàn thành xác định hơn.
  • Đầu ra có cấu trúc hoạt động thông qua API tương thích với OpenAI qua tham số response_format