Vai al contenuto principale

Come migliorare le prestazioni del RAG: 5 tecniche chiave con esempi

Esplora diversi approcci per potenziare i sistemi RAG: Chunking, Reranking e trasformazioni delle query.
Aggiornato 29 set 2026

Scopri con l'IA

ChatGPTClaudePerplexity

Il Retrieval Augmented Generation (RAG) è una delle tecniche più diffuse per migliorare l’accuratezza e l’affidabilità dei Large Language Models (LLM). Questo è possibile fornendo informazioni aggiuntive da fonti di dati esterne. In questo modo, le risposte possono essere adattate a contesti specifici e aggiornate senza fine-tuning e retraining.

Nonostante la popolarità del RAG, non funziona bene in tutti i contesti. In questo articolo, spiegheremo passo dopo passo come costruire pipeline RAG in modo efficace, esploreremo i limiti del RAG e come affrontarli. Iniziamo!

Come funziona il Retrieval Augmented Generation (RAG)?

Immagine dalla documentazione di LlamaIndex

Le pipeline di Retrieval Augmented Generation (RAG) includono tre fasi: indicizzazione, recupero e generazione.

Indicizzazione

L’indicizzazione è fondamentale per ottenere risposte accurate e consapevoli del contesto con gli LLM. Per prima cosa si estraggono e puliscono dati con diversi formati di file, come documenti Word, file PDF o file HTML. Una volta puliti, i dati vengono convertiti in testo semplice standardizzato. Per evitare limitazioni di contesto negli LLM, il testo viene suddiviso in porzioni più piccole. Questo processo si chiama Chunking. Successivamente, ogni chunk viene trasformato in un vettore numerico o embedding utilizzando un modello di embedding. Infine, viene creato un indice per archiviare i chunk e i relativi embedding come coppie chiave-valore.

Recupero

Durante la fase di recupero, anche la query dell’utente viene convertita in una rappresentazione vettoriale usando lo stesso modello di embedding. Poi si calcolano i punteggi di similarità tra il vettore della query e i chunk vettorializzati. Il sistema recupera i primi K chunk con la maggiore somiglianza alla query dell’utente.

Generazione

La query dell’utente e i chunk recuperati vengono inseriti in un prompt template. Il prompt aumentato ottenuto dai passaggi precedenti viene infine fornito in input all’LLM.

Limitazioni del RAG

Quando costruisci sistemi RAG, puoi incontrare sfide significative in tutte e tre le fasi descritte in precedenza, come le seguenti:

  • Indicizzazione: L’efficacia del RAG è fortemente influenzata dalla qualità dei dati. Se la fonte di dati esterna è più rumorosa che informativa, le risposte generate dall’LLM non saranno utili.
  • Recupero: A seconda dei tipi di file e di come hai configurato il tuo sistema RAG, il sistema non sempre recupera chunk che aiutano a rispondere alle query degli utenti.
  • Generazione: Anche se il sistema RAG è configurato in modo efficace, l’LLM può comunque generare risposte errate basate su fatti immaginati.

Di seguito, esploreremo strategie per aggirare queste limitazioni. Parleremo di tre strategie generali: Chunking, Re-Ranking e trasformazioni delle query. Inoltre, mostreremo come queste strategie possano aiutare a migliorare le prestazioni del RAG costruendo un sistema RAG che risponde a domande su voci di Wikipedia usando Llamaindex e le API di OpenAI. Tuffiamoci!

Configurare il sistema RAG di base

Prima di esplorare i trucchi per migliorare le prestazioni di un sistema RAG, dobbiamo stabilire una baseline creando una pipeline RAG semplice. Iniziamo installando i pacchetti llama-index e openai.

!pip install llama-index
!pip install openai

Llamaindex è un framework dati per applicazioni basate su Large Language Models (LLM). Permette di acquisire diversi tipi di fonti di dati esterne, costruire sistemi di Retrieval Augmentation Generation (RAG) e astrarre le integrazioni con altri LLM in poche righe di codice. Inoltre, offre diverse tecniche per generare output più accurati con gli LLM.

Per impostazione predefinita, utilizza il modello OpenAI gpt-3.5-turbo per la generazione di testo e il modello text-embedding-ada-002 per il recupero e gli embedding. Per usare questi modelli, è necessario creare un account gratuito sulla piattaforma OpenAI e ottenere una chiave API di OpenAI. Per ottenere la chiave, visita la documentazione delle API di OpenAI.

import os
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"

Ora che i pacchetti sono installati, costruiremo un sistema RAG che risponde a domande basate sulle pagine Wikipedia di Emma Stone, Ryan Gosling e La La Land. Per prima cosa, dobbiamo installare la libreria wikipedia per estrarre le pagine di Wikipedia:

!pip install wikipedia

Poi possiamo scaricare facilmente i dati da Wikipedia:

# Import packages
from llama_index.core import (VectorStoreIndex,ServiceContext, download_loader)

# Download the documents from Wikipedia and load them
WikipediaReader = download_loader("WikipediaReader")
loader = WikipediaReader()
pages = ['Emma_Stone', 'La_La_Land', 'Ryan_Gosling']
documents = loader.load_data(pages=pages, auto_suggest=False, redirect = False)

Una volta estratti i dati, possiamo dividere i documenti in chunk di 256 caratteri senza sovrapposizione. In seguito, questi chunk vengono trasformati in vettori numerici usando il modello di embedding e indicizzati in un Vector Store.

# Initialize the gpt3.5 model
gpt3 = OpenAI(temperature=0, model="gpt-3.5-turbo-instruct", api_key=OPENAI_API_KEY)
# Initialize the embedding model
embed_model = OpenAIEmbedding(model= OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002, api_key=OPENAI_API_KEY)
# Transform chunks into numerical vectors using the embedding model
service_context_gpt3 = ServiceContext.from_defaults(llm=gpt3, chunk_size = 256, chunk_overlap=0, embed_model=embed_model)
index = VectorStoreIndex.from_documents(documents, service_context=service_context_gpt3)
retriever = index.as_retriever(similarity_top_k=3)

Per ridurre il rischio di allucinazioni, usiamo il modulo PromptTemplate per garantire che le risposte dell’LLM si basino solo sul contesto fornito.

from llama_index.core.prompts import PromptTemplate
# Build a prompt template to only provide answers based on the loaded documents 
template = (
"We have provided context information below. \n"
    "---------------------\n"
    "{context_str}"
    "\n---------------------\n"
    "Given this information, please answer the question: {query_str}\n"
    "Don't give an answer unless it is supported by the context above.\n"
)

qa_template = PromptTemplate(template)

Ora che abbiamo configurato il nostro sistema RAG, possiamo testarlo con domande basate sui documenti recuperati. Mettiamolo alla prova!

Query 1: “Qual è la trama del film che ha portato Emma Stone a vincere il suo primo Academy Award?”

Questa prima query è impegnativa perché richiede al modello di consultare diverse informazioni:

  • Il nome del film che ha portato al primo Academy Award di Emma Stone (che in questo caso è La La Land)
  • La trama di quello specifico film.
# Create a prompt for the model
question = "What is the plot of the film that led Emma Stone to win her first Academy Award?"

# Retrieve the context from the model
contexts = retriever.retrieve(question)
context_list = [n.get_content() for n in contexts]
prompt = qa_template.format(context_str="\n\n".join(context_list), query_str=question)

# Generate the response 
response = gpt3.complete(prompt)
print(str(response))

Output:

The plot of the film that made Emma Stone win her first Academy Award is not explicitly mentioned in the provided context.

Query 2: "Confronta le famiglie di Emma Stone e Ryan Gosling”

Questa seconda query è ancora più impegnativa della precedente, perché chiede di selezionare i chunk rilevanti relativi alle famiglie dei due attori.

# Create a prompt for the model
question = "Compare the families of Emma Stone and Ryan Gosling"
# Retrieve the context from the model
contexts = retriever.retrieve(question)
context_list = [n.get_content() for n in contexts]
prompt = qa_template.format(context_str="\n\n".join(context_list), query_str=question)
# Generate the response 
response = gpt3.complete(prompt)
print(str(response))

