- Create a new Google Sheets file
- Go to Extensions → Apps Script
- Remove all the code and copy-paste the following instead
- Create an account on OpenAI, get its API key and paste it instead of OPENAI_API_KEY in the script below
- Save your project and go back to your sheet
- Use =runOpenAI(), like classic Google Sheets Formula
The new function in Google Sheets:
The code to paste in Apps Script inside Google Sheets:
function runOpenAI(messages) {
const API_KEY = "OPENAI_API_KEY";
model = "gpt-3.5-turbo"
messages=[
{"role": "user", "content": messages}
]
// Set up the request body with the given parameters
const requestBody = {
"model": model,
"messages": messages,
};
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 ChatGPT 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
}