Creating a Product Description Generator Using PrestaShop & ChatGPT

Written by sinenko | Published 2023/05/15
Tech Story Tags: prestashop | chatgpt | ai | gpt-4 | artificial-intelligence | programming | software-engineering | content-creation

TLDRAfter the release of Chat GPT-4 by OpenAI, we tested its ability to generate descriptions for obscure products for online stores. We were pleasantly surprised when, in some cases, it outperformed our content manager and did it much faster.via the TL;DR App

In our company, which is engaged in online sales of electronic components, creating product descriptions is quite a labor-intensive process, especially when it comes to some obscure chip with little information available or information in unknown languages.

After the release of Chat GPT-4 by OpenAI, we tested its ability to generate descriptions for obscure products for online stores. We were pleasantly surprised when, in some cases, it outperformed our content manager and did it much faster.

It became clear that we could now increase the speed of adding new product listings to our website and do it much more cost-effectively, while the services of the content manager would still be needed for creating descriptions for products unknown to Chat GPT-4 and for reviewing the generated responses before publishing.

It turned out that we started using PrestaShop from the beginning of our company's establishment, although we have since moved away from this CMS. PrestaShop is quite a popular e-commerce engine, and I thought someone might find that interesting.

Today we will be creating a module for generating product descriptions using Chat GPT-4 in an online store based on PrestaShop. This will simplify the life of the content manager. The content manager will only need to fill in the product name field, and the module will generate the description based on it.

I will demonstrate an example on PrestaShop version 8.0.4, but the same method will work for most older versions of PrestaShop and probably for new ones as well. Creating modules in PrestaShop is not difficult, and I believe it won't pose any challenges, even for beginners.

To start, create a directory with the name of our module in the /modules/ directory, for example: /gptdescription

Now, in the /modules/gptdescription directory, create a file with the same name as our module: gptdescription.php

In this file, we will have all the main code of the module. Create a class in it that should inherit from the Module class.

class GPTDescription extends Module
{


}

First, let's add a constructor:

private $api_key;
private $model;


public function __construct()
{
    $this->name = 'gptdescription';
    $this->tab = 'administration';
    $this->version = '0.1';
    $this->author = 'sinenko';
    $this->need_instance = 0;
    $this->ps_versions_compliancy = ['min' => '8.0.4', 'max' => '8.0.4'];
    $this->bootstrap = true;


    $this->api_key = Configuration::get('GPT4INTEGRATION_API_KEY'); // API key
    $this->model = Configuration::get('GPT4INTEGRATION_MODEL'); // GPT model


    parent::__construct();


    $this->displayName = $this->l('GPT-4 product description generator');
    $this->description = $this->l('Automatically generate product descriptions using GPT-4.');


    $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
}

In the constructor, we specify the name, version, author, and description of our module, which will be displayed during the installation and uninstallation of the module. We also specify two parameters, api_key and model, which will be configurable in the module's configuration through the admin panel.

Now let's create a method that will generate a description based on the product title.

private function generateDescription($productTitle)
{
    $api_key =  $this->api_key;
    $model = $this->model;


}


In this method, we will use CURL to make requests to the OpenAI API and generate our description.

To obtain an API key, we need to go to the following link: https://platform.openai.com/account/api-keys and complete the registration process. After registration, you need to create a new API key and save it. We will specify this key in the settings of our future module.


Now let's go to the documentation and see which models are currently available to us at https://platform.openai.com/docs/models.

At the time of writing this article, specifically in May 2023, the following models are available: We are interested in GPT-4 (Limited beta as of May 2023), and if you don't have access to the GPT-4 model, we will add the ability to switch to GPT-3.5 in our module:

  • gpt-4
  • gpt-4-0314
  • gpt-4-32k
  • gpt-4-32k-0314

GPT-3.5:

  • gpt-3.5-turbo
  • gpt-3.5-turbo-0301
  • text-davinci-003
  • text-davinci-002
  • code-davinci-002

Based on my small tests, we will use gpt-4 and gpt-3.5-turbo as they are more suitable for generating product descriptions.

Now, according to the documentation at https://platform.openai.com/docs/api-reference/chat, to interact with the chat, we need to send a POST request to the following URL https://api.openai.com/v1/chat/completions in the following format:

{
    "model": "gpt-4", // Selected GPT model
    "messages": [
      {
        "role": "assistant", // Role of the assistant
        "content": "Please make a product description for me" // Text of the request
      }
    ],
    "max_tokens": 4000, // Maximum number of tokens in the response
    "n": 1, // Number of text variants
    "stop": [ // Up to 4 sequences where the API will stop generating further tokens.
      "\\n"
    ],
    "temperature": 0.1 // Temperature (creative component)
  }

In the "content" parameter, we will pass our prompt query to the chat for generating the description.

"max_tokens" is the token limit for the response. OpenAI charges for API usage based on the number of tokens used for the request and response. Therefore, the shorter the query and the shorter the response, the cheaper it will be for you to generate the product description. If you're not familiar with tokens, you can think of one token roughly equaling one word.

Prices at the time of writing this article are as follows:

  • GPT-3.5-turbo $0.002/1K tokens of all
  • GPT-4 8K $0.03/1K tokens of promts $0.06/1K tokens of response
  • GPT-4 32K$0.06/1K tokens of promts$0.12/1K tokens of response

The lower the "temperature" parameter, the more precise and deterministic the chat will generate the product description. You can experiment with it depending on the type of products in your catalog.

Let's make a test request to the API and see the format of the response.

private function generateDescription($productTitle = '74HC4066N')
{
    $api_key =  'your_key';
    $model = 'gpt-4';


    if (!$api_key || empty($api_key) || !$model || empty($model)) {
        return null;
    }


    $url = 'https://api.openai.com/v1/chat/completions'; // URL GPT-4 API


    $prompt = 'make a product description for online-store: ';
    $prompt .= $productTitle;


    $data = [
        'model' => $model, // Selected GPT model
        'messages' => [[
            'role' => 'assistant',
            'content' => $prompt // Text of the request
        ]],
        'max_tokens' => 4000, // Maximum number of tokens in the response
        'n' => 1, // Number of text variants
        'temperature' => 0.1 // Temperature (creative component)
    ];


    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ];


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch); 
    curl_close($ch);


    print_r($response);


}

After the request, we receive the following response:

{
    "id": "chatcmpl-7EbpN1nlH4PwMQ3YPmVcoMspPNtqy",
    "object": "chat.completion",
    "created": 1683716357,
    "model": "gpt-4-32k-0314",
    "usage": {
      "prompt_tokens": 11,
      "completion_tokens": 219,
      "total_tokens": 230
    },
    "choices": [
      {
        "message": {
          "role": "assistant",
          "content": "Product Title: 74HC4066N Quad Bilateral ..... Add it to your cart now!"
        },
        "finish_reason": "stop",
        "index": 0
      }
    ]
  }

We can see that the response includes the number of tokens used for the request and response, which allows us to analyze the service load and estimate the cost of generating our descriptions. The chat-generated messages in response to our request are stored in the "choices" array. The "message" objects contain the "content" parameter, which is the description of our product. I made a request for generating a description for the 74HC4066N microchip, and the complete chat response looks as follows:

Product Title: 74HC4066N Quad Bilateral Switch IC

Product Description:

The 74HC4066N is a high-speed Si-gate CMOS device, built to provide exceptional performance in a wide range of applications. As a quad bilateral switch, it integrates four independent switches into one compact package, with each switch having two input/output terminals and an active HIGH enable input.

Key Features:

1. Quad Bilateral Switch: The 74HC4066N houses four independent switches, allowing for versatile usage in various electronic circuits.

2. High-Speed CMOS Logic: Designed for optimal performance, the 74HC4066N is built with high-speed CMOS logic, ensuring fast and efficient operation.

3. Low Power Dissipation: This device offers low power dissipation, making it ideal for battery-powered or energy-efficient applications.

4. Versatility: Each switch in the 74HC4066N can pass both digital and analog signals, from DC up to the MHz range, making it suitable for a diverse range of applications.

5. Low ON Resistance: The device offers low "on" resistance, ensuring maximum signal integrity.

Applications:

The 74HC4066N is perfect for a variety of applications, including signal gating, chopping, modulation or demodulation (modem), and signal multiplexing for analog-to-digital and digital-to-analog conversion systems.

Package Information:

This IC comes in a 14-pin PDIP (Plastic Dual-In-line Package), designed for easy integration into your circuit board.

The 74HC4066N is an ideal choice for designers and hobbyists looking for a versatile, high-performance switch IC. Its consistent performance and reliability make it a staple in any electronic toolkit. 

Please note: Always ensure that you operate this device within its recommended specifications to guarantee its longevity and performance.

If you're looking for an efficient and versatile switch for your electronic projects, the 74HC4066N Quad Bilateral Switch IC is the perfect choice. Add it to your cart now!

As we can see, the product description is very clear and well-written, almost comparable to what a content manager would have written.

Now let's complete our function and add the ability to edit and save the product descriptions. Additionally, PrestaShop supports product descriptions in HTML format, so we can modify our prompt to specify that the product description should be formatted with HTML tags. We can also notice that ChatGPT suggests not only the description but also the title of the product. Let's ask GPT to format the response and indicate where the title of the product is and where the short description, and we will save this information in the corresponding fields in PrestaShop.

The new prompt will look as follows:

$prompt = 'Provide an answer: a description with product specifications for an online store in pure html format (without classes, styles, and id, give the product title id="product-title", make the product summary id="product-summary",  make the product description and key-features id="product-description "), if the product is unknown to you, then write {not-found}: ';

Now the product description will look as follows:

<div>
  <h1 id="product-title">74HC4066N Quad Bilateral Switch IC</h1>
 
  <p id="product-summary">
    The 74HC4066N is a high-speed Si-gate CMOS device, offering exceptional performance in a wide range of applications. As a quad bilateral switch, it integrates four independent switches into one compact package.
  </p>


  <div id="product-description">
    <h2>Product Description and Key Features</h2>
    <p>
      1. <strong>Quad Bilateral Switch:</strong> The 74HC4066N houses four independent switches, allowing for versatile usage in various electronic circuits.
    </p>
    <p>
      2. <strong>High-Speed CMOS Logic:</strong> Designed for optimal performance, the 74HC4066N is built with high-speed CMOS logic, ensuring fast and efficient operation.
    </p>
    <p>
      3. <strong>Low Power Dissipation:</strong> This device offers low power dissipation, making it ideal for battery-powered or energy-efficient applications.
    </p>
    <p>
      4. <strong>Versatility:</strong> Each switch in the 74HC4066N can pass both digital and analog signals, from DC up to the MHz range, making it suitable for a diverse range of applications.
    </p>
    <p>
      5. <strong>Low ON Resistance:</strong> The device offers low "on" resistance, ensuring maximum signal integrity.
    </p>
    <p>
      This IC comes in a 14-pin PDIP (Plastic Dual-In-line Package), designed for easy integration into your circuit board. If you're looking for an efficient and versatile switch for your electronic projects, the 74HC4066N Quad Bilateral Switch IC is the perfect choice.
    </p>
  </div>
</div>

Now we can easily parse this response into its components if needed. Additionally, if the GPT chat doesn't recognize such a product, it will return the response {not-found}. Let's complete the code that will return an array with the ready product description:

// Checking if the response is set
if (isset($response_data['choices'][0]['message'])) {
    // Checking if the response is not {not-found}
    if ($response_data['choices'][0]['message']['content'] !== '{not-found}') {
        $result['content'] = $response_data['choices'][0]['message']['content'];


    }
   
    $pattern = '/<[^>]*id="product-title"[^>]*>(.*?)<\/[^>]*>/';
    preg_match($pattern, $response_data['choices'][0]['message']['content'], $matches_title);
   
    // Checking if the title is set
    if (!empty($matches_title)) {
        $result['title'] = $matches_title[1];
    }
   
   
    $pattern = '/<[^>]*id="product-summary"[^>]*>(.*?)<\/[^>]*>/';
    preg_match($pattern, $response_data['choices'][0]['message']['content'], $matches_summary);
   
    // Checking if the summary is set
    if (!empty($matches_summary)) {
        $result['summary'] = $matches_summary[1];
    }
   
    return $result;
}

Now our function retrieves the product name, short description, and full description from the response of the GPT chat and returns a ready array for saving.

Now we just need to save the obtained data into the necessary fields of PrestaShop. To do this, we will add a hook called hookActionProductUpdate to our module. This hook is executed when we update (edit and save) a product. Therefore, all the code we specify in this hook will be executed when the "Update" button is pressed in the product editing panel:

public function hookActionProductUpdate($params)
{
    $product = $params['product'];


    // Checking if the description is already generated
    if($product->description[1] !== '{gpt}' && $product->description[1] !== '<p>{gpt}</p>') {
        return;
    }
    $productTitle = $product->name[1]; // Getting the product name
    $generatedDescription = $this->generateDescription($productTitle); // Generating the description


    if ($generatedDescription !== null) {
        if(!empty($generatedDescription['title'])) {
   
            $product->name[1] = $generatedDescription['title'];
        }
        if(!empty($generatedDescription['summary'])) {
            $product->description_short[1] = $generatedDescription['summary'];
        }
        if(!empty($generatedDescription['content'])) {
            $product->description[1] = $generatedDescription['content'];
        }
    }
    $product->validateFields();
}

Here we specified that we need to generate a new description only if, when pressing the Update button during editing, the text {gpt} is present in the description field. In all other cases, the description will remain the same as before pressing the Update button.

Our module is almost ready; we just need to make a small adjustment. I'm not sure about other versions of PrestaShop, but in version 8.0.3, the hook hookActionProductUpdate is called in the Product->update() method after saving the product. Therefore, our changes will not be saved. Hence, we need to create a directory in our module called override/classes. In this directory, create a file named Product.php and override the update() method. In this method, we need to place the hook calls before saving the product.

Our module is ready; we just need to add installation, uninstallation, and create an interface for module configuration, specifically for entering the API key and selecting the model. I won't go into detail about this in the article, but you can view the complete module on GitHub.

https://github.com/sinenko/gptPrestaProductDescription

Now, after installing the module, we go to its settings and enter our API key. If you don't have access to the GPT-4 model, then switch the model to GPT-3.5. It is also capable of generating product descriptions, but it does it less effectively. Sometimes it adds nonexistent facts, and even if the model is not familiar with a particular product, it still tries to come up with a description for it, which may not be acceptable in our task.

Now open our arbitrary product, enter the text {gpt} in the description field, and click on Update:

After saving, we get a new title for the product and a short description generated by the GPT chat:

Additionally, we have the full product description generated by the GPT chat:

Thus, in less than an hour, we have created a module that has the potential to improve the quality of product descriptions and simplify the work of content managers. Moreover, based on this module, it is possible to create a module that translates product descriptions into other languages or corrects errors found in previously added products.



Written by sinenko | CEO, WEB Software Engineer, Production of 3D printers
Published by HackerNoon on 2023/05/15