How to Build AI powered App in 5 minutes in Node.js
OpenAI api in action for a product-marketplace
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!
Create a new project
Init
npm init es6
Install open AI package
npm install openai
Create a file
index.js
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();
Execute the file
node index.js
Check terminal or console, you would see the following
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?
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.