開始使用免費開始

建立擷取函式

在 Retrieval Augmented Generation(RAG)流程中,一個關鍵步驟是從資料庫擷取資料。這題中,你將設計一個名為 retrieve() 的自訂函式,來執行這個關鍵步驟,並在本課最後的練習中使用。

本練習屬於課程

使用 Pinecone 構建 AI 應用

檢視課程

練習說明

  • 使用你的 API 金鑰初始化 Pinecone 用戶端(OpenAI 用戶端已提供為 client)。
  • 定義函式 retrieve,其參數為 querytop_knamespaceemb_model
  • 使用 emb_model 參數將輸入的 query 轉為嵌入向量。
  • 取回與 query_emb 最相似的 top_k 個向量,並包含其中繼資料,且將函式提供的 namespace 指定給查詢。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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)
編輯並執行程式碼