ChatGPT API Requests Using Node.js
Andrew Knight
Posted on August 2, 2024
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:
Log into the OpenAI API site
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.
Create your API Key - User API keys are now legacy, so you should create a Project API Key.
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];
}
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.
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.
Posted on August 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.