Contextual Retrieval là gì?
Mặc dù các hệ thống RAG truyền thống hữu ích, chúng có một nhược điểm lớn: thường chia tài liệu thành các đoạn nhỏ để dễ truy xuất hơn, nhưng điều này có thể làm mất ngữ cảnh quan trọng.
Ví dụ, một đoạn có thể nói “Hơn 3,85 triệu cư dân của nó khiến đây là thành phố đông dân nhất Liên minh Châu Âu” nhưng không đề cập thành phố hay quốc gia nào đang nói đến. Thiếu ngữ cảnh có thể dẫn tới kết quả không đầy đủ hoặc không liên quan, đặc biệt khi cần chi tiết cụ thể.

Nguồn: Introducing Contextual Retrieval
Contextual retrieval khắc phục điều này bằng cách tạo và thêm một phần giải thích ngắn, theo ngữ cảnh, cho mỗi đoạn trước khi nhúng. Trong ví dụ trên, đoạn sẽ được chuyển đổi như sau:
contextualized_chunk = """Berlin is the capital and largest city of Germany, known for being the EU's most populous city within its limits.
Its more than 3.85 million inhabitants make it the European Union's most populous city, as measured by population within city limits.
"""

Nguồn: Introducing Contextual Retrieval
Nhìn chung, các thử nghiệm nội bộ của Anthropic trên nhiều lĩnh vực, gồm mã nguồn, bài báo khoa học và tác phẩm văn học, cho thấy contextual retrieval giảm lỗi truy xuất 49% khi sử dụng cùng mô hình contextual embedding và Contextual BM25.

Nguồn: Introducing Contextual Retrieval
Triển khai Contextual Retrieval
Tiếp theo, tôi sẽ giải thích từng bước cách triển khai contextual retrieval. Chúng ta sẽ dùng tài liệu mẫu sau làm ví dụ:
# Input text for the knowledge base
input_text = """Berlin is the capital and largest city of Germany, both by area and by population.
Its more than 3.85 million inhabitants make it the European Union's most populous city, as measured by population within city limits.
The city is also one of the states of Germany and is the third smallest state in the country in terms of area.
Paris is the capital and most populous city of France.
It is situated along the Seine River in the north-central part of the country.
The city has a population of over 2.1 million residents within its administrative limits, making it one of Europe's major population centers."""
Bước 1: Chia tài liệu thành các đoạn
Bước đầu tiên là chia tài liệu mẫu thành những đoạn nhỏ, độc lập. Trong ví dụ này, chúng ta sẽ tách theo từng câu.
# Splitting the input text into smaller chunks
test_chunks = [
'Berlin is the capital and largest city of Germany, both by area and by population.',
"\\n\\nIts more than 3.85 million inhabitants make it the European Union's most populous city, as measured by population within city limits.",
'\\n\\nThe city is also one of the states of Germany and is the third smallest state in the country in terms of area.',
'\\n\\n# Paris is the capital and most populous city of France.',
'\\n\\n# It is situated along the Seine River in the north-central part of the country.',
"\\n\\n# The city has a population of over 2.1 million residents within its administrative limits, making it one of Europe's major population centers."
]
Bước 2: Định nghĩa mẫu prompt
Tiếp theo, chúng ta sẽ thiết lập prompt mà mô hình dùng để tạo ngữ cảnh cho từng đoạn. Anthropic cung cấp một mẫu hữu ích cho việc này. Prompt sẽ nhận hai đầu vào: toàn bộ tài liệu và đoạn văn bản cụ thể cần đặt vào ngữ cảnh.
from langchain.prompts import ChatPromptTemplate, PromptTemplate, HumanMessagePromptTemplate
# Define the prompt for generating contextual information
anthropic_contextual_retrieval_system_prompt = """<document>
{WHOLE_DOCUMENT}
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{CHUNK_CONTENT}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else."""
# Create a PromptTemplate for WHOLE_DOCUMENT and CHUNK_CONTENT
anthropic_prompt_template = PromptTemplate(
input_variables=['WHOLE_DOCUMENT', 'CHUNK_CONTENT'],
template=anthropic_contextual_retrieval_system_prompt
)
# Wrap the prompt in a HumanMessagePromptTemplate
human_message_prompt = HumanMessagePromptTemplate(prompt=anthropic_prompt_template)
# Create the final ChatPromptTemplate
anthropic_contextual_retrieval_final_prompt = ChatPromptTemplate(
input_variables=['WHOLE_DOCUMENT', 'CHUNK_CONTENT'],
messages=[human_message_prompt]
)
Bước 3: Khởi tạo mô hình ngôn ngữ bạn chọn
Tại đây, bạn có thể chọn bất kỳ LLM nào để tạo ngữ cảnh cho từng đoạn. Trong ví dụ, chúng ta sẽ dùng mô hình GPT-4o của OpenAI.
import os
from langchain_openai import ChatOpenAI
# Load environment variables
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
# Initialize the model instance
llm_model_instance = ChatOpenAI(
model="gpt-4o",
)
Bước 4: Ghép mọi thứ lại với nhau
Chúng ta sẽ nối mẫu prompt với mô hình ngôn ngữ để tạo thành một chuỗi LLM sẵn sàng xử lý các đoạn đã tạo trước đó.
from langchain.output_parsers import StrOutputParser
# Chain the prompt with the model instance
contextual_chunk_creation = anthropic_contextual_retrieval_final_prompt | llm_model_instance | StrOutputParser()
Bước 5: Xử lý từng đoạn
Giờ chúng ta sẽ lặp qua các đoạn, tạo thông tin ngữ cảnh cho từng đoạn và in kết quả bằng chuỗi LLM contextual_chunk_creation.
# Process each chunk and generate contextual information
for test_chunk in test_chunks:
res = contextual_chunk_creation.invoke({
"WHOLE_DOCUMENT": input_text,
"CHUNK_CONTENT": test_chunk
})
print(res)
print('-----')
The document compares Berlin and Paris, highlighting Berlin as Germany's capital and largest city by area and population, and noting its significance within the European Union.
-----
Berlin is the capital and largest city of Germany, known for being the EU's most populous city within its limits.
-----
Berlin is the capital and largest city of Germany, both by area and by population.
-----
Paris, the capital of France, is a major population center in Europe with over 2.1 million residents.
-----
Paris is the capital and most populous city of France.
-----
Paris is the capital and most populous city of France, with a population of over 2.1 million residents within its administrative limits.
-----
Cải thiện bằng Reranking
Dù contextual retrieval nâng độ chính xác truy xuất, bạn có thể đẩy xa hơn nữa với reranking. Kỹ thuật lọc này đảm bảo chỉ các đoạn liên quan nhất được gửi tới mô hình, nâng chất lượng phản hồi và giảm chi phí lẫn thời gian xử lý.
Reranking hoạt động bằng cách chấm điểm các đoạn được truy xuất ở bước đầu và chỉ giữ lại những đoạn tốt nhất. Trong thử nghiệm của chúng tôi, reranking giảm lỗi truy xuất từ 5,7% xuống chỉ 1,9%, cải thiện độ chính xác 67% so với phương pháp truyền thống.

