Altitude de referência

Na IA generativa, embasamento é a capacidade de conectar a saída do modelo a fontes de informações verificáveis. Se você fornecer aos modelos acesso a fontes de dados específicas, o embasamento da saída deles a esses dados reduz as chances de inventar conteúdo.

Com a Vertex AI, é possível embasar as saídas do modelo das seguintes maneiras:

  • Terreno com a Pesquisa Google: basear um modelo com dados da Web disponíveis publicamente.
  • Ter fundamento nos seus próprios dados: basear um modelo com seus próprios dados da Vertex AI para Pesquisa como um repositório de dados (pré-lançamento).

Para mais informações sobre embasamento, consulte Visão geral de embasamento.

Modelos compatíveis

Modelo Versão
Gemini 2.0 Flash apenas com entrada de texto gemini-2.0-flash-001
Gemini 1.5 Pro apenas com entrada de texto gemini-1.5-pro-002
gemini-1.5-pro-001
Gemini 1.5 Flash apenas com entrada de texto gemini-1.5-flash-002
gemini-1.5-flash-001
Gemini 1.0 Pro apenas com entrada de texto gemini-1.0-pro-001
gemini-1.0-pro-002

Limitações

O embasamento está disponível apenas para solicitações de texto.

Exemplo de sintaxe

Este exemplo mostra a sintaxe para fundamentar um modelo e especificar o idioma com suporte. Para saber mais sobre o suporte a idiomas, consulte Idiomas.


Especifique os valores das seguintes variáveis:
  • PROMPT_TEXT: sua solicitação de texto enviada a um modelo de linguagem para receber uma resposta.
  • SYSTEM_INSTRUCTION: um conjunto de instruções que informa ao modelo como se comportar e responder aos comandos.
  • FACT_TEXT_1: informações verificadas usadas pelo modelo para gerar uma resposta.
  • TITLE_1: o nome da sua fonte de informações verificada.
  • URI_1: uma string que identifica exclusivamente um local da sua fonte de informações verificada.
  • AUTHOR_1: o provedor das informações verificadas usadas pelo modelo para gerar uma resposta.
  • FACT_TEXT_2: informações verificadas usadas pelo modelo para gerar uma resposta.
  • TITLE_2: o nome da sua fonte de informações verificada.
  • URI_2: uma string que identifica exclusivamente um local da sua fonte de informações verificada.
  • FACT_TEXT_3: informações verificadas usadas pelo modelo para gerar uma resposta.
  • TITLE_3: o nome da sua fonte de informações verificada.
  • URI_3: uma string que identifica exclusivamente um local da sua fonte de informações verificada.
  • PROJECT_NUMBER: identifica de forma exclusiva o projeto Google Cloud , que contém seus recursos.
  • APP_ID_1: um aplicativo que interage com o modelo.
  • APP_ID_2: um aplicativo que interage com o modelo.
  • MODEL_ID: identifica o modelo com que o app interage.
  • LANGUAGE_CODE: identifica o idioma usado na geração de uma resposta fundamentada.

