Note
Ollama Cloud ปัจจุบันยังไม่รองรับเอาต์พุตที่มีโครงสร้าง
เอาต์พุตที่มีโครงสร้างช่วยให้คุณบังคับใช้ JSON schema กับคำตอบของโมเดล เพื่อให้สามารถสกัดข้อมูลที่มีโครงสร้างได้อย่างเชื่อถือได้ อธิบายรูปภาพ หรือทำให้คำตอบทุกข้อมีความสอดคล้องกัน
การสร้าง 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 ที่มีโครงสร้างพร้อมกับ schema
ส่ง JSON schema ไปยังฟิลด์ format
Note
วิธีที่ดีที่สุดคือส่ง JSON schema ในรูปแบบสตริงไปพร้อมกับ prompt ด้วย เพื่อให้คำตอบของโมเดลสอดคล้องกับ schema ที่กำหนด
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
ใช้ `z.toJSONSchema()` เพื่อ serialize schema ของ Zod และแยกวิเคราะห์คำตอบที่มีโครงสร้าง:
```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 เหมือนกัน ซึ่งช่วยให้สามารถสร้างคำอธิบายรูปภาพที่ deterministic ได้:
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)เคล็ดลับสำหรับเอาต์พุตที่มีโครงสร้างที่เชื่อถือได้
- กำหนด schema โดยใช้ Pydantic (สำหรับ Python) หรือ Zod (สำหรับ JavaScript) เพื่อให้สามารถนำไปใช้ในการตรวจสอบความถูกต้อง ซ้ำได้
- ลดค่า temperature (เช่น ตั้งค่าเป็น
0) เพื่อให้ได้ผลลัพธ์ที่ deterministic มากขึ้น - เอาต์พุตที่มีโครงสร้างสามารถใช้งานได้ผ่าน API ที่เข้ากันได้กับ OpenAI โดยใช้พารามิเตอร์
response_format