Node js로 CHATGPT 구현

Mar 16 2023
ChatGPT는 무엇입니까 : ChatGPT는 OpenAI에서 개발하고 2022년 11월에 출시한 인공 지능 챗봇입니다. OpenAI의 GPT-3 제품군의 대규모 언어 모델 위에 구축되었으며 감독 [ 기계 학습 방법을 모두 사용하여 미세 조정되었습니다. 데이터에는 정답 키가 있으므로 모델은 정답 자체로 학습됩니다.

ChatGPT란 무엇입니까 ?

ChatGPT는 OpenAI에서 개발하고 2022년 11월에 출시한 인공 지능 챗봇입니다. OpenAI의 GPT-3 계열의 대규모 언어 모델을 기반으로 구축되었으며 감독 [ 훈련 데이터에 답이 있는 머신 러닝 방법을 모두 사용하여 미세 조정 되었습니다 . 키를 사용하여 모델이 정답 자체로 훈련되도록 함] 및 강화 [지능형 에이전트(컴퓨터 프로그램)가 환경과 상호 작용하고 그 내에서 행동하는 방법을 배우는 기계 학습 방법] 학습 기술.

간단히 말해서 "ChatGPT는 사용자와 인간의 언어로 채팅하는 챗봇입니다."라고 말할 수 있습니다.

Node js 애플리케이션에서 구현

노드 js 애플리케이션에서 ChatGPT를 사용하려면 OpenAI apis를 사용합니다 . openAI api를 사용하려면 openAI에서 API 키를 가져와 openai npm 패키지와 같은 API 클라이언트 라이브러리를 사용하여 노드 js 애플리케이션에서 API에 요청해야 합니다.

OpenAI 웹사이트에서 API 키 받기:

openAI 웹사이트( https://openai.com/ ) 로 이동하여 가입 후 계정 설정에서 "API" 섹션을 검색하고 API 키를 생성합니다. API 키를 비밀로 안전하게 유지하는 것을 잊지 마십시오.

기본 노드 애플리케이션 만들기:

먼저 터미널로 이동하여 다음을 사용하여 프로젝트를 생성합니다.

mkdir chatgpt-nodeproject
cd chatgpt-nodeproject
code .

npm init -y
npm install express openai dotenv 
touch server.js
touch .env
touch config.js

PORT=5003
OPEN_AI_KEY="PASTE YOUR API KEY HERE"

require('dotenv').config({ debug: process.env.DEBUG });

let cfg = { 
        port: process.env.PORT,
        openaikey:process.env.OPEN_AI_KEY
     }

module.exports = {
        cfg
}

const express = require('express');
const config =  require("./config").cfg;
const app = express();
app.use(express.json());

app.listen(config.port, () => {
  console.log(`Example app listening at http://localhost:${config.port}`);
});

const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
    apiKey: config.openaikey,
});
const openai = new OpenAIApi(configuration);

app.post("/find-complexity", async(req,res)=> {
    try{
        const {prompt} = req.body;
        const response = openai.createCompletion({
            model: "text-davinci-003",
            prompt: `${prompt} The complexity of this function is `, //{"prompt": "const example = (arr)=> { arr.map((item)=> { console.log(item)});}"}
          });
        return res.status(200).json({success:true,data:(await response).data.choices[0].text})
    }catch(error){console.log(error,"error....")}
})

const express = require('express');
const config =  require("./config").cfg;
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
    apiKey: config.openaikey,
});
const openai = new OpenAIApi(configuration);
const app = express();

app.use(express.json());

app.post("/factual-answering", async(req,res)=> { 
    try{
        const {prompt} = req.body;
        const response = await openai.createCompletion({
            model: "text-davinci-003",
            prompt: `${prompt}`, // {"prompt": "Q: Pros and cons of callback and Promise\nA:"}
            max_tokens: 100,
          });
        return res.status(200).json({success:true,data:(await response).data.choices[0].text})
    }catch(error){console.log(error,"error....")}
})
  
app.post("/find-complexity", async(req,res)=> {
    try{
        const {prompt} = req.body;
        const response = openai.createCompletion({
            model: "text-davinci-003",
            prompt: `${prompt} The complexity of this function is `, //{"prompt": "const example = (arr)=> { arr.map((item)=> { console.log(item)});}"}
          });
        return res.status(200).json({success:true,data:(await response).data.choices[0].text})
    }catch(error){console.log(error,"error....")}
})

app.post("/imageGenerator-from-text", async(req,res)=> {
    try{
        const {prompt} = req.body;
        const response = await openai.createImage({
            prompt: `${prompt}`, //{"prompt": "kasoli in winter"}
            n: 2, // number of images to create
            size: "1024x1024",
          });          
        return res.status(200).json({success:true,data:(await response).data})
    }catch(error){console.log(error,"error....")}
})

app.post("/interview-questions", async(req,res)=> {
    try{
        const {prompt} = req.body;
        const response = await openai.createCompletion({
            model: "text-davinci-003",
            prompt: `${prompt}`,//{  "prompt": "Create a list of 8 questions for interview in MERN:"}
            max_tokens : 150
        });

    return res.status(200).json({success:true,data:(await response).data.choices[0].text})
    }catch(error){console.log(error,"error....")}
})

app.listen(config.port, () => {
  console.log(`Example app listening at http://localhost:${config.port}`);
});

우편 배달부로 이동하여 POST 요청 “http://localhost:5003/factual-answering” 누르기

내 저장소 " https://github.com/aditiipriya/chatgptImplementation " 을 복제할 수도 있습니다 .

도움이 되길 바랍니다 .. 감사합니다 !! :)