結構化輸出內容

您可以確保模型產生的輸出內容一律遵循特定結構定義,以便收到格式一致的回應。舉例來說,您可能會建立資料結構定義,用於其他工作。如果模型採用相同的結構定義,您可以直接從模型輸出內容中擷取資料,無需進行任何後置處理。

如要指定模型輸出的結構,請定義回覆結構定義,這類似於模型回覆的藍圖。提交提示並納入回覆結構定義時,模型的回覆一律會遵循您定義的結構定義。

您可以使用下列模型控管產生的輸出內容:

應用實例

套用回應結構定義的用途之一,是確保模型回應會產生有效的 JSON 並符合結構定義。生成式模型輸出內容可能會出現一定程度的變化,因此請加入回應結構定義,確保您一律會收到有效的 JSON。因此,後續工作可確實從產生的回應中取得有效的 JSON 輸入內容。

另一個範例是限制模型的回應方式。舉例來說,您可以讓模型使用使用者定義的標籤標註文字,而非使用模型產生的標籤。當您預期會收到 positivenegative 等特定標籤,且不希望收到模型可能產生的其他標籤 (例如 goodpositivenegativebad) 時,這項限制就很實用。

注意事項

以下是使用回應結構定義時的考量事項,其中討論了可能的限制:

  • 您必須使用 API 定義及使用回應結構定義。不支援控制台。
  • 回應結構定義的大小會計入輸入符記限制。
  • 僅支援特定輸出格式,例如 application/jsontext/x.enum。詳情請參閱 Gemini API 參考資料中的 responseMimeType 參數。
  • 結構化輸出支援 Vertex AI 結構定義參考資料的子集。詳情請參閱「支援的結構定義欄位」。
  • 複雜的結構定義可能會導致 InvalidArgument: 400 錯誤。複雜度可能來自長的屬性名稱、長的陣列長度限制、具有許多值的列舉、具有許多選用屬性的物件,或這些因素的組合。

    如果您在使用有效結構定義時收到這項錯誤,請進行下列一或多項變更來解決錯誤:

    • 縮短屬性名稱或列舉名稱。
    • 展開巢狀陣列。
    • 減少含有限制的屬性數量,例如設有最小值和最大值限制的數字。
    • 減少具有複雜限制的屬性數量,例如具有 date-time 等複雜格式的屬性。
    • 減少選用屬性數量。
    • 減少列舉的有效值數量。

支援的結構定義欄位

結構化輸出支援 Vertex AI 結構定義中的下列欄位。如果您使用不支援的欄位,Vertex AI 仍可處理要求,但會忽略該欄位。

  • anyOf
  • enum
  • format
  • items
  • maximum
  • maxItems
  • minimum
  • minItems
  • nullable
  • properties
  • propertyOrdering*
  • required

* propertyOrdering 專供結構化輸出使用,並非 Vertex AI 結構定義的一部分。這個欄位會定義產生屬性的順序。列出的屬性不得重複,且必須是 properties 字典中的有效鍵。

Vertex AI 支援以下 format 欄位值:datedate-timedurationtime。每個值的說明和格式請參閱 OpenAPI Initiative Registry

事前準備

定義回覆結構定義,指定模型輸出的結構、欄位名稱,以及每個欄位的預期資料類型。請只使用「注意事項」一節中列出的支援欄位。系統會忽略其他所有欄位。

請僅在 responseSchema 欄位中加入回應結構定義。請勿在輸入提示中重複架構。否則,產生的輸出內容可能品質較低。

如需結構定義範例,請參閱「結構定義和模型回應範例」一節。

模型行為和回應結構定義

模型產生回覆時,會使用提示中的欄位名稱和脈絡。因此,建議您使用明確的結構和不含歧義的欄位名稱,以便清楚表達意圖。

根據預設,欄位為選填,也就是說模型可以填入欄位或略過欄位。您可以將欄位設為必填,強制模型提供值。如果相關輸入提示的脈絡資訊不足,模型會根據訓練資料產生回覆。

如果未顯示預期結果,請在輸入提示中加入更多背景資訊,或修改回應結構定義。例如,查看模型的回覆內容,瞭解模型如何回應,接著,您可以更新回應結構定義,以便更符合模型的輸出內容。

傳送含有回覆結構定義的提示

根據預設,所有欄位均為選填欄位,也就是說模型可能會針對某個欄位產生回覆。如要強制模型一律針對欄位產生回覆,請將欄位設為必填欄位。

Gen AI SDK for Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions

response_schema = {
    "type": "ARRAY",
    "items": {
        "type": "OBJECT",
        "properties": {
            "recipe_name": {"type": "STRING"},
            "ingredients": {"type": "ARRAY", "items": {"type": "STRING"}},
        },
        "required": ["recipe_name", "ingredients"],
    },
}

prompt = """
    List a few popular cookie recipes.
"""

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=prompt,
    config={
        "response_mime_type": "application/json",
        "response_schema": response_schema,
    },
)

print(response.text)
# Example output:
# [
#     {
#         "ingredients": [
#             "2 1/4 cups all-purpose flour",
#             "1 teaspoon baking soda",
#             "1 teaspoon salt",
#             "1 cup (2 sticks) unsalted butter, softened",
#             "3/4 cup granulated sugar",
#             "3/4 cup packed brown sugar",
#             "1 teaspoon vanilla extract",
#             "2 large eggs",
#             "2 cups chocolate chips",
#         ],
#         "recipe_name": "Chocolate Chip Cookies",
#     }
# ]

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for Go

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithRespSchema shows how to use a response schema to generate output in a specific format.
func generateWithRespSchema(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	config := &genai.GenerateContentConfig{
		ResponseMIMEType: "application/json",
		// See the OpenAPI specification for more details and examples:
		//   https://spec.openapis.org/oas/v3.0.3.html#schema-object
		ResponseSchema: &genai.Schema{
			Type: "array",
			Items: &genai.Schema{
				Type: "object",
				Properties: map[string]*genai.Schema{
					"recipe_name": {Type: "string"},
					"ingredients": {
						Type:  "array",
						Items: &genai.Schema{Type: "string"},
					},
				},
				Required: []string{"recipe_name", "ingredients"},
			},
		},
	}
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "List a few popular cookie recipes."},
		}},
	}
	modelName := "gemini-2.0-flash-001"

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

	// Example response:
	// [
	//   {
	//     "ingredients": [
	//       "2 1/4 cups all-purpose flour",
	//       "1 teaspoon baking soda",
	//       ...
	//     ],
	//     "recipe_name": "Chocolate Chip Cookies"
	//   },
	//   {
	//     ...
	//   },
	//   ...
	// ]

	return nil
}

REST

使用任何要求資料之前,請先替換以下項目:

  • GENERATE_RESPONSE_METHOD:您希望模型產生的回應類型。選擇一種方法,讓模型產生所需的回覆:
    • streamGenerateContent:回應會在產生時串流傳輸,以減少使用者感知的延遲時間。
    • generateContent:回應會在完全產生後傳回。
  • LOCATION:處理要求的區域。
  • PROJECT_ID:您的專案 ID
  • MODEL_ID:您要使用的多模態模型的模型 ID。
  • ROLE:與內容相關聯的對話中角色。即使是單轉使用情境,也必須指定角色。可接受的值包括:
    • USER:指定您傳送的內容。
  • TEXT:提示中要納入的文字指示。
  • RESPONSE_MIME_TYPE:產生的候選文字格式類型。如需支援的值清單,請參閱 Gemini API 中的 responseMimeType 參數。
  • RESPONSE_SCHEMA:產生回應時,模型應遵循的結構定義。詳情請參閱 Schema 參考資料。

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD

JSON 要求主體:

{
  "contents": {
    "role": "ROLE",
    "parts": {
      "text": "TEXT"
    }
  },
  "generation_config": {
    "responseMimeType": "RESPONSE_MIME_TYPE",
    "responseSchema": RESPONSE_SCHEMA,
  }
}

如要傳送要求,請選擇以下其中一個選項:

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/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

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/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

您應該會收到類似以下的 JSON 回應。

curl 指令範例

LOCATION="us-central1"
MODEL_ID="gemini-2.0-flash"
PROJECT_ID="test-project"
GENERATE_RESPONSE_METHOD="generateContent"

cat << EOF > request.json
{
  "contents": {
    "role": "user",
    "parts": {
      "text": "List a few popular cookie recipes."
    }
  },
  "generation_config": {
    "maxOutputTokens": 2048,
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "recipe_name": {
            "type": "string",
          },
        },
        "required": ["recipe_name"],
      },
    }
  }
}
EOF

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:${GENERATE_RESPONSE_METHOD} \
-d '@request.json'

JSON 輸出內容的結構定義範例

以下各節將示範各種提示和回應結構定義。每個程式碼範例後方也會附上模型回應範例。

預測一週每天的天氣

以下範例會針對每週的每一天輸出 forecast 物件,其中包含一組屬性,例如當天的預期溫度和濕度等級。部分屬性會設為可為空值,因此當模型沒有足夠的背景資訊來產生有意義的回應時,可以傳回空值。這項策略有助於減少幻覺。

Gen AI SDK for Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions

response_schema = {
    "type": "OBJECT",
    "properties": {
        "forecast": {
            "type": "ARRAY",
            "items": {
                "type": "OBJECT",
                "properties": {
                    "Day": {"type": "STRING", "nullable": True},
                    "Forecast": {"type": "STRING", "nullable": True},
                    "Temperature": {"type": "INTEGER", "nullable": True},
                    "Humidity": {"type": "STRING", "nullable": True},
                    "Wind Speed": {"type": "INTEGER", "nullable": True},
                },
                "required": ["Day", "Temperature", "Forecast", "Wind Speed"],
            },
        }
    },
}

prompt = """
    The week ahead brings a mix of weather conditions.
    Sunday is expected to be sunny with a temperature of 77°F and a humidity level of 50%. Winds will be light at around 10 km/h.
    Monday will see partly cloudy skies with a slightly cooler temperature of 72°F and the winds will pick up slightly to around 15 km/h.
    Tuesday brings rain showers, with temperatures dropping to 64°F and humidity rising to 70%.
    Wednesday may see thunderstorms, with a temperature of 68°F.
    Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%.
    Friday returns to partly cloudy conditions, with a temperature of 73°F and the Winds will be light at 12 km/h.
    Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
"""

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=prompt,
    config=GenerateContentConfig(
        response_mime_type="application/json",
        response_schema=response_schema,
    ),
)

print(response.text)
# Example output:
# {"forecast": [{"Day": "Sunday", "Forecast": "sunny", "Temperature": 77, "Wind Speed": 10, "Humidity": "50%"},
#   {"Day": "Monday", "Forecast": "partly cloudy", "Temperature": 72, "Wind Speed": 15},
#   {"Day": "Tuesday", "Forecast": "rain showers", "Temperature": 64, "Wind Speed": null, "Humidity": "70%"},
#   {"Day": "Wednesday", "Forecast": "thunderstorms", "Temperature": 68, "Wind Speed": null},
#   {"Day": "Thursday", "Forecast": "cloudy", "Temperature": 66, "Wind Speed": null, "Humidity": "60%"},
#   {"Day": "Friday", "Forecast": "partly cloudy", "Temperature": 73, "Wind Speed": 12},
#   {"Day": "Saturday", "Forecast": "sunny", "Temperature": 80, "Wind Speed": 8, "Humidity": "40%"}]}

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for Go

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithNullables shows how to use the response schema with nullable values.
func generateWithNullables(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	prompt := `
The week ahead brings a mix of weather conditions.
Sunday is expected to be sunny with a temperature of 77°F and a humidity level of 50%. Winds will be light at around 10 km/h.
Monday will see partly cloudy skies with a slightly cooler temperature of 72°F and the winds will pick up slightly to around 15 km/h.
Tuesday brings rain showers, with temperatures dropping to 64°F and humidity rising to 70%.
Wednesday may see thunderstorms, with a temperature of 68°F.
Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%.
Friday returns to partly cloudy conditions, with a temperature of 73°F and the Winds will be light at 12 km/h.
Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
`
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: prompt},
		}},
	}
	config := &genai.GenerateContentConfig{
		ResponseMIMEType: "application/json",
		// See the OpenAPI specification for more details and examples:
		//   https://spec.openapis.org/oas/v3.0.3.html#schema-object
		ResponseSchema: &genai.Schema{
			Type: "object",
			Properties: map[string]*genai.Schema{
				"forecast": {
					Type: "array",
					Items: &genai.Schema{
						Type: "object",
						Properties: map[string]*genai.Schema{
							"Day":         {Type: "string", Nullable: true},
							"Forecast":    {Type: "string", Nullable: true},
							"Temperature": {Type: "integer", Nullable: true},
							"Humidity":    {Type: "string", Nullable: true},
							"Wind Speed":  {Type: "integer", Nullable: true},
						},
						Required: []string{"Day", "Temperature", "Forecast", "Wind Speed"},
					},
				},
			},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

	// Example response:
	// {
	// 	"forecast": [
	// 		{"Day": "Sunday", "Forecast": "Sunny", "Temperature": 77, "Wind Speed": 10, "Humidity": "50%"},
	// 		{"Day": "Monday", "Forecast": "Partly Cloudy", "Temperature": 72, "Wind Speed": 15},
	// 		{"Day": "Tuesday", "Forecast": "Rain Showers", "Temperature": 64, "Wind Speed": null, "Humidity": "70%"},
	// 		{"Day": "Wednesday", "Forecast": "Thunderstorms", "Temperature": 68, "Wind Speed": null},
	// 		{"Day": "Thursday", "Forecast": "Cloudy", "Temperature": 66, "Wind Speed": null, "Humidity": "60%"},
	// 		{"Day": "Friday", "Forecast": "Partly Cloudy", "Temperature": 73, "Wind Speed": 12},
	// 		{"Day": "Saturday", "Forecast": "Sunny", "Temperature": 80, "Wind Speed": 8, "Humidity": "40%"}
	// 	]
	// }

	return nil
}

分類產品

以下範例包含列舉,其中模型必須從指定值清單中分類物件的類型和狀態。

Gen AI SDK for Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What type of instrument is an oboe?",
    config=GenerateContentConfig(
        response_mime_type="text/x.enum",
        response_schema={
            "type": "STRING",
            "enum": ["Percussion", "String", "Woodwind", "Brass", "Keyboard"],
        },
    ),
)

