Skip to content

Instantly share code, notes, and snippets.

@wilhelmklopp
Created November 26, 2024 14:45
Show Gist options
  • Save wilhelmklopp/959804d44feb55dc2533104213cc26e8 to your computer and use it in GitHub Desktop.
Save wilhelmklopp/959804d44feb55dc2533104213cc26e8 to your computer and use it in GitHub Desktop.
Google apps script for an =openai() function
function openai(prompt) {
var scriptProperties = PropertiesService.getScriptProperties();
var apiKey = scriptProperties.getProperty('OPENAI_API_KEY');
var apiEndpoint = "https://api.openai.com/v1/chat/completions";
var data = {
"model": "gpt-4o", // Specifying the model
"messages": [
{"role": "system", "content": prompt},
],
"max_tokens": 150,
};
var options = {
"method": "post",
"contentType": "application/json",
"payload": JSON.stringify(data),
"headers": {
"Authorization": "Bearer " + apiKey
},
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(apiEndpoint, options);
var responseText = response.getContentText();
var responseData = JSON.parse(responseText);
if (responseData.error) {
return "Error: " + responseData.error.message; // Improved error handling
}
console.log(responseData.choices[0].message.content.trim())
return responseData.choices[0].message.content.trim();
}
openai("hello world")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment