DeepInfra Structured Outputs — JSON 형식으로 응답 받기
DeepInfra Structured Outputs — JSON 형식으로 응답 받기
채팅 완성 결과를 텍스트가 아니라 구조화된 JSON으로 받고 싶을 때가 있어요. DeepInfra API는 response_format을 이용해 문자 응답을 JSON 형식으로 돌려줄 수 있어요. 이는 추론 API와 OpenAI 호환 API 양쪽에서 지원되며, 많은 모델에서 동작해요.
두 가지 모드가 있어요.
| 모드 | 사용법 | 언제 쓰는지 |
|---|---|---|
json_object |
{"type": "json_object"} |
스키마 없이 어떤 JSON 객체든 받고 싶을 때 |
json_schema |
{"type": "json_schema", "json_schema": {...}} |
엄격한 출력 스키마를 강제하고 싶을 때 |
json_object 모드
JSON 출력을 받는 가장 간단한 방법이에요. 모델이 유효한 JSON 객체를 돌려주지만, 정확한 형태는 제어할 수 없어요.
import openai
import json
client = openai.OpenAI(
base_url="https://api.deepinfra.com/v1/openai",
api_key="$DEEPINFRA_TOKEN",
)
messages = [
{
"role": "user",
"content": "Provide a JSON list of 3 famous scientific breakthroughs in the past century, all of the countries which contributed, and in what year."
}
]
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=messages,
response_format={"type": "json_object"},
)
print(response.choices[0].message.content)
curl "https://api.deepinfra.com/v1/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DEEPINFRA_TOKEN" \
-d '{
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"messages": [
{
"role": "user",
"content": "Provide a JSON list of 3 famous scientific breakthroughs."
}
],
"response_format": {"type": "json_object"}
}'
json_schema 모드
JSON Schema로 엄격한 출력 스키마를 강제해요. 모델은 스키마에 맞는 값만 생성하도록 제한돼요. 다운스트림 코드가 고정된 구조에 의존할 때 유용해요.
import openai
import json
client = openai.OpenAI(
base_url="https://api.deepinfra.com/v1/openai",
api_key="$DEEPINFRA_TOKEN",
)
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[
{
"role": "user",
"content": "Extract the name, country, and year from: 'Alexander Fleming discovered Penicillin in the UK in 1928.'"
}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "breakthrough",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"country": {"type": "string"},
"year": {"type": "integer"}
},
"required": ["name", "country", "year"],
"additionalProperties": False
}
}
}
)
print(json.loads(response.choices[0].message.content))
출력 예시예요.
{"name": "Penicillin", "country": "UK", "year": 1928}
팁
모델에 JSON 생성을 항상 프롬프트로 지시해요. json_object에 꼭 필요한 건 아니지만, 기대 형식을 프롬프트에 언급하면 일관성이 좋아져요.
프로덕션엔 json_schema를 선호해요. 코드가 특정 필드명·타입에 의존한다면 "strict": true를 쓴 json_schema가 형태 깜짝 놀람을 없애줘요.
잘림을 주의해요. 모델이 max_tokens나 length 때문에 중간에 멈추면 JSON이 불완전할 수 있어요. 파싱 전에 항상 검증해요.
주의사항
JSON 모드는 모델의 정렬(alignment)에 영향을 줄 수 있어요. 구조화된 출력을 강제하면 일부 모델은 "모르겠어요"라고 말하는 대신 값을 지어내기(할루시네이션) 쉬워져요. 특히 실시간 데이터(날씨, 주가 등)에 관한 프롬프트에서 두드러져요.
예: JSON 모드에서 "샌프란시스코 날씨 어때?"라고 물으면, 모델이 실시간 데이터가 없다고 설명하는 대신 날씨 예보를 지어낼 수 있어요.
모범 사례:
- JSON 모드는 일반 질의응답이 아니라 구조화된 데이터 추출 작업에 써요
- 프롬프트를 기대 스키마에 맞게 구체적으로 유지해요
- 프로덕션에 쓰기 전에 모델 출력을 검증해요
- 더 일관된 구조를 위해 낮은 temperature(< 0.7)를 써요
더 알아보기
- Chat Completions —
response_format이 동작하는 채팅 완성 API - Tool Calling — 구조화된 인자 전달과 결합
- DeepInfra 문서 전체 인덱스