curl

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
-d '
{
"contents": [
 {
   "role": "user",
   "parts": [
     {
       "text": "PROMPT_TEXT"
     }
   ]
 }
],
"systemInstruction": {
   "parts": {
       "text": "SYSTEM_INSTRUCTION"
   }
},
"groundingSpec": {
 "groundingSources": [
   {
     "inlineSource": {
       "groundingFacts": [
         {
           "factText": "FACT_TEXT_1",
           "attributes": {
             "title": "TITLE_1",
             "uri": "URI_1",
             "author": "AUTHOR_1"
           }
         }
       ]
     }
   },
   {
     "inlineSource": {
       "groundingFacts": [
         {
           "factText": "FACT_TEXT_2",
           "attributes": {
             "title": "TITLE_2",
             "uri": "URI_2"
           }
         },
         {
           "factText": "FACT_TEXT_3",
           "attributes": {
             "title": "TITLE_3",
             "uri": "URI_3"
           }
         }
       ]
     }
   },
   {
     "searchSource": {
       "servingConfig": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID_1/servingConfigs/default_search"
     }
   },
   {
     "searchSource": {
       "servingConfig": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID_2/servingConfigs/default_search"
     }
   }
  ]
},
"generationSpec": {
  "modelId": "MODEL_ID",
  "temperature": TEMPERATURE,
  "topP": TOP_P,
  "topK": TOP_K,
},
"user_context": {
  "languageCode: "LANGUAGE_CODE"
  "latLng": {
    "latitude": 46.7,
    "longitude": 8.9
  },
}'

Lista de parâmetros

Confira exemplos para detalhes de implementação.

GoogleSearchRetrieval

Baseie a resposta com dados públicos.

Parâmetros

google_search_retrieval

Obrigatório: Object

Terreno com dados da Web disponíveis publicamente.

Retrieval

Baseie a resposta com dados particulares da Vertex AI para Pesquisa como um repositório de dados. Define uma ferramenta de recuperação que o modelo pode chamar para acessar conhecimento externo.

Parâmetros

source

Obrigatório: VertexAISearch

Informações básicas sobre as fontes de dados da Vertex AI para Pesquisa.

VertexAISearch

Parâmetros

datastore

Obrigatório: string

ID do recurso de repositório de dados totalmente qualificado da Vertex AI para Pesquisa, no seguinte formato: projects/{project}/locations/{location}/collections/default_collection/dataStores/{datastore}

Exemplos

Resposta empírica em dados públicos da Web usando a Pesquisa Google

Baseie a resposta com dados públicos da Pesquisa Google. Inclua a ferramenta google_search_retrieval na solicitação. Nenhum parâmetro adicional é necessário.

REST

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • LOCATION: a região para processar a solicitação.
  • PROJECT_ID: o ID do projeto.
  • MODEL_ID: o ID do modelo multimodal. Somente os modelos Gemini 1.0 e Gemini 1.5 oferecem suporte à recuperação dinâmica. Os modelos do Gemini 2.0 não oferecem suporte à recuperação dinâmica.
  • TEXT: as instruções de texto a serem incluídas no comando.
  • DYNAMIC_THRESHOLD: um campo opcional para definir o limite para invocar a configuração de recuperação dinâmica. É um valor de ponto flutuante no intervalo [0,1]. Se você não definir o campo dynamicThreshold, o valor de limite será 0,7.

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "tools": [{
    "googleSearchRetrieval": {
      "dynamicRetrievalConfig": {
        "mode": "MODE_DYNAMIC",
        "dynamicThreshold": DYNAMIC_THRESHOLD
      }
    }
  }],
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID"
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
   "candidates": [
     {
       "content": {
         "role": "model",
         "parts": [
           {
             "text": "Chicago weather changes rapidly, so layers let you adjust easily. Consider a base layer, a warm mid-layer (sweater-fleece), and a weatherproof outer layer."
           }
         ]
       },
       "finishReason": "STOP",
       "safetyRatings":[
       "..."
    ],
       "groundingMetadata": {
         "webSearchQueries": [
           "What's the weather in Chicago this weekend?"
         ],
         "searchEntryPoint": {
            "renderedContent": "....................."
         }
         "groundingSupports": [
            {
              "segment": {
                "startIndex": 0,
                "endIndex": 65,
                "text": "Chicago weather changes rapidly, so layers let you adjust easily."
              },
              "groundingChunkIndices": [
                0
              ],
              "confidenceScores": [
                0.99
              ]
            },
          ]
          "retrievalMetadata": {
              "webDynamicRetrievalScore": 0.96879
            }
       }
     }
   ],
   "usageMetadata": { "..."
   }
 }

Python

import vertexai

from vertexai.generative_models import (
    GenerationConfig,
    GenerativeModel,
    Tool,
    grounding,
)

# 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-flash-001")

# Use Google Search for grounding
tool = Tool.from_google_search_retrieval(
    grounding.GoogleSearchRetrieval(
        # Optional: For Dynamic Retrieval
        dynamic_retrieval_config=grounding.DynamicRetrievalConfig(
            dynamic_threshold=0.7,
        )
    )
)

prompt = "When is the next total solar eclipse in US?"
response = model.generate_content(
    prompt,
    tools=[tool],
    generation_config=GenerationConfig(
        temperature=0.0,
    ),
)

print(response.text)
# Example response:
# The next total solar eclipse visible from the contiguous United States will be on **August 23, 2044**.

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContentWithGoogleSearchGrounding(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  const generativeModelPreview = vertexAI.preview.getGenerativeModel({
    model: model,
    generationConfig: {maxOutputTokens: 256},
  });

  const googleSearchRetrievalTool = {
    googleSearchRetrieval: {},
  };

  const request = {
    contents: [{role: 'user', parts: [{text: 'Why is the sky blue?'}]}],
    tools: [googleSearchRetrievalTool],
  };

  const result = await generativeModelPreview.generateContent(request);
  const response = await result.response;
  const groundingMetadata = response.candidates[0].groundingMetadata;
  console.log(
    'Response: ',
    JSON.stringify(response.candidates[0].content.parts[0].text)
  );
  console.log('GroundingMetadata is: ', JSON.stringify(groundingMetadata));
}

Java

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.GoogleSearchRetrieval;
import com.google.cloud.vertexai.api.GroundingMetadata;
import com.google.cloud.vertexai.api.Tool;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;
import java.util.Collections;

public class GroundingWithPublicData {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.5-flash-001";

    groundWithPublicData(projectId, location, modelName);
  }

  // A request whose response will be "grounded" with information found in Google Search.
  public static String groundWithPublicData(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)) {
      Tool googleSearchTool =
          Tool.newBuilder()
              .setGoogleSearchRetrieval(
                  // Enable using the result from this tool in detecting grounding
                  GoogleSearchRetrieval.newBuilder())
              .build();

      GenerativeModel model =
          new GenerativeModel(modelName, vertexAI)
              .withTools(Collections.singletonList(googleSearchTool));

      GenerateContentResponse response = model.generateContent("Why is the sky blue?");

      GroundingMetadata groundingMetadata = response.getCandidates(0).getGroundingMetadata();
      String answer = ResponseHandler.getText(response);

      System.out.println("Answer: " + answer);
      System.out.println("Grounding metadata: " + groundingMetadata);

      return answer;
    }
  }
}

Resposta em base em dados particulares usando a Vertex AI para Pesquisa

Baseie a resposta com dados de um repositório da Vertex AI para Pesquisa. Para mais informações, consulte o Vertex AI Agent Builder.

Antes de fundamentar uma resposta com dados particulares, crie um repositório de dados e um app de pesquisa.

AVISO: por enquanto, essa interface de "aterramento" não oferece suporte ao "modo de bloco" da Pesquisa da Vertex AI.

REST

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • LOCATION: a região para processar a solicitação.
  • PROJECT_ID: o ID do projeto.
  • MODEL_ID: o ID do modelo multimodal.
  • TEXT: as instruções de texto a serem incluídas no comando.

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "tools": [{
    "retrieval": {
      "vertexAiSearch": {
        "datastore": projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID
      }
    }
  }],
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID"
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "You can make an appointment on the website https://dmv.gov/"
          }
        ]
      },
      "finishReason": "STOP",
      "safetyRatings": [
        "..."
      ],
      "groundingMetadata": {
        "retrievalQueries": [
          "How to make appointment to renew driving license?"
        ],
        "groundingChunks": [
          {
            "retrievedContext": {
              "uri": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/AXiHM.....QTN92V5ePQ==",
              "title": "dmv"
            }
          }
        ],
        "groundingSupport": [
          {
            "segment": {
              "startIndex": 25,
              "endIndex": 147
            },
            "segment_text": "ipsum lorem ...",
            "supportChunkIndices": [1, 2],
            "confidenceScore": [0.9541752, 0.97726375]
          },
          {
            "segment": {
              "startIndex": 294,
              "endIndex": 439
            },
            "segment_text": "ipsum lorem ...",
            "supportChunkIndices": [1],
            "confidenceScore": [0.9541752, 0.9325467]
          }
        ]
      }
    }
  ],
  "usageMetadata": {
    "..."
  }
}

Python

import vertexai

from vertexai.preview.generative_models import (
    GenerationConfig,
    GenerativeModel,
    Tool,
    grounding,
)

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# data_store_id = "your-data-store-id"

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

model = GenerativeModel("gemini-1.5-flash-001")

tool = Tool.from_retrieval(
    grounding.Retrieval(
        grounding.VertexAISearch(
            datastore=data_store_id,
            project=PROJECT_ID,
            location="global",
        )
    )
)

prompt = "How do I make an appointment to renew my driver's license?"
response = model.generate_content(
    prompt,
    tools=[tool],
    generation_config=GenerationConfig(
        temperature=0.0,
    ),
)

print(response.text)

NodeJS

const {
  VertexAI,
  HarmCategory,
  HarmBlockThreshold,
} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContentWithVertexAISearchGrounding(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001',
  dataStoreId = 'DATASTORE_ID'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  const generativeModelPreview = vertexAI.preview.getGenerativeModel({
    model: model,
    // The following parameters are optional
    // They can also be passed to individual content generation requests
    safetySettings: [
      {
        category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
      },
    ],
    generationConfig: {maxOutputTokens: 256},
  });

  const vertexAIRetrievalTool = {
    retrieval: {
      vertexAiSearch: {
        datastore: `projects/${projectId}/locations/global/collections/default_collection/dataStores/${dataStoreId}`,
      },
      disableAttribution: false,
    },
  };

  const request = {
    contents: [{role: 'user', parts: [{text: 'Why is the sky blue?'}]}],
    tools: [vertexAIRetrievalTool],
  };

  const result = await generativeModelPreview.generateContent(request);
  const response = result.response;
  const groundingMetadata = response.candidates[0];
  console.log('Response: ', JSON.stringify(response.candidates[0]));
  console.log('GroundingMetadata is: ', JSON.stringify(groundingMetadata));
}

Java

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.GroundingMetadata;
import com.google.cloud.vertexai.api.Retrieval;
import com.google.cloud.vertexai.api.Tool;
import com.google.cloud.vertexai.api.VertexAISearch;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;
import java.util.Collections;

public class GroundingWithPrivateData {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.5-flash-001";
    String datastore = String.format(
        "projects/%s/locations/global/collections/default_collection/dataStores/%s",
        projectId, "datastore_id");

    groundWithPrivateData(projectId, location, modelName, datastore);
  }

  // A request whose response will be "grounded"
  // with information found in Vertex AI Search datastores.
  public static String groundWithPrivateData(String projectId, String location, String modelName,
                                             String datastoreId)
      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)) {
      Tool datastoreTool = Tool.newBuilder()
          .setRetrieval(
              Retrieval.newBuilder()
                  .setVertexAiSearch(VertexAISearch.newBuilder().setDatastore(datastoreId))
                  .setDisableAttribution(false))
          .build();

      GenerativeModel model = new GenerativeModel(modelName, vertexAI).withTools(
          Collections.singletonList(datastoreTool)
      );

      GenerateContentResponse response = model.generateContent(
          "How do I make an appointment to renew my driver's license?");

      GroundingMetadata groundingMetadata = response.getCandidates(0).getGroundingMetadata();
      String answer = ResponseHandler.getText(response);

      System.out.println("Answer: " + answer);
      System.out.println("Grounding metadata: " + groundingMetadata);

      return answer;
    }
  }
}

A seguir

Para consultar a documentação detalhada, acesse: