DEV Community

Cover image for ChatGPT API Requests Using Node.js
Andrew Knight
Andrew Knight

Posted on

ChatGPT API Requests Using Node.js

This week, I began learning how to integrate ChatGPT into my lifestyle assistant app. My journey has only begun and there is a lot to learn, but I want to share my growth with you in case it helps you get started faster.

The Baby Steps

Here are the steps I took to get started:

  1. Log into the OpenAI API site

  2. You can purchase credits to get started on the billing page unless you are eligible for a free trial. I only purchased $10 USD worth of credits to get started, and it will take me a while to use all of them. On the Billing page, make sure Auto recharge is off if you do not want to be automatically charged when you run out of tokens.

  3. Create your API Key - User API keys are now legacy, so you should create a Project API Key.

  4. Integrate ChatGPT into your application easily. I created a service in my React application with the following code. IMPORTANT: This will get you started with testing, but it is best to pull the API key value from a resource file instead of embedding it. You will be warned that setting the "dangerouslyAllowBrowser" value to true puts your application at risk. I will post an update as I learn of an improved way to do this.

import OpenAI from "openai";

const openai = new OpenAI({ 
  apiKey: 'API-KEY-HERE',
  dangerouslyAllowBrowser: true
});

export async function askChatGpt(role, content) {
  const completion = await openai.chat.completions.create({
    messages: [{ role: role, content: content }],
    model: "gpt-4o-mini",
  });

  return completion.choices[0];
}
Enter fullscreen mode Exit fullscreen mode

Example

In my app, the user completes the Wellness Plan form, and a call is made to ChatGPT to generate a wellness plan using the request JSON and return the result in a JSON format that I provide in the prompt. I'm sure there is a better way to do this, but I haven't learned that yet. I'll post an update as I learn of an improved way.

The Request
I use react-hook-form to construct my JSON as the form is completed, using the form control, and then I add that JSON into my prompt as criteria.

HelloLife.ai Wellness Form

The Response
In my prompt, I specify the JSON format that I would like ChatGPT to respond with, and then I store the response JSON and display it to the user.

HelloLife.ai Wellness Plan

HelloLife.ai Dashboard with Wellness Widget

Top comments (0)