Output strutturato

Puoi garantire che l'output generato da un modello rispetti sempre uno schema specifico in modo da ricevere risposte formattate in modo coerente. Ad esempio, potresti avere uno schema di dati consolidato che utilizzi per altre attività. Se il modello segue lo stesso schema, puoi estrarre direttamente i dati dall'output del modello senza alcuna post-elaborazione.

Per specificare la struttura dell'output di un modello, definisci uno schema di risposta, che funziona come un progetto per le risposte del modello. Quando invii un prompt e includi lo schema di risposta, la risposta del modello segue sempre lo schema che hai definito.

Puoi controllare l'output generato quando utilizzi i seguenti modelli:

Per i modelli aperti, segui questa guida per l'utente.

Esempi di casi d'uso

Un caso d'uso per l'applicazione di uno schema di risposta è garantire che la risposta di un modello produca un JSON valido e sia conforme allo schema. Gli output del modello generativo possono avere un certo grado di variabilità, quindi l'inclusione di uno schema di risposta garantisce di ricevere sempre un JSON valido. Di conseguenza, le attività downstream possono prevedere in modo affidabile un input JSON valido dalle risposte generate.

Un altro esempio è limitare il modo in cui un modello può rispondere. Ad esempio, puoi chiedere a un modello di annotare il testo con etichette definite dall'utente, non con etichette prodotte dal modello. Questo vincolo è utile quando prevedi un insieme specifico di etichette, ad esempio positive o negative, e non vuoi ricevere un mix di altre etichette che il modello potrebbe generare, come good, positive, negative o bad.

Considerazioni

Le seguenti considerazioni riguardano le potenziali limitazioni se prevedi di utilizzare uno schema di risposta:

  • Devi utilizzare l'API per definire e utilizzare uno schema di risposta. Non è disponibile il supporto per le console.
  • Le dimensioni dello schema di risposta vengono conteggiate ai fini del limite di token di input.
  • Sono supportati solo determinati formati di output, ad esempio application/json o text/x.enum. Per ulteriori informazioni, consulta il parametro responseMimeType nel riferimento API Gemini.
  • L'output strutturato supporta un sottoinsieme del riferimento allo schema Vertex AI. Per maggiori informazioni, vedi Campi dello schema supportati.
  • Uno schema complesso può generare un errore InvalidArgument: 400. La complessità potrebbe derivare da nomi di proprietà lunghi, limiti di lunghezza degli array lunghi, enumerazioni con molti valori, oggetti con molte proprietà facoltative o una combinazione di questi fattori.

    Se ricevi questo errore con uno schema valido, apporta una o più delle seguenti modifiche per risolverlo:

    • Abbreviare i nomi delle proprietà o degli enum.
    • Appiattisci gli array nidificati.
    • Riduci il numero di proprietà con vincoli, ad esempio numeri con limiti minimi e massimi.
    • Riduci il numero di proprietà con vincoli complessi, ad esempio proprietà con formati complessi come date-time.
    • Riduci il numero di proprietà facoltative.
    • Riduci il numero di valori validi per le enumerazioni.

Campi dello schema supportati

L'output strutturato supporta i seguenti campi dello schema Vertex AI. Se utilizzi un campo non supportato, Vertex AI può comunque gestire la tua richiesta, ma ignora il campo.

  • anyOf
  • enum: sono supportati solo gli enum string
  • format
  • items
  • maximum
  • maxItems
  • minimum
  • minItems
  • nullable
  • properties
  • propertyOrdering*
  • required

* propertyOrdering è specifico per l'output strutturato e non fa parte dello schema Vertex AI. Questo campo definisce l'ordine in cui vengono generate le proprietà. Le proprietà elencate devono essere univoche e devono essere chiavi valide nel dizionario properties.

Per il campo format, Vertex AI supporta i seguenti valori: date, date-time, duration e time. La descrizione e il formato di ogni valore sono descritti nel registro dell'OpenAPI Initiative.

Prima di iniziare

Definisci uno schema di risposta per specificare la struttura dell'output di un modello, i nomi dei campi e il tipo di dati previsto per ogni campo. Utilizza solo i campi supportati elencati nella sezione Considerazioni. Tutti gli altri campi vengono ignorati.

Includi lo schema della risposta solo nel campo responseSchema. Non duplicare lo schema nel prompt di input. In questo caso, l'output generato potrebbe essere di qualità inferiore.

Per gli schemi di esempio, consulta la sezione Schemi di esempio e risposte del modello.

Comportamento del modello e schema di risposta

Quando un modello genera una risposta, utilizza il nome del campo e il contesto del prompt. Pertanto, ti consigliamo di utilizzare una struttura chiara e nomi di campi univoci in modo che l'intent sia chiaro.

Per impostazione predefinita, i campi sono facoltativi, il che significa che il modello può compilarli o saltarli. Puoi impostare i campi come obbligatori per forzare il modello a fornire un valore. Se il prompt di input associato non fornisce un contesto sufficiente, il modello genera risposte basate principalmente sui dati su cui è stato addestrato.

Se non vedi i risultati che ti aspetti, aggiungi più contesto ai prompt di input o rivedi lo schema di risposta. Ad esempio, esamina la risposta del modello senza output strutturato per vedere come risponde il modello. Puoi quindi aggiornare lo schema di risposta in modo che si adatti meglio all'output del modello.

Inviare un prompt con uno schema di risposta

Per impostazione predefinita, tutti i campi sono facoltativi, il che significa che un modello potrebbe generare una risposta a un campo. Per forzare il modello a generare sempre una risposta a un campo, imposta il campo come obbligatorio.

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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",
#     }
# ]

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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."},
		},
			Role: "user"},
	}
	modelName := "gemini-2.5-flash"

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

	respText := resp.Text()

	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

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • GENERATE_RESPONSE_METHOD: il tipo di risposta che vuoi che il modello generi. Scegli un metodo che generi la modalità di restituzione della risposta del modello:
    • streamGenerateContent: La risposta viene trasmessa in streaming durante la generazione per ridurre la percezione della latenza per il pubblico umano.
    • generateContent: la risposta viene restituita dopo essere stata generata completamente.
  • LOCATION: la regione in cui elaborare la richiesta.
  • PROJECT_ID: il tuo ID progetto
  • MODEL_ID: L'ID modello del modello multimodale che vuoi utilizzare.
  • ROLE: Il ruolo in una conversazione associata ai contenuti. La specifica di un ruolo è obbligatoria anche nei casi d'uso a singolo turno. I valori accettabili includono:
    • USER: specifica i contenuti inviati da te.
  • TEXT: Le istruzioni di testo da includere nel prompt.
  • RESPONSE_MIME_TYPE: Il tipo di formato del testo candidato generato. Per un elenco dei valori supportati, consulta il parametro responseMimeType nell'API Gemini.
  • RESPONSE_SCHEMA: Schema che il modello deve seguire durante la generazione delle risposte. Per saperne di più, consulta la documentazione di riferimento sullo schema.

Metodo HTTP e URL:

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

Corpo JSON della richiesta:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, ed esegui questo comando:

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

Salva il corpo della richiesta in un file denominato request.json, ed esegui questo comando:

$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

Dovresti ricevere una risposta JSON simile alla seguente.

Comando curl di esempio

LOCATION="us-central1"
MODEL_ID="gemini-2.5-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'

Esempi di schemi per l'output JSON

Le sezioni seguenti mostrano una serie di prompt di esempio e schemi di risposta. Dopo ogni esempio di codice è inclusa anche una risposta di esempio del modello.

Effettua previsioni meteo per ogni giorno della settimana

L'esempio seguente restituisce un oggetto forecast per ogni giorno della settimana, che include un array di proprietà come la temperatura e il livello di umidità previsti per il giorno. Alcune proprietà sono impostate su Nullable in modo che il modello possa restituire un valore nullo quando non dispone di un contesto sufficiente per generare una risposta significativa. Questa strategia aiuta a ridurre le allucinazioni.

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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%"}]}

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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.5-flash"
	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},
		},
			Role: "user"},
	}
	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: genai.Ptr(true)},
							"Forecast":    {Type: "string", Nullable: genai.Ptr(true)},
							"Temperature": {Type: "integer", Nullable: genai.Ptr(true)},
							"Humidity":    {Type: "string", Nullable: genai.Ptr(true)},
							"Wind Speed":  {Type: "integer", Nullable: genai.Ptr(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 := resp.Text()

	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
}

Classifica un prodotto

L'esempio seguente include enumerazioni in cui il modello deve classificare il tipo e le condizioni di un oggetto da un elenco di valori specificati.

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What type of instrument is an oboe?"},
		}, Role: "user"},
	}
	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 := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// Woodwind

	return nil
}

Node.js

Installa

npm install @google/genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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.5-flash',
    contents: 'What type of instrument is an oboe?',
    config: {
      responseMimeType: 'text/x.enum',
      responseSchema: responseSchema,
    },
  });

  console.log(response.text);

  return response.text;
}

Java

Scopri come installare o aggiornare Java.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# 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 ControlledGenerationWithEnumSchema {

  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.5-flash";
    generateContent(modelId, contents);
  }

  // Generates content with an enum response schema
  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()
            .location("global")
            .vertexAI(true)
            .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();
    }
  }
}