结构化输出功能可让模型生成始终遵循特定架构的输出。例如,您可以为模型提供响应架构,以便响应为有效的 JSON。Vertex AI 模型即服务 (MaaS) 上提供的所有开放模型都支持结构化输出。 如需详细了解结构化输出的概念,请参阅结构化输出简介。 本指南将介绍如何将结构化输出与开放模型搭配使用,以便模型回答遵循特定架构,涵盖以下主题: 在以下使用情形中,您设置了回答架构,以便模型输出包含属性 模型输出遵循以下 JSON 架构: 如果您提供“Alice and Bob are going to a science fair on Friday”这一提示,模型可能会生成以下回答: 以下示例使用递归架构,其中 模型输出遵循代码中指定的 响应可能如下所示:使用结构化输出
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)
response_format=CalendarEvent
实参指示模型生成符合 CalendarEvent
Pydantic 模型的输出。模型输出 JSON,SDK 会自动将其解析为 CalendarEvent
对象。{ "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)
Response
Pydantic 对象的架构。对于提示“制作用户个人资料表单”,有效的回答可能是: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')
]
)
开放模型的结构化输出
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-19。