제어 생성

모델에서 생성된 출력이 항상 특정 스키마를 준수하도록 보장하여 일관된 형식의 대답을 받을 수 있습니다. 예를 들어 다른 태스크에 사용하는 기존 데이터 스키마가 있을 수 있습니다. 모델이 같은 스키마를 따르는 경우 후처리 없이 모델 출력에서 데이터를 직접 추출할 수 있습니다.

모델 출력 구조를 지정하려면 모델 대답 청사진처럼 작동하는 응답 스키마를 정의합니다. 프롬프트를 제출하고 응답 스키마를 포함하면 모델 응답이 항상 정의된 스키마를 따릅니다.

다음 모델을 사용할 때 생성된 출력을 제어할 수 있습니다.

사용 사례

응답 스키마를 적용하는 한 가지 사용 사례는 모델의 응답이 유효한 JSON을 생성하고 스키마를 준수하도록 하는 것입니다. 생성 모델 출력은 어느 정도 가변적일 수 있으므로 응답 스키마를 포함하면 항상 유효한 JSON을 수신할 수 있습니다. 따라서 다운스트림 태스크는 생성된 응답에서 유효한 JSON 입력을 안정적으로 기대할 수 있습니다.

또 다른 예시로는 모델이 응답하는 방식을 제한하는 것입니다. 예를 들어 모델이 모델에서 생성하는 라벨이 아닌 사용자 정의 라벨로 텍스트에 주석을 달 수 있습니다. 이 제약 조건은 positive 또는 negative와 같은 특정 라벨 세트를 예상하고 모델에서 생성할 수 있는 다른 라벨(예: good, positive, negative, bad)이 혼합되어 표시되지 않게 하려는 경우에 유용합니다.

고려사항

다음 고려사항에서는 응답 스키마를 사용할 경우의 잠재적 제한사항을 설명합니다.

  • API를 사용하여 응답 스키마를 정의하고 사용해야 합니다. 콘솔 지원은 없습니다.
  • 응답 스키마 크기는 입력 토큰 한도에 반영됩니다.
  • application/json 또는 text/x.enum과 같은 특정 출력 형식만 지원됩니다. 자세한 내용은 Gemini API 참조responseMimeType 파라미터를 참조하세요.
  • 제어된 생성은 Vertex AI 스키마 참조 하위 집합을 지원합니다. 자세한 내용은 지원되는 스키마 필드를 참조하세요.
  • 복잡한 스키마로 인해 InvalidArgument: 400 오류가 발생할 수 있습니다. 복잡성은 긴 속성 이름, 긴 배열 길이 제한, 값이 많은 enum, 선택적 속성이 많은 객체 또는 이러한 요소의 조합에서 비롯될 수 있습니다.

    유효한 스키마로 이 오류가 발생하면 다음 중 하나 이상을 변경하여 오류를 해결합니다.

    • 속성 이름이나 enum 이름을 줄입니다.
    • 중첩된 배열을 평탄화합니다.
    • 최저 한도 및 최대 한도가 있는 숫자와 같이 제약 조건이 있는 속성 수를 줄입니다.
    • date-time과 같이 형식이 복잡한 속성 등 복잡한 제약 조건이 있는 속성 수를 줄입니다.
    • 선택적 속성 수를 줄입니다.
    • enum의 유효한 값 수를 줄입니다.

지원되는 스키마 필드

제어된 생성은 Vertex AI 스키마의 다음 필드를 지원합니다. 지원되지 않는 필드를 사용해도 Vertex AI는 요청을 처리할 수 있지만 필드를 무시합니다.

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

* propertyOrdering은 특히 제어된 생성에 사용되며 Vertex AI 스키마의 일부가 아닙니다. 이 필드는 속성이 생성되는 순서를 정의합니다. 나열된 속성은 고유해야 하며 properties 사전에서 유효한 키여야 합니다.

format 필드의 경우 Vertex AI는 date, date-time, duration, time 값을 지원합니다. 각 값의 설명과 형식은 OpenAPI 이니셔티브 레지스트리에 설명되어 있습니다.

시작하기 전에

응답 스키마를 정의하여 모델 출력 구조, 필드 이름, 각 필드의 예상 데이터 유형을 지정합니다. 고려사항 섹션에 나열된 대로 지원되는 필드만 사용합니다. 다른 모든 필드는 무시됩니다.

응답 스키마를 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=us-central1
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.0-flash-001",
    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",
#     }
# ]

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • GENERATE_RESPONSE_METHOD: 모델에서 생성하려는 응답 유형입니다. 모델의 응답을 반환할 방법을 생성하는 메서드를 선택합니다.
    • streamGenerateContent: 지연 시간에 대한 인식을 줄이기 위해 응답이 생성되는 동안 스트리밍됩니다.
    • generateContent: 응답은 완전히 생성된 후에 반환됩니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • PROJECT_ID: 프로젝트 ID
  • MODEL_ID: 사용할 멀티모달 모델의 모델 ID입니다. 옵션은 다음과 같습니다.
    • gemini-1.5-flash
    • gemini-1.5-pro
  • ROLE: 콘텐츠와 연결된 대화의 역할입니다. 싱글턴 사용 사례에서도 역할을 지정해야 합니다. 허용되는 값은 다음과 같습니다.
    • USER: 전송한 콘텐츠를 지정합니다.
  • TEXT: 프롬프트에 포함할 텍스트 안내입니다.
  • RESPONSE_MIME_TYPE: 생성된 후보 텍스트의 형식 유형입니다. 지원되는 값 목록은 Gemini APIresponseMimeType 파라미터를 참조하세요.
  • RESPONSE_SCHEMA: 응답을 생성할 때 모델이 따라야 하는 스키마입니다. 자세한 내용은 스키마 참조를 확인하세요.

HTTP 메서드 및 URL:

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-1.5-pro"
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 \
-d `@request.json`

JSON 출력 스키마 예시

다음 섹션에서는 다양한 샘플 프롬프트와 응답 스키마를 보여줍니다. 각 코드 샘플 뒤에 샘플 모델 응답도 포함되어 있습니다.

요일별 일기예보

다음 예시에서는 예상 온도 및 습도 수준과 같은 속성 배열이 포함된 요일별 forecast 객체를 출력합니다. 일부 속성은 의미 있는 응답을 생성하기에 충분한 컨텍스트가 없을 때 모델에서 null 값을 반환할 수 있도록 nullable로 설정됩니다. 이 전략은 할루시네이션을 줄이는 데 도움이 됩니다.

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=us-central1
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.0-flash-001",
    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%"}]}

제품 분류

다음 예시에는 모델이 주어진 값 목록에서 객체 유형과 조건을 분류해야 하는 enum이 포함되어 있습니다.

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=us-central1
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.0-flash-001",
    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

이미지에서 객체 식별

다음 예시에서는 Cloud Storage에 저장된 이미지 2개에서 객체를 식별합니다.

Python

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Vertex AI Python API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel, Part

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
vertexai.init(project=PROJECT_ID, location="us-central1")

response_schema = {
    "type": "ARRAY",
    "items": {
        "type": "ARRAY",
        "items": {
            "type": "OBJECT",
            "properties": {
                "object": {"type": "STRING"},
            },
        },
    },
}

model = GenerativeModel("gemini-1.5-pro-002")

response = model.generate_content(
    [
        # Text prompt
        "Generate a list of objects in the images.",
        # Http Image
        Part.from_uri(
            "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/office-desk.jpeg",
            "image/jpeg",
        ),
        # Cloud storage object
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/gardening-tools.jpeg",
            "image/jpeg",
        ),
    ],
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

print(response.text)
# Example response:
# [
#     [
#         {"object": "globe"}, {"object": "tablet"}, {"object": "toy car"},
#         {"object": "airplane"}, {"object": "keyboard"}, {"object": "mouse"},
#         {"object": "passport"}, {"object": "sunglasses"}, {"object": "money"},
#         {"object": "notebook"}, {"object": "pen"}, {"object": "coffee cup"},
#     ],
#     [
#         {"object": "watering can"}, {"object": "plant"}, {"object": "flower pot"},
#         {"object": "gloves"}, {"object": "garden tool"},
#     ],
# ]

모델 응답 예시

candidates {
  content {
    role: "model"
    parts {
      text: "[\n    [\n        {\n            \"object\": \"globe model\"\n        },\n        {\n            \"object\": \"tablet computer\"\n        },\n        {\n            \"object\": \"shopping cart\"\n        },\n        {\n            \"object\": \"Eiffel Tower model\"\n        },\n        {\n            \"object\": \"airplane model\"\n        },\n        {\n            \"object\": \"coffee cup\"\n        },\n        {\n            \"object\": \"computer keyboard\"\n        },\n        {\n            \"object\": \"computer mouse\"\n        },\n        {\n            \"object\": \"passport\"\n        },\n        {\n            \"object\": \"sunglasses\"\n        },\n        {\n            \"object\": \"US Dollar bills\"\n        },\n        {\n            \"object\": \"notepad\"\n        },\n        {\n            \"object\": \"pen\"\n        }\n    ],\n    [\n        {\n            \"object\": \"watering can\"\n        },\n        {\n            \"object\": \"oregano\"\n        },\n        {\n            \"object\": \"flower pot\"\n        },\n        {\n            \"object\": \"flower pot\"\n        },\n        {\n            \"object\": \"gardening gloves\"\n        },\n        {\n            \"object\": \"hand rake\"\n        },\n        {\n            \"object\": \"hand trowel\"\n        },\n        {\n            \"object\": \"grass\"\n        }\n    ]\n] "
    }
  }
  finish_reason: STOP
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
    probability_score: 0.1872812658548355
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.16357900202274323
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: LOW
    probability_score: 0.37920594215393066
    severity: HARM_SEVERITY_LOW
    severity_score: 0.29320207238197327
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
    probability_score: 0.14175598323345184
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.12074951827526093
  }
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
    probability_score: 0.12241825461387634
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.0955180674791336
  }
}
usage_metadata {
  prompt_token_count: 525
  candidates_token_count: 333
  total_token_count: 858
}

Go

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Vertex AI Go API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// controlledGenerationResponseSchema6 shows how to make sure the generated output
// will always be valid JSON and adhere to a specific schema.
func controlledGenerationResponseSchema6(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-pro-001"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	model.GenerationConfig.ResponseMIMEType = "application/json"

	// Build an OpenAPI schema, in memory
	model.GenerationConfig.ResponseSchema = &genai.Schema{
		Type: genai.TypeArray,
		Items: &genai.Schema{
			Type: genai.TypeArray,
			Items: &genai.Schema{
				Type: genai.TypeObject,
				Properties: map[string]*genai.Schema{
					"object": {
						Type: genai.TypeString,
					},
				},
			},
		},
	}

	// These images in Cloud Storage are viewable at
	// https://storage.googleapis.com/cloud-samples-data/generative-ai/image/office-desk.jpeg
	// https://storage.googleapis.com/cloud-samples-data/generative-ai/image/gardening-tools.jpeg

	img1 := genai.FileData{
		MIMEType: "image/jpeg",
		FileURI:  "gs://cloud-samples-data/generative-ai/image/office-desk.jpeg",
	}

	img2 := genai.FileData{
		MIMEType: "image/jpeg",
		FileURI:  "gs://cloud-samples-data/generative-ai/image/gardening-tools.jpeg",
	}

	prompt := "Generate a list of objects in the images."

	res, err := model.GenerateContent(ctx, img1, img2, genai.Text(prompt))
	if err != nil {
		return fmt.Errorf("unable to generate contents: %v", err)
	}

	if len(res.Candidates) == 0 ||
		len(res.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	fmt.Fprint(w, res.Candidates[0].Content.Parts[0])
	return nil
}

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.GenerationConfig;
import com.google.cloud.vertexai.api.Schema;
import com.google.cloud.vertexai.api.Type;
import com.google.cloud.vertexai.generativeai.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;

public class ControlledGenerationSchema6 {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "genai-java-demos";
    String location = "us-central1";
    String modelName = "gemini-1.5-pro-001";

    controlGenerationWithJsonSchema6(projectId, location, modelName);
  }

  // Generate responses that are always valid JSON and comply with a JSON schema
  public static String controlGenerationWithJsonSchema6(
      String projectId, String location, String modelName)
      throws IOException {
    // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) {
      GenerationConfig generationConfig = GenerationConfig.newBuilder()
          .setResponseMimeType("application/json")
          .setResponseSchema(Schema.newBuilder()
              .setType(Type.ARRAY)
              .setItems(Schema.newBuilder()
                  .setType(Type.OBJECT)
                  .putProperties("object", Schema.newBuilder().setType(Type.STRING).build())
                  .build())
              .build())
          .build();

      GenerativeModel model = new GenerativeModel(modelName, vertexAI)
          .withGenerationConfig(generationConfig);

      // These images in Cloud Storage are viewable at
      // https://storage.googleapis.com/cloud-samples-data/generative-ai/image/office-desk.jpeg
      // https://storage.googleapis.com/cloud-samples-data/generative-ai/image/gardening-tools.jpeg

      GenerateContentResponse response = model.generateContent(
          ContentMaker.fromMultiModalData(
              PartMaker.fromMimeTypeAndData("image/jpeg",
                  "gs://cloud-samples-data/generative-ai/image/office-desk.jpeg"),
              PartMaker.fromMimeTypeAndData("image/jpeg",
                  "gs://cloud-samples-data/generative-ai/image/gardening-tools.jpeg"),
              "Generate a list of objects in the images."
          )
      );

      String output = ResponseHandler.getText(response);
      System.out.println(output);
      return output;
    }
  }
}

