The demand for Generative AI integration is at an all-time high. Whether you are building a SaaS product or a personal portfolio, knowing how to connect a backend to an LLM (Large Language Model) is a “must-have” skill for the modern developer.

In this guide, we will build a simple but powerful AI script using Node.js and the OpenAI SDK.

Prerequisites

Before we start, ensure you have:

  • Node.js installed on your machine.
  • An OpenAI API Key (from platform.openai.com).

Step 1: Initialize Your Project

Create a new folder and initialize your npm package:

Bash

mkdir ai-chatbot-node
cd ai-chatbot-node
npm init -y
npm install openai dotenv

Step 2: Secure Your API Key

Create a .env file in your root directory. Never hardcode your API keys!

Plaintext

OPENAI_API_KEY=your_secret_key_here

Step 3: The Code Implementation

Create a file named index.js and add the following logic:

JavaScript

import OpenAI from "openai";
import 'dotenv/config';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function askAI(prompt) {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-4o", // Using the latest high-efficiency model
      messages: [{ role: "user", content: prompt }],
      max_tokens: 150,
    });

    console.log("AI Response:", response.choices[0].message.content);
  } catch (error) {
    console.error("Error communicating with OpenAI:", error);
  }
}

askAI("What are the top 3 benefits of using React for Gen AI interfaces?");

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *