DEV Community

hikari.huang
hikari.huang

Posted on

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

Top comments (0)