GCP/Apps Script

Apps Script로 ChatGPT의 openAPI를 Google Sheets에서 호출하기

whistory 2023. 4. 14. 11:20
반응형

 

💡 Apps Script로 ChatGPT openAPI를 호출해본다.

 

 

요새 ChatGPT가 핫하다.

그래서 Google Sheets에서 ChatGPT를 사용할 수 있는 테스트 해보고 방법을 정리해봣다.

 

 

1. API를 사용하기 위해, key를 발급 받는다.

ChatGPT로 물어 물어봤다.

 

 

 

1.1 아래 웹페이지로 접속한다.

 

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

1.2 로그인 후 [View API Keys] 를 클릭한다

1.3 [Create new secert key] 를 이용해 key 를 발급받는다.

 

 

2. ChatGPT를 실행하는 코드를 작성한다.

const SECRET_KEY = "생성한 API KEY";
const MAX_TOKENS = 800;
const TEMPERATURE = 0.9;
const MODEL = "gpt-3.5-turbo";

function callChatGpt(prompt) {
  prompt = "chatgpt api 키는 어떻게 발급받지";
  console.log(`질문 => ${prompt}`);
  const url = "<https://api.openai.com/v1/chat/completions>";
  const payload = {
    model: MODEL,
    temperature: TEMPERATURE,
    max_tokens: MAX_TOKENS,
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: prompt },
    ],
  };
  const options = {
    contentType: "application/json",
    headers: { Authorization: "Bearer " + SECRET_KEY },
    payload: JSON.stringify(payload),
  };
  const res = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
  console.log(res.choices[0].message.content.trim());
  return res.choices[0].message.content.trim();
}

 

 

3. Google Sheets에서 함수를 테스트해본다.

 

4. event trigger에 함수를 추가한다.

event trigger에서 callChatGpt() 함수를 실행시켜본다.

 

Simple trigger에서는 동작하지 않아,

Installable Triggers 에서 동작하도록 했다.

function onEditCustom(e) {
	const getValue    = e.value;
	const sheetName   = spreadSheet.getActiveSheet().getName();
	const column      = e.range.getColumn();
	const row         = e.range.getRow();
	const activeCell  = spreadSheet.getActiveCell();
	
	if ( sheetName == "chatGPT" && (column == 1 && row > 1 ) ) {
		const resultCell = activeCell.offset(0, 1);
		if ( getValue != null ) {
			const resultMessage = callChatGpt(getValue);
			resultCell.setValue(resultMessage);
		} else {
			resultCell.clearContent();
	}
}

 

 

실행 로그

예시 화면

반응형