Riceviamo il seguente output:

Based on the context provided, it is not possible to compare the families of Emma Stone and Ryan Gosling as the information focuses on their professional collaboration and experiences while working on the film "La La Land." There is no mention of their personal family backgrounds or relationships in the context provided.

Come puoi vedere, in entrambi i casi abbiamo ricevuto risposte sotto la media. Nelle sezioni seguenti, esploriamo come migliorare le prestazioni di questo sistema RAG!

Migliorare le prestazioni del RAG aggiornando la dimensione dei chunk

Possiamo iniziare personalizzando la dimensione dei chunk e la sovrapposizione. Come detto sopra, i documenti vengono suddivisi in chunk con una specifica sovrapposizione. Per impostazione predefinita, LlamaIndex utilizza 1024 come dimensione del chunk e 20 come sovrapposizione del chunk. Oltre a questi iperparametri, il sistema recupera di default i primi 2 chunk.

Per esempio, possiamo impostare la dimensione dei chunk a 512, la sovrapposizione a 50 e aumentare il numero dei chunk recuperati in cima:

# modify default values of chunk size and chunk overlap
service_context_gpt3 = ServiceContext.from_defaults(llm=gpt3, chunk_size = 512, chunk_overlap=50, embed_model=embed_model)

# build index
index = VectorStoreIndex.from_documents(
    documents, service_context=service_context_gpt3

)
# returns the engine for the index
query_engine = index.as_query_engine(similarity_top_k=4)

Query 1: “Qual è la trama del film che ha portato Emma Stone a vincere il suo primo Academy Award?”

# generate the response
response = query_engine.query("What is the plot of the film that led Emma Stone to win her first Academy Award?")
print(response)

Output:

The film that made Emma Stone win her first Academy Award is a romantic musical called La La Land.

Rispetto alla risposta precedente, è leggermente migliore. Ha riconosciuto correttamente La La Land come il film che ha portato Emma Stone a vincere il suo primo Academy Award, ma non è riuscita a descriverne la trama.

Query 2: "Confronta le famiglie di Emma Stone e Ryan Gosling”

# generate the response
response = query_engine.query("Compare the families of Emma Stone and Ryan Gosling")
print(response)

Output:

Emma Stone has expressed her close relationship with her family and mentioned being blessed with great family and people around her. She has also shared about her mother's battle with breast cancer and their celebration by getting matching tattoos. On the other hand, there is no specific information provided about Ryan Gosling's family or his personal relationships in the context.

Anche in questo caso, l’output della pipeline RAG è migliorato, ma ancora non cattura informazioni sulla famiglia di Ryan Gosling.

Migliorare le prestazioni del RAG con il Re-Ranking

Man mano che il dataset cresce in dimensioni e complessità, selezionare informazioni rilevanti per restituire risposte mirate a query complesse diventa cruciale. A questo scopo, una famiglia di tecniche chiamate Re-Ranking ti permette di capire quali chunk sono importanti nel testo. Riordinano e filtrano i documenti, classificando per primi i più rilevanti.

Esistono due approcci principali per il Re-Ranking:

  • Utilizzare modelli di Re-Ranking come tecniche alternative ai modelli di embedding. Prendono in input la query e il contesto e restituiscono punteggi di similarità invece di embedding
  • Usare gli LLM per catturare in modo più efficace l’informazione semantica nei documenti.

Prima di applicare questi approcci di Re-Ranking, valutiamo cosa restituisce il sistema RAG di base come primi tre chunk per la nostra seconda query:

# Retrieve the top three chunks for the second query
retriever = index.as_retriever(similarity_top_k=3)
query = "Compare the families of Emma Stone and Ryan Gosling"
nodes = retriever.retrieve(query)
# Print the chunks
for node in nodes:
    print('----------------------------------------------------')
    display_source_node(node, source_length = 500)

Questo è l’output prima del Re-Ranking; ogni chunk ha un Node ID con un punteggio di similarità.

Node ID: 9b3817fe-3a3f-4417-83d2-2e2996c8b468
Similarity: 0.8415899563985404
Text: Emily Jean "Emma" Stone (born November 6, 1988) is an American actress and producer. She is the recipient of various accolades, including two Academy Awards, two British Academy Film Awards, and two Golden Globe Awards. In 2017, she was the world's highest-paid actress and named by Time magazine as one of the 100 most influential people in the world. Born and raised in Scottsdale, Arizona, Stone began acting as a child in a theater production of The Wind in the Willows in 2000. As a teenager,...
----------------------------------------------------

Node ID: 1bef0308-8b0f-4f7e-9cd6-92ce5acf811f
Similarity: 0.831147173341674
Text: Coincidentally, Gosling turned down the Beast role in Beauty and the Beast in favor of La La Land. Chazelle subsequently decided to make his characters somewhat older, with experience in struggling to make their dreams, rather than younger newcomers just arriving in Los Angeles. Emma Stone plays Mia, an aspiring actress in Los Angeles. Stone has loved musicals since she saw Les Misérables when she was eight years old. She said "bursting into song has always been a real dream of mine", and her ...
----------------------------------------------------

Node ID: 576ae445-b12e-4d20-99b7-5e5a91ee7d74
Similarity: 0.8289486590392277
Text: Stone was named the best-dressed woman of 2012 by Vogue and was included on similar listings by Glamour in 2013 and 2015, and People in 2014.
== Personal life == Stone moved from Los Angeles to Greenwich Village, New York, in 2009. In 2016, she moved back to Los Angeles. Despite significant media attention, she refuses to publicly discuss her personal life. Concerned with living a normal life, Stone has said she dislikes receiving paparazzi attention outside her home. She has expressed her ...

Re-Ranking con FlagEmbeddingReranker

Per recuperare i chunk rilevanti, possiamo usare un modello di Re-Ranking open source da Hugging Face, chiamato modello bge-ranker-base.

Proprio come per le API di OpenAI, usare Hugging Face richiede di ottenere un token di accesso utente. Puoi creare un token di accesso utente da Hugging Face seguendo questa documentazione.

HF_TOKEN = userdata.get('HF_TOKEN')
os.environ['HF_TOKEN'] = HF_TOKEN

Prima di procedere, dobbiamo anche installare le librerie necessarie per usare il modello di Re-Ranking:

%pip install llama-index-postprocessor-flag-embedding-reranker
!pip install git+https://github.com/FlagOpen/FlagEmbedding.git

Infine, usiamo il modello bge-ranker-base per restituire i chunk più rilevanti.

# Import packages
from llama_index.postprocessor.flag_embedding_reranker import FlagEmbeddingReranker

from llama_index.core.schema import QueryBundle
# Re-Rank chunks based on the bge-reranker-base-model
reranker = FlagEmbeddingReranker(
    top_n = 3,
    model = "BAAI/bge-reranker-base",
)
# Return the updated chunks
query_bundle = QueryBundle(query_str=query)
ranked_nodes = reranker._postprocess_nodes(nodes, query_bundle = query_bundle)
for ranked_node in ranked_nodes:
    print('----------------------------------------------------')
    display_source_node(ranked_node, source_length = 500)

Questo è il risultato dopo il Re-Ranking:

Node ID: 9b3817fe-3a3f-4417-83d2-2e2996c8b468
Similarity: 3.0143558979034424
Text: Emily Jean "Emma" Stone (born November 6, 1988) is an American actress and producer. She is the recipient of various accolades, including two Academy Awards, two British Academy Film Awards, and two Golden Globe Awards. In 2017, she was the world's highest-paid actress and named by Time magazine as one of the 100 most influential people in the world. Born and raised in Scottsdale, Arizona, Stone began acting as a child in a theater production of The Wind in the Willows in 2000. As a teenager,...
----------------------------------------------------

Node ID: 576ae445-b12e-4d20-99b7-5e5a91ee7d74
Similarity: 2.2117154598236084
Text: Stone was named the best-dressed woman of 2012 by Vogue and was included on similar listings by Glamour in 2013 and 2015, and People in 2014.
== Personal life == Stone moved from Los Angeles to Greenwich Village, New York, in 2009. In 2016, she moved back to Los Angeles. Despite significant media attention, she refuses to publicly discuss her personal life. Concerned with living a normal life, Stone has said she dislikes receiving paparazzi attention outside her home. She has expressed her ...
----------------------------------------------------

Node ID: 1bef0308-8b0f-4f7e-9cd6-92ce5acf811f
Similarity: 1.6185210943222046
Text: Coincidentally, Gosling turned down the Beast role in Beauty and the Beast in favor of La La Land. Chazelle subsequently decided to make his characters somewhat older, with experience in struggling to make their dreams, rather than younger newcomers just arriving in Los Angeles.Emma Stone plays Mia, an aspiring actress in Los Angeles. Stone has loved musicals since she saw Les Misérables when she was eight years old. She said "bursting into song has always been a real dream of mine", and her ...

Dall’output è chiaro che il nodo con ID 1bef0308-8b0f-4f7e-9cd6-92ce5acf811f passa dalla seconda alla terza posizione. Inoltre, vale la pena notare che c’è maggiore variabilità nei punteggi di similarità.

Ora che abbiamo usato il Re-Ranking, valutiamo come appare la risposta del RAG alla query originale:

# Initialize the query engine with Re-Ranking
query_engine = index.as_query_engine(      
    similarity_top_k = 3,
    node_postprocessors=[reranker]
)

# Print the response from the model 
response = query_engine.query("Compare the families of Emma Stone and Ryan Gosling")

print(response)

Questa è la risposta fornita dopo aver applicato il modello di Re-Ranking:

Both Emma Stone and Ryan Gosling have close relationships with their families. Stone has expressed her gratitude for having a great family and people around her who keep her grounded. Gosling, on the other hand, has drawn from his own experiences as an aspiring artist, indicating a connection to his personal background.

C’è un miglioramento significativo rispetto alle risposte precedenti, ma è ancora incompleta. Valutiamo come un approccio di Re-Ranking basato su LLM possa aiutare a migliorare le prestazioni del RAG.

Re-Ranking con RankGPTRerank

Questa volta possiamo affidarci a un LLM come Re-Ranker. Qui usiamo il modulo RankGPT, che sfrutta le capacità del modello GPT per classificare i documenti all’interno del sistema RAG. Per iniziare, installiamo i pacchetti necessari:

%pip install llama-index-postprocessor-rankgpt-rerank

Usiamo la funzione RankGPTRerank per riordinare i chunk utilizzando il modello gpt-3.5-turbo-0125.

# Import packages
from llama_index.postprocessor.rankgpt_rerank import RankGPTRerank
# Re-Rank the top 3 chunks based on the gpt-3.5-turbo-0125 model
reranker = RankGPTRerank(
    top_n = 3,
    llm = OpenAI(model="gpt-3.5-turbo-0125"),
)
# Display the top 3 chunks based on RankGPT
query_bundle = QueryBundle(query_str=query)
ranked_nodes = reranker._postprocess_nodes(nodes, query_bundle = query_bundle)

for ranked_node in ranked_nodes:
    print('----------------------------------------------------')
    display_source_node(ranked_node, source_length = 500)

Usando RankGPT, otteniamo i seguenti chunk:

----------------------------------------------------

Node ID: 1bef0308-8b0f-4f7e-9cd6-92ce5acf811f
Similarity: 1.6185210943222046
Text: Coincidentally, Gosling turned down the Beast role in Beauty and the Beast in favor of La La Land. Chazelle subsequently decided to make his characters somewhat older, with experience in struggling to make their dreams, rather than younger newcomers just arriving in Los Angeles.Emma Stone plays Mia, an aspiring actress in Los Angeles. Stone has loved musicals since she saw Les Misérables when she was eight years old. She said "bursting into song has always been a real dream of mine", and her ...
----------------------------------------------------

Node ID: 9b3817fe-3a3f-4417-83d2-2e2996c8b468
Similarity: 3.0143558979034424
Text: Emily Jean "Emma" Stone (born November 6, 1988) is an American actress and producer. She is the recipient of various accolades, including two Academy Awards, two British Academy Film Awards, and two Golden Globe Awards. In 2017, she was the world's highest-paid actress and named by Time magazine as one of the 100 most influential people in the world. Born and raised in Scottsdale, Arizona, Stone began acting as a child in a theater production of The Wind in the Willows in 2000. As a teenager,...
----------------------------------------------------

Node ID: 576ae445-b12e-4d20-99b7-5e5a91ee7d74
Similarity: 2.2117154598236084
Text: Stone was named the best-dressed woman of 2012 by Vogue and was included on similar listings by Glamour in 2013 and 2015, and People in 2014.
== Personal life == Stone moved from Los Angeles to Greenwich Village, New York, in 2009. In 2016, she moved back to Los Angeles. Despite significant media attention, she refuses to publicly discuss her personal life. Concerned with living a normal life, Stone has said she dislikes receiving paparazzi attention outside her home. She has expressed her ...

Poiché RankGPT non ordina i passaggi in base al punteggio di similarità, i punteggi presentati nell’output non sono aggiornati. Dall’output possiamo osservare che il primo nodo considerato più rilevante menziona sia Emma Stone che Ryan Gosling, mentre i restanti nodi contengono più dettagli sulla vita di Emma Stone.

Ora, se stampiamo la risposta del modello con questa metodologia di Re-Ranking, otteniamo il seguente output:

Both Emma Stone and Ryan Gosling have close relationships with their families. Stone has expressed gratitude for having a great family and supportive people around her, while Gosling has drawn from his own experiences as an aspiring artist, indicating a connection to his family as well. Stone's family has played a significant role in her life, supporting her career pursuits and celebrating important milestones with her. Similarly, Gosling's experiences as an actor have likely been influenced by his family dynamics and relationships.

La risposta è più lunga e contiene più dettagli rispetto alla tecnica di Re-Ranking precedente.

Migliorare le prestazioni del RAG con le trasformazioni delle query

La trasformazione della query, detta anche riscrittura della query, è un approccio che converte una query in un’altra query invece di usare la query grezza per recuperare i primi k chunk. Esploreremo le seguenti tecniche:

  • HyDE: dove trasformiamo le query degli utenti e le loro risposte ipotetiche in embedding per recuperare documenti che corrispondono strettamente nello spazio vettoriale.
  • Trasformazioni multi-step delle query: dove dividiamo una query complessa dell’utente in sotto-domande sequenziali per un’elaborazione efficace.

Migliorare le prestazioni del RAG con HyDE

HyDE sta per Hypothetical Document Embeddings. Si compone di due passaggi. Per prima cosa crea una risposta ipotetica a una query dell’utente. Una volta determinata la risposta/documento ipotetici, la risposta e la query vengono trasformate in embedding. Quindi, il sistema recupera i documenti più vicini agli embedding nello spazio vettoriale. Vediamolo in azione!

# Import packages
from llama_index.core.indices.query.query_transform import HyDEQueryTransform
from llama_index.core.query_engine.transform_query_engine import (
    TransformQueryEngine,
)
# build index and query engine for the index
index = VectorStoreIndex.from_documents(documents, service_context=service_context_gpt3)
query_engine = index.as_query_engine(similarity_top_k=4)

# HyDE setup
hyde = HyDEQueryTransform(include_original=True)
# Transform the query engine using HyDE
hyde_query_engine = TransformQueryEngine(query_engine, hyde)

# Print the response from the model
response = hyde_query_engine.query("Compare the families of Emma Stone and Ryan Gosling")
print(response)

Questo è l’output:

Both Emma Stone and Ryan Gosling come from diverse family backgrounds. Ryan Gosling's parents were of part French Canadian descent, along with some German, English, Scottish, and Irish. He grew up in a family that practiced the Church of Jesus Christ of Latter-day Saints. On the other hand, Emma Stone was born and raised in Scottsdale, Arizona, without specific details provided about her family's ethnic background or religious affiliation.

