Get startedGet started for free

Product recommendation system

In this exercise, you'll make a recommendation system for an online retailer that sells a variety of products. This system recommends three similar products to users who visit a product page but don't purchase, based on the last product they visited.

You've been provided with a list of dictionaries of products available on the site,

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",
            ...
            "Fast wireless charging"
        ]
    },
    ...
]

and a dictionary for the last product the user visited, stored in last_product.

The following custom functions defined earlier in the course are also available for you to use:

  • create_embeddings(texts) → returns a list of embeddings for each text in texts.
  • create_product_text(product) → combines the product features into a single string for embedding.
  • find_n_closest(query_vector, embeddings, n=3) → returns the n closest distances and their indexes between the query_vector and embeddings, based on cosine distances.

This exercise is part of the course

Introduction to Embeddings with the OpenAI API

View Course

Exercise instructions

  • Combine the text features in last_product, and for each product in products, using create_product_text().
  • Embed the last_product_text and product_texts using create_embeddings(), ensuring that last_product_embeddings is a single list.
  • Find the three smallest cosine distances and their indexes using find_n_closest().

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Combine the features for last_product and each product in products
last_product_text = ____
product_texts = ____

# Embed last_product_text and product_texts
last_product_embeddings = ____
product_embeddings = ____

# Find the three smallest cosine distances and their indexes
hits = ____(____, product_embeddings)

for hit in hits:
  product = products[hit['index']]
  print(product['title'])
Edit and Run Code