API di grounding

Nell'AI generativa, il grounding è la capacità di collegare l'output del modello a fonti di informazione verificabili. Se fornisci ai modelli l'accesso a origini dati specifiche, il grounding collega il loro output a questi dati e riduce le probabilità di inventare contenuti.

Con Vertex AI, puoi basare gli output del modello nei seguenti modi:

  • Grounding con Ricerca Google: basa un modello con dati web disponibili pubblicamente.
  • Grounding con Google Maps: basa un modello con dati geospaziali di Google Maps.
  • Grounding con i tuoi dati: basa un modello con i tuoi dati di Agent Search come datastore.

Per saperne di più sul grounding, consulta la Panoramica del grounding.

Modelli supportati

Elenco dei parametri

Consulta gli esempi per i dettagli di implementazione.

googleSearch

Basa la risposta sui dati web disponibili pubblicamente di Ricerca Google.

googleMaps

Basa la risposta sui dati geospaziali disponibili pubblicamente di Google Maps.

L'input dell'API include il seguente parametro:

Parametro di input

enable_widget

Obbligatorio: boolean

Flag che può essere impostato su true o false. Un valore true restituisce un token utilizzando la risposta dell'API che puoi utilizzare con l'interfaccia utente del widget di contesto di Google Maps.

La struttura della risposta dell'API include il seguente parametro:

Parametro di risposta

grounding_metadata

Obbligatorio: Object

Il campo principale che contiene le informazioni di grounding.

  • grounding_support: un sotto-campo che indica il livello di supporto per il grounding.
  • grounding_chunks.maps: un sotto-campo contenente le origini dei luoghi utilizzate per generare la risposta basata sul grounding.
    • place_answer_sources.review_snippets: un sotto-campo all'interno di grounding_chunks.maps che viene visualizzato quando viene utilizzata una risposta del luogo per rispondere a una query. Le risposte del luogo forniscono informazioni contestuali più approfondite su un luogo specifico utilizzando dati come le recensioni degli utenti. La risposta del luogo è supportata da un elenco di origini come le recensioni degli utenti.

Attributi

Un'origine di recensione di un luogo o di un utente ha i seguenti attributi:

Attributi

title

Obbligatorio: Object

Il titolo dell'origine.

uri

Obbligatorio: string

Un URI che rimanda all'origine.

place_id

Obbligatorio: string

Un identificatore univoco per il luogo.

review_id

Obbligatorio: string

Un identificatore univoco per la recensione.

retrieval

Basa la risposta sui dati privati di Agent Search come datastore. Definisce uno strumento di recupero che il modello può chiamare per accedere a conoscenze esterne.

Parametri

vertexAiSearch

Obbligatorio: VertexAISearch

Basa la risposta sulle origini dati di Agent Search.

VertexAISearch

Parametri

datastore

Obbligatorio: string

ID risorsa del datastore completo di Agent Search, nel seguente formato: projects/{project}/locations/{location}/collections/default_collection/dataStores/{datastore}

Esempi

Questa sezione fornisce esempi di grounding di una risposta sui dati web pubblici utilizzando Ricerca Google e di grounding di una risposta sui dati privati utilizzando Agent Search.

Basare la risposta sui dati web pubblici utilizzando Ricerca Google

Basa la risposta sui dati pubblici di Ricerca Google. Includi lo strumento google_search_retrieval nella richiesta. Non sono necessari parametri aggiuntivi.

Python

Installare

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,
    GoogleSearch,
    HttpOptions,
    Tool,
)

client = genai.Client(http_options=HttpOptions(api_version="v1"))

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="When is the next total solar eclipse in the United States?",
    config=GenerateContentConfig(
        tools=[
            # Use Google Search Tool
            Tool(
                google_search=GoogleSearch(
                    # Optional: Domains to exclude from results
                    exclude_domains=["domain.com", "domain2.com"]
                )
            )
        ],
    ),
)

print(response.text)
# Example response:
# 'The next total solar eclipse in the United States will occur on ...'

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

// generateWithGoogleSearch shows how to generate text using Google Search.
func generateWithGoogleSearch(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: "When is the next total solar eclipse in the United States?"},
		},
			Role: genai.RoleUser},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{GoogleSearch: &genai.GoogleSearch{ExcludeDomains: []string{"example.com", "example.org"}}},
		},
	}

	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:
	// The next total solar eclipse in the United States will occur on March 30, 2033, but it will only ...

	return nil
}

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.GoogleSearch;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Tool;

public class ToolsGoogleSearchWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates content with Google Search tool
  public static String generateContent(String modelId) {
    // 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()) {

      // Create a GenerateContentConfig and set Google Search tool
      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId, "When is the next total solar eclipse in the United States?", contentConfig);

      System.out.print(response.text());
      // Example response:
      // The next total solar eclipse in the United States will occur on...
      return response.text();
    }
  }
}

Node.js

Installare

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} = require('@google/genai');

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

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

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: 'When is the next total solar eclipse in the United States?',
    config: {
      tools: [
        {
          googleSearch: {},
        },
      ],
    },
  });

  console.log(response.text);

  // Example response:
  //    'The next total solar eclipse in United States will occur on ...'

  return response.text;
}

Basare la risposta sui dati privati utilizzando Agent Search

Basa la risposta sui dati di un datastore di Agent Search. Per saperne di più, consulta Agent Search.

Prima di basare una risposta sui dati privati, crea un datastore e un'app di ricerca.

ATTENZIONE: per il momento, questa interfaccia di "grounding" non supporta la "modalità chunk" di Agent Search.

SDK Gen AI per Python

from google import genai
from google.genai.types import (
    GenerateContentConfig,
    HttpOptions,
    Retrieval,
    Tool,
    VertexAISearch,
)

client = genai.Client(http_options=HttpOptions(api_version="v1"))

# Load Data Store ID from Vertex AI Search
# datastore = "projects/111111111111/locations/global/collections/default_collection/dataStores/data-store-id"

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="How do I make an appointment to renew my driver's license?",
    config=GenerateContentConfig(
        tools=[
            # Use Vertex AI Search Tool
            Tool(
                retrieval=Retrieval(
                    vertex_ai_search=VertexAISearch(
                        datastore=datastore,
                    )
                )
            )
        ],
    ),
)

print(response.text)
# Example response:
# 'The process for making an appointment to renew your driver's license varies depending on your location. To provide you with the most accurate instructions...'

Passaggi successivi

Per la documentazione dettagliata, consulta le seguenti risorse: