구조화된 출력

구조화된 출력 (JSON 모드) (Structured Outputs)

빠른 시작

  • SDK
  • PROXY
from litellm import completion
import os 

os.environ["OPENAI_API_KEY"] = ""

response = completion(
  model="gpt-5.6-luna",
  response_format={ "type": "json_object" },
  messages=[
    {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
    {"role": "user", "content": "Who won the world series in 2020?"}
  ]
)
print(response.choices[0].message.content)
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{
    "model": "gpt-5.6-luna",
    "response_format": { "type": "json_object" },
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant designed to output JSON."
      },
      {
        "role": "user",
        "content": "Who won the world series in 2020?"
      }
    ]
  }'

출처: 문서

본문

모델 지원 확인

1. 모델이 response_format을 지원하는지 확인

litellm.get_supported_openai_params 를 호출해 모델/프로바이더가 response_format 을 지원하는지 확인해요.

from litellm import get_supported_openai_params

params = get_supported_openai_params(model="anthropic.claude-sonnet-5", custom_llm_provider="bedrock")

assert "response_format" in params

2. 모델이 json_schema를 지원하는지 확인

이는 다음을 전달할 수 있는지 확인하는 데 사용돼요:

  • response_format={ "type": "json_schema", "json_schema": … , "strict": true }
  • response_format=<Pydantic Model>
from litellm import supports_response_schema

assert supports_response_schema(model="gemini-3.1-pro-preview", custom_llm_provider="bedrock")

모델과 response_schema 지원의 전체 목록은 model_prices_and_context_window.json 을 확인하세요.

'json_schema' 전달

구조화된 출력을 쓰려면 다음을 지정하세요:

response_format: { "type": "json_schema", "json_schema": … , "strict": true }

다음에서 동작해요:

  • OpenAI 모델

  • Azure OpenAI 모델

  • xAI 모델 (Grok-2 이상)

  • Google AI Studio - Gemini 모델

  • Vertex AI 모델 (Gemini + Anthropic)

  • Bedrock 모델

  • Anthropic API 모델

  • Groq 모델

  • Ollama 모델

  • Databricks 모델

  • SDK

  • PROXY

import os
from litellm import completion 
from pydantic import BaseModel

# add to env var 
os.environ["OPENAI_API_KEY"] = ""

messages = [{"role": "user", "content": "List 5 important events in the XIX century"}]

class CalendarEvent(BaseModel):
  name: str
  date: str
  participants: list[str]

class EventsList(BaseModel):
    events: list[CalendarEvent]

resp = completion(
    model="gpt-5.6-terra",
    messages=messages,
    response_format=EventsList
)

print("Received={}".format(resp))

events_list = EventsList.model_validate_json(resp.choices[0].message.content)

Proxy 사용

  1. config.yaml에 openai 모델 추가
model_list:
  - model_name: "gpt-5.6-terra"
    litellm_params:
      model: "gpt-5.6-terra"
  1. config.yaml로 프록시 시작
litellm --config /path/to/config.yaml
  1. OpenAI SDK / Curl로 호출!

openai sdk의 'base_url'만 교체하면 proxy를 openai 모델용 'json_schema'로 호출할 수 있어요.

OpenAI SDK:

from pydantic import BaseModel
from openai import OpenAI

client = OpenAI(
    api_key="anything",  # 👈 PROXY KEY (can be anything, if master_key not set)
    base_url="http://0.0.0.0:4000"  # 👈 PROXY BASE URL
)

class Step(BaseModel):
    explanation: str
    output: str

class MathReasoning(BaseModel):
    steps: list[Step]
    final_answer: str

