How to Build AI powered App in 5 minutes in Node.js

How to Build AI powered App in 5 minutes in Node.js

OpenAI api in action for a product-marketplace

·

2 min read

Hello

Hello

Did you try AI for real in your projects?
Specifically OpenAI API or just announeced Vertex from Google?

Here we are.
We will create a product generator for your next marketplace solution!

  1. Create a new project

  2. Init npm init es6

  3. Install open AI package npm install openai

  4. Create a file index.js

  5. Add this code

import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: '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' 
// Input Your Open AI key here from
// https://platform.openai.com/account/api-keys
});
const openai = new OpenAIApi(configuration);

async function getImage(info) {
  const response = await openai.createImage({
    prompt: info,
    n: 1,
    size: "256x256"
  });

  return response.data.data[0].url;
}

async function getProductInfo(info) {
  const completion = await openai.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [{ "role": "user", "content": `Generate a creative info in JSON for product type ${info}, use following structure  "{name: string, price: string, currency: string }", respond only with JSON` }]
  });

  const output = completion.data.choices[0].message.content;
  return JSON.parse(output);
}

function getProduct(info) {
  const productInfo$ = getProductInfo(info);
  const image$ = getImage(info);
  return Promise.all([productInfo$, image$]).then(([product, image]) => ({ ...product, imageUrl: image }));
}

async function execute() {
   const topic = 'Kid Toy';
   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);
}

execute();
  1. Execute the file node index.js

  2. Check terminal or console, you would see the following

Log example

Can you imagine? you just generated quite real products, it could be anything else. Be creative - test it out.

Ready

Now you have a list of products including price and image. Simple as that. You can render it into HTML and get results like on the image below?

Result example

What is the next step?

  • You can play around with prompt and experiment to make it

  • You can convert this into the server and build API or do a SPA

Let me know if you want to see the evolution of this project!
Will post more.

Follow me on Twitter
Connect on Linkedin