Controllare il grounding con RAG

Nell'ambito della tua esperienza di Retrieval Augmented Generation (RAG) in Agent Search, puoi verificare il grounding per determinare quanto un testo (chiamato risposta candidata) sia fondato in un determinato insieme di testi di riferimento (chiamati fatti).

L'API Check Grounding restituisce un punteggio di supporto complessivo compreso tra 0 e 1, che indica quanto la risposta candidata è in linea con i fatti forniti. La risposta include anche citazioni dei fatti che supportano ogni affermazione nella risposta candidata.

La base perfetta richiede che ogni affermazione nella risposta candidata sia supportata da uno o più fatti forniti. In altre parole, l'affermazione è interamente supportata dai fatti. Se l'affermazione è solo parzialmente implicata, non è considerata fondata. Ad esempio, l'affermazione "Google è stata fondata da Larry Page e Sergey Brin nel 1975" è solo parzialmente corretta: i nomi dei fondatori sono corretti, ma la data è sbagliata e, di conseguenza, l'intera affermazione è considerata infondata. In questa versione dell'API di verifica del grounding, una frase è considerata un'unica affermazione.

Puoi utilizzare l'API di verifica del grounding per controllare qualsiasi testo. Può essere un blurb generato da un essere umano o una risposta generata automaticamente. Un caso d'uso tipico è quello di verificare una risposta generata da un LLM rispetto a un determinato insieme di fatti. L'API Check Grounding è progettata per essere veloce, con una latenza inferiore a 500 ms. Questa velocità consente ai chatbot di chiamare l'API Check Grounding durante ogni inferenza, senza subire un rallentamento significativo. L'API di controllo del grounding può anche fornire riferimenti a supporto dei risultati, in modo che gli utenti possano capire quali parti della risposta generata sono affidabili. L'API fornisce anche un punteggio di supporto per indicare l'accuratezza complessiva della risposta. Impostando una soglia di citazione, i chatbot possono filtrare le risposte in fase di inferenza che potrebbero contenere affermazioni allucinate.

Questa pagina descrive come verificare il grounding utilizzando l'API di verifica del grounding.

Termini definiti e spiegati

Prima di utilizzare l'API Check Grounding, è utile comprendere gli input e gli output e come strutturare i dati di grounding per ottenere i risultati migliori.

Dati di input

L'API di verifica del grounding richiede i seguenti input nella richiesta.

  • Candidato alla risposta: un candidato alla risposta può essere qualsiasi testo di cui vuoi verificare il grounding. Ad esempio, nel contesto di Agent Search, il candidato alla risposta potrebbe essere il riepilogo della ricerca generato che risponde a una query. L'API determina quindi il livello di grounding del riassunto rispetto ai fatti di input. Una risposta candidata può avere una lunghezza massima di 4096 token, dove un token è definito come una parola in una frase o un punto (un segno di punteggiatura utilizzato per terminare la frase). Ad esempio, la frase "They wore off-the-rack clothes in 2024." è composta da sette token, tra cui sei parole e un punto.

  • Fatti: un insieme di segmenti di testo da utilizzare come riferimenti per il grounding. Con ogni segmento di testo è possibile fornire un insieme di attributi dei metadati (coppie chiave-valore). Ad esempio, "Autore" e "Titolo" sono chiare chiavi di attributo.

    Il servizio supporta fino a 200 fatti, ciascuno con un massimo di 10.000 caratteri.

    Google sconsiglia di fornire un unico fatto molto grande che contenga tutte le informazioni. Puoi invece ottenere risultati migliori suddividendo i fatti di grandi dimensioni in fatti più piccoli e fornendo attributi appropriati per questi ultimi. Ad esempio, puoi suddividere un fatto di grandi dimensioni per titolo, autore o URL e fornire queste informazioni negli attributi.

  • Soglia di citazione: un valore in virgola mobile compreso tra 0 e 1 che controlla l'affidabilità delle citazioni che supportano la risposta candidata. Una soglia più alta impone una confidenza più rigorosa. Pertanto, una soglia più alta genera meno citazioni, ma più forti.

Dati di output

