>

상세 컨텐츠

본문 제목

내가 만든 사이트에서 gpt를 API로 연결해 사용하기(javascript편)

7. 봉드로이드_개발공부

by 마켓플레이어, 마케터 봉 2024. 10. 17. 12:04

본문

우선 일잘러를 위한 단계면 솔직히 아래 2개면 어느 정도 해결이 된다.

1. 구글 시트와 gpt 연동해서 사용하기 (기본 함수 사용) ▶︎ https://marketerbong.tistory.com/67 

2. 구글 독스와 나만의 gpt를 API로 연결해 사용하기 (apps script 사용) ▶︎https://marketerbong.tistory.com/68

 

그런데 솔직히 제약이 너무 많다.

내가 원하는대로 이미지를 만들거나, 나만의 커스텀 gpt를 만들어서 사용하고 싶다.

 

그래서 open ai의 API를 활용해 내가 만든 사이트에서 gpt를 사용할 수 있도록 했다.

자세한 건 아래 openAI 개발자 문서를 참고했으며, gpt한테 물어가며 만들었다.

https://platform.openai.com/docs/api-reference/introduction

 

방법은 총 2가지이다.

1. html파일(javascript)로 만들기

2. python으로 만들기(streamlit 패키지 사용)

 

이 포스팅은 javascript로 만들어 보았다.

스크립트는 다음과 같다.

<!DOCTYPE html><html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>봉드로이드 GPT</title>
  
 // 스타일
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 600px;
      margin: 20px auto;
      padding: 20px;
      background-color: #f4f4f9;
    }
    textarea {
      width: 100%;
      height: 100px;
      margin-bottom: 10px;
      font-size: 16px;
      padding: 10px;
    }
    button {
      padding: 10px 20px;
      font-size: 16px;
      cursor: pointer;
    }
    .response {
      margin-top: 20px;
      padding: 20px;
      background-color: #e8f4e5;
      border-left: 4px solid #34a853;
    }
    .error {
      color: red;
      margin-top: 10px;
    }
  </style>
  
  // GPT호출함수
  <script>
    async function getOpenAIResponse() {
      const apiKey = 'YOUR_OPENAI_API_KEY';  // OpenAI API key를 넣어주세요
      const prompt = document.getElementById("userInput").value;

      // 아웃풋 확인
      document.getElementById("responseOutput").innerHTML = '';
      document.getElementById("errorOutput").innerHTML = '';

      try {
        // API call 준비
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
          },
          body: JSON.stringify({
            model: 'gpt-3.5-turbo',
            messages: [{ role: "user", content: prompt }],
            max_tokens: 100
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();
        
        // 답변표시하기
        document.getElementById("responseOutput").innerHTML = `<strong>Response:</strong> ${data.choices[0].message.content.trim()}`;
      } catch (error) {
        // 에러가 뜬다면 표시하기
        document.getElementById("errorOutput").innerHTML = `Error: ${error.message}`;
      }
    }
  </script>
  
  
  </head>
  
  <body>

    <h1>무엇이든 물어보세요</h1>
    <p>질문할 내용을 입력해주세요</p>
  
    <textarea id="userInput" placeholder="테스트로 100token 제한 있음. 내가 유료결제 안하면 작동 안하지."></textarea>
    <button onclick="getOpenAIResponse()">질문하기</button>
  
    <div class="response" id="responseOutput"></div>
    <div class="error" id="errorOutput"></div>


</body>
</html>

 

만들고 질문을 해보았다.

잘 대답한다.

 

근데 open ai가 아닌 마케터라고 대답한다.

이건 gpt한테 역할을 부여해놨기 때문이다. 아래 이미지와 같이 메세지 영역에 system의 role을 부여했고, 거기에 내가 생각하는 역할을 부여해놨다. 그렇기에 질문에 대한 답변도 system의 role에 맞게 하는 것이다.

 

관련글 더보기