null 값으로 제어된 생성 JSON 출력

의미 있는 응답을 생성하기에 충분한 컨텍스트가 없을 때 모델이 null 응답을 출력하도록 허용합니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

C#

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

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

public async Task<string> GenerateContentWithResponseSchema3(
    string projectId = "your-project-id",
    string location = "us-central1",
    string publisher = "google",
    string model = "gemini-1.5-pro-001")
{

    var predictionServiceClient = new PredictionServiceClientBuilder
    {
        Endpoint = $"{location}-aiplatform.googleapis.com"
    }.Build();

    var responseSchema = new OpenApiSchema
    {
        Type = Type.Object,
        Properties =
        {
            ["forecast"] = new()
            {
                Type = Type.Array,
                Items = new()
                {
                    Type = Type.Object,
                    Properties =
                    {
                        ["Forecast"] = new() { Type = Type.String },
                        ["Humidity"] = new() { Type = Type.String },
                        ["Temperature"] = new() { Type = Type.Integer },
                        ["Wind Speed"] = new() { Type = Type.Integer }
                    }
                }
            }
        }
    };

    string 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 humidity increasing to 55%. 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%. Expect stronger winds at 20 km/h.
    Wednesday may see thunderstorms, with a temperature of 68°F and high humidity of 75%. Winds will be gusty at 25 km/h.
    Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%. Winds will ease slightly to 18 km/h.
    Friday returns to partly cloudy conditions, with a temperature of 73°F and lower humidity at 45%. 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.";

    var generateContentRequest = new GenerateContentRequest
    {
        Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
        Contents =
        {
            new Content
            {
                Role = "USER",
                Parts =
                {
                    new Part { Text = prompt }
                }
            }
        },
        GenerationConfig = new GenerationConfig
        {
            ResponseMimeType = "application/json",
            ResponseSchema = responseSchema
        },
    };

    GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

    string responseText = response.Candidates[0].Content.Parts[0].Text;
    Console.WriteLine(responseText);

    return responseText;
}

Go

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

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

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

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

// controlledGenerationResponseSchema3 shows how to make sure the generated output
// will always be valid JSON and adhere to a specific schema.
func controlledGenerationResponseSchema3(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.TypeObject,
		Properties: map[string]*genai.Schema{
			"forecast": {
				Type: genai.TypeArray,
				Items: &genai.Schema{
					Type: genai.TypeObject,
					Properties: map[string]*genai.Schema{
						"Day": {
							Type: genai.TypeString,
						},
						"Forecast": {
							Type: genai.TypeString,
						},
						"Humidity": {
							Type: genai.TypeString,
						},
						"Temperature": {
							Type: genai.TypeInteger,
						},
						"Wind Speed": {
							Type: genai.TypeInteger,
						},
					},
					Required: []string{"Day", "Temperature", "Forecast"},
				},
			},
		},
	}

	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 humidity increasing to 55%. 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%. Expect stronger winds at 20 km/h.
		Wednesday may see thunderstorms, with a temperature of 68°F and high humidity of 75%. Winds will be gusty at 25 km/h.
		Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%. Winds will ease slightly to 18 km/h.
		Friday returns to partly cloudy conditions, with a temperature of 73°F and lower humidity at 45%. 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.
	`

	res, err := model.GenerateContent(ctx, 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.GenerativeModel;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;
import java.util.Arrays;

public class ControlledGenerationSchema3 {
  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";

    controlGenerationWithJsonSchema3(projectId, location, modelName);
  }

  // Generate responses that are always valid JSON and comply with a JSON schema
  public static String controlGenerationWithJsonSchema3(
      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.OBJECT)
              .putProperties("forecast", Schema.newBuilder()
                      .setType(Type.ARRAY)
                      .setItems(Schema.newBuilder()
                          .setType(Type.OBJECT)
                          .putProperties("Day", Schema.newBuilder()
                              .setType(Type.STRING)
                              .build())
                          .putProperties("Forecast", Schema.newBuilder()
                              .setType(Type.STRING)
                              .build())
                          .putProperties("Humidity", Schema.newBuilder()
                              .setType(Type.STRING)
                              .build())
                          .putProperties("Temperature", Schema.newBuilder()
                              .setType(Type.INTEGER)
                              .build())
                          .putProperties("Wind Speed", Schema.newBuilder()
                              .setType(Type.INTEGER)
                              .build())
                          .addAllRequired(Arrays.asList("Day", "Temperature", "Forecast"))
                          .build())
                      .build())
              )
          .build();

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

      GenerateContentResponse response = model.generateContent(
          "The week ahead brings a mix of weather conditions.\n"
              + "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.\n"
              + "Monday will see partly cloudy skies with a slightly cooler temperature of 72°F "
              + "and humidity increasing to 55%. Winds will pick up slightly to around 15 km/h.\n"
              + "Tuesday brings rain showers, with temperatures dropping to 64°F and humidity"
              + "rising to 70%. Expect stronger winds at 20 km/h.\n"
              + "Wednesday may see thunderstorms, with a temperature of 68°F and high humidity "
              + "of 75%. Winds will be gusty at 25 km/h.\n"
              + "Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%. "
              + "Winds will ease slightly to 18 km/h.\n"
              + "Friday returns to partly cloudy conditions, with a temperature of 73°F and lower "
              + "humidity at 45%. Winds will be light at 12 km/h.\n"
              + "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."
      );

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

Python

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

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

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")

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.
"""

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

response = model.generate_content(
    prompt,
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

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

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.