Rispetto ai metodi di Re-Ranking, osserviamo un miglioramento parziale. In precedenza, gli output riguardavano maggiormente il rapporto degli attori con le loro famiglie. Ora si concentrano di più sulle origini.

Migliorare le prestazioni del RAG con trasformazioni multi-step delle query

L’approccio di trasformazione multi-step della query suddivide la query dell’utente in sotto-domande sequenziali. Questo metodo può essere utile quando si lavora con domande complesse.

Come abbiamo notato, gli LLM tendono a faticare quando confrontano due fatti, anche se possono rispondere correttamente quando la domanda riguarda solo un argomento specifico. Qui possiamo vedere in azione le trasformazioni multi-step delle query.

# Multi-step query setup
step_decompose_transform_gpt3 = StepDecomposeQueryTransform(gpt3, verbose=True)
index_summary = "Breaks down the initial query"
# Return query engine for the index
multi_step_query_engine = MultiStepQueryEngine(
    query_engine=query_engine,
    query_transform=step_decompose_transform_gpt3,
    index_summary=index_summary
)

# print the response from the model
response = multi_step_query_engine.query("Compare the families of Emma Stone and Ryan Gosling")

Possiamo vedere le domande intermedie che ci permettono di arrivare all’output finale:

> Current query: Compare the families of Emma Stone and Ryan Gosling
> New query: What is the family background of Emma Stone and Ryan Gosling?
> Current query: Compare the families of Emma Stone and Ryan Gosling
> New query: What is the specific family background of Emma Stone?
> Current query: Compare the families of Emma Stone and Ryan Gosling
> New query: What is Emma Stone's relationship with her family like?

Questa è la seguente risposta alla query dell’utente:

Both Ryan Gosling and Emma Stone have strong family connections, with Emma Stone emphasizing the importance of her family in keeping her grounded. Ryan Gosling's family background includes a mix of French Canadian, German, English, Scottish, and Irish heritage.

In questo caso, usare la trasformazione multi-step della query per confrontare le famiglie di Emma Stone e Ryan Gosling è stato utile.

Conclusione

In questo articolo hai imparato diverse tecniche per migliorare le prestazioni del RAG. Che si tratti di Chunking, Re-Ranking o trasformazioni delle query, l’approccio migliore dipende spesso dal caso d’uso e dall’output desiderato per una determinata query.

Se vuoi approfondire il RAG, ti consigliamo di guardare i nostri code-along su Retrieval Augmented Generation con LlamaIndex e Retrieval Augmented Generation con GPT e Milvus. Questi video mostrano come combinare LLM con database vettoriali usando il retrieval augmented generation in diversi casi d’uso.


Eugenia Anello's photo
Author
Eugenia Anello
LinkedIn

Data Scientist - CRIF

Argomenti
Intelligenza artificiale

Continua oggi il tuo percorso nell’AI!

Corso

Database vettoriali per Embeddings con Pinecone

3 ore
12.2K
Scopri come il database vettoriale Pinecone sta cambiando il modo di sviluppare le app di intelligenza artificiale!
Vedi i dettagliRight Arrow
Inizia Il Corso
Mostra altroRight Arrow
Correlato

blog

I 15 migliori server MCP remoti che ogni AI builder dovrebbe conoscere nel 2026

Scopri i 15 migliori server MCP remoti che stanno trasformando lo sviluppo AI nel 2026. Scopri come migliorano automazione, ragionamento, sicurezza e velocità dei workflow.
Abid Ali Awan's photo

Abid Ali Awan

15 min

blog

Tokenizzazione nel NLP: come funziona, sfide e casi d'uso

Guida al preprocessing NLP nel machine learning. Copriamo spaCy, i transformer di Hugging Face e come funziona la tokenizzazione in casi d'uso reali.
Abid Ali Awan's photo

Abid Ali Awan

10 min

blog

Che cos'è Snowflake? Guida per principianti alla piattaforma dati cloud

Esplora le basi di Snowflake, la piattaforma dati cloud. Scopri la sua architettura, le sue funzionalità e come integrarla nelle tue pipeline di dati.
Tim Lu's photo

Tim Lu

12 min

Mostra AltroMostra Altro