본문 바로가기
JavaScript

[JavaScript] ChatGPT API로 간단한 챗봇 만들기

by teamnova 2023. 11. 17.

안녕하세요.

이번 시간에는 ChatGPT API를 사용해서 간단한 챗봇을 만들어보겠습니다.

 

 

1. ChatGPT API 키 받아오기

먼저 ChatGPT API 키를 받아야합니다.

OpenAI 에 회원가입 또는 로그인합니다.

https://platform.openai.com/

 

 

그리고 좌측 메뉴에서 API keys 버튼을 클릭합니다.

 

 

Create new sceret key 를 눌러 API 키를 생성합니다.

API 키는 생성됐을때 한번만 볼 수 있으니 꼭 따로 저장해두세요. 

 

 

2. 전체 코드

전체 코드는 다음과 같습니다.

해당 예제에서는 질문에 프롬프트를 덧붙여서 진행했습니다.

앞에서 받은 API 키를 api_key 변수에 저장한뒤 실행해주세요. 

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>chatGPT API</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <style>
    /* page-loading */
    #loading {
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      position: fixed;
      display: block;
      opacity: 0.6;
      background: #e4e4e4;
      z-index: 99;
      text-align: center;
    }

    #loading>img {
      position: absolute;
      top: 40%;
      left: 45%;
      z-index: 100;
    }

    #loading>p {
      position: absolute;
      top: 57%;
      left: 43%;
      z-index: 101;
    }
  </style>
</head>

<body>
  <h1>chatGPT API</h1>
  <div>무엇이든 질문해보세요 !!</div>

  <input type="text" id="keywords" name="keywords" required />
  <button onclick="chatGPT()">입력</button>
  <div id="result"></div>

  <div id="loading">
    <img src="https://studentrights.sen.go.kr/images/common/loading.gif">
  </div>
  <script>
    $(document).ready(function () {
      $('#loading').hide();
    });

    function chatGPT() {
      const api_key = ""  // <- API KEY 입력
      
      const keywords = document.getElementById('keywords').value
      $('#loading').show();

      const prompt = "\n\n 지금부터 앞의 질문에 어떻게 대답해야할지 말씀드릴게요. 아래 사항을 모두 읽고 따라주세요.\n"
                      + "1. 50자 이내로 대답하세요.\n"
                      + "2. 친절하게 대답하세요.\n";
     
      const messages = [
        { role: 'user', content: keywords + prompt },
      ]

      const data = {
        model: 'gpt-3.5-turbo',
        messages: messages,
        max_tokens: 1000, // 응답받을 메시지 최대 토큰(단어) 수 설정
        top_p: 1, // 토큰 샘플링 확률을 설정
        frequency_penalty: 0.5, // 일반적으로 나오지 않는 단어를 억제하는 정도
        presence_penalty: 0.5, // 동일한 단어나 구문이 반복되는 것을 억제하는 정도
        temperature: 0.5,
      }

      $.ajax({
        url: "https://api.openai.com/v1/chat/completions",
        method: 'POST',
        headers: {
          Authorization: "Bearer " + api_key,
          'Content-Type': 'application/json',
        },
        data: JSON.stringify(data),
      }).then(function (response) {
        $('#loading').hide();
        console.log(response)
        let result = document.getElementById('result')
        let pre = document.createElement('pre')

        pre.innerHTML = "\n\n" + response.choices[0].message.content
        result.appendChild(pre)

        document.getElementById('keywords').value = ''
      });
    }
  </script>
</body>

</html>

 

 

3. 결과