L'API Check Grounding restituisce quanto segue per una risposta candidata:

  • Punteggio di supporto: il punteggio di supporto è un numero compreso tra 0 e 1 che indica il livello di grounding di una risposta candidata nell'insieme di fatti fornito. Approssima in modo generico la frazione di affermazioni nella risposta candidata che sono risultate fondate su uno o più dei fatti forniti.

  • Segmenti citati: i segmenti citati sono parti dei fatti di input che supportano la risposta candidata.

  • Affermazioni e citazioni: le affermazioni e le citazioni collegano un'affermazione (in genere una frase) della risposta candidata a uno o più dei segmenti citati che la confermano.

    Una rivendicazione è delimitata dalle sue posizioni di inizio e fine. Queste sono le posizioni dei byte della stringa della dichiarazione con codifica UTF-8. Tieni presente che questa lunghezza non viene misurata in caratteri e, pertanto, deve essere visualizzata nell'interfaccia utente tenendo presente che alcuni caratteri occupano più di un byte. Ad esempio, se il testo della rivendicazione contiene caratteri non ASCII, le posizioni di inizio e fine variano se misurate in caratteri (dipendenti dal linguaggio di programmazione) e se misurate in byte (indipendenti dal linguaggio di programmazione).

  • Punteggio di supporto a livello di affermazione: quando il punteggio a livello di affermazione è abilitato, con ogni affermazione viene restituito un punteggio di supporto sotto forma di numero da 0 a 1 che indica quanto l'affermazione è fondata nell'insieme di fatti fornito. Per saperne di più, consulta Ottieni punteggi a livello di affermazione per un candidato alla risposta.

  • Controllo di grounding richiesto: con ogni affermazione, viene restituito un valore booleano grounding-check-required. Quando viene restituito False, significa che il sistema ritiene che l'affermazione non richieda il grounding e, pertanto, non vengono restituite citazioni. Ad esempio, una frase come "Ecco cosa ho trovato" non è un fatto di per sé e, pertanto, non richiede un controllo di grounding.

    Quando grounding-check-required restituisce true, significa che è stato eseguito un controllo di grounding e vengono restituiti i punteggi di supporto e le citazioni, se presenti.

Ottenere un punteggio di supporto per una risposta candidata

Per scoprire quanto una risposta candidata è fondata su un insieme di fatti, segui questi passaggi:

  1. Prepara l'insieme di fatti. Per ulteriori informazioni ed esempi, consulta Termini definiti e spiegati.

  2. Chiama il metodo check utilizzando il seguente codice:

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-H "X-Goog-User-Project: PROJECT_ID" \
"https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/groundingConfigs/default_grounding_config:check" \
-d '{
  "answerCandidate": "CANDIDATE",
  "facts": [
  {
    "factText": "TEXT_0",
    "attributes": {"ATTRIBUTE_A": "VALUE_A0","ATTRIBUTE_B": "VALUE_B0"}
  },
  {
    "factText": "TEXT_1",
    "attributes": {"ATTRIBUTE_A": "VALUE_A1","ATTRIBUTE_B": "VALUE_B1"}
  },
  {
    "factText": "TEXT_2",
    "attributes": {"ATTRIBUTE_A": "VALUE_A2","ATTRIBUTE_B": "VALUE_B2"}
  }
  ],
  "groundingSpec": {
    "citationThreshold": "CITATION_THRESHOLD"
  }
}'

