본문 바로가기

개발이야기

next.js에서 chatGPT api 요청 보내기 ( express.js로 서버 열기 )

이번 프로젝트에서 chatGPT를 활용해보려고 했다. 제공해주는 API가 있었기 때문에 그냥 요청 보내서 답 받는 형식으로 하면 굉장히 많은 프로젝트가 가능할 것 같았다!

 

난 게임파인더에서 사용했다. 아래는 내 깃헙 링크 

https://github.com/mayo516/-GameFinder

 

GitHub - mayo516/-GameFinder: 맨날 무슨 게임할지 고민하고 추천 요청 글 쓰러 다니는 게이머들의 소중

맨날 무슨 게임할지 고민하고 추천 요청 글 쓰러 다니는 게이머들의 소중한 시간을 아끼기 위해서 만든 페이지 - GitHub - mayo516/-GameFinder: 맨날 무슨 게임할지 고민하고 추천 요청 글 쓰러 다니는

github.com

 

API 문서를 읽으면서 

문서를 읽으면서 음? 하는 생각이 들었다. 내가 전에 봤던 api 명세와 형식이 달랐다고 해야하나..? 요청 방식, 요청 형태만 알고 요청만 보내면 될 줄 알았는데

https://platform.openai.com/docs/introduction

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

그리고 잘 읽어보면 

 

You can interact with the API through HTTP requests from any language, via our official Python bindings, our official Node.js library, or a community-maintained library.

 

node.js와 python라이브러리를 이용해서 요청을 할 수 있다...라

그리고 밑으로는 쭉 node와 파이썬 환경에서 요청 보내는 방법이 나와있다. 

근데 나의 프로젝트는 브라우저에서 작동하고 브라우저 상에서 api 요청을 보내려고 했는데...? node.js 라이브러리는 곧 서버 라이브러리라는 뜻 아닌가? 나는 클라이언튼데.. 

혼란에 빠지기 시작.

그래도 여기 까지 생각이 미치니깐 그럼 그냥 서버 만들어서 요청 보내고 내가 만든 서버에 브라우저에서 요청 보내면 되겠다? 라는 결론이 났다.

 

즉, 클라이언트 => node.js 서버로 요청을 보내면 node서버가 chatGPT한테 보낸 내용을 다시 클라이언트에게 알려준다. 

 

express.js로 서버 열기

우선 서버용 패키지들을 설치해준다

npm install openai express body-parser cors

 

자바스크립트 만세 ,, 한개의 언어로 백프론트를 왔다갔다 할 수 있다니! 

 

밑은 server.js파일

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: "여기는 개인 키코드 넣는 곳",
});
const openai = new OpenAIApi(configuration);

// Set up the server
const app = express();
app.use(bodyParser.json());
app.use(cors());

// Set up the ChatGPT endpoint
app.post("/chat", async (req, res) => {
  // Get the prompt from the request
  const { prompt } = req.body;

  // Generate a response with ChatGPT
  const completion = await openai.createCompletion({
    model: "text-davinci-003",
    prompt: prompt,
  });
  console.log(completion.data.choices[0].text);
  res.send(completion.data.choices[0].text);
});

// Start the server
const port = 8080;
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

난 express 문법을 몰랐기 때문에 구글링의 도움을 받으며 서버를 열었다. 

node server.js
//Server listening on port 8080 라는 문구로 서버가 열림

해서 8080 포트로 서버를 열어주고 postman으로 해당 서버에 요청이 잘 가는지 확인했다. 

중간에 이렇게 확인하는 과정을 거치면 문제가 발생했을때 어디까지는 잘 되는지 빠르게 예상할 수 있어서 좋다.

 

내 서버에 post 요청으로 

헤더에는 이런 형식으로 

바디는 json 형식으로 요청을 날리면! 

이렇게 내 서버가 응답해준다!!

 

next.js에서 node서버로 요청 보내기

이제 남은건 클라이언트에서 서버로 요청만 보내면 된다. ( 형식만 잘 지켜서 !

 

import axios from "axios";

const handleSubmit = (e) => {
  e.preventDefault();
  let prompt = "Hi!";
  // Send a request to the server with the prompt
  axios
    .post("http://localhost:8080/chat", JSON.stringify({ prompt: "hi!!!" }), {
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((res) => {
      // Update the response state with the server's response
      console.log(res);
    })
    .catch((err) => {
      console.error(err);
    });
};

export default handleSubmit;

난 axios로 요청을 보냈고 

데이터도 잘 받아졌다 !!!

이제 남은건 프로젝트에 활용하는 일 뿐!! 

 


[참고 사이트]

https://www.codingthesmartway.com/how-to-use-chatgpt-with-react/

 

How to use ChatGPT with React

ChatGPT is a variant of the GPT (Generative Pre-training Transformer) language model that is specifically designed for generating human-like text in chatbot applications. To use ChatGPT with React, you will need to set up a server that can handle requests

www.codingthesmartway.com

https://medium.com/codingthesmartway-com-blog/a-beginners-guide-to-integrating-chatgpt-with-node-js-9daf8557234

 

A Beginner’s Guide to Integrating ChatGPT with Node.js

ChatGPT is a chatbot platform developed by OpenAI that allows developers to build custom chatbots using the GPT-3 language model. The GPT-3…

medium.com

 

 

* 더 좋고 효율적인 방법이 있다면 언제든지 알려주시면 감사하겠습니다!