completion = client.beta.chat.completions.parse(
    model="gpt-5.6-terra",
    messages=[
        {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."},
        {"role": "user", "content": "how can I solve 8x + 7 = -23"}
    ],
    response_format=MathReasoning,
)

math_reasoning = completion.choices[0].message.parsed

Curl:

curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ***" \
-d '{
  "model": "gpt-5.6-terra",
  "messages": [
    {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."},
    {"role": "user", "content": "how can I solve 8x + 7 = -23"}
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "math_reasoning",
      "schema": {
        "type": "object",
        "properties": {
          "steps": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "explanation": { "type": "string" },
                "output": { "type": "string" }
              },
              "required": ["explanation", "output"],
              "additionalProperties": false
            }
          },
          "final_answer": { "type": "string" }
        },
        "required": ["steps", "final_answer"],
        "additionalProperties": false
      },
      "strict": true
    }
  }
}'

JSON 스키마 검증

모든 모델이 json_schema를 네이티브로 전달하는 것을 지원하지는 않아요. 이를 해결하기 위해 LiteLLM은 json_schema의 클라이언트 측 검증을 지원합니다.

litellm.enable_json_schema_validation=True

litellm.enable_json_schema_validation=True 가 설정되면, LiteLLM은 jsonvalidator 로 json 응답을 검증합니다.

  • SDK
  • PROXY
# !gcloud auth application-default login - run this to add vertex credentials to your env
import litellm, os
from litellm import completion 
from pydantic import BaseModel 

messages=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ]

litellm.enable_json_schema_validation = True
litellm.set_verbose = True # see the raw request made by litellm

class CalendarEvent(BaseModel):
  name: str
  date: str
  participants: list[str]

resp = completion(
    model="gemini/gemini-3.1-pro-preview",
    messages=messages,
    response_format=CalendarEvent,
)

print("Received={}".format(resp))

Proxy 사용법:

model_list:
  - model_name: "gemini-3.8-flash"
    litellm_params:
      model: "gemini/gemini-3.8-flash"
      api_key: os.environ/GEMINI_API_KEY

litellm_settings:
  enable_json_schema_validation: True
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{
    "model": "gemini-3.8-flash",
    "messages": [
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    "response_format": { 
        "type": "json_schema",
        "json_schema": {
          "name": "math_reasoning",
          "schema": {
            "type": "object",
            "properties": {
              "steps": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "explanation": { "type": "string" },
                    "output": { "type": "string" }
                  },
                  "required": ["explanation", "output"],
                  "additionalProperties": false
                }
              },
              "final_answer": { "type": "string" }
            },
            "required": ["steps", "final_answer"],
            "additionalProperties": false
          },
          "strict": true
        }
    },
  }'

Gemini - 네이티브 JSON 스키마 형식 (Gemini 2.0+)

Gemini 2.0+ 모델은 표준 JSON Schema 형식과 더 나은 호환성을 제공하는 네이티브 responseJsonSchema 파라미터를 자동으로 사용합니다.

이점 (Gemini 2.0+):

  • 표준 JSON Schema 형식 (string, object 같은 소문자 타입)
  • 더 엄격한 검증을 위한 additionalProperties: false 지원
  • Pydantic의 model_json_schema() 와 더 나은 호환성
  • propertyOrdering 불필요

사용법

  • SDK
  • PROXY
from litellm import completion
from pydantic import BaseModel

class UserInfo(BaseModel):
    name: str
    age: int

response = completion(
    model="gemini/gemini-3.8-flash",
    messages=[{"role": "user", "content": "Extract: John is 25 years old"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "user_info",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"}
                },
                "required": ["name", "age"],
                "additionalProperties": False  # Supported on Gemini 2.0+
            }
        }
    }
)
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{
    "model": "gemini-3.8-flash",
    "messages": [
        {"role": "user", "content": "Extract: John is 25 years old"}
    ],
    "response_format": {
        "type": "json_schema",
        "json_schema": {
            "name": "user_info",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"}
                },
                "required": ["name", "age"],
                "additionalProperties": false
            }
        }
    }
  }'

모델 동작

모델 사용 형식 additionalProperties 지원
Gemini 2.0+ responseJsonSchema (JSON Schema) ✅ Yes
Gemini 1.5 responseSchema (OpenAPI) ❌ No

LiteLLM은 모델 버전에 따라 적절한 형식을 자동으로 선택합니다.

더 알아보기 (Learn more)