-
구글 스프레드시트에서 Apps Script로 GPT API 활용하기Experiences/Education technology 2025. 1. 19. 03:24
이 글에 관심 있으신 분들은 여기 폼을 답변해주세요.
구체적 방법을 안내하는 기회가 있을 때 먼저 연락드리겠습니다.GPT API는 OpenAI의 모델을 외부 어플리케이션에서도 사용할 수 있게 해줍니다. 주로 사용하는 구글 스프레드시트에서 GPT를 사용하고 싶다는 생각이 있었는데, 예전에는 비교적 무료 (API비용만 내면 가능했던)였던 GPT for Sheets and Docs가 유료로 전환하며 조금 부담스러운 상황이 되었습니다. 다양한 수식이 있어서 prompts를 쓰는 고민 없이 자연스럽게 GPT 모델을 연결해 사용할 수 있기 때문에 아직도 많은 분들이 사용하고 있습니다. 아주 많이 사용하게 된다면 구매할 마음도 있지만 지금 마음에서는...
하지만 Google Apps Script는 이 과정을 직접 구현할 수 있게 해줍니다. 기본 포멧이 정해져있고 그것을 반복적으로 사용한다면 이 방식을 사용하는 것도 나쁘지 않습니다. 예를 들어 학생들의 피드백이 어떤 시트로 들어올 것인지 정해져 있다면, 별다른 스크립트의 수정 없이 GPT API를 불러올 수 있습니다.
아래는 제 예시 코드 입니다. I2에 prompt를 쓰고 스크립트를 실행시키면 C3:C25의 내용을 바탕으로 I2에 답변을 줍니다.
function onOpen() { // Add a custom menu to the Google Sheet const ui = SpreadsheetApp.getUi(); ui.createMenu("GPT API") // Custom menu name .addItem("Call GPT", "callGPTAPI") // Add menu item and link it to the function .addToUi(); } function callGPTAPI() { // Get the active sheet const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Get prompt and data from designated cells const promptCell = "I1"; // Cell with the prompt const dataRange = "C3:C25"; // Range with input data const outputCell = "I2"; // Cell for the API output const prompt = sheet.getRange(promptCell).getValue(); const inputData = sheet.getRange(dataRange).getValues().flat().join("\n"); // Define the API URL const apiUrl = "https://api.openai.com/v1/chat/completions"; // Create the API request payload const payload = { model: "gpt-3.5-turbo", // Use an updated model name messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: `${prompt}\n\n${inputData}` } ], max_tokens: 1000, // Adjust token limit as needed }; // Set up the request options const options = { method: "post", contentType: "application/json", headers: { Authorization: `Bearer YOUR_API_KEY`, // Replace with your actual API key }, payload: JSON.stringify(payload), }; try { // Send the request to the GPT API const response = UrlFetchApp.fetch(apiUrl, options); const json = JSON.parse(response.getContentText()); const output = json.choices[0].message.content.trim(); // Write the response back to the designated output cell sheet.getRange(outputCell).setValue(output); } catch (error) { // Log and display the error message Logger.log("Error: " + error.message); sheet.getRange(outputCell).setValue("Error: " + error.message); // Display error in output cell } }
스크립트 실행을 편리하게 하기 위해 아래 코드 처럼 onOpen 기능을 이용해 스프레드 시트에 새로운 메뉴를 하나 만들었습니다. GPT API라고 메뉴를 만들고 그 안에 Call GPT 아이템을 만들어 이 버튼을 누르면 스크립트가 실행되도록 만들었습니다. 이 스크립트가 적용되는 구글 시트에만 아래 그림의 빨간 동그라미처럼 새로운 메뉴가 나옵니다.
function onOpen() { // Add a custom menu to the Google Sheet const ui = SpreadsheetApp.getUi(); ui.createMenu("GPT API") // Custom menu name .addItem("Call GPT", "callGPTAPI") // Add menu item and link it to the function .addToUi(); }