구조화된 출력을 사용하면 모델이 항상 특정 스키마를 준수하는 출력을 생성할 수 있습니다. 예를 들어 모델에 응답 스키마를 제공하여 응답이 유효한 JSON을 생성하도록 할 수 있습니다. Vertex AI 서비스형 모델(MaaS)에서 사용할 수 있는 모든 개방형 모델은 구조화된 출력을 지원합니다.
구조화된 출력 기능에 관한 자세한 개념 정보는 구조화된 출력 소개를 참조하세요.
구조화된 출력 사용
다음 사용 사례에서는 모델 출력이 name, date, participants 속성이 있는 JSON 객체임을 보장하는 응답 스키마를 설정합니다. Python 코드는 OpenAI SDK와 Pydantic 객체를 사용하여 JSON 스키마를 생성합니다.
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="MODEL_NAME",
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,
)
print(completion.choices[0].message.parsed)
모델 출력은 다음 JSON 스키마를 준수합니다.
{ "name": STRING, "date": STRING, "participants": [STRING] }
'앨리스와 밥은 금요일에 과학 박람회에 갈 거야'라는 프롬프트가 제공되면 모델은 다음과 같은 응답을 생성할 수 있습니다.
{
"name": "science fair",
"date": "Friday",
"participants": [
"Alice",
"Bob"
]
}
상세 예시
다음 코드는 재귀 스키마의 예시입니다. UI
클래스에는 children
목록이 포함되어 있으며, 이 목록은 UI
클래스일 수도 있습니다.
from pydantic import BaseModel
from openai import OpenAI
from enum import Enum
from typing import List
client = OpenAI()
class UIType(str, Enum):
div = "div"
button = "button"
header = "header"
section = "section"
field = "field"
form = "form"
class Attribute(BaseModel):
name: str
value: str
class UI(BaseModel):
type: UIType
label: str
children: List["UI"]
attributes: List[Attribute]
UI.model_rebuild() # This is required to enable recursive types
class Response(BaseModel):
ui: UI
completion = client.beta.chat.completions.parse(
model="MODEL_NAME",
messages=[
{"role": "system", "content": "You are a UI generator AI. Convert the user input into a UI."},
{"role": "user", "content": "Make a User Profile Form"}
],
response_format=Response,
)
print(completion.choices[0].message.parsed)
모델 출력은 이전 스니펫에 지정된 Pydantic 객체의 스키마를 따릅니다. 이 예시에서 모델은 다음 UI 양식을 생성할 수 있습니다.
Form
Input
Name
Email
Age
응답은 다음과 같습니다.
ui = UI(
type=UIType.div,
label='Form',
children=[
UI(
type=UIType.div,
label='Input',
children=[],
attributes=[
Attribute(name='label', value='Name')
]
),
UI(
type=UIType.div,
label='Input',
children=[],
attributes=[
Attribute(name='label', value='Email')
]
),
UI(
type=UIType.div,
label='Input',
children=[],
attributes=[
Attribute(name='label', value='Age')
]
)
],
attributes=[
Attribute(name='name', value='John Doe'),
Attribute(name='email', value='john.doe@example.com'),
Attribute(name='age', value='30')
]
)