In this blog post, we’ll dive into the exciting world of custom Google Sheets functions and OpenAI’s GPT-3.5 Turbo model. With this combination, we can create a function that takes an input and outputs an answer generated by the powerful language model.
Table of Contents
Open Table of Contents
Introduction
We’ll start by introducing the basics of Google Sheets functions and how they work. Then we’ll explore how we can use the Google Apps Script platform to create custom functions that extend the functionality of Google Sheets.
Next, we’ll dive into the details of OpenAI’s GPT-3.5 Turbo model and how we can use it to generate text based on a given input. We’ll cover the basics of how to access the GPT-3.5 Turbo API and how to format the input and output for use in a custom Google Sheets function.
Finally, we’ll put it all together and walk through the steps of creating a custom Google Sheets function that uses the GPT-3.5 Turbo model to generate text based on a given input. We’ll provide code examples and step-by-step instructions to help you get started with creating your own custom functions.
By the end of this post, you’ll have a solid understanding of how to use Google Sheets functions and OpenAI’s GPT-3.5 Turbo model together to create powerful and customized tools for your data analysis needs.
The Code Block
/**
* WLM Functions for using OpenAI's GPT-3.5-turbo model
* @param {string} prompt The prompt to feed to the GPT-3 model
* @param {string} cell The cell of the context to append to the prompt
* @return {string} The generated text
* @customfunction
*/
function chatOpenAI(prompt, cell) {
const API_KEY = "OPENAI_API_KEY";
model = "gpt-3.5-turbo";
prompt = prompt + cell + ":";
// Set up the request body with the given parameters
const requestBody = {
model: model,
messages: [{ role: "user", content: prompt }],
};
console.log(requestBody);
// Set up the request options with the required headers
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + API_KEY,
},
payload: JSON.stringify(requestBody),
};
// Send the request to the GPT-3 API endpoint for completions
const response = UrlFetchApp.fetch(
"https://api.openai.com/v1/chat/completions",
requestOptions
);
console.log(response.getContentText());
// Get the response body as a JSON object
const responseBody = JSON.parse(response.getContentText());
let answer = responseBody.choices[0].message.content;
// Return the generated text from the response
return answer;
}