RunJS LogoRunJS

How to use the ChatGPT JavaScript API - 3 Easy Steps (2023)

Published on

chatgpt javascript api

ChatGPT has state-of-the-art language models trained by OpenAI.

It can generate human-like text responses based on given prompts.

With its ability to understand context and respond conversationally, it has become a popular choice for various applications, including chatbots, virtual assistants, content writing, SEO, and third-party integrations.

The ChatGPT JavaScript API provides a convenient way to interact directly with the OpenAI language models from JavaScript code.

By making API requests, developers can send chat requests to the models and receive real-time responses.

This guide will teach you how to build a real-world application with the ChatGPT JavaScript API.

Benefits of Using the ChatGPT JavaScript API (OpenAI)

There are several benefits to using the ChatGPT JavaScript API:

Flexibility:

The API provides an organized JSON response that you can use differently to meet the application's needs.

Continuous Updates:

OpenAI frequently updates its models and APIs, so developers can always have access to the most advanced language models for their applications.

Easy integration:

It allows developers to integrate OpenAI's AI model into their applications easily.

Real-time conversation:

Developers can create applications for real-time interactive conversational experiences with users, making them ideal for chatbots and other interactive applications.

Versatility:

You can use it in various applications - from creating a digital personal assistant and powering customer service chatbots to creating interesting characters, personas, and reports.

Perform Analysis:

You can build tools that can help you analyze things like real-time stock data, SEO keywords, content, and much more.

Supported OpenAI Models for ChatGPT:

There are several AI language Models by OpenAI to serve specific purposes:

  • GPT-4: Especially for broad general knowledge or expertise. It can solve difficult problems with accuracy.
  • GPT-3.5 Turbo: It is good for dialogues or conversations between you and the AI. You can use and see it in action with ChatGPT Free Account.
  • DALL.E: It can create super realistic images with your prompts from a description in natural language.
  • Whisper: You can transcribe from speech to text and translations of many languages.
  • GPT-3: It is now considered a legacy model that can understand and generate natural language.
  • Davinci, Curie, Babbage, and Ada mainly use base models for fine-tuning by providing training data.

Since you are learning about ChatGPT API integration, let's stay on it and use the GPT-3.5 turbo model.

Integration of OpenAI API with JavaScript:

Our goal is to create a simple application that should return the five unique titles based on user input.

Note: UI is not involved, but you will learn to request ChatGPT API with JavaScript and return JSON responses.

1. Get Your OpenAI API Key

To use the ChatGPT JavaScript API, you must obtain an API key from OpenAI.

Sign up for OpenAI and create an API key through their official website.

Once you have your API key, you can proceed with the integration process.

chatgpt openai api key

2. Install the openai package in Node.JS:

To ensure the secrecy of our apikey and prevent it from being accessed by the public, we are utilizing a NodeJS backend environment.

You can test the API directly on the RunJS JavaScript playground without worrying about installing the packages or set it up inside Visual Studio Code.

For VS code, you will have to install openai by using the following command:

npm i openai

In RunJS, you can install packages using the shortcut ctrl + i (windows) or cmd + i (MacOS) to open the NPM packages manager.

Search for openai and click install.

runjs openai installation

Note: RunJS comes with the support of NodeJS. So you don't have to install it separately.

3. Create a blog post title Generator:

Our primary objective is to develop a tool for generating blog post titles.

Add the openai package to your code and create an instance of it to get started.

// Initial import of openai npm package
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "YOU_OPENAI_API_KEY",
});

Next, take the user input and write the main function to get a response.

const userInput = "Success Tips";
const getResponse = async () => {
const response = await openai.chat.completions.create({
messages: [
{
role: "user",
content: `Suggest 5 catchy titles for blog post about ${userInput}`,
},
],
model: "gpt-3.5-turbo",
});
console.log(response.choices[0].message);
};
getResponse();
  • The user input is hard coded for this example.
  • openai.chat.completions.create is specifically used for ChatGPT models.
  • Define the specific model you want to use here. I used gpt-3.5-turbo.
  • roles can be system, user, or assistant.
  • content is like a command you are giving to chatGPT.
  • Get access to the output of Chat completion responses through choices and message.

Output:

output of blog titles generator

Considering this simple approach, you can build anything using the ChatGPT API in JavaScript.

Project ideas for Developers with the ChatGPT API:

  • Create a customer support chatbot.
  • Develop a language translation tool.
  • Build an interactive story generator.
  • Design a virtual assistant for scheduling and productivity tasks.
  • Develop an intelligent search engine.
  • Create an AI-powered tutor or educational tool.
  • Build a recommendation system for movies, books, or products.
  • Design a creative writing assistant.
  • Design an AI-powered chatbot for mental health support, offering encouragement and resources to users.
  • Build a fitness coach chatbot that provides personalized workout routines, nutrition tips, and motivation.

The possibilities are endless.

All you need is to spend time playing with AI, and the best way to play quickly is by using a JavaScript playground.

RunJS can help you to test APIs and rapidly prototype your code.

Best practices for using ChatGPT Models:

There are several points that you should keep in mind while using such APIs; some of them are below:

  • Start by defining a clear use case and objective for using the ChatGPT API.
  • Structure your conversation into multiple messages with alternating user and assistant messages.
  • Use system-level instructions to guide the assistant's behavior throughout the conversation.
  • Be specific in your user prompts to get more relevant responses from the model.
  • Experiment with temperature and max tokens parameters to control the response randomness and length.
  • If you want more control over the output, use manual intervention or implement safety checks on the responses.
  • Iterate and experiment with different inputs, instructions, and settings to refine and improve results.

FAQs:

Can I use ChatGPT API for free?

When you sign up for OpenAI, you will receive an initial $18 credit for API usage during the first month. After that, you can continue to use the service on a pay-as-you-go basis.

Can ChatGPT write JavaScript code?

Yes, ChatGPT can write JavaScript code. However, its ability to write code greatly depends on the prompt and instructions provided. You can ask specific questions or provide a desired outcome, and it can assist you in writing JavaScript code snippets or provide explanations and suggestions related to JavaScript programming.

What is the role of the API key in using the ChatGPT JavaScript API?

To access and use OpenAI models, you need a unique identifier called the API key. This key verifies your requests and ensures only authorized users interact with the API.

How does the ChatGPT API utilize natural language processing capabilities?

It uses the real ChatGPT OpenAI models, which have been trained on a large amount of text data using natural language processing techniques. That allows it to understand and conversationally respond to natural language inputs.

TwitterShareFacebookShareLinkedInShareRedditShareY CombinatorShare

Join the RunJS mailing list

You'll receive an occasional newsletter with development updates and articles from the blog. Unsubscribe at any time.

Recent posts