Python을 이용할 경우 데이터 검증을 위한 라이브러리인 Pydantic을 이용하여 출력 형식을 지정할 수 있음
예시: 수학문제 풀기
답변 형식 정의
from openai import OpenAI
from pydantic import BaseModel
classStep(BaseModel):
explanation: str
output: strclassMathReasoning(BaseModel):
steps: list[Step]
final_answer: str
response = client.responses.parse(
model="gpt-4o",
input="방정식 8x + 7 = -23 을 한국어로 풀어라",
text_format=MathReasoning,
)
response.output_parsed
예시: 감성 분석
from enum import Enum
from pydantic import BaseModel, Field
classSentiment(str, Enum): # 감성은 다음 3가지 중에 하나로 정의
positive = '긍정'
negative = '부정'
neutral = '중립'classSentimentAnalysis(BaseModel):
text: str# 텍스트 문자열
sentiment: Sentiment # 감성(긍정/부정/중립)
keywords: str = Field(description="문장에 포함된 감정 단어 목록")
response = client.responses.parse(
model="gpt-5",
input="'생성형 AI 수업 너무 재밌어요'를 긍정/부정/중립으로 평가해라",
text_format=SentimentAnalysis
)
response.output_parsed
예시: 토큰 분류
classLabel(str, Enum):
DT = '날짜'
LC = '장소'
PS = '사람'classEntity(BaseModel):
named_entity: str
label: Label
classNER(BaseModel):
entities: list[Entity]
response = client.responses.parse(
model="gpt-5",
input="""다음 내용을 개체명 인식을 하여 날짜/장소/사람으로 각 토큰을 분류해라
오늘 12시 서울특별시 성북구에 있는 국민대 경영대학원에서
유재명 교수가 1가지 주제로 수업을 한다.""",
text_format=NER
)
response.output_parsed