많은 앱은 모델의 답변을 정해진 구조로 받아야 합니다. 텍스트 문단이 아니라 특정 필드를 가진 JSON 객체가 필요합니다. 프롬프트에서 정중하게 부탁("JSON으로 답해 줘")하면 대개 통하지만 항상 그렇지는 않습니다. 모델이 JSON 앞에 문장을 덧붙이거나, 마크다운 코드 블록으로 감싸거나, 필드를 빠뜨릴 수 있습니다. 신뢰도는 가장 약한 것부터 가장 강한 것까지 세 단계로 나뉩니다.
1단계: 프롬프트로 요청하기
대부분 잘 작동하지만 가끔 실패합니다. 중요도가 낮은 경우에만 사용하거나, 아래의 더 강력한 방법과 함께 사용하세요.
messages = [{"role": "user", "content":
'Extract the name and age from this text as JSON with keys "name" and "age": '
'"Maria is 34 years old."'}]
2단계: JSON 모드
response_format={"type": "json_object"}를 설정하면 출력이 문법적으로 올바른 JSON이 되도록 강제합니다. 어떤 필드가 들어갈지는 강제하지 않으므로, 프롬프트에 정확한 필드 이름을 적으세요.
from openai import OpenAI
import json
client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])
resp = client.chat.completions.create(
model="gpt-6-luna",
response_format={"type": "json_object"},
messages=[{"role": "user", "content":
'Extract the name and age as JSON with keys "name" and "age": "Maria is 34 years old."'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["name"], data["age"])
JSON 모드를 쓰려면 대화 어딘가(보통 system 또는 user 메시지)에 "JSON"이라는 단어가 있어야 합니다. 그렇지 않으면 오류를 반환하는 모델도 있습니다.
3단계: JSON Schema (권장)
response_format을 JSON Schema로 설정하면 문법과 구조를 모두 제한합니다. 필수 필드, 타입, enum이 생성 후에 검사되는 것이 아니라 생성 과정에서 강제됩니다.
schema = {
"type": "json_schema",
"json_schema": {
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
"additionalProperties": False,
},
"strict": True,
},
}
resp = client.chat.completions.create(
model="gpt-6-luna",
response_format=schema,
messages=[{"role": "user", "content": "Maria is 34 years old."}],
)
data = json.loads(resp.choices[0].message.content)
스키마는 작업에 필요한 만큼만 작게 유지하세요. 선택 필드와 중첩 객체가 많은 스키마는 필수 필드 몇 개로 이루어진 평평한 스키마보다 모델이 정확하게 채우기 어렵습니다.
Anthropic Messages 형식
Messages API에는 전용 JSON 모드가 없습니다. 안정적인 방법은 system 프롬프트에 스키마를 설명하고 모델에게 도구를 호출하도록 하는 것입니다. 도구 호출 인수는 이미 JSON Schema를 엄격하게 따르기 때문입니다.
import anthropic
client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
tools = [{
"name": "extract_person",
"description": "Record the extracted person",
"input_schema": {
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
"required": ["name", "age"],
},
}]
resp = client.messages.create(
model="claude-opus-4-8", max_tokens=256,
tool_choice={"type": "tool", "name": "extract_person"},
tools=tools,
messages=[{"role": "user", "content": "Maria is 34 years old."}],
)
data = next(b.input for b in resp.content if b.type == "tool_use")
그래도 파싱이 실패할 때의 대비책
스키마를 사용하더라도 응답은 신뢰할 수 없는 입력으로 취급하세요. 긴 컨텍스트, 특이한 엣지 케이스, 모델의 한계 때문에 여전히 깨진 출력이 나올 수 있습니다. 파싱을 재시도로 감싸세요.
import json
def extract(prompt, retries=2):
last_err = None
for _ in range(retries + 1):
resp = client.chat.completions.create(model="gpt-6-luna", response_format=schema,
messages=[{"role": "user", "content": prompt}])
try:
return json.loads(resp.choices[0].message.content)
except json.JSONDecodeError as e:
last_err = e
raise last_err
API가 서버 측에서 스키마를 강제하더라도, 사용하기 전에 코드에서 파싱된 객체를 스키마로 다시 검증하세요(pydantic이나 jsonschema 같은 라이브러리 사용). 모델이 채운 필드는 데이터베이스 쿼리, 셸 명령, 파일 경로에 들어가기 전에 사용자 입력과 마찬가지로 신뢰할 수 없는 입력으로 취급하세요.
모델 지원
JSON Schema 지원 여부는 모델마다 다릅니다. strict: true에 의존하기 전에 마켓플레이스의 모델 페이지에서 기능 목록을 확인하세요. 구조화된 출력을 지원하는 몇몇 모델은 다음과 같습니다.
| 모델 | 입력 / 100만 토큰 | 출력 / 100만 토큰 | 공식 가격 대비 |
|---|---|---|---|
GPT-6 Lunagpt-6-luna | $0.05 | $0.30 | 40% 할인 |
Claude Opus 4.8claude-opus-4-8 | $0.375 | $1.875 | 92.5% 할인 |
DeepSeek V4 Prodeepseek-v4-pro | $0.3857 | $1.1571 | 41.6% 할인 |