DEV Community

Cover image for How to code a product recommendation engine in PYTHON using ChatGPT?
giveitatry
giveitatry

Posted on • Originally published at dev.to

How to code a product recommendation engine in PYTHON using ChatGPT?

In today's highly competitive e-commerce landscape, personalized product recommendations are crucial for businesses to attract and retain customers. Machine learning algorithms can help achieve this goal by analyzing customer data and providing recommendations based on their preferences and behavior. In this article, I will explore how to code a product recommendation system using Python and the ChatGPT language model. We will leverage its capabilities to create a recommendation system that can suggest products to customers based on their previous purchases and browsing history.

Video explanation what we are going to code

Although the video demonstrates the execution of ChatGPT within the Tracardi platform, we will not be reproducing this process. Instead, we will examine the coding of the plugin to learn the methodology employed, which we can apply to our own projects.

If you're interested in using Tracardi for your projects or contributing to its development, you can access its repository on GitHub. Tracardi is an open-source project that allows developers to create highly customizable automation workflows and customer journey maps.

I encourage you to give them at least a github star for sharing how to use ChatGPT in product recommendations.

Getting started

To start using ChatGPT API, you will need to create an account with OpenAI and obtain an API key. The API key will give you access to the GPT-4 language model, which you can then use to generate text in a variety of contexts.

There are multiple pricing models available, each with different capabilities and price points. The pricing is based on the number of tokens you use, with 1,000 tokens roughly equivalent to 750 words.

You don't need to worry about the price of ChatGPT, as the pricing is quite reasonable for programmers and I have personally used it for a while without paying more than a dollar.

Library installation

The OpenAI API can be accessed through HTTP requests from any programming language using either the official Python bindings. To install the official Python bindings, use the command:

pip install openai
Enter fullscreen mode Exit fullscreen mode

As I mentioned the API uses API keys for authentication, which can be obtained from the API Keys page. Remember to keep your API key secure and not expose it in any client-side code.

All API requests should include your API key in an Authorization HTTP header as follows:

Authorization: Bearer OPENAI_API_KEY
Enter fullscreen mode Exit fullscreen mode

Requesting organization

For users who belong to multiple organizations, you can pass a header to specify which organization is used for an API request. Usage from these API requests will count against the specified organization's subscription quota.

Example curl command:

curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Organization: YOUR_ORG_ID"
Enter fullscreen mode Exit fullscreen mode

Example with the openai Python package:

import os
import openai
openai.organization = "YOUR_ORG_ID"
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Model.list()
Enter fullscreen mode Exit fullscreen mode

Making requests

To make your first API request, simply copy and paste the command below into your terminal. Just be sure to replace "$OPENAI_API_KEY" with your own secret API key.

Tracardi utilizes asynchronous API calls using asyncio, so it doesn't use the openai library. Therefore, I will adopt the same method and use raw REST API calls instead of the library. This approach will make the code more efficient and flexible.

To make an API call, you can use any existing library that you are familiar with. For simplicity, I will use the requests library.

We will be using the "https://api.openai.com/v1/completions" POST endpoint.

The plugin sends the following payload to that API, where prompt is the actual prompt:

prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length

payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
Enter fullscreen mode Exit fullscreen mode

Remember to set the headers:

headers = {
    "Authorization": f"Bearer {OPENAI_API_KEY}",
    "Content-Type": "application/json"
}
Enter fullscreen mode Exit fullscreen mode

Putting it all together, here's the actual request in Python using the requests library:

import requests

# set the OpenAI API endpoint
url = "https://api.openai.com/v1/completions"

# set the prompt and other parameters for the request
prompt = "Hello, how are you?"
prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length
payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# send the request to the OpenAI API endpoinsk-Nnndgp2NfhIVwXNcPC6kT3BlbkFJUJmZOlWuYImxSGaGdB4Gt
response = requests.post(url, headers=headers, json=payload)

# print the response content
print(response.json())
Enter fullscreen mode Exit fullscreen mode

Integrating ChatGPT response with your code

Tracardi has implemented a clever trick to integrate ChatGPT response with their code. They ask the chat to respond in JSON format, which is then parsed into a dictionary that can be used in the code.

To generate the desired response from ChatGPT, you need to provide the right prompt. Tracardi uses the following prompt for their use case:

Customer bought HERE_LIST_OF_PRODUCTS. What other products would you suggest to this customer? Please provide at least 3 suggestions as a pair of product name and category. Respond with a JSON list of objects. 
Enter fullscreen mode Exit fullscreen mode

Make sure to replace HERE_LIST_OF_PRODUCTS with the actual list of products that the customer bought.

So our code could look like this:

import requests

# set the OpenAI API endpoint
url = "https://api.openai.com/v1/completions"

# Add your api key
YOUR_API_KEY = ""

list_of_products = ["Adidas sneakers", "t-shirt"]
list_of_products = ",".join(list_of_products)

# set the prompt and other parameters for the request
prompt = f"Customer bought {list_of_products}. What other products would you suggest to this customer? Please provide at least 3 suggestions as a pair of product name and category. Respond with a JSON list of objects. "
prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length
payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
headers = {
    "Authorization": f"Bearer {YOUR_API_KEY}",
    "Content-Type": "application/json"
}

# send the request to the OpenAI API endpoint
response = requests.post(url, headers=headers, json=payload)

# print the response content
print(response.json())
Enter fullscreen mode Exit fullscreen mode

When I ran this code I got this response:

{
  "id": "cmpl-7d9JftFrUQy30f0amNadsryzd6V",
  "object": "text_completion", 
  "created": 1682415119,
  "model": "text-davinci-003", 
  "choices": [
    {"text": "\n\n[\n  {\n    "Product Name": "Adidas Track Pants",\n    "Category": "Clothing"\n  },\n  {\n    "Product Name": "Adidas Backpack",\n    "Category": "Bags"\n  },\n  {\n    "Product Name": "Adidas Sunglasses",\n    "Category": "Accessories"\n  }\n]", "index": 0, "logprobs": None, "finish_reason": "stop"}
  ], 
  "usage": {
    "prompt_tokens": 43, 
    "completion_tokens": 86, 
    "total_tokens": 129
  }
}
Enter fullscreen mode Exit fullscreen mode

We need to parse "choices" into dict and we can use the response in python code.

Here is the code to do that:

result = response.json()
choices = json.loads(result["choices"][0]["text"])
print(choices)
Enter fullscreen mode Exit fullscreen mode

We can certainly improve the accuracy of the prompt by including more specific information about our products. For example:

Customer bought {list_of_products}. What other products would you suggest to this customer, knowing that we sell {list_of_our_product_categories}. Please provide at least 3 suggestions as a pair of product name and category. Respond with a JSON list of objects in "choices" key. 
Enter fullscreen mode Exit fullscreen mode

With the fixed prompt I got the following result:

{
"choices": [
  {"product": "Energy Drinks", "category": "Beverages"}, 
  {"product": "Gym Bag", "category": "Training Equipment"},
  {"product": "Running Shorts", "category": "Sport Apparel"}
]
}
Enter fullscreen mode Exit fullscreen mode

Copy past code

import json
import requests

# set the OpenAI API endpoint
url = "https://api.openai.com/v1/completions"

# Add your api key
YOUR_API_KEY = ""

list_of_products = ["Adidas sneakers", "t-shirt"]
list_of_products = ",".join(list_of_products)
list_of_our_product_categories = "Sport apparel, energy drinks, training equipment, etc."

# set the prompt and other parameters for the request
prompt = f"Customer bought {list_of_products}. What other products would you suggest to this customer, " \
         f"knowing that we sell {list_of_our_product_categories}. Please provide at least 3 suggestions as " \
         f"a pair of product name and category. Respond with a JSON list of objects in \"choices\" key. "
prompt_length = len(prompt.split())
max_tokens = 1024 - prompt_length
payload = {
    "model": "text-davinci-003",
    "prompt": prompt,
    "max_tokens": max_tokens,
    "temperature": 0.5,
    "top_p": 1,
    "n": 1
}
headers = {
    "Authorization": f"Bearer {YOUR_API_KEY}",
    "Content-Type": "application/json"
}

# send the request to the OpenAI API endpoint
response = requests.post(url, headers=headers, json=payload)

# print the response content
result = response.json()
choices = json.loads(result["choices"][0]["text"])
print(choices)
Enter fullscreen mode Exit fullscreen mode

This simple trick can make you integration with chatGPT very easy. If you would like to use this approach within a customer journey - you can always install Tracardi and add your custom python plugins to it.

Top comments (0)