How to build AI solution capable to build a e-commerce store
Tags: gpt3, javascript, api, marketplace
Published: 2023-07-11 18:32:14

AI today is everywhere, while big corporates fight for a place under the shining sun, we can use AI for quite a practical purpose.

One issue every person faces once is building something from scratch. The same happens for code. If you join an existing project you can just repeat and change. You don't need to build a thing from scratch quite often.

The same happens every day in other areas users act: would it be a marketplace product description, or bio for your Twitter profile, it's all could be generated via AI today and it would be in the best English ever and it would be in the tone you want it to be.

### **What is the goal of this post?**

This post is an evolution of another one I did a [month ago](https://dev.to/igorboky/how-to-build-ai-powered-app-in-5-minutes-in-nodejs-1413). Now we do the next step and talk more about system prompts, which we usually provide to AI as a general context. We will talk about ChatGPT API, but the idea is the same for other APIs.

**So this time we will go deeper and make a small node.js app that allows us to build a full e-commerce store!**  
  
Ready to go?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7eals8r0ulsq3nqcc0m6.gif)


  

### The plan

It's pretty simple, we need to prepare all the information, collect it together and share it with the world.

* Generate Products + Images [(done in prev post)](https://dev.to/igorboky/how-to-build-ai-powered-app-in-5-minutes-in-nodejs-1413)
    
* Generate Categories
    
* Distribute products among categories
    
* Present the result as a single JSON.
    

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukhlmrp1ath00d9mbhbp.gif)


### Preparations

Please start with this guide and [repeat all steps there](https://dev.to/igorboky/how-to-build-ai-powered-app-in-5-minutes-in-nodejs-1413)

On top of it, there is one more function to handle ChatGPT API responses in a better way from [this post](https://dev.to/igorboky/how-to-ask-ai-to-return-json-in-the-right-way-181i). It allows to retry requests to API in case it responses with not a pure JSON.

```javascript
async function createChatCompletition(prompt, retryAttempts = 2, currentAttempt = 1) {
  const completion = await openai.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [{ "role": "user", "content": prompt }]
  });

  const output = completion.data.choices[0].message.content;
  try {
    return JSON.parse(output);
  }
  catch (err) {
    if (retryAttempts > currentAttempt) {
      return createChatCompletition(prompt, retryAttempts, currentAttempt + 1)
    }

    return throw 'Not a json from API';
  }
}
```

### Every Product Needs a Category

Let's start by creating a list of categories and then distributing products generated last time between them. To create categories we need a simple method

```javascript
function getCategories(info, count) {
  const propmt = `Generate array of ${count} objects where each object is a unique product category of marketplace which is described as ${info},
  use following structure  "{name: string}",
  respond only with JSON`;

  return createChatCompletition(propmt);
}
```

That's it, now we have to distribute existing products. We will write a simple method working like this

```typescript
  products.forEach((product, index) => {
    product.category = categories[index] ? categories[index]["name"] : categories[0];
  })
```

It doesn't guarantee that all categories would be connected to at least one product, you can experiment here to make it better, and you can also as ChatGPT to do that distribution for you.

### Let's collect things together

So far we have products and categories, what is a missing puzzle here? Let's think about a company that could sell this. Let's ask API to create a nice name for a company that could sell these beautiful products

```typescript
function getCompany(info) {
  const propmt = `Use ${info} to generate information about the company: name, slug, slogan, description 2 sentences. Please respond with JSON in format {name, slug, description}. Send only JSON`;
  return createChatCompletition(propmt);
}
```

So the final result would look like this.

```javascript
async function execute() {
   const topic = 'Toy for kids';
   const productNumbers = 4;
  
   const promises = [];
   for (let i = 0; i < productNumbers; ++i) {
     promises.push(getProduct(topic))
   }

   const products = await Promise.all(promises);
   console.log('PRODUCTS', products);
   const categories = await getCategories(topic, 3);
   console.log('CATEGORIES', categories);
   addCategoriesToProducts(products, categories);
   const companyInfo = await getCompanyInfo(topic);

   console.log({
    ...companyInfo,
    products,
    categories,
   });
}

execute();
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mt4c7h17y89fcm20abvi.gif)


### What could be the next step or many?!

If we can imagine that we continue in that direction we can come up with a nice tool, we can call [AI Marketplace Builder](https://apps.fleexy.dev/demo/build-marketplace). Fleexy team just released one to test this out.

[![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689076501381/133fa504-c55b-4aba-9f21-421ed7b30546.png align="center")](https://apps.fleexy.dev/demo/build-marketplace)

### At the end

We did one more step ahead to build something new, just imagine we didn't have this possibility a year ago, now it's time for such creative solutions to become real. I would continue experimenting with AI on such practical aspects to post further.  
  
  
**Gift me your likes/stars, it will help me to stay motivated!**


Follow me on [Twitter](https://twitter.com/BotanMan)
Connect on [Linkedin](https://www.linkedin.com/in/igorboky/)