Sostituisci quanto segue:

  • PROJECT_ID: il numero o l'ID del tuo progetto Google Cloud .

  • CANDIDATE: la stringa della risposta candidata per la quale vuoi ottenere un punteggio di supporto, ad esempio Titanic was directed by James Cameron. It was released in 1997.. Una risposta candidata può avere una lunghezza massima di 4096 token, dove un token è definito come una parola in una frase o un punto (un segno di punteggiatura utilizzato per terminare la frase). Ad esempio, la frase "They wore off-the-rack clothes in 2024." è composta da sette token, tra cui sei parole e un punto.

  • TEXT: il segmento di testo da utilizzare per il grounding, ad esempio Titanic is a 1997 American epic... Academy Awards. (consulta il testo completo in Esempi di fatti).

  • ATTRIBUTE: il nome di un attributo dei metadati associato al fatto, ad esempio author o title. Si tratta di un'etichetta definita dall'utente per aggiungere ulteriori informazioni al testo del fatto. Ad esempio, se il testo del fatto Toronto is the capital of Ontario ha un attributo author con valore Wikipedia, le seguenti affermazioni sono considerate fondate sul fatto:

    • Wikipedia cites that Toronto is the capital of Ontario
    • Toronto is the capital of Ontario

      Tuttavia, l'affermazione che Government of Ontario claims that Toronto is the capital of Ontario non è così fondata come le prime due.

  • VALUE: il valore dell'attributo, ad esempio Simple Wikipedia o Titanic (1997 film).

  • CITATION_THRESHOLD: un valore in virgola mobile compreso tra 0 e 1 che determina se un fatto deve essere citato per un'affermazione nella risposta candidata. Una soglia più alta genera un numero inferiore di citazioni, ma più forti, mentre una soglia più bassa genera un numero maggiore di citazioni, ma più deboli. Se non viene impostato, il valore di soglia predefinito è 0.6.

Python

Per saperne di più, consulta la documentazione di riferimento dell'API Agent Search Python.

Per eseguire l'autenticazione in Agent Search, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"

client = discoveryengine.GroundedGenerationServiceClient()

# The full resource name of the grounding config.
# Format: projects/{project_id}/locations/{location}/groundingConfigs/default_grounding_config
grounding_config = client.grounding_config_path(
    project=project_id,
    location="global",
    grounding_config="default_grounding_config",
)

request = discoveryengine.CheckGroundingRequest(
    grounding_config=grounding_config,
    answer_candidate="Titanic was directed by James Cameron. It was released in 1997.",
    facts=[
        discoveryengine.GroundingFact(
            fact_text=(
                "Titanic is a 1997 American epic romantic disaster movie. It was directed, written,"
                " and co-produced by James Cameron. The movie is about the 1912 sinking of the"
                " RMS Titanic. It stars Kate Winslet and Leonardo DiCaprio. The movie was released"
                " on December 19, 1997. It received positive critical reviews. The movie won 11 Academy"
                " Awards, and was nominated for fourteen total Academy Awards."
            ),
            attributes={"author": "Simple Wikipedia"},
        ),
        discoveryengine.GroundingFact(
            fact_text=(
                'James Cameron\'s "Titanic" is an epic, action-packed romance'
                "set against the ill-fated maiden voyage of the R.M.S. Titanic;"
                "the pride and joy of the White Star Line and, at the time,"
                "the largest moving object ever built. "
                'She was the most luxurious liner of her era -- the "ship of dreams" -- '
                "which ultimately carried over 1,500 people to their death in the "
                "ice cold waters of the North Atlantic in the early hours of April 15, 1912."
            ),
            attributes={"author": "Simple Wikipedia"},
        ),
    ],
    grounding_spec=discoveryengine.CheckGroundingSpec(citation_threshold=0.6),
)

response = client.check_grounding(request=request)

# Handle the response
print(response)

Esempi di fatti

Di seguito sono riportati un paio di esempi di fatti e dei relativi attributi. Questi esempi ti aiutano a comprendere la risposta di grounding e il formato del comando curl.

  • Fact 0

    • Testo: "Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. The movie is about the 1912 sinking of the RMS Titanic. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards."

    • Attributi: {"Author": "Simple Wikipedia"}

  • Fact 1

    • Testo: "James Cameron's "Titanic" is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era -- the "ship of dreams" -- which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912."

    • Attributi: {"Author": "Rotten Tomatoes"}

Esempio di richiesta

Dopo aver preparato i fatti, puoi inviare la seguente richiesta, sostituendo il campo CANDIDATE con stringhe diverse di cui vuoi verificare il grounding.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/groundingConfigs/default_grounding_config:check" \
    -d '{
    "answerCandidate": "CANDIDATE",
    "facts": [
     {
      "factText": "Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. The movie is about the 1912 sinking of the RMS Titanic. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.",
      "attributes": {"author":"Simple Wikipedia"}
     },
     {
      "factText": "James Cameron's \"Titanic\" is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era -- the \"ship of dreams\" -- which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912.",
      "attributes": {"author":"Simple Wikipedia"}
     }
    ],
    "groundingSpec": {
      "citationThreshold": "0.6"
    }
    }'

Esempi di risposte candidate e risposte di grounding

La tabella seguente mostra esempi di diverse risposte candidate e risposte quando invii la richiesta di esempio, in base ai fatti di esempio.

Risposta candidata Controlla la risposta di grounding
Here is what I found. Titanic was directed by James Cameron. Punteggio di supporto: 0.99

Sezioni citate:
  1. [From FACT 0]....Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.....
Affermazioni e citazioni:
  • 0. Here is what I found.
    Controllo di grounding richiesto: false
  • 1. Titanic was directed by James Cameron.
    Citazioni: [0]
    Controllo di grounding richiesto: true
Titanic was directed by James Cameron. It was released in 1997. Punteggio di supporto: 0.99

Sezioni citate:
  1. [From FACT 0]....Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.....
  2. [From FACT 1]...Titanic is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912....
Affermazioni e citazioni:
  • 0. Titanic was directed by James Cameron.
    Citazioni: [0]
    Controllo di grounding richiesto: true
  • 1. It was released in 1997.
    Citazioni: [1]
    Controllo di grounding richiesto: true
Titanic was directed by James Cameron. It was based on the sinking of the RMS Titanic that led to the death of 1500 people. Punteggio di supporto: 0.95

Sezioni citate:
  1. [From FACT 0]....Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.....
  2. [From FACT 1]...Titanic is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912....
Affermazioni e citazioni:
  • 0. Cited chunks: Titanic was directed by James Cameron.
    Citazioni: [0]
    Controllo di grounding richiesto: true
  • 1. Cited chunks: It was based on the sinking of the RMS Titanic that led to the death of 1500 people.
    Citazioni: [1]
    Controllo di grounding richiesto: true
Titanic was directed by James Cameron. It starred Brad Pitt and Kate Winslet Punteggio di supporto: 0.54

Sezioni citate:
  1. [From FACT 0]....Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.....
  2. [From FACT 1]...Titanic is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912....
Affermazioni e citazioni:
  • 0. Titanic was directed by James Cameron.
    Citazioni: [0]
    Controllo di grounding richiesto: true
  • 1. It starred Brad Pitt and Kate Winslet
    Citazioni: []
    Controllo di grounding richiesto: true
Nota: anche se Kate Winslet ha recitato nel film, poiché l'affermazione "It starred Brad Pitt and Kate Winslet" non è completamente vera, non riceve citazioni.

Ottieni punteggi a livello di affermazione per una risposta candidata

Oltre al punteggio di supporto a livello di risposta, puoi ottenere un punteggio di supporto a livello di affermazione per ogni affermazione in una risposta candidata.

