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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more