print(response.text)
# Example output:
# Woodwind

Gen AI SDK for Go

瞭解如何安裝或更新 Gen AI SDK for Go

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithEnumSchema shows how to use enum schema to generate output.
func generateWithEnumSchema(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What type of instrument is an oboe?"},
		}},
	}
	config := &genai.GenerateContentConfig{
		ResponseMIMEType: "text/x.enum",
		ResponseSchema: &genai.Schema{
			Type: "STRING",
			Enum: []string{"Percussion", "String", "Woodwind", "Brass", "Keyboard"},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

	// Example response:
	// Woodwind

	return nil
}

Gen AI SDK for Node.js

安裝

npm install @google/genai

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

const {GoogleGenAI, Type} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const ai = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const responseSchema = {
    type: Type.STRING,
    enum: ['Percussion', 'String', 'Woodwind', 'Brass', 'Keyboard'],
  };

  const response = await ai.models.generateContent({
    model: 'gemini-2.0-flash',
    contents: 'What type of instrument is an oboe?',
    config: {
      responseMimeType: 'text/x.enum',
      responseSchema: responseSchema,
    },
  });

  console.log(response.text);

  return response.text;
}

Gen AI SDK for Java

瞭解如何安裝或更新 Gen AI SDK for Java

詳情請參閱 SDK 參考說明文件

設定環境變數,以便在 Vertex AI 中使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import java.util.List;

public class GenerateContentWithEnumSchema {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String contents = "What type of instrument is an oboe?";
    String modelId = "gemini-2.0-flash";
    generateContent(modelId, contents);
  }

  public static String generateContent(String modelId, String contents) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client = Client.builder()
        .httpOptions(HttpOptions.builder().apiVersion("v1").build())
        .build()) {

      // Define the response schema with an enum.
      Schema responseSchema =
          Schema.builder()
              .type(Type.Known.STRING)
              .enum_(
                  List.of("Percussion", "String", "Woodwind", "Brass", "Keyboard"))
              .build();

      GenerateContentConfig config = GenerateContentConfig.builder()
          .responseMimeType("text/x.enum")
          .responseSchema(responseSchema)
          .build();

      GenerateContentResponse response =
          client.models.generateContent(modelId, contents, config);

      System.out.print(response.text());
      // Example response:
      // Woodwind
      return response.text();
    }
  }
}