構造化出力を使用すると、モデルは常に特定のスキーマを遵守する出力を生成できます。たとえば、レスポンスが有効な JSON を生成するように、モデルにレスポンス スキーマを指定できます。Vertex AI Model as a Service(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')
    ]
)
JSON オブジェクト レスポンスを取得する
response_format フィールドを { "type": "json_object" } に設定すると、構文的に有効な JSON オブジェクトのみを出力するようにモデルを制約できます。これは JSON モードと呼ばれることがよくあります。JSON モードは、関数呼び出しや JSON 入力を必要とする他のダウンストリーム タスクで使用する JSON を生成する場合に便利です。
JSON モードが有効になっている場合、モデルは有効な JSON オブジェクトに解析される文字列のみを生成するように制約されます。このモードでは、出力が構文的に正しい JSON になることが保証されますが、特定のスキーマは適用されません。特定のスキーマに準拠した JSON をモデルが出力するようにするには、次の例に示すように、プロンプトに手順を含める必要があります。
次のサンプルは、JSON モードを有効にして、特定の構造の JSON オブジェクトを返すようにモデルに指示する方法を示しています。
Python
このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、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 メソッドと URL:
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 レスポンスが返されます。