JavaScript & React/JS 기초

JavaScript에서 ChatGPT API 호출 방법 코드 예제

jimmy_AI 2024. 4. 20. 13:18
반응형

자바스크립트에서 GPT 등의 openai 모델에 대한 API를 호출하는 방법을

간략한 코드 예제로 쉽게 정리해보도록 하겠습니다.

 

 

1. 프롬프트 준비

우선, 프롬프트 목록에 대한 리스트를 아래와 같은 양식으로 준비해 줍시다.

const messages = [
	{ role: 'system', content: "답변은 항상 한국어로 해주세요."}
	{ role: 'user', content: "Who is the first president of USA?"}
    ]

 

 

2. GPT 호출 파라미터 준비

이후, openai api 호출을 위한 json input 양식을 준비해줍시다.

예시는 다음과 같습니다.(위에서 정의한 messages 변수를 사용합니다.)

const gptInput = {
        model: 'gpt-3.5-turbo',
        temperature: 0.5,
        messages: messages,
      }

 

 

3. OPENAI API 호출

이제, fetch 함수를 통하여 위 정보를 기반으로 openai api를 호출해주시면 됩니다.

코드 스니펫 예제는 다음과 같습니다.(input으로 2번 스텝에서 정의한 json 양식을 사용합니다.)

const APIKEY = "sk-***" // your openai api key

const CallGPT = async (gptInput) => {

    try {
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${APIKEY}`
            },
            body: JSON.stringify(gptInput)
        });

        const resultJSON = await response.json();
		
        // GPT가 실제로 반환한 값 추출
        const resultContent = resultJSON.choices[0].message.content

        return resultContent;
        
    } catch (error) {
        console.error('Error: ', error);
        return "";
    }
    
};

async 방식으로 함수가 선언되었음에 유의해주시면 좋습니다.

gptInput은 JSON.stringify로 문자열 변환 과정이 있었으며,

APIKEY는 유출 위험이 있으니 환경 변수 등으로 다루어주시는 것을 권장합니다.