Easily restore your project to a previous version with our new Instant One-click Backup Recovery

Using AI to generate product descriptions in Hygraph

Learn how to expand Hygraph’s management features to create a custom field that can generate text using ChatGPT.
Raji Sankar

Raji Sankar

Sep 12, 2023
Using AI to generate product descriptions in Hygraph

In this pioneering era of AI, new uses for the technology are appearing all the time. If you have an online shop, you might want to consider using AI to generate your product descriptions. With the Hygraph headless CMS, you can easily create and fill custom fields with ChatGPT-generated text, saving you significant time and creative energy.

This article shows you step by step how to streamline product description creation for a sample eCommerce system. You’ll learn how to expand Hygraph’s management features to create a custom field that can generate text using ChatGPT’s completion capability.

#Why Hygraph?

As a headless CMS, Hygraph gives you the administration tools to manage your content so you can focus on your eCommerce shop’s presentation.

Common CMS capabilities, such as creating, editing, and publishing content, are available out of the box, as are pre-built starter schemas for eCommerce, blogs, portfolios, documentation, marketing, podcasts, and travel apps. You can access content created in Hygraph via GraphQL in your UI. And with Hygraph’s localized content management, you can even deliver content specific to a user's location.

Hygraph also offers extension options that enhance its capability beyond its basic features, which is how you’ll be able to complete the objectives in this tutorial. You can extend Hygraph's content management UI in a couple different ways:

  • Create a custom field element. You can add this to any object as a type while defining the schema. The following tutorial uses this method.

    Schema editing

  • Include a sidebar element. Find this in Hygraph’s sidebar, when content is created or edited.

    Content editing

#Setting up Hygraph for AI-generated product descriptions

Before you dive into this tutorial headfirst, we’re assuming a few things about you:

Editor's Note

You can access the code for this project on GitHub

Create content for your eCommerce CMS

To begin, create a Hygraph account. After logging in, create a new project from the Commerce Shop starter project. Give it a name (this tutorial uses My Clothing Shop) and a description in the dialogue that appears.

To access sample content, select Include Template Content. Select where you wish to host the project, and click Add Project. This adds the sample content to the project and sets up all the necessary schema for hosting a shop.

Once your project is built, you can access the schema, view content, and explore various Hygraph capabilities. To view endpoint information, click Project Settings. Make note of the content endpoint; you’ll use it to retrieve data.

Project Settings

Create a simple React application to view data

Clone Hygraph’s GitHub project and change the directory to hygraph-examples/with-reactjs. Use a text editor to modify src/App.js.

Change the request URL to the content endpoint you noted earlier from Hygraph’s project settings. Change the Product GraphQL to retrieve the name, ID, and slug along with the description and images.

Your code should look as follows:

{
products {
id
name
slug
description
images {
url
width
height
}
}
}

Change src/Product.js to show the extra fields retrieved:

return (
<div>
<h1>{product.name}</h1>
<p>{product.slug}</p>
<p>{product.description}</p>
<img src={product.images[0].url} width={product.images[0].width} height={product.images[0].height}/>
</div>
);

Run npm install, then run npm start. You can view the application at http://localhost:3000/products/snapback. Click a product listing to see more details.

Create a custom field element

As mentioned earlier, this tutorial uses a custom field element to generate a product description. While field elements can have various extension types—String, Integer, Float, JSON, or complex types that combine several fields into one component—this tutorial uses a String field element, shown as a text box with a Generate Description button.

We’ll use Hygraph’s boilerplate project to develop a simple custom field that will allow the user to store and get a String. Run the following command to generate a Next.js project containing a starter field element and sidebar element:

npx create-next-app --example https://github.com/hygraph/hygraph-app-nextjs-quick-start auto-fill-description

You can see the created directory structure here:

Directory structure of project

Note that:

  • The pages/setup.tsx file includes the code that runs when this app is installed for a project.
  • The basic field element code is located in pages/field.tsx.
  • The sidebar element code is located in pages/sidebar.tsx.
  • A standard pages/api/hello.ts file implements an API.

Hygraph offers three node modules for use in the app framework code:

  • @graphcms/app-sdk: This contains SDK components like AppProps, FieldExtensionProps, and FormSidebarExtensionProps that give access to often-requested properties for the app, such installation status or access to the form data.
  • @graphcms/app-sdk-react: This module exposes the SDK components as custom React hooks.
  • @hygraph/baukasten: The node modules under @hygraph have to do with UI and rendering. They include layouts, rendering components like Input and TextArea, icons, and themes, among others.

We'll use the boilerplate setup code for this article, but you can change it as you see fit. For instance, you can change it so that the OpenAI secret key is configured rather than hardcoded.

The boilerplate code in field.tsx is simple:

<Flex>
<Input
placeholder="Type something here"
value={value || ""}
onChange={(e: any) => onChange(e.target.value)}
/>
</Flex>

Flex is a layout and Input is a rendering component provided by Hygraph in the @hygraph/baukasten package. The rendering components shown in the following screenshot are also provided by Hygraph:

hygraph/baukasten package

The FieldExtensionProps offered by @graphcms/app-sdk allows you to access the form data and events like onChange and onBlur. When the data in the input field is changed, the boilerplate code calls the API's onChange method, which stores the modified data in the form.

Editor's Note

Check out Hygraph’s documentation for more information.

The boilerplate code in sidebar.tsx is also simple:

<Flex>
<Button flex="1" onClick={() => alert("Hello!")}>
Click Me
</Button>
</Flex>

As you can see, the boilerplate only provides a button that displays an alert after clicking. For now, let's just run the server with the boilerplate as is and configure the app.

Run npm install, then npm run dev in the autofill description directory to launch the server on port 3000 by default. Note that when you access the URL directly in the web browser (eg http://localhost:3000/setup), you’ll encounter the SDK connection error, check logs error. You must use Hygraph for access.

To create the app, select the eCommerce project you created (ie My Clothing Shop) from your Hygraph dashboard. Select Apps from the sidebar, then click Add new app.

Note that after your app is created, you can’t alter the permissions. For this tutorial, select read/write access for all options.

General Details

Add the field element and give details for it as shown:

Add Element

Click Register app and save the client ID and secret from the pop-up dialogue box. Close the dialogue and select Back to app list. The app you just registered should be listed here.

Registered app

Your Auto Fill Description app is now created in Hygraph and is currently available for installation on many projects.

Let's go ahead and install it for your My Clothing Shop project. Click the install icon next to the app, and in the dialogue that appears, select My Clothing Shop, then Master Environment. Finally, click Install app.

App install

In the dialogue that appears, provide the app with the permissions you selected when you created it. The setup page from the boilerplate code displays after authorization, with the Install component code first. Click Install App, then the Configure component code will appear.

Setup page

Click Save to install the app for the project.

The custom field element included in the boilerplate code is now available for use in this project.

Add the field to the product schema

Click Schema in Hygraph’s sidebar, then Product. The custom field should be listed as Generate Description under STRING. Click it to add it to the Product schema.

Add description field

The field should now be displayed in the Product schema and editable in the Product content.

Display the generate description button

In order to replace the default input box with a Generate Description button over a text area, modify pages/field.tsx as follows:

//add this function to FieldElement
function changevalue() {
}
//change the return statement
return (
<Stack>
<Button onClick={ () => changevalue() }>Generate Description</Button>
<TextArea
placeholder="Type something here"
value={value || ""}
onChange={(e: any) => onChange(e.target.value)}
/>
</Stack>
);

This switches the component from Input to TextArea; alters the layout from Flex to Stack; and adds a button labeled Generate Description.

Currently, when you click the button, it simply calls an empty changevalue function. You need to add code to generate the description.

Add an API to call ChatGPT

You can, of course, manually modify the description in the text section. However, this tutorial is going to generate it with AI.

You want a click on Generate Description to build a prompt based on information from the other product fields. ChatGPT’s gpt-3.5-turbo model will then call OpenAI’s completion API to generate a description. The additional product field values will pass to this API using Next.js’s dynamic routing feature. A hypothetical URL to call the API might be http://localhost:3000/api/gpt/backpack/back-pack/, which includes the product name and slug. This tutorial will design the API to accept product name, slug, description, price, and variants.

First, register and create an OpenAI API key. Copy the generated key to use later.

OpenAI API Key

Create a directory called gpt under pages/api, then create a file called [...product].ts under this directory. You can refer to OpenAI’s chat completion API for the code to call OpenAI.

Use npm install openai --save to install the OpenAI node module. Edit your [...product].ts file and add this function to call OpenAI for a given prompt and return the completion as a String:

const openaifetcher=async (prompt: String) : Promise<String> => {
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: '<Your openai api key>',
});
const openai = new OpenAIApi(configuration);
const completion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{role: "user", content: prompt }],
});
return completion.data.choices[0].message.content;
}

Be sure to include the handler, which will respond to API calls.

This code creates a prompt with the following text:

Editor's Note

marketing description for a black/medium t-shirt costing $20. Start with this description: A comfortable T-shirt.

Of course, the prompt will change depending on the available data. You can play around with different prompts—remember that GitHub has the whole source code.

type Completion = {
description: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Completion>
) {
const { query } = req;
const { product : [name, slug, description, price, variants] } = query;
let prompt = `"A marketing description for "`;
if (variants) {
prompt += `" a ${variants} "`;
}
prompt += `" ${name} "`;
if (price) {
prompt += `" costing ${price}"`;
}
if (description) {
prompt += `". Start with this description: ${description}."`;
}
openaifetcher(prompt).then((description) => {
res.status(200).json(`${description}`);
});
}

Access the URL http://localhost:3000/api/gpt/backpack/back-pack/ in a browser to test the API. Make sure you receive content.

Editor's Note

Note that the API created here is not secure. You can add security to ensure that only authorized users access it.

Generated content

Call the API upon button click

Now you need to edit the pages/fields.tsx to invoke the API you just developed with the appropriate parameters.

The form variable is available in FieldExtensionProps, which you can use to access the other values in the form. Declare the form variable in the custom hook together with value and onChange (const value, form, onChange = useFieldExtension();). The async function getState() returns all of the values in the form.

Use these values to access additional fields in the Product object and build the API URL. Change the code as follows:

function changevalue() {
const formvalues = form.getState().then((values) => {
console.log(values.values);
let api = "/api/gpt/" + values.values.localization_en.name + "/" + values.values.localization_en.slug;
api += "/" + values.values.localization_en.description;
api += "/" + values.values.localization_en.price;
fetch(api).then((res) => {
const data = res.json();
data.then((content) => {
console.log(content);
onChange(content);
});
});
});
}

The values are stored based on localization. In this instance, you’ve used localization_en values. You can change the function to accommodate other requirements, like using unsaved values and other locale data. Following that, the code calls fetch to invoke the API and retrieve a description. The onChange method sets this as the content of the text area in the custom field element.

Now, refresh the product’s edit page and click Generate Description. ChatGPT should generate a description and populate it into the text box.

Generated description

Save and then publish the product to save and publish the AI description.

You can now change the ecommerce React.js app you created earlier to show aiProductDescription instead of description—modify the GraphQL in App.js to use aiProductDescription instead of description, and modify Product.js to use product.aiProductDescription instead of product.description. Load your app page, and it should show the description generated.

Keep in mind, of course, that this tutorial uses your local machine to test the custom field element. This has to be productionalized (ie installed, configured, secured) and then deployed onto a production server. After that, you can change the app details as necessary to service all users.

#Conclusion

As technology figures out how to work with AI created content, you might want to consider how you could integrate it with your CMS to save you time and creative energy. In this article, you learned how to set up an ecommerce CMS in Hygraph, as well as how to create a UI to access and view data. You made use of Hygraph’s enhanced content management capabilities by adding a custom field that uses ChatGPT to generate a product description for you.

Blog Author

Raji Sankar

Raji Sankar

Technical writer

Raji Sankar has more than 25 years of experience as an enterprise architect, and product design in various domains such as supply chain execution, order management, warehouse management, and middleware diagnostics. She holds patents in fields related to performance analysis of middleware systems as part of the middleware diagnostics solution envisioned and developed in Oracle. Raji has been involved in conceptualizing and architecting a next-generation cloud SaaS platform that received the TechSpark 2013 award.

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.