為產品描述建立嵌入向量
你拿到一個名為 products 的字典清單,其中包含某線上零售商所販售產品的資訊。你的任務是為每個產品的 'short_description' 建立嵌入向量,以便在該零售商網站上進行語意搜尋。
以下是 products 字典清單的預覽:
products = [
{
"title": "Smartphone X1",
"short_description": "The latest flagship smartphone with AI-powered features and 5G connectivity.",
"price": 799.99,
"category": "Electronics",
"features": [
"6.5-inch AMOLED display",
"Quad-camera system with 48MP main sensor",
"Face recognition and fingerprint sensor",
"Fast wireless charging"
]
},
...
]
一個 OpenAI 用戶端已建立並指定給 client。
本練習屬於課程
Introduction to Embeddings with the OpenAI API
練習說明
- 使用串列生成式建立名為
product_descriptions的清單,內容為products中每個產品的'short_description'。 - 使用「批次(batching)」為每個產品的
'short_description'產生嵌入向量,並將輸入傳給text-embedding-3-small模型。 - 從
response_dict萃取每個產品的嵌入向量,並以新的鍵'embedding'儲存在對應的products項目中。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Extract a list of product short descriptions from products
product_descriptions = [____ for product in ____]
# Create embeddings for each product description
response = ____
response_dict = response.model_dump()
# Extract the embeddings from response_dict and store in products
for i, product in ____:
product['embedding'] = response_dict[____][____][____]
print(products[0].items())