Simple AI Tutorial for Front-end - 1. Connecting to OpenAI
Tags: openai, frontend, ai, webdev
Published: 2023-12-23 15:18:25

## Introduction
This should be the first post in a series, sharing some knowledge and insights from my development of applications related to Large Language Models (LLM) over the past year. The entire series will cover the following topics:

- How to use `OpenAI`
- Basic knowledge of using prompts
- Function calls
- Brief overview of `Langchain`
- How to make LLM respond based on company documents
- Integration possibilities with [Browser AI](https://courageous-manatee-a625e9.netlify.app/) packages and front-end frameworks


------------------------------------------

## Theme
This article will cover a very simple task – connecting to the OpenAI API, a process that can be completed in about 10 minutes. The following are the two main steps:

1. Obtain an API KEY
2. Make a Request on the Webpage

## A. Obtain OpenAI API KEY

### 1. Register an account on OpenAI

Visit https://platform.openai.com/docs/introduction

In the top right corner, you should see "sign up." Click on it to start the registration process.
Follow the registration process to create your account.

![OpenAI - sign up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rj244vizgzoewz2kbcox.png)

### 2. Confirm Quota

After registration, you'll be redirected to the documentation page. You can click on "settings" on the left side, then navigate to "Limits." Scroll down to the bottom, where you'll find the following text. It mentions that you are currently on a free plan, and payment will only start after reaching $5. For experimenting, this amount should be more than sufficient.

![OpenAI - free tier](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c9y54igfsttinxgtp8r7.png)

You can also click on "Usage" on the left to check your usage:

![OpenAI - free tier usage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v2vbug0jogtjjif6w0jh.png)

### 3. Obtain API Key
Click on "API keys" on the left side to access the page shown in the image below:

![OpenAI - api key page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n944obnjk2fnqiabkb4r.png)

To create an API key, you need to undergo phone verification. Click the button in the image below and follow the steps to proceed:
![OpenAI - verify phone number button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onuce42z5o500ziijlrw.png)

After completing the phone verification, click on **Create new secret key.**

![OpenAI - create new secret key button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0caxkituw57xkxm4drik.png)

Here, pay a little attention:

First, you'll need to enter a name; just choose a simple one.
After submitting the name, the API KEY will appear in the same pop-up. Copy the key and keep it secure, avoiding sharing it with others.
If, by chance, you accidentally close this pop-up without copying the key, delete the existing key and create a new one.

![OpenAI - Enter new secret key name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ynpg9dhsq06gylk0t1o.png)

![OpenAI - Copy new secret key value](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odi3fxoo8sam1jxer49l.png)

Now that you have the API key, you can start making API calls.


## B. Calling the GPT on the Webpage
After preparing the API key, let's move on to calling the most commonly used chatCompletion API.

Create an HTML file and use the following code: (Remember to replace "your API key" with your actual API key in the variable)

```html
<body>
  <button id="ask">Ask</button>

  <script>
    const my_openai_key='Paste your key here'

    const chatCompletion=() => {
      fetch("https://api.openai.com/v1/chat/completions",{
        method: "POST",
        headers: {
          "Authorization": "Bearer "+my_openai_key,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          model: "gpt-3.5-turbo",
          messages: [
            {role: "user",content: "Hello ChatGPT"}
          ]
        })
      })
        .then(response => response.json())
        .then(res => {
          alert(
            res.choices[0].message.content
          )
        })

    }
    document.getElementById("ask").addEventListener("click",chatCompletion);
  </script>
</body>

```


Then, open this HTML file, click the "Ask" button, wait for a moment, and you should see the response below. This indicates that the connection has been successfully established.

![Chat completion API result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hb30ajoir1o5pxjcths.png)

If you want to continue the conversation, copy the AI's response, add it to the "messages" array along with your message, like the example below:

```ts
{
  body: JSON.stringify({
     model: "gpt-3.5-turbo",
     messages: [
       {role: "user",content: "Hello ChatGPT"},

       // Put ai response here like this
       {role: "assistant",content: "Hello, how can I assist you today?"},

       // Then add user response here
       {role: "user",content: "I just want to say hi"},
     ]
  })
}
```

Then, click the "Ask" button again, and you'll see it responding with new content.

---------------------------

So, this article concludes here.

The next article will discuss how to make OpenAI's GPT generate the responses you desire.

---------------------------

## Reference:
Here is the specification and documentation for the chatCompletion API we just called. Feel free to explore it if you're interested.

- [OpenAI - Text generation](https://platform.openai.com/docs/guides/text-generation)

- [OpenAI - Create chat completion](https://platform.openai.com/docs/api-reference/chat/create)

------------------------------------------

## Advertisment - Browser AI
Use `Browser AI` to help you build an LLM powered website!
Repository: https://github.com/shunnNet/browser-ai
Documentation: https://courageous-manatee-a625e9.netlify.app/