Per ottenere i punteggi a livello di rivendicazione, segui questi passaggi:

  1. Prepara l'insieme di fatti. Per ulteriori informazioni ed esempi, consulta Termini definiti e spiegati.

  2. Chiama il metodo check utilizzando il seguente comando curl:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/groundingConfigs/default_grounding_config:check" \
    -d '{
    "answerCandidate": "CANDIDATE",
    "facts": [
     {
      "factText": "TEXT_0",
      "attributes": {"ATTRIBUTE_A": "VALUE_A0","ATTRIBUTE_B": "VALUE_B0"}
     },
     {
      "factText": "TEXT_1",
      "attributes": {"ATTRIBUTE_A": "VALUE_A1","ATTRIBUTE_B": "VALUE_B1"}
     },
     {
      "factText": "TEXT_2",
      "attributes": {"ATTRIBUTE_A": "VALUE_A2","ATTRIBUTE_B": "VALUE_B2"}
     },
    ],
    "groundingSpec": {
      "citationThreshold": "CITATION_THRESHOLD",
      "enableClaimLevelScore": "ENABLE_CLAIM_LEVEL_SCORE",
    }
    }'
    

    Sostituisci quanto segue:

    • PROJECT_ID: il numero o l'ID del tuo progettoGoogle Cloud .

    • CANDIDATE: la stringa della risposta candidata per la quale vuoi ottenere un punteggio di supporto, ad esempio Titanic was directed by James Cameron. It was released in 1997.. Una risposta candidata può avere una lunghezza massima di 4096 token, dove un token è definito come una parola in una frase o un punto (un segno di punteggiatura utilizzato per terminare la frase). Ad esempio, la frase "They wore off-the-rack clothes in 2024." è composta da sette token, tra cui sei parole e un punto.

    • TEXT: il segmento di testo da utilizzare per il grounding, ad esempio Titanic is a 1997 American epic... Academy Awards. (vedi il testo completo in Esempi di fatti).

    • ATTRIBUTE: il nome di un attributo dei metadati associato al fatto, ad esempio author o title. Si tratta di un'etichetta definita dall'utente per aggiungere ulteriori informazioni al testo del fatto. Ad esempio, se il testo del fatto Toronto is the capital of Ontario ha un attributo author con valore Wikipedia, le seguenti affermazioni sono ben fondate:

      • Wikipedia cites that Toronto is the capital of Ontario
      • Toronto is the capital of Ontario

      Tuttavia, l'affermazione che Government of Ontario claims that Toronto is the capital of Ontario non è altrettanto fondata.

    • VALUE: il valore dell'attributo, ad esempio Simple Wikipedia o Titanic (1997 film).

    • CITATION_THRESHOLD: un valore in virgola mobile compreso tra 0 e 1 che determina se un fatto deve essere citato per un'affermazione nella risposta candidata. Una soglia più alta genera un numero inferiore di citazioni, ma più solide, a supporto dell'affermazione, mentre una soglia più bassa genera un numero maggiore di citazioni, ma più deboli. Se non viene impostato, il valore di soglia predefinito è 0,6.

    • ENABLE_CLAIM_LEVEL_SCORE: un valore booleano. Imposta questo campo su true per attivare la funzionalità di punteggio a livello di rivendicazione. Per disattivare questa funzionalità, rimuovi questo campo o impostalo su false.

Esempio di richiesta

Utilizzando i fatti di esempio della sezione precedente, puoi inviare la seguente richiesta. Sostituisci il campo CANDIDATE con stringhe diverse di cui vuoi verificare il grounding per ogni claim.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/groundingConfigs/default_grounding_config:check" \
    -d '{
    "answerCandidate": "CANDIDATE",
    "facts": [
     {
      "factText": "Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. The movie is about the 1912 sinking of the RMS Titanic. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.",
      "attributes": {"author":"Simple Wikipedia"}
     },
     {
      "factText": "James Cameron's \"Titanic\" is an epic, action-packed romance set against the ill-fated maiden voyage of the R.M.S. Titanic; the pride and joy of the White Star Line and, at the time, the largest moving object ever built. She was the most luxurious liner of her era -- the \"ship of dreams\" -- which ultimately carried over 1,500 people to their death in the ice cold waters of the North Atlantic in the early hours of April 15, 1912.",
      "attributes": {"author":"Simple Wikipedia"}
     }
    ],
    "groundingSpec": {
      "citationThreshold": "0.6",
      "enableClaimLevelScore": true,
    }
    }'

Esempio di risposte con punteggi a livello di affermazione

La tabella seguente mostra un esempio di risposta candidata e la relativa risposta quando invii la richiesta di esempio, in base ai fatti di esempio.

Risposta candidata Controlla la risposta di grounding
Here is what I found. Titanic was directed by James Cameron. It starred Kate Winslet and Leonardo DiCaprio. Punteggio di supporto: 0.99

Sezioni citate:
  1. [From FACT 0]....Titanic is a 1997 American epic romantic disaster movie. It was directed, written, and co-produced by James Cameron. It stars Kate Winslet and Leonardo DiCaprio. The movie was released on December 19, 1997. It received positive critical reviews. The movie won 11 Academy Awards, and was nominated for fourteen total Academy Awards.....
Affermazioni e citazioni:
  • 0. Here is what I found.
    Controllo di grounding richiesto: false
  • 1. Titanic was directed by James Cameron.
    Citazioni: [0]
    Controllo di grounding richiesto: true
    Punteggio: 0.99
  • 2. It starred Kate Winslet and Leonardo DiCaprio.
    Citazioni: [0]
    Controllo di grounding richiesto: true
    Punteggio: 0.99