Bắt đầu ngayBắt đầu miễn phí

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

Xem khóa học

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 retrieve nhậ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_k vector tương tự nhất với query_emb kèm metadata, và chỉ định namespace đượ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)
Chỉnh sửa và Chạy Mã