Khóa học
Retrieval Augmented Generation (RAG) là một trong những kỹ thuật phổ biến nhất để cải thiện độ chính xác và độ tin cậy của các Mô hình Ngôn ngữ Lớn (LLM). Điều này khả thi nhờ cung cấp thêm thông tin từ các nguồn dữ liệu bên ngoài, giúp câu trả lời phù hợp với ngữ cảnh cụ thể và có thể cập nhật mà không cần fine-tune hay huấn luyện lại.
Dù RAG rất phổ biến, nó không phải lúc nào cũng hoạt động tốt trong mọi ngữ cảnh. Bài viết này sẽ giải thích từng bước cách xây dựng pipeline RAG hiệu quả, các hạn chế của RAG và cách khắc phục. Bắt đầu thôi!
RAG (Retrieval Augmented Generation) hoạt động như thế nào?

Hình ảnh từ Tài liệu LlamaIndex
Pipeline RAG gồm ba bước: Lập chỉ mục (Indexing), Truy xuất (Retrieval) và Sinh (Generation).
Lập chỉ mục
Lập chỉ mục là nền tảng để có được câu trả lời chính xác và nhận biết ngữ cảnh với LLM. Trước tiên, dữ liệu được trích xuất và làm sạch từ nhiều định dạng tệp như Word, PDF hoặc HTML. Khi dữ liệu đã được làm sạch, nó được chuyển sang văn bản thuần theo chuẩn. Để tránh giới hạn ngữ cảnh trong LLM, văn bản được chia thành các đoạn nhỏ hơn (chunk). Quá trình này gọi là Chunking. Sau đó, mỗi chunk được biến đổi thành một vector số hoặc embedding bằng mô hình embedding. Cuối cùng, một chỉ mục được xây dựng để lưu trữ các chunk và embedding tương ứng dưới dạng cặp khóa-giá trị.
Truy xuất
Trong giai đoạn truy xuất, truy vấn của người dùng cũng được chuyển thành biểu diễn vector bằng cùng mô hình embedding. Sau đó, điểm tương đồng giữa vector truy vấn và các chunk đã vector hóa được tính toán. Hệ thống truy xuất ra K chunk có độ tương đồng lớn nhất với truy vấn.
Sinh
Truy vấn của người dùng và các chunk được truy xuất được đưa vào một mẫu prompt. Prompt được tăng cường từ các bước trước sẽ được đưa làm đầu vào cho LLM.
Hạn chế của RAG
Khi xây dựng hệ thống RAG, bạn có thể gặp những thách thức đáng kể ở cả ba bước vừa nêu, chẳng hạn như:
- Lập chỉ mục: Hiệu quả của RAG bị ảnh hưởng nhiều bởi chất lượng dữ liệu. Nếu nguồn dữ liệu bên ngoài nhiễu nhiều hơn hữu ích, câu trả lời do LLM tạo ra sẽ không có giá trị.
- Truy xuất: Tùy thuộc vào loại tệp và cách bạn thiết lập RAG, hệ thống không phải lúc nào cũng truy xuất được những chunk giúp trả lời truy vấn.
- Sinh: Ngay cả khi hệ thống RAG được thiết lập hiệu quả, LLM vẫn có thể tạo ra câu trả lời sai dựa trên các “sự kiện tưởng tượng”.
Dưới đây, chúng ta sẽ khám phá các chiến lược để vượt qua những hạn chế này. Chúng ta sẽ bàn về ba nhóm chiến lược: Chunking, Re-Ranking và Biến đổi truy vấn. Ngoài ra, chúng ta sẽ trình diễn cách những chiến lược này giúp cải thiện hiệu năng RAG bằng cách xây dựng một hệ thống RAG trả lời câu hỏi về các bài viết Wikipedia sử dụng LlamaIndex và OpenAI API. Cùng đào sâu nhé!
Thiết lập hệ thống RAG cơ sở
Trước khi tìm mẹo cải thiện hiệu năng RAG, chúng ta cần thiết lập một baseline bằng một pipeline RAG đơn giản. Bắt đầu bằng cách cài đặt các gói llama-index và openai.
!pip install llama-index
!pip install openai
LlamaIndex là một framework dữ liệu cho các ứng dụng dựa trên Mô hình Ngôn ngữ Lớn (LLM). Nó cho phép nạp nhiều loại nguồn dữ liệu bên ngoài, xây dựng hệ thống Retrieval Augmentation Generation (RAG) và trừu tượng hóa việc tích hợp với các LLM khác chỉ bằng vài dòng code. Ngoài ra, nó cung cấp nhiều kỹ thuật để tạo đầu ra chính xác hơn với LLM.
Theo mặc định, nó dùng mô hình OpenAI gpt-3.5-turbo để sinh văn bản và text-embedding-ada-002 cho truy xuất và embedding. Để sử dụng các mô hình này, bạn cần tạo tài khoản miễn phí trên nền tảng OpenAI và lấy khóa API. Để lấy khóa, vui lòng truy cập tài liệu API của OpenAI.
import os
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
Giờ khi các gói đã được cài đặt, chúng ta sẽ xây dựng hệ thống RAG trả lời câu hỏi dựa trên trang Wikipedia của Emma Stone, Ryan Gosling và La La Land. Trước tiên, cài đặt thư viện wikipedia để trích xuất các trang Wikipedia:
!pip install wikipedia
Sau đó, ta có thể dễ dàng tải dữ liệu từ 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)
Khi dữ liệu đã được trích xuất, ta chia tài liệu thành các chunk 256 ký tự, không chồng lắp. Sau đó các chunk này được biến đổi thành vector số bằng mô hình embedding và được lập chỉ mục trong 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)
Để giảm rủi ro “ảo giác”, chúng ta sử dụng mô-đun PromptTemplate để đảm bảo câu trả lời của LLM chỉ dựa trên ngữ cảnh đã cung cấp.
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)
Khi hệ thống RAG đã sẵn sàng, chúng ta có thể kiểm thử bằng các câu hỏi dựa trên tài liệu đã truy xuất. Hãy thử nhé!
Truy vấn 1: “Cốt truyện của bộ phim giúp Emma Stone giành tượng vàng Oscar đầu tiên là gì?”
Truy vấn đầu tiên khó vì yêu cầu mô hình xem xét nhiều mẩu thông tin:
- Tên bộ phim giúp Emma Stone giành tượng vàng Oscar đầu tiên (trong trường hợp này là La La Land)
- Cốt truyện của bộ phim đó.
# 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))
Kết quả:
The plot of the film that made Emma Stone win her first Academy Award is not explicitly mentioned in the provided context.
Truy vấn 2: "So sánh gia đình của Emma Stone và Ryan Gosling”
Truy vấn thứ hai còn khó hơn vì yêu cầu chọn các chunk liên quan đến gia đình của hai diễn viên.
# 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))
Chúng ta nhận được kết quả sau:
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.
Như bạn thấy, cả hai lần đều cho câu trả lời chưa tốt. Ở các phần tiếp theo, hãy xem cách cải thiện hiệu năng hệ thống RAG này!
Cải thiện hiệu năng RAG bằng cách cập nhật kích thước chunk
Ta có thể bắt đầu bằng cách tùy chỉnh kích thước và độ chồng lắp của chunk. Như đã nói, tài liệu được chia thành các chunk với một mức chồng lắp cụ thể. Mặc định, LlamaIndex dùng kích thước chunk 1024 và độ chồng lắp 20. Ngoài các siêu tham số này, hệ thống mặc định truy xuất 2 chunk hàng đầu.
Ví dụ, ta có thể đặt kích thước chunk là 512, độ chồng lắp là 50 và tăng số chunk truy xuất hàng đầu:
# 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)
Truy vấn 1: “Cốt truyện của bộ phim giúp Emma Stone giành tượng vàng Oscar đầu tiên là gì?”
# 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)
Kết quả:
The film that made Emma Stone win her first Academy Award is a romantic musical called La La Land.
So với câu trả lời trước, đã khá hơn một chút. Mô hình nhận ra La La Land là bộ phim giúp Emma Stone giành tượng vàng Oscar đầu tiên, nhưng vẫn chưa mô tả được cốt truyện.
Truy vấn 2: "So sánh gia đình của Emma Stone và Ryan Gosling”
# generate the response
response = query_engine.query("Compare the families of Emma Stone and Ryan Gosling")
print(response)
Kết quả:
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.
Tiếp tục có cải thiện, nhưng vẫn chưa nắm bắt được thông tin về gia đình của Ryan Gosling.
Cải thiện hiệu năng RAG với Re-Ranking
Khi tập dữ liệu lớn và phức tạp hơn, việc chọn thông tin liên quan để trả lời sát các truy vấn phức tạp trở nên sống còn. Vì mục đích này, nhóm kỹ thuật Re-Ranking cho phép bạn xác định những chunk quan trọng trong văn bản. Chúng sắp xếp lại và lọc tài liệu, xếp hạng những tài liệu liên quan nhất lên trước.
Có hai cách tiếp cận chính cho Re-Ranking:
- Dùng mô hình Re-Ranking như một kỹ thuật thay thế cho mô hình embedding. Chúng nhận đầu vào là truy vấn và ngữ cảnh, trả về điểm tương đồng thay vì embedding
- Dùng LLM để nắm bắt thông tin ngữ nghĩa trong tài liệu hiệu quả hơn.
Trước khi áp dụng các cách Re-Ranking này, hãy đánh giá ba chunk đứng đầu mà hệ thống RAG cơ sở trả về cho truy vấn thứ hai:
# 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)
Đây là đầu ra trước khi Re-Ranking; mỗi chunk có Node ID cùng điểm tương đồng.
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 với FlagEmbeddingReranker
Để truy xuất các chunk liên quan, ta có thể dùng một mô hình Re-Ranking mã nguồn mở từ Hugging Face, gọi là bge-reranker-base.
Giống OpenAI API, dùng Hugging Face yêu cầu bạn có user access token. Bạn có thể tạo token theo tài liệu này.
HF_TOKEN = userdata.get('HF_TOKEN')
os.environ['HF_TOKEN'] = HF_TOKEN
Trước khi tiếp tục, ta cũng cần cài đặt các thư viện cần thiết để dùng mô hình Re-Ranking:
%pip install llama-index-postprocessor-flag-embedding-reranker
!pip install git+https://github.com/FlagOpen/FlagEmbedding.git
Cuối cùng, ta dùng mô hình bge-reranker-base để trả về các chunk liên quan nhất.
# 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)
Đây là kết quả sau 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 ...
Từ đầu ra, có thể thấy node có ID 1bef0308-8b0f-4f7e-9cd6-92ce5acf811f chuyển từ vị trí thứ hai xuống thứ ba. Ngoài ra, đáng chú ý là độ biến thiên điểm tương đồng lớn hơn.
Giờ khi đã dùng Re-Ranking, hãy xem phản hồi RAG cho truy vấn gốc trông như thế nào:
# 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)
Đây là phản hồi sau khi áp dụng mô hình 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ó cải thiện đáng kể so với trước đó, nhưng vẫn chưa đầy đủ. Hãy xem cách tiếp cận Re-Ranking dựa trên LLM có thể giúp gì thêm.
Re-Ranking với RankGPTRerank
Lần này, chúng ta dựa vào một LLM như một Re-Ranker. Ở đây, ta dùng mô-đun RankGPT, tận dụng khả năng của GPT để xếp hạng tài liệu trong hệ thống RAG. Bắt đầu bằng cách cài đặt các gói cần thiết:
%pip install llama-index-postprocessor-rankgpt-rerank
Ta dùng hàm RankGPTRerank để Re-Rank các chunk bằng mô hình 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)
Dùng RankGPT, ta nhận được các chunk sau:
----------------------------------------------------
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 ...
Vì RankGPT không sắp xếp đoạn theo điểm tương đồng, các điểm trong đầu ra không được cập nhật. Từ đầu ra, có thể thấy node đầu tiên được xem là liên quan nhất đề cập cả Emma Stone và Ryan Gosling, trong khi các node còn lại chứa chi tiết về cuộc sống của Emma Stone.
Giờ nếu in phản hồi của mô hình với phương pháp Re-Ranking này, ta được kết quả sau:
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.
Câu trả lời dài hơn và chứa nhiều chi tiết hơn so với kỹ thuật Re-Ranking trước.
Cải thiện hiệu năng RAG với Biến đổi truy vấn
Biến đổi truy vấn (query transformation), còn gọi là viết lại truy vấn, là cách chuyển một truy vấn thành truy vấn khác thay vì dùng truy vấn gốc để truy xuất top k chunk. Chúng ta sẽ khám phá các kỹ thuật sau:
- HyDE: Chuyển truy vấn người dùng và câu trả lời giả định của nó thành embedding để truy xuất tài liệu gần nhất trong không gian vector.
- Biến đổi truy vấn nhiều bước: Chia truy vấn phức tạp thành các tiểu câu hỏi tuần tự để xử lý hiệu quả.
Cải thiện hiệu năng RAG với HyDE
HyDE là viết tắt của Hypothetical Document Embeddings. Gồm hai bước. Đầu tiên, tạo câu trả lời giả định cho truy vấn. Khi đã có câu trả lời/tài liệu giả định, cả câu trả lời và truy vấn được biến đổi thành embedding. Sau đó, hệ thống truy xuất các tài liệu gần nhất với embedding trong không gian vector. Cùng thử nhé!
# 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)
Kết quả:
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.
So với các phương pháp Re-Ranking, ta thấy có cải thiện một phần. Trước đây, đầu ra nghiêng về mối quan hệ với gia đình; giờ tập trung hơn vào nguồn gốc.
Cải thiện hiệu năng RAG với Biến đổi truy vấn nhiều bước
Cách biến đổi truy vấn nhiều bước sẽ tách truy vấn của người dùng thành các câu hỏi phụ theo trình tự. Phương pháp này hữu ích khi xử lý câu hỏi phức tạp.
Như ta đã thấy, LLM thường gặp khó khi so sánh hai thực tế, dù có thể trả lời đúng khi câu hỏi chỉ liên quan một chủ đề cụ thể. Đây là lúc biến đổi truy vấn nhiều bước phát huy tác dụng.
# 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")
Ta có thể thấy các câu hỏi trung gian giúp đi đến đầu ra cuối:
> 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?
Đây là phản hồi cho truy vấn của người dùng:
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.
Trong trường hợp này, dùng biến đổi truy vấn nhiều bước để so sánh gia đình của Emma Stone và Ryan Gosling tỏ ra hữu ích.
Kết luận
Trong bài viết này, bạn đã học nhiều kỹ thuật để cải thiện hiệu năng RAG. Dù là Chunking, Re-Ranking hay Biến đổi truy vấn, cách tiếp cận tốt nhất thường phụ thuộc vào bài toán và đầu ra bạn mong muốn cho một truy vấn nhất định.
Nếu muốn đào sâu về RAG, chúng tôi khuyến nghị xem các video code-along về Retrieval Augmented Generation với LlamaIndex và Retrieval Augmented Generation với GPT và Milvus. Các video này minh họa cách kết hợp LLM với cơ sở dữ liệu vector bằng retrieval augmented generation trong nhiều bài toán khác nhau.