Nguồn: Introducing Contextual Retrieval
Các lưu ý bổ sung
Nghiên cứu của Anthropic cho thấy không phải tình huống nào cũng cần độ phức tạp của contextual retrieval. Với các kho tri thức nhỏ dưới 200.000 token (xấp xỉ 500 trang), lựa chọn tốt hơn có thể là đưa thẳng toàn bộ kho tri thức vào prompt của mô hình, bỏ qua nhu cầu dùng hệ thống truy xuất.
Họ cũng khuyến nghị tận dụng prompt caching, một tính năng được giới thiệu cho Claude. Bằng cách lưu tạm các prompt thường dùng giữa các lần gọi API, nhà phát triển có thể giảm chi phí tới 90% và rút ngắn thời gian phản hồi hơn hai lần. Sổ tay prompt caching này cung cấp hướng dẫn từng bước để triển khai.
Kết luận
Contextual retrieval của Anthropic là một phương pháp đơn giản nhưng hiệu quả để cải thiện hệ thống truy xuất. Kết hợp contextual embeddings, BM25 và reranking giúp nâng độ chính xác của các hệ thống này một cách đáng kể.
Để tìm hiểu thêm về các kỹ thuật truy xuất khác, tôi khuyến nghị các bài blog sau:
Ryan là trưởng nhóm khoa học dữ liệu, chuyên xây dựng các ứng dụng AI sử dụng LLM. Anh là nghiên cứu sinh Tiến sĩ về Xử lý Ngôn ngữ Tự nhiên và Đồ thị Tri thức tại Imperial College London, nơi anh cũng hoàn thành bằng Thạc sĩ Khoa học Máy tính. Ngoài lĩnh vực khoa học dữ liệu, anh viết bản tin Substack hàng tuần, The Limitless Playbook, nơi anh chia sẻ một ý tưởng có thể áp dụng ngay từ các tư tưởng gia hàng đầu thế giới và đôi khi viết về những khái niệm cốt lõi của AI.

Retrieval-augmented generation (RAG) giúp các mô hình AI bổ sung thêm tri thức từ nguồn bên ngoài. Tuy nhiên, các hệ thống này thường làm mất ngữ cảnh quan trọng, dẫn đến kết quả kém chính xác.
Anthropic đã phát triển contextual retrieval, một cách đơn giản nhưng hiệu quả để cải thiện truy xuất thông tin. Giữ đúng ngữ cảnh cho từng đoạn giúp giảm lỗi truy xuất tới 67%, nhờ đó nâng cao đáng kể hiệu suất ở các tác vụ phía sau.
Trong bài viết này, tôi sẽ giải thích contextual retrieval và cách bạn có thể sử dụng nó trong ứng dụng của mình.