DEV Community

Igor Boky
Igor Boky

Posted on

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

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();
Enter fullscreen mode Exit fullscreen mode

6) Execute the file node index.js
7) 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 expirement 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] (https://www.linkedin.com/in/igorboky/

Top comments (5)

Collapse
 
n_demia profile image
Natalia Demianenko

Awesome, waiting for the next post

Collapse
 
eliazer_braun_2b427f370f4 profile image
Eliazer Braun

make sure to mask your api key (if not yet)

Collapse
 
igorboky profile image
Igor Boky

It was revoked at the moment of publishing :) But thanks for checking!

Collapse
 
mohamad_reza_7c2640b8d31a profile image
Mohamad Reza

import { Configuration, OpenAIApi } from "openai";
^^^^^^^^^^^^^
SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'
at ModuleJob._instantiate (node:internal/modules/esm/module_job:134:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:217:5)
at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)

Node.js v20.15.0

Collapse
 
mohamad_reza_7c2640b8d31a profile image
Mohamad Reza

file:///media/sonic/NTFS/AI/index.js:1
import { Configuration, OpenAIApi } from "openai";
^^^^^^^^^^^^^
SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'
at ModuleJob._instantiate (node:internal/modules/esm/module_job:134:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:217:5)
at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)

Node.js v20.15.0