본문 바로가기
Coding/JavaScript

[JavaScript] ChatGPT API 를 활용하여 나만의 인공지능 비서만드는 방법2 !!

by 포스트it 2023. 11. 24.
반응형

 

[JavaScript] ChatGPT API 를 활용하여 나만의 인공지능 비서만드는 방법2 !!

 

openai 공식홈페이지에 있는 예시 연결하는 영상입니다.

https://youtu.be/VzIa4RH2vzs

 

아래코드는 영상에 나와있는 예시 코드입니다 :)

<!DOCTYPE html>
<html>

<head>
  <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>요리사GPT</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 = "YOUR_KEY"
      const keywords = document.getElementById('keywords').value
      $('#loading').show();

      const messages = [
        { role: 'system', content: '너는 세계에서 유명한 요리사야. 요리에 대한 전문지식을 친절하게 알려줘.' },
        { role: 'user', content: keywords }
      ]

      const data = {
        model: 'gpt-3.5-turbo',
        messages: messages,
      }

      $.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>
728x90
반응형

댓글