Skip to content

Instantly share code, notes, and snippets.

@cliffordp
Created October 11, 2024 17:45
Show Gist options
  • Save cliffordp/571a38daac6f80bc3fecb23efb5ccf23 to your computer and use it in GitHub Desktop.
Save cliffordp/571a38daac6f80bc3fecb23efb5ccf23 to your computer and use it in GitHub Desktop.
Create a Google Sheets `=GPT("...")` function with your OpenAI API Key
// Source: https://jonathanboshoff.com/free-gpt-4-sheets-alternative/
function GPT(Input) {
const GPT_API = "AAAAAAAAAAAAA"; // Replace with your actual API key
const BASE_URL = "https://api.openai.com/v1/chat/completions";
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${GPT_API}`
};
const options = {
headers,
method: "POST",
muteHttpExceptions: true,
payload: JSON.stringify({
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant powered by OpenAI's GPT-4o model."
},
{
"role": "user",
"content": Input
}
],
"temperature": 0.8,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
})
};
try {
const response = UrlFetchApp.fetch(BASE_URL, options);
const responseJson = JSON.parse(response.getContentText());
Logger.log(responseJson); // Log the entire response for debugging
if (responseJson.error) {
Logger.log("Error from OpenAI: " + responseJson.error.message);
return "Error: " + responseJson.error.message;
} else {
// Check the model used in the response
if (responseJson.model && responseJson.model.startsWith("gpt-4")) {
return responseJson.choices && responseJson.choices.length > 0 ? responseJson.choices[0].message.content : "No response";
} else {
return "Error: The response is not from the GPT-4 model.";
}
}
} catch (e) {
Logger.log("Error: " + e.message);
return "Error: " + e.message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment