본문 바로가기

Graduation Project

Node.js chatGPT API v4 연결하기

openai버전 4가 나왔습니다.

버전 4에 맞게 chatgpt API 호출 코드를 변경해야합니다.

 

Installation

package.json에서 openai v4로 업데이트를 진행합니다.

  "openai": "^4.0.0"

 

 

migration

초기화 로직, 메소드 이름, 오류 처리에 변경 사항이 있습니다. API 매개변수 이름은 변경되지 않아야 합니다.

 

Initialization

version 3

// Old
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

 

version 4

// New
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY // This is also the default, can be omitted
});

 

Creating a chat completion

version 3

// Old
const chatCompletion = await openai.createChatCompletion({
  model: "gpt-3.5-turbo",
  messages: [{role: "user", content: "Hello world"}],
});
console.log(chatCompletion.data.choices[0].message);

 

version 4

// New
const chatCompletion = await openai.chat.completions.create({
  model: "gpt-3.5-turbo",
  messages: [{"role": "user", "content": "Hello!"}],
});
console.log(chatCompletion.choices[0].message);

 

Creating a streaming chat completion (new)

version 4

// New
const stream = await openai.chat.completions.create({
  model: "gpt-3.5-turbo",
  messages: [{"role": "user", "content": "Hello!"}],
  stream: true,
});
for await (const part of stream) {
  console.log(part.choices[0].delta);
}

 

Creating a completion

version 3

// Old
const completion = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "This story begins",
  max_tokens: 30,
});
console.log(completion.data.choices[0].text);

 

version 4

// New
const completion = await openai.completions.create({
  model: "text-davinci-003",
  prompt: "This story begins",
  max_tokens: 30,
});
console.log(completion.choices[0].text);

 

Creating a streaming completion (new)

version 4

// New
const stream = await openai.completions.create({
  model: "text-davinci-003",
  prompt: "This story begins",
  max_tokens: 30,
  stream: true,
});
for await (const part of stream) {
  console.log(part.choices[0]);
}

 

Creating a transcription (whisper)

음성 파일의 내용을 텍스트로 생성합니다.

 

version 3

// Old
const response = await openai.createTranscription(
  fs.createReadStream("audio.mp3"),
  "whisper-1"
);

 

version 4

// New
const response = await openai.audio.transcriptions.create({
  model: 'whisper-1',
  file: fs.createReadStream('audio.mp3'),
});

 

Error handling

version 3

// Old
try {
  const completion = await openai.createCompletion({...});
} catch (error) {
  if (error.response) {
    console.log(error.response.status); // e.g. 401
    console.log(error.response.data.message); // e.g. The authentication token you passed was invalid...
    console.log(error.response.data.code); // e.g. 'invalid_api_key'
    console.log(error.response.data.type); // e.g. 'invalid_request_error'
  } else {
    console.log(error);
  }
}

 

version 4

// New
try {
  const response = await openai.completions.create({...});
} catch (error) {
  if (error instanceof OpenAI.APIError) {
    console.error(error.status);  // e.g. 401
    console.error(error.message); // e.g. The authentication token you passed was invalid...
    console.error(error.code);  // e.g. 'invalid_api_key'
    console.error(error.type);  // e.g. 'invalid_request_error'
  } else {
    // Non-API error
    console.log(error);
  }
}

 

Headers

version 3

// Old
const response = openai.createChatCompletion(params)
response.headers['x-ratelimit-remaining-tokens']
response.data.id

 

version 4

// New
const { data, response } = openai.chat.completions.create(params).withResponse()
response.headers.get('x-ratelimit-remaining-tokens')
data.id

 

 

졸업 작품에 사용한 코드

 

채팅 API 버전 4를 활용해 채팅 함수를 만들었습니다.

import OpenAI from 'openai';

const chatGPT = async (input, history) => {
    try{
        const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
        const messages = [];
        for (const chat of history) {
            messages.push({ "role":chat.role, "content":chat.text });
        }
        if (input){
            messages.push({ "role": "user", "content":input });
            history.push({chatID:null, text:input, role:"user"});
        }
        
        const chatCompletion = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: messages,
            temperature: 0.8, //degree of diversity
        });
        const gptText = chatCompletion.choices[0].message.content;
        history.push({chatID: "????", text: gptText, role: "assistant"});
        return {
            gptText: gptText,
            history : history
        };
    }catch(error){
        throw error;
    }
};

 

https://github.com/openai/openai-node/discussions/217 참고