반응형

chatgpt에도 openapi가 존재한다.

ChatGPT API사용법은 chatgpt에게 물어보면 잘 대답해준다.
이런 소스인데 기본적으론 python으로 답을 해주고 javascript로 소스 샘플을 짜달라면 node.js로 보내온다.
하지만 쌩 javascript도 가능하니 node.js가 아닌 javascript로만 답을 해달라고 하자.
그럼 이런 답을 얻을 수 있다.

<!DOCTYPE html>
<html>
<head>
  <title>GPT-3.5 Turbo Chat</title>
</head>
<body>
  <div>
    <label for="userInput">질문:</label>
    <input type="text" id="userInput" />
    <button onclick="getChatResponse()">답변 받기</button>
  </div>
  <div>
    <strong>ChatGPT 답변:</strong>
    <p id="response"></p>
  </div>

  <script>
    async function getChatResponse() {
      const userInput = document.getElementById("userInput").value;
      const apiUrl = "https://api.openai.com/v1/completions"; // OpenAI API URL
      const apiKey = "내가 받은 api key"

      const requestBody = {
        model: "gpt-3.5-turbo",
        messages: [
          {
            role: "user",
            content: userInput,
          },
        ],
      };

      try {
        const response = await fetch(apiUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`,
          },
          body: JSON.stringify(requestBody),
        });

        const data = await response.json();
        var strResult;

        if (data.hasOwnProperty("error")) { // error 속성이 존재하는 경우
            strResult = data.error.message;
        } else if (data.hasOwnProperty("choices")) { // choices 속성이 존재하는 경우
            strResult = data.choices[0].message.content;
        } else {    // 그 외의 경우
            strResult = "Unknown response format.";
        }

        document.getElementById("response").innerText = `ChatGPT: ${strResult}`;
      } catch (error) {
        console.error("Error:", error.message);
        document.getElementById("response").innerText = "Error occurred.";
      }
    }
  </script>
</body>
</html>

대충 chatgpt API 사이트에 보니 모델을 지정하고 API키만 입력하고 질문입력해서 보내면 답을 주는 매우 간단한 구조다.
API구조는 chat gpt버전에 따라 다르다. 
구조가 저러하다 정도만 이해하고 나머진 규격에 맞게 requestBody를 구성하면 되겠다.


그러면 이제 API KEY를 얻어보자.
API KEY를 얻기 위해선 아래 페이지에 가서 신청하면 받을 수 있다.

https://platform.openai.com/account/api-keys

 

OpenAI Platform

Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.

platform.openai.com

본격적인 개발을 진행하기 전 postman이란 프로그램을 이용하면 미리 테스트가 가능하니 postman을 다운로드 받자.
https://www.postman.com/downloads/

 

Download Postman | Get Started for Free

Try Postman for free! Join 25 million developers who rely on Postman, the collaboration platform for API development. Create better APIs—faster.

www.postman.com

설치까지 다 했다면 실행 후 호출할 주소창에 https://api.openai.com/v1/completions를입력하고 호출 방법은 POST를 선택한다.


CHAT GPT OPEN API는 Bearer 인증방식을 취하고 있는데 
이 설정방법을 소개하려 한다.
Authorization탭으로 이동한다.
그리고 Type에서 BearerToken을 선택하고 Token에 아까 받아온 api key를 입력하면 된다.   

그다음으론 전송할 데이터를 입력해야 하는데 소스를 보면 json형식이니 모델과 메세지를 보내야 하는데 Body로 이동해 raw라디오 버튼을 선택하고 아래처럼 json을 입력하면 된다.

{
    "model""gpt-3.5-turbo",
    "messages": [
        {
            "role""user",
            "content""Hello!"
        }
    ]
}

이제 Send를 눌러 결과를 확인해보자.

API문서에 따르면 이런 규격의 response를 보게 될 것 같다.(정확하진 않다.)
{
   "id":"chatcmpl-abc123",
   "object":"chat.completion",
   "created":1677858242,
   "model":"gpt-3.5-turbo-0301",
   "usage":{
      "prompt_tokens":13,
      "completion_tokens":7,
      "total_tokens":20
   },
   "choices":[
      {
         "message":{
            "role":"assistant",
            "content":"\n\nThis is a test!"
         },
         "finish_reason":"stop",
         "index":0
      }
   ]
}

하지만 아래 같은 결과를 확인할 수 있다.

{
    "error": {
        "message""You exceeded your current quota, please check your plan and billing details.",
        "type""insufficient_quota",
        "param"null,
        "code""insufficient_quota"
    }
}

돈 내란다. -_-

이상하다.
chat gpt 사이트에는 분명 이렇게 5딸라까지 호출 여유가 있는데 쿼터를 오버했다니....

자세히보니 Expires가 2023년 7월 1일까지라 그런것 같다.
오늘은 8월이다.

오호라 아이디를 그럼 새로 파서 API KEY를 신청하면 5딸라 받아 테스트 가능하겠네?
신나게 아이디를 새로 파보니 그새 또 뭔가 달라졌나보다 -_-

예전에 생성했던 계정은 만료 5딸라가 보이지만 오늘 새로 생성한 chatgpt 계정은 그른그 읎다.
그냥 set up a paid account 답정이다.
역시 m$인가?

검색해보니 예전엔 18딸라까지 무료 지원을 했었는데 그마저도 5딸라로 개악된듯하고
이젠 그마저도 지원 안하나보다.

카드 정보 입력하기 껄끄러워 여기까지만 진행해야겠다.

반응형
Posted by Hippalus
,