# OpenAI’s ChatGPT API in JavaScript:
Transform Your Projects with AI Have you ever wondered how to
harness the incredible power of AI in your JavaScript projects?
I'm David from Kodaps, and today, we're diving into OpenAI's ChatGPT API
and how to use it in JavaScript. It's simpler to use than you might think, and the
possibilities are endless. Let's get started! We’ll look into how to set up the API,
connect to it, and integrate it into your different projects with practical
examples. We’ll also cover the important concepts to grasp to interact efficiently
with the API. And there’s one new feature that’s enabled by ChatGPT’s JSON output that I’m
particularly excited about. More on that later. First, before we go any further, if you’ve looked
at OpenAI’s documentation, you’ll see that ChatGPT has a “REST” API, and you may be wondering what
a ReST API is and how to interact with it. I’ve explained in more detail elsewhere what a ReST
API is. However, in this specific case, you _don’t_ need to understand how REST works because
there are clients for all the major web languages. All the hard work has already been done for
you. A client is (basically) a library that does all the REST interaction for you, so
all we need to do is set it up and use it. How do we do that? ## Signing up for the OpenAI API key
The first step is to sign up for an OpenAI API key. If we type “OpenAI API” in Google, we’ll
land on the appropriate page on OpenAI’s website. Now, let’s sign up to the OpenAI API. You need to create an account
if you don’t have one yet. Now let’s head to the settings to the “API
Keys” section and click on “Create a new secret key”. You need to save this right
away to a safe place. Once you navigate away from this page, the full key will not
be available again for security reasons.
The proper place to save your key
is in a secrets file, for example, a “.env” file. Give it a name like
`OPENAI_API_KEY `and copy-paste the value, so your `.env`file now looks like this:
OPENAI_API_KEY=skkdjdkjdkjdkjdkjdkjdkjd Now, we need to install the OpenAI client, read the key and initialise the client with
the key we’ve stored in the `.env`file. ## Installing the OpenAI client
The next step is to install the OpenAI client library in your project. In JavaScript, you run
`npm install --save openai` or `yarn add openai` This command will install the OpenAI
library, giving you access to all the functionalities of the ChatGPT API
directly in your JavaScript environment. Once the library is installed, we'll
move on to the exciting part – coding! Let's start by importing the OpenAI
library into our script. In JavaScript, we simply need to type `import
OpenAI from 'openai';`. ## Loading the environment file
The next step is to load the environment file. In JavaScript, the library
used to load the `.env`file is called `dotenv`. It will need to be installed into your
project using the package manager, so type "npm install --save dotenv" or
the equivalent for your package manager. Once it is installed, the next step is to import the dotenv library in to
your code. That's as simple as require('dotenv').config() The contents of the `.env`file is now
available as environment variables in our code. Now let’s use that to initialise
the client and start talking to the API! ## Initialising the client with the API key
To do so, we first need to initialise the client with the API key.
All we need to do is type: const openAIClient = new OpenAI({ apiKey: process.env['OPENAI_API_KEY']
}); Here, because we’ve used `OPENAI_API_KEY` which is the default value, we could omit
the lines where we set the `api_key`. Now our client is set up, we can
use it to interact with the API. ## Interacting with the API Now, to interact with ChatGPT via the API,
you will need to create a “chat completion”. In JavaScript, this looks something like this: const chatCompletion = await
openAIClient.chat.completions.create({ messages: [{ role: 'user',
content: 'Say this is a test' }], model: 'gpt-3.5-turbo',
}); As you can see, there are
two required parameters here. The first one, the “model” parameter, is easy to
understand. It defines the ChatGPT model you will be interacting with, here ChatGPT 3.5. If you have
a paid account you can use "gpt-4-turbo-preview". The second is the messages field that
lists conversation, as it exists until now. This is perhaps the most important thing
to remember: it’s your responsibility, as the developer, to track everything that
has been said. ChatGPT will not store the conversation nor remember what you have previously
said, unlike what happens via the website. As you can see, the conversation
is an array of messages. Each message is an object with two fields:
* a `role` that tracks who is talking and * the `content` which is the
message that was exchanged. A discussion is simply a
sequence of these objects, the messages being exchanged back and forth,
which you need to find a way to track if you want to build a coherent conversation.
I’ve used a REDIS database to track the conversion using JSON encoding,
but many other valid ways exist. However you store it, the API will then
respond with the message provided by the LLM, which you can then add to the conversation. ## Calling functions There is one other feature particularly
worth highlighting. As I mentioned earlier, ChatGPT can produce a deterministic JSON output. Now stated in those terms, it
does not seem very exciting. However, when I took a closer look, I realised
it opens some doors I’m very excited about. You can tell ChatGPT about
helper functions in your code. You add a “tools” parameter to your
function call. That parameter is a list of objects describing available
functions that chatGPT can call. Each object has a `type` field, which is
worth `function` (presumably, other types of tools might be added later) and a `function`
object that allows you to define the function. Each function object has a `name` field.
It can also have a `parameters` field, where you can specify a JSON schema that
describes the function parameters. You can leave this blank if the function is to be called
without parameters. The function object also has an optional `description` field that describes
what the function does in natural language. The JavaScript library provides a
helper function called `runTools`. You add this to the client call, and
that does the work. That is to say, it calls any functions the API requests
and returns the response to ChatGPT. This opens up some wonderful opportunities. The example in the
documentation has two functions: * One called `getLocation` that
returns the user’s location * Another called `getWeather` that, when
provided with a location, provides the weather. The example is basic, but imagine all
the doors it opens to allow our code and ChatGPT to combine and work
together. And it’s inspired me to delve deeper and explore even more,
and look at tools like LangChain. Let me know what you think
and what you’d like to build. And I’ll see you in the next video.