为产品描述创建嵌入向量
您拿到一个名为 products 的字典列表,其中包含一家在线零售商所售不同产品的信息。您的任务是为每个产品的 'short_description' 创建嵌入向量(embedding — 向量表示),以支持该网站的语义搜索。
以下是 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。
本练习是课程的一部分
使用 OpenAI API 的 Embeddings 入门
练习说明
- 使用列表推导式创建名为
product_descriptions的列表,包含products中每个产品的'short_description'。 - 使用批处理(batching)为每个产品的
'short_description'创建嵌入向量,输入到text-embedding-3-small模型。 - 从
response_dict中提取每个产品的嵌入向量,并将其存入products,键名为'embedding'。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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())