Skip to content

Note

Ollama Cloud는 현재 구조화된 출력을 지원하지 않습니다.

구조화된 출력을 사용하면 모델 응답에 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 스키마를 제공하세요.

Note

프롬프트에 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)로 스키마를 정의하여 검증 과정에서 재사용할 수 있도록 하세요.
  • 더 결정론적인 완성 결과를 얻으려면 온도를 낮추세요(예: 0으로 설정).
  • 구조화된 출력은 OpenAI 호환 API를 통해 response_format으로 작동합니다.