Home
Blog
Community

Use ChatGPT to Automate Product Description Writing

Jan 19, 2023 by

Ashutosh Krishna

Ashutosh avatar

Ashutosh Krishna

Never think about product descriptions. Automate product description creation with ChatGPT and Medusa

Use ChatGPT to Automate Product Description Writing - Featured image

Notice Medusa is under active development, so the content of this post may be outdated. Please check out our documentation instead.

In today's fast-paced ecommerce world, it's more important than ever to have compelling product descriptions that clearly and accurately convey the value of your offerings. However, crafting effective descriptions can be time-consuming, especially if you have a large catalog of products. This is where ChatGPT comes in.

With ChatGPT, you can easily automate the writing of your product descriptions, saving you time and effort while still delivering top-notch content to your customers. What if I told you that the previous paragraph was written by ChatGPT? Did you see how ChatGPT generated human-like text that is indistinguishable?

In this tutorial, you’ll learn how to use ChatGPT to automate writing your product descriptions in Medusa. Medusa is a composable ecommerce platform that can be integrated with any third-party services, including ChatGPT.

You can find the code for the tutorial in this repository.

Here’s a demo of the end result.

medusa-chatgpt-2462f90e

What is Medusa?

Medusa is an open source composable commerce engine for developers who want to take ownership of their ecommerce stack. The platform is highly extensible and easy to customize which has made it the #1 JavaScript Ecommerce Platform on Github in record time with 16K+ stars.

Medusa is composed of three components: the headless backend, the admin dashboard, and the storefront. You can set up an entire ecommerce store within minutes by running just a couple of commands.

Since Medusa is highly extensible, it allows developers to build custom features or integrate third-party services such as ChatGPT into Medusa very easily. You can learn more about the official and community plugins here.

What is ChatGPT?

OpenAI has developed a revolutionary long-form question-answering AI called ChatGPT; it is capable of answering complex questions conversationally. This technology is groundbreaking because it has been trained to understand the intended meaning behind human questions.

ChatGPT (Generative Pre-trained Transformer) is a powerful AI tool that leverages the capabilities of OpenAI's GPT-3.5 family of large language models. It has been fine-tuned using a combination of supervised and reinforcement learning techniques to deliver optimal performance.

Different Models Offered by GPT-3

The GPT-3 language models have the ability to understand and generate natural language. Four main language models are available, each with varying levels of power and capabilities to suit different tasks.

  • Copy to clipboardtext-davinci-003: It is the most advanced and capable language model in the GPT-3 family. It is capable of completing any task that the other models can perform, often with higher quality, longer output, and better ability to follow instructions. Additionally, it has the ability to insert completions within the text
  • Copy to clipboardtext-curie-001: It is highly capable, but faster and more cost-effective than Davinci.
  • Copy to clipboardtext-babbage-001: It can complete straightforward tasks efficiently and at a lower cost compared to other models.
  • Copy to clipboardtext-ada-001: It is capable of performing simple tasks quickly and at a low cost. It is typically the fastest model in the GPT-3 family.

Out of the above four, you’ll use the Copy to clipboardtext-davinci-003 for text completion in this tutorial as it yields the best results.

Getting Your OpenAI API Key

OpenAI provides different APIs to interact with its AI models. It provides you free credit worth $18 to experiment for the first three months.

Follow the steps below to get your free OpenAI API key:

  1. Go to OpenAI API and sign up for a free account. Follow the instructions, and you’ll be redirected to the API Dashboard.
  2. Click on your profile picture to view the menu bar, and then click on View API Keys to go to the API Keys page.
Screenshot_2023-01-02_141710
  1. Click on Create new secret key to create a new API Key.
Screenshot_2023-01-02_141730
  1. Copy the API Key and store it safely to use later in the tutorial.
Screenshot_2023-01-02_141752

Prerequisites

Before you get started with the tutorial, you should have installed:

Setting up Your Medusa Development Environment

In this section, you’ll create a Medusa server where you’ll integrate ChatGPT in the next step.

Setting up Your Medusa Server

Create a new Medusa store called Copy to clipboardmy-medusa-store and seed the test data using the following command:

medusa new my-medusa-store --seed

Start your Medusa server using the following command:

cd my-medusa-store
medusa develop

The above two steps take a couple of minutes to set up and run your server on port 9000. You can test your server by going to Copy to clipboardhttp://localhost:9000/store/products on your browser or by running the following command:

curl localhost:9000/store/products

If you get a list of products, your server is successfully set up.

Create a Subscriber to Handle Empty Descriptions

In this section, you’ll create a subscriber in your Medusa server that will listen to the Copy to clipboardproduct.created event. The subscriber then calls a function to handle the description field of the product. If the description field is empty, another function will be called to interact with ChatGPT’s Copy to clipboardtext-davinci-003 language model.

While you can directly interact with the models using their APIs, OpenAI also provides you with several official and community libraries for different languages.

Install the official OpenAI library in your Medusa server:

npm install openai

Add the Copy to clipboardOPENAI_API_KEY in the Copy to clipboard.env file in your Medusa server:

OPENAI_API_KEY=your-api-key-here
Note: Replace the value of Copy to clipboardyour-api-key-here with a valid API key that you obtained from OpenAI earlier in the tutorial.

Since you’re going to create a subscriber in your Medusa server, make sure you enable Redis in the Copy to clipboardmedusa-config.js:

module.exports = {
projectConfig: {
redis_url: REDIS_URL, // Enable Redis Here
//...
},
plugins,
};

Create a Copy to clipboarddescription.js file inside Copy to clipboardsrc/subscribers directory in the Medusa server and add the following content:

import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY, // Replace with your API key
});
class DescriptionSubscriber {
constructor({ productService, eventBusService }) {
this.productService_ = productService;
eventBusService.subscribe("product.created", this.handleDescription);
}
handleDescription = async (data) => {
let productDescription = "";
const product = await this.productService_.retrieve(data.id);
if (product.description == null) {
try {
const productName = product.title;
const productFeatures = [product.subtitle, product.material];
const prompt = `Write a product description for ${productName}, which has the following features: ${productFeatures.join(
", "
)}.`;
productDescription = await this.prepareDescription(prompt);
} catch (error) {
const errorMessage = error.response.data.error.message;
console.error("Error: " + errorMessage);
return;
}
product.description = productDescription;
await this.productService_.update(product.id, product);
}
};
prepareDescription = async (
prompt,
model = "text-davinci-003",
temperature = 0.7,
maxTokens = 256,
topP = 1,
frequencyPenalty = 0,
presencePenalty = 0
) => {
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model,
prompt,
temperature,
max_tokens: maxTokens,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
});
return response.data.choices[0].text.trim();
};
}
export default DescriptionSubscriber;

In the above code, you import the Copy to clipboardConfiguration class from the Copy to clipboardopenai module and then create a new Copy to clipboardConfiguration object using the Copy to clipboardConfiguration class. The Copy to clipboardConfiguration object is initialized with an API key for the OpenAI API.

You also define a subscriber called Copy to clipboardDescriptionSubscriber which includes a constructor and two methods: Copy to clipboardhandleDescription and Copy to clipboardprepareDescription.

The Copy to clipboardconstructor method subscribes to an event called Copy to clipboardproduct.created using the Copy to clipboardeventBusService and specifies that the Copy to clipboardhandleDescription method should be called whenever this event is emitted.

The Copy to clipboardhandleDescription method is an async function that is called with a Copy to clipboarddata argument. As mentioned in the documentation, the event data payload, i.e., the Copy to clipboarddata argument contains just the Copy to clipboardid of the created product. This method retrieves a product from the Copy to clipboardproductService using the Copy to clipboardid property of the Copy to clipboarddata object.

If the Copy to clipboarddescription of the product is Copy to clipboardnull, the method generates a description using the Copy to clipboardprepareDescription method and updates the product with the new description.

Copy to clipboardprepareDescription is an async function that is used to generate product descriptions using OpenAI's Text Completion API. The function takes several parameters as inputs:

  • Copy to clipboardprompt: a string that specifies the text prompt that the API should use as a starting point for generating text. In this case, the text that asks for a description of a product by its properties such as name, material, etc.
  • Copy to clipboardmodel: (optional, default: Copy to clipboard"text-davinci-003") a string that specifies the ID of the model that should be used to generate text.
  • Copy to clipboardtemperature: (optional, default: Copy to clipboard0.7) a float that specifies the sampling temperature to use when generating text.
  • Copy to clipboardmaxTokens: (optional, default: Copy to clipboard256) an integer that specifies the maximum number of tokens (i.e., words or word pieces) that should be generated.
  • Copy to clipboardtopP: (optional, default: Copy to clipboard1) a float that specifies the "top-p" value to use when generating text. Higher values will produce more conservative and deterministic output, while lower values will allow for more randomness and diversity in the output.
  • Copy to clipboardfrequencyPenalty: (optional, default: Copy to clipboard0) a float that specifies the frequency penalty to use when generating text. Higher values will produce more diverse output, while lower values will allow the model to reuse more common tokens.
  • Copy to clipboardpresencePenalty: (optional, default: Copy to clipboard0) a float that specifies the presence penalty to use when generating text.

The function creates an instance of the Copy to clipboardOpenAIApi class, which is used to communicate with the OpenAI API, and then calls the Copy to clipboardcreateCompletion method on this instance to generate text.

Testing the Flow

Once you’ve made the required changes in your Medusa server, you’ll need to build your project using the command:

npm run build

Next, you can restart your server using the command:

medusa develop

Setting up Your Medusa Admin

You can test the flow both from the Medusa Admin and the Admin APIs. In this case, you’ll test using the Medusa Admin.

Medusa Admin is an intuitively designed admin dashboard for your ecommerce Medusa server. Medusa Admin is built with Vite 3 and React. It allows merchants to manage their data such as products, orders, discounts, regions, and more.

Follow the steps to set up your Medusa Admin and create products:

Clone the Medusa Admin GitHub repository and change your path to the cloned directory:

git clone https://github.com/medusajs/admin my-medusa-admin
cd my-medusa-admin

Install the dependencies using the following command:

npm install

Once all the dependencies are installed, run the Admin server using the following command:

npm run start

The Medusa Admin runs on port 7000, so go to Copy to clipboardhttp://localhost:7000 in your browser to open your Admin Panel.

Screenshot_2023-01-02_153211

Since you’ve already seeded the data in your Medusa server, you can use the email Copy to clipboardadmin@medusa-test.com and password Copy to clipboardsupersecret to log in.

Creating Products in Medusa Admin

Click on the Copy to clipboardProducts tab on the left side and then click on the Copy to clipboardNew Product button.

Screenshot_2023-01-05_102325-173349ed

Since the admin is configured to fetch the products right after the product is created, which is before the subscriber runs, you’ll need to refresh the page to see the changes. You can customize the admin to refetch the product after it’s created to resolve this.

Screenshot_2023-01-05_102712

Once you publish a product without a description, your product will initially be created with an empty description. The Copy to clipboardproduct.created event is then emitted, and the Copy to clipboardDescriptionSubscriber is triggered.

Since the description is empty, the subscriber uses the Copy to clipboardprepareDescription function to generate a description and updates the description of the product.

Screenshot_2023-01-05_102525

Conclusion

In this tutorial, you learned how you can use ChatGPT to automate writing your product description. You can add more product features such as its price, variants, and more to generate a more unique description.

This integration was made easy due to Medusa’s composable architecture. You can learn more about Medusa through its documentation. Here are some documents that you can start with:

Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team via Discord.

Share this post

Try Medusa

Spin up your environment in a few minutes.