DEV Community

Cover image for Simple AI Tutorial for Front-end - 1. Connecting to OpenAI
shunnNet
shunnNet

Posted on

Simple AI Tutorial for Front-end - 1. Connecting to OpenAI

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 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

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

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

OpenAI - free tier usage

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

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

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

OpenAI - create new secret key button

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

OpenAI - Copy new secret key value

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)

<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>

Enter fullscreen mode Exit fullscreen mode

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

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:

{
  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"},
     ]
  })
}
Enter fullscreen mode Exit fullscreen mode

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.


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/

Top comments (0)