DEV Community

hikari.huang
hikari.huang

Posted on

1

How to use OpenAI API with JavaScript

(This article is translated from https://zenn.dev/hikaelis/articles/b93cc6f94a6bd3)
This shows how to access to GPT4/3.5 using openai v4 of JavaScript Library.
The usage was changed from version 4 . I tried it on node18.

1. Install the Library

Install openai v4 via npm or yarn

npm install --save openai
# or
yarn add openai
Enter fullscreen mode Exit fullscreen mode

2. Get API KEY of OpenAI

Get API KEY of OpenAI from OpenAI site. Please be careful it isn't the same as ChatGPT Plus.
https://openai.com/blog/openai-api

3. Coding

The usage was significantly changed from v4 (it became easier)
I learned from this video(is it ok? cuz he showed his API KEY...)
How to use the OpenAI API in NodeJS

The example of coding is below↓

const openai = new OpenAI({
    apiKey: OPENAI_API_KEY // API KEY
})
const message = "message to GPT"
const completion = await openai.chat.completions.create({
                model: "gpt-4", // GPT Model name
                messages: [{ "role": "user", "content": message }],
});
console.log(completion.choices[0].message.content); // GPT answer
Enter fullscreen mode Exit fullscreen mode

You can confirm available GPT models on this Document.
https://platform.openai.com/docs/models

4. Summary

If you just want to listen to GPT in chat format, I think this usage is sufficient.
I am actually using this usage to run the bot. (I will write an article about it later.)
https://github.com/hikaelis/nostr_shinjiro_bot_public

GPT is rapidly making progress, so usage will probably be changed when updates. So please check out openai-node documents.
https://github.com/openai/openai-node

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

PulumiUP 2025 image

PulumiUP 2025: Cloud Innovation Starts Here

Get inspired by experts at PulumiUP. Discover the latest in platform engineering, IaC, and DevOps. Keynote, demos, panel, and Q&A with Pulumi engineers.

Register Now

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay