생성형 AI를 실제 서비스 서비스나 DB와 연동하려면 단순 텍스트 답변이 아닌 규격화된 **JSON 데이터(Structured Output)**로 결과를 받아야 합니다.
1. JSON 스키마 출력 강제 (response_format)
OpenAI API는 response_format={"type": "json_object"} 설정을 제공합니다. (단, 시스템 프롬프트에 JSON이라는 단어를 명시해야 함)
import json
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "너는 입력을 받으면 JSON으로만 결과를 반환하는 객체 분석기야. JSON keys: name, age, skills(array)"},
{"role": "user", "content": "이인상 개발자는 30세이고 Python, JS, C를 잘해요."}
]
)
# JSON 문자열을 파이썬 딕셔너리로 변환
data = json.loads(response.choices[0].message.content)
print(data["skills"]) # ['Python', 'JS', 'C']
2. Pydantic 라이브러리를 활용한 엄격한 타입 검증
pydantic을 이용해 데이터 클래스 모델을 정의하면 타입 오류 없는 안전한 JSON 추출이 가능합니다.
from pydantic import BaseModel
class UserProfile(BaseModel):
name: str
age: int
is_developer: bool
# OpenAI Structured Output (Beta)
completion = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "홍길동 25세 비개발자"}],
response_format=UserProfile,
)
user = completion.choices[0].message.parsed
print(user.name, user.age) # 홍길동 25
3. 자주 묻는 질문 (Q&A)
Q. AI가 출력한 JSON 문법이 깨져서 json.loads() 에러가 날 때 대처법은?
A. 최신 API의 Structured Output 기능 또는 pydantic 모델을 사용하면 문법 오류율을 0%에 가깝게 보장할 수 있습니다.