為語意搜尋進行向量 upsert
是時候把一些文字資料轉成嵌入向量(embedding),並將向量與中繼資料 upsert 到你的 'pinecone-datacamp' 索引了!已提供名為 squad_dataset.csv 的資料集,且已將其中 200 筆樣本載入為 DataFrame df。
在本練習中,要透過 OpenAI API 使用其 embedding 模型,你不需要建立並使用自己的 API 金鑰。 已為你建立可用的 OpenAI 用戶端,並指定給變數 client。
你的任務是使用 OpenAI 的 API 將文字轉成嵌入向量,並將這些向量與中繼資料以命名空間 squad_dataset upsert 到 Pinecone 索引中。
本練習屬於課程
使用 Pinecone 構建 AI 應用
練習說明
- 使用你的 API 金鑰初始化 Pinecone 用戶端(OpenAI 用戶端已可用,變數為
client)。 - 從每個批次的
row中擷取'id'、'text'與'title'的中繼資料。 - 使用 OpenAI 的
'text-embedding-3-small',並設定維度為1536,對texts進行編碼。 - 將向量與中繼資料 upsert 到名為
'squad_dataset'的命名空間。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize the Pinecone client
pc = Pinecone(api_key="____")
index = pc.Index('pinecone-datacamp')
batch_limit = 100
for batch in np.array_split(df, len(df) / batch_limit):
# Extract the metadata from each row
metadatas = [{
"text_id": row['____'],
"text": row['____'],
"title": row['____']} for _, row in batch.iterrows()]
texts = batch['text'].tolist()
ids = [str(uuid4()) for _ in range(len(texts))]
# Encode texts using OpenAI
response = ____(input=____, model="____")
embeds = [np.array(x.embedding) for x in response.data]
# Upsert vectors to the correct namespace
____(vectors=____(ids, embeds, metadatas), namespace=____)