Side Project/Chat-GPT

[Chat-GPT] Open AI API로 Chat GPT 사용해보기(1)

  • -
728x90

Open AI 의 API로 Chat GPT와 간단한 터미널 채팅을 구현해 보자.

 

Open API Key 발급

  1. https://openai.com/ 회원가입
  2. 로그인 후 https://platform.openai.com/docs/introduction 로 이동 (메뉴에 Developers로 이동해도 된다)
  3. 우상단 프로필 아이콘 클릭
  4. Veiw API Keys 클릭
  5. Create new secret key 를 눌러 api key 를 발급받는다.

 

ChatGPT API 호출

fetch() 함수를 이용하여 ChatGPT API에 "안녕"이라는 메시지를 전송해보자.

// chat.js
function chat() {
  return fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer APIKEY`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "gpt-3.5-turbo",
      messages: [{ role: "user", content: "안녕?" }],
    }),
  })
    .then((res) => res.json())
    .then((data) => console.log(JSON.stringify(data, null, 2)));
}

chat();

위와 같이 "안녕"이라는 메시지를 전송 후 응답을 확인해보면 아래와 같다.

커멘드라인 인터페이스 구현

위 코드와 readline 함수를 바탕으로 커멘드라인 인터페이스를 구현해보자.

function chat(question) {
  return fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer APIKEY`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "gpt-3.5-turbo",
      messages: [{ role: "user", content: question }],
    }),
  })
    .then((res) => res.json())
    .then((data) => data.choices[0].message.content);
}

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

console.log("💬 ChatGPT 터미널 챗앱 💬\n");
rl.prompt();

rl.on("line", (question) => {
  chat(question).then((answer) => {
    console.log(`🤖 ${answer}\n`);
    rl.prompt();
  });
});

자꾸 이상한소리한다.

웹에서 직접 물어보니, 2021년 9월까지의 정보를 제공한다고 한다.

 

 

참조
https://www.daleseo.com/chatgpt-cli-js/

 

728x90
300x250
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.