본문 바로가기
Flutter로 1인 앱 개발 해보기

OpenAI API - Structured output 사용 시 json 파싱 제대로 안될 때.

by 유티끌 2024. 10. 6.

GPT API를 사용할 때, GPT에게 답변을 json 포맷으로 달라고 말하면서 schema를 명시적으로 선언해주는 것은 약간은 비효율적이다. 본문 내에 적어야하기 때문에 토큰도 소모하기도 하고..

아래 모델 이후 모델부터는 response_format 파라미터를 통해서 출력형태를 직접 지정해줄 수 있다.

from pydantic import BaseModel
from openai import OpenAI

client = OpenAI()

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

completion = client.beta.chat.completions.parse(
    model="gpt-4o-2024-08-06",
    messages=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    response_format=CalendarEvent,
)

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

이렇게 parsed 된 상태면 파이썬 객체 상태라서, json형태로 파싱해야할 때는 제대로 파싱되지 않는다.

예시에서는 pydantic의 BaseModel을 상속받고 있는데, 관련 문서에서 보면 객체를 json으로 파싱하는 방법을 확인할 수 있다.

https://docs.pydantic.dev/latest/concepts/serialization/#modelmodel_dump

 

Serialization - Pydantic

Data validation using Python type hints

docs.pydantic.dev

from datetime import datetime

from pydantic import BaseModel


class BarModel(BaseModel):
    whatever: int


class FooBarModel(BaseModel):
    foo: datetime
    bar: BarModel


m = FooBarModel(foo=datetime(2032, 6, 1, 12, 13, 14), bar={'whatever': 123})
print(m.model_dump_json())
#> {"foo":"2032-06-01T12:13:14","bar":{"whatever":123}}
print(m.model_dump_json(indent=2))
"""
{
  "foo": "2032-06-01T12:13:14",
  "bar": {
    "whatever": 123
  }
}
"""

끝!

반응형

댓글