Xây dựng hàm truy xuất (retrieval)
Một bước quan trọng trong quy trình Retrieval Augmented Generation (RAG) là truy xuất dữ liệu từ cơ sở dữ liệu. Trong bài tập này, bạn sẽ thiết kế một hàm tùy chỉnh tên là retrieve() để thực hiện bước then chốt này trong bài tập cuối khóa.
Bài tập này là một phần của khóa học
Cơ sở dữ liệu vector cho Embeddings với Pinecone
Hướng dẫn bài tập
- Khởi tạo Pinecone client với API key của bạn (OpenAI client đã có sẵn là
client). - Định nghĩa hàm
retrievenhận bốn tham số:query,top_k,namespace, vàemb_model. - Tạo embedding cho
queryđầu vào bằng đối sốemb_model. - Truy xuất
top_kvector tương tự nhất vớiquery_embkèm metadata, và chỉ địnhnamespaceđược truyền vào hàm làm đối số.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Initialize the Pinecone client
pc = Pinecone(api_key="____")
index = pc.Index('pinecone-datacamp')
# Define a retrieve function that takes four arguments: query, top_k, namespace, and emb_model
def retrieve(query, top_k, namespace, emb_model):
# Encode the input query using OpenAI
query_response = ____(
input=____,
model=____
)
query_emb = query_response.data[0].embedding
# Query the index using the query_emb
docs = index.query(vector=____, top_k=____, namespace=____, include_metadata=True)
retrieved_docs = []
sources = []
for doc in docs['matches']:
retrieved_docs.append(doc['metadata']['text'])
sources.append((doc['metadata']['title'], doc['metadata']['url']))
return retrieved_docs, sources
documents, sources = retrieve(
query="How to build next-level Q&A with OpenAI",
top_k=3,
namespace='youtube_rag_dataset',
emb_model="text-embedding-3-small"
)
print(documents)
print(sources)