有了結構化輸出內容,模型就能生成一律符合特定結構定義的輸出內容。舉例來說,模型可能會收到回應結構定義,確保回應產生有效的 JSON。Vertex AI Model as a Service (MaaS) 提供的所有開放模型都支援結構化輸出。
如要進一步瞭解結構化輸出功能的概念,請參閱「結構化輸出簡介」。
使用結構化輸出內容
下列用途是設定回應結構定義,確保模型輸出內容為具有下列屬性的 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] }
如果提示詞是「Alice and Bob are going to a science fair on Friday」, 模型可能會產生以下回覆:
{
"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')
]
)
取得 JSON 物件回應
您可以將 response_format
欄位設為 { "type": "json_object" }
,限制模型只輸出語法有效的 JSON 物件。這通常稱為「JSON 模式」。如果需要產生 JSON,以用於函式呼叫或其他需要 JSON 輸入的下游工作,JSON 模式就非常實用。
啟用 JSON 模式後,模型只會產生可剖析為有效 JSON 物件的字串。雖然這個模式可確保輸出內容是語法正確的 JSON,但不會強制使用任何特定結構定義。如要確保模型輸出符合特定結構定義的 JSON,請務必在提示中加入指示,如下列範例所示。
下列範例說明如何啟用 JSON 模式,並指示模型傳回特定結構的 JSON 物件:
Python
在試用這個範例之前,請先按照Python使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Python API 參考說明文件。
如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
執行這個範例前,請務必設定 OPENAI_BASE_URL
環境變數。
詳情請參閱「驗證和憑證」。
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="MODEL", response_format={ "type": "json_object" }, messages=[ {"role": "user", "content": "List 5 rivers in South America. Your response must be a JSON object with a single key \"rivers\", which has a list of strings as its value."}, ] ) print(response.choices[0].message.content)
將 MODEL
替換為要使用的模型名稱,例如 meta/llama3-405b-instruct-maas
。
REST
設定環境後,即可使用 REST 測試文字提示。下列範例會將要求傳送至發布商模型端點。
使用任何要求資料之前,請先替換以下項目:
- PROJECT_ID:您的 Google Cloud 專案 ID。
- LOCATION:支援開放式模型的區域。
- MODEL:要使用的模型名稱,例如
meta/llama3-405b-instruct-maas
。
HTTP 方法和網址:
POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions
JSON 要求主體:
{ "model": "MODEL", "response_format": { "type": "json_object" }, "messages": [ { "role": "user", "content": "List 5 rivers in South America. Your response must be a JSON object with a single key \"rivers\", which has a list of strings as its value." } ] }
如要傳送要求,請選擇以下其中一個選項:
curl
將要求主體儲存在名為 request.json
的檔案中,然後執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions"
PowerShell
將要求主體儲存在名為 request.json
的檔案中,然後執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions" | Select-Object -Expand Content
您應該會收到類似如下的 JSON 回應。