Sortie JSON de génération contrôlée avec énumération

Affiche un objet au format JSON avec une valeur d'énumération, en fonction d'une description de l'objet et d'une liste de valeurs à choisir.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C#

Avant d'essayer cet exemple, suivez les instructions de configuration pour C# décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI C#.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

public async Task<string> GenerateContentWithResponseSchema4(
    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.Array,
        Items = new()
        {
            Type = Type.Object,
            Properties =
            {
                ["to_discard"] = new() { Type = Type.Integer },
                ["subcategory"] = new() { Type = Type.String },
                ["safe_handling"] = new() { Type = Type.Integer },
                ["item_category"] = new()
                {
                    Type = Type.String,
                    Enum =
                    {
                        "clothing",
                        "winter apparel",
                        "specialized apparel",
                        "furniture",
                        "decor",
                        "tableware",
                        "cookware",
                        "toys"
                    }
                },
                ["for_resale"] = new() { Type = Type.Integer },
                ["condition"] = new()
                {
                    Type = Type.String,
                    Enum =
                    {
                        "new in package",
                        "like new",
                        "gently used",
                        "used",
                        "damaged",
                        "soiled"
                    }
                }
            }
        }
    };

    string prompt = @"
        Item description:
        The item is a long winter coat that has many tears all around the seams and is falling apart.
        It has large questionable stains on it.";

    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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Go décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI Go.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

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

// controlledGenerationResponseSchema4 shows how to make sure the generated output
// will always be valid JSON and adhere to a specific schema.
func controlledGenerationResponseSchema4(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.TypeObject,
			Properties: map[string]*genai.Schema{
				"to_discard":    {Type: genai.TypeInteger},
				"subcategory":   {Type: genai.TypeString},
				"safe_handling": {Type: genai.TypeString},
				"item_category": {
					Type: genai.TypeString,
					Enum: []string{
						"clothing",
						"winter apparel",
						"specialized apparel",
						"furniture",
						"decor",
						"tableware",
						"cookware",
						"toys",
					},
				},
				"for_resale": {Type: genai.TypeInteger},
				"condition": {
					Type: genai.TypeString,
					Enum: []string{
						"new in package",
						"like new",
						"gently used",
						"used",
						"damaged",
						"soiled",
					},
				},
			},
		},
	}

	prompt := `
		Item description:
		The item is a long winter coat that has many tears all around the seams and is falling apart.
		It has large questionable stains on it.
	`

	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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI Java.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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 ControlledGenerationSchema4 {
  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";

    controlGenerationWithJsonSchema4(projectId, location, modelName);
  }

  // Generate responses that are always valid JSON and comply with a JSON schema
  public static String controlGenerationWithJsonSchema4(
      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)) {
      Schema itemSchema = Schema.newBuilder()
          .setType(Type.OBJECT)
          .putProperties("to_discard", Schema.newBuilder().setType(Type.INTEGER).build())
          .putProperties("subcategory", Schema.newBuilder().setType(Type.STRING).build())
          .putProperties("safe_handling", Schema.newBuilder().setType(Type.INTEGER).build())
          .putProperties("item_category", Schema.newBuilder()
              .setType(Type.STRING)
              .addAllEnum(Arrays.asList(
                  "clothing", "winter apparel", "specialized apparel", "furniture",
                  "decor", "tableware", "cookware", "toys"))
              .build())
          .putProperties("for_resale", Schema.newBuilder().setType(Type.INTEGER).build())
          .putProperties("condition", Schema.newBuilder()
              .setType(Type.STRING)
              .addAllEnum(Arrays.asList(
                  "new in package", "like new", "gently used", "used", "damaged", "soiled"))
              .build())
          .build();

      GenerationConfig generationConfig = GenerationConfig.newBuilder()
          .setResponseMimeType("application/json")
          .setResponseSchema(Schema.newBuilder()
              .setType(Type.ARRAY)
              .setItems(itemSchema)
              .build())
          .build();

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

      GenerateContentResponse response = model.generateContent(
          "Item description:\n"
              + "The item is a long winter coat that has many tears all around the seams "
              + "and is falling apart.\n"
              + "It has large questionable stains on it."
      );

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

Python

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI Python.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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": "ARRAY",
    "items": {
        "type": "OBJECT",
        "properties": {
            "to_discard": {"type": "INTEGER"},
            "subcategory": {"type": "STRING"},
            "safe_handling": {"type": "INTEGER"},
            "item_category": {
                "type": "STRING",
                "enum": [
                    "clothing",
                    "winter apparel",
                    "specialized apparel",
                    "furniture",
                    "decor",
                    "tableware",
                    "cookware",
                    "toys",
                ],
            },
            "for_resale": {"type": "INTEGER"},
            "condition": {
                "type": "STRING",
                "enum": [
                    "new in package",
                    "like new",
                    "gently used",
                    "used",
                    "damaged",
                    "soiled",
                ],
            },
        },
    },
}

prompt = """
    Item description:
    The item is a long winter coat that has many tears all around the seams and is falling apart.
    It has large questionable stains on it.
"""

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:
# [
#     {
#         "condition": "damaged",
#         "item_category": "clothing",
#         "subcategory": "winter apparel",
#         "to_discard": 123,
#     }
# ]

Étape suivante

Pour rechercher et filtrer des exemples de code pour d'autres Google Cloud produits, consultez l'explorateur d'exemplesGoogle Cloud .