Nota
Il cloud di Ollama attualmente non supporta gli output strutturati.
Gli output strutturati ti consentono di imporre uno schema JSON sulle risposte del modello, in modo da poter estrarre dati strutturati in modo affidabile, descrivere immagini o mantenere ogni risposta coerente.
Generazione di JSON strutturato
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)Generazione di JSON strutturato con uno schema
Fornisci uno schema JSON nel campo format.
Nota
È ideale passare anche lo schema JSON come stringa nel prompt per ancorare la risposta del modello.
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
Utilizza modelli Pydantic e passa model_json_schema() a format, quindi valida la risposta:
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
Serializza uno schema Zod con z.toJSONSchema() e analizza la risposta strutturata:
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)Esempio: Estrazione di dati strutturati
Definisci gli oggetti che desideri ricevere e lascia che il modello popoli i campi:
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)Esempio: Visione con output strutturati
I modelli di visione accettano lo stesso parametro format, consentendo descrizioni deterministiche delle immagini:
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)Consigli per output strutturati affidabili
- Definisci schemi con Pydantic (Python) o Zod (JavaScript) in modo che possano essere riutilizzati per la validazione.
- Abbassa la temperatura (ad esempio, impostala a
0) per completamenti più deterministici. - Gli output strutturati funzionano tramite l'API compatibile con OpenAI attraverso
response_format