구조화된 출력을 사용하면 모델이 항상 특정 스키마를 준수하는 출력을 생성할 수 있습니다. 예를 들어 모델에 응답 스키마를 제공하여 응답이 유효한 JSON을 생성하도록 할 수 있습니다. Vertex AI 서비스형 모델 (MaaS)에서 사용할 수 있는 모든 개방형 모델은 구조화된 출력을 지원합니다.
다음 사용 사례에서는 모델 출력이 name, date, participants 속성이 있는 JSON 객체임을 보장하는 응답 스키마를 설정합니다.
Python 코드는 OpenAI SDK와 Pydantic 객체를 사용하여 JSON 스키마를 생성합니다.
frompydanticimportBaseModelfromopenaiimportOpenAIclient=OpenAI()classCalendarEvent(BaseModel):name:strdate:strparticipants: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)
다음 코드는 재귀 스키마의 예입니다. UI 클래스에는 children 목록이 포함되어 있으며, 이 목록은 UI 클래스일 수도 있습니다.
frompydanticimportBaseModelfromopenaiimportOpenAIfromenumimportEnumfromtypingimportListclient=OpenAI()classUIType(str,Enum):div="div"button="button"header="header"section="section"field="field"form="form"classAttribute(BaseModel):name:strvalue:strclassUI(BaseModel):type:UITypelabel:strchildren:List["UI"]attributes:List[Attribute]UI.model_rebuild()# This is required to enable recursive typesclassResponse(BaseModel):ui:UIcompletion=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 양식을 생성할 수 있습니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[],[],null,["# Structured output for open models\n\nStructured outputs enable a model to generate output that always adheres to a\nspecific schema. For example, a model may be provided with a response schema to\nensure that the response produces valid JSON. All open models available on the\nVertex AI Model as a Service (MaaS) support structured outputs.\n\nFor more conceptual information about the structured output capability, see\n[Introduction to structured output](../../multimodal/control-generated-output).\n\nUse structured outputs\n----------------------\n\nThe following use case sets a response schema that ensures that the model output\nis a JSON object with the following properties: name, date, and participants.\nThe Python code uses the OpenAI SDK and Pydantic objects to generate the JSON\nschema. \n\n from pydantic import BaseModel\n from openai import OpenAI\n\n client = OpenAI()\n\n class CalendarEvent(BaseModel):\n name: str\n date: str\n participants: list[str]\n\n completion = client.beta.chat.completions.parse(\n model=\"\u003cvar label=\"model name\" translate=\"no\"\u003eMODEL_NAME\u003c/var\u003e\",\n messages=[\n {\"role\": \"system\", \"content\": \"Extract the event information.\"},\n {\"role\": \"user\", \"content\": \"Alice and Bob are going to a science fair on Friday.\"},\n ],\n response_format=CalendarEvent,\n )\n\n print(completion.choices[0].message.parsed)\n\n| **Note:** The response has a `CalendarEvent` object, which is populated with the defined fields. The model outputs JSON, which the SDK parses into a Pydantic object.\n\nThe model output will adhere to the following JSON schema: \n\n { \"name\": STRING, \"date\": STRING, \"participants\": [STRING] }\n\nWhen provided the prompt, \"Alice and Bob are going to a science fair on Friday\",\nthe model could produce the following response: \n\n {\n \"name\": \"science fair\",\n \"date\": \"Friday\",\n \"participants\": [\n \"Alice\",\n \"Bob\"\n ]\n }\n\nDetailed example\n----------------\n\nThe following code is an example of a recursive schema. The `UI` class contains\na list of `children`, which can also be of the `UI` class. \n\n from pydantic import BaseModel\n from openai import OpenAI\n from enum import Enum\n from typing import List\n\n client = OpenAI()\n\n class UIType(str, Enum):\n div = \"div\"\n button = \"button\"\n header = \"header\"\n section = \"section\"\n field = \"field\"\n form = \"form\"\n\n class Attribute(BaseModel):\n name: str\n value: str\n\n class UI(BaseModel):\n type: UIType\n label: str\n children: List[\"UI\"]\n attributes: List[Attribute]\n\n UI.model_rebuild() # This is required to enable recursive types\n\n class Response(BaseModel):\n ui: UI\n\n completion = client.beta.chat.completions.parse(\n model=\"\u003cvar label=\"model name\" translate=\"no\"\u003eMODEL_NAME\u003c/var\u003e\",\n messages=[\n {\"role\": \"system\", \"content\": \"You are a UI generator AI. Convert the user input into a UI.\"},\n {\"role\": \"user\", \"content\": \"Make a User Profile Form\"}\n ],\n response_format=Response,\n )\n\n print(completion.choices[0].message.parsed)\n\nThe model output will adhere to the schema of the Pydantic object specified in\nthe previous snippet. In this example, the model could generate the following UI\nform: \n\n Form\n Input\n Name\n Email\n Age\n\nA response could look like the following: \n\n ui = UI(\n type=UIType.div,\n label='Form',\n children=[\n UI(\n type=UIType.div,\n label='Input',\n children=[],\n attributes=[\n Attribute(name='label', value='Name')\n ]\n ),\n UI(\n type=UIType.div,\n label='Input',\n children=[],\n attributes=[\n Attribute(name='label', value='Email')\n ]\n ),\n UI(\n type=UIType.div,\n label='Input',\n children=[],\n attributes=[\n Attribute(name='label', value='Age')\n ]\n )\n ],\n attributes=[\n Attribute(name='name', value='John Doe'),\n Attribute(name='email', value='john.doe@example.com'),\n Attribute(name='age', value='30')\n ]\n )"]]