How to use the new OpenAI ChatGPT API with Nodejs and TypeScript

Stanislas Randriamilasoa
2 min readMar 1, 2023
Source: www.fdesouche.com

OpenAI’s ChatGPT and Whisper models are now available through their API, providing developers with access to advanced language and speech-to-text capabilities. With significant cost reductions and optimized system-wide improvements, these models are more accessible and affordable for developers. This article will provide a comprehensive guide to using the new Open API ChatGPT with Node.js, allowing developers to take full advantage of these powerful language capabilities.

1- At the time I write this article, it is important to ensure that you have the latest version of the OpenAI npm module, which is currently 3.2.0, installed or updated.

npm install openai
OR
yarn add openai
package.json
{

"openai": "^3.2.0"

}

2- To create a ChatGPT Client class using TypeScript, you can use the following code. It includes all necessary OpenAI imports to ensure clarity and functionality in your implementation.

import { OpenAIApi, Configuration, CreateChatCompletionRequest, ChatCompletionRequestMessage } from 'openai';

class ChatGPTClient{
private openAI: OpenAIApi;

constructor() {

const configuration = new Configuration({
apiKey: 'OPENAI_API_KEY',
});
this.openAI = new OpenAIApi(configuration);
}

async respond(chatGPTMessages: Array<ChatCompletionRequestMessage>) {
try {
if (!chatGPTMessages) {
return {
text: 'No chatGPTMessages',
};
}

const request: CreateChatCompletionRequest = {
messages: chatGPTMessages,
model: 'gpt-3.5-turbo',

};

const response = await this.openAI.createChatCompletion(request);
if (!response.data || !response.data.choices) {

return {
text: "The bot didn't respond. Please try again later.",
};
}

return {
text: response.data.choices[0].message?.content,
messageId: response.data.id,
};
} catch (error) {
console.log('E: ', error);
throw new Error(error);
}
}
}

3- Once you have created the ChatGPT Client class using the TypeScript code provided, you can begin utilizing its functionality.

import {
ChatCompletionRequestMessageRoleEnum,
} from 'openai';

const chatGptMessages = [
{
role: ChatCompletionRequestMessageRoleEnum.System,
content: 'You are a helpful assistant.',
},
{
role: ChatCompletionRequestMessageRoleEnum.User,
content: 'Hello',
}
]

const client = new ChatGPTClient()

const sendChatRequest = async () {
const result = await client.respond(chatGptMessages)
console.log(result)
}

While there may not be an official example available at the time of writing, for more information about the API, please refer to the official API documentation.

I hope this tutorial has been helpful in guiding you through the process of setting up and using the Open API Chatgpt with Node.js. If you found this tutorial useful, don’t hesitate to follow me for more tutorials, tips, and tricks. And if you enjoyed this article, please give it a clap ! ;-)

--

--