enum 출력 스키마 예시

다음 예시에서는 설명을 기반으로 영화 장르를 식별합니다. 출력은 모델이 응답 스키마에 정의된 목록 값에서 선택하는 일반 텍스트 enum 값 하나입니다.

Python용 Vertex AI SDK

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python용 Vertex AI SDK API 참조 문서를 확인하세요.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"

vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel("gemini-1.5-pro")

response_schema = {"type": "STRING", "enum": ["drama", "comedy", "documentary"]}

prompt = (
    "The film aims to educate and inform viewers about real-life subjects, events, or people."
    "It offers a factual record of a particular topic by combining interviews, historical footage, "
    "and narration. The primary purpose of a film is to present information and provide insights "
    "into various aspects of reality."
)

response = model.generate_content(
    prompt,
    generation_config=GenerationConfig(
        response_mime_type="text/x.enum", response_schema=response_schema
    ),
)

print(response.text)
# Example response:
#     'documentary'

모델 응답 예시

candidates {
  content {
    role: "model"
    parts {
      text: "documentary"
    }
  }
  finish_reason: STOP
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
    probability_score: 0.051025390625
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.08056640625
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: NEGLIGIBLE
    probability_score: 0.1416015625
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.068359375
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
    probability_score: 0.11572265625
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.0439453125
  }
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
    probability_score: 0.099609375
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.146484375
  }
  avg_logprobs: -8.783838711678982e-05
}
usage_metadata {
  prompt_token_count: 33
  candidates_token_count: 2
  total_token_count: 35
}

Go

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Vertex AI Go API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// controlledGenerationResponseSchemaEnum demonstrates how to constrain model responses
// to a predefined set of enum values for genre classification.
func controlledGenerationResponseSchemaEnum(w io.Writer, projectID, location, modelName string) error {
	// location = "us-central1"
	// modelName = "gemini-1.5-pro-001"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("failed to create GenAI client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	model.GenerationConfig.ResponseMIMEType = "text/x.enum"
	model.GenerationConfig.ResponseSchema = &genai.Schema{
		Type: genai.TypeString,
		Enum: []string{"drama", "comedy", "documentary"},
	}

	prompt := `
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
`

	res, err := model.GenerateContent(ctx, genai.Text(prompt))
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	if len(res.Candidates) == 0 || len(res.Candidates[0].Content.Parts) == 0 {
		return errors.New("got empty response from model")
	}

	fmt.Fprintf(w, "Candidate label: %q", res.Candidates[0].Content.Parts[0])
	// Example response:
	// Candidate label: "documentary"

	return nil
}