-
-
Save wilhelmklopp/959804d44feb55dc2533104213cc26e8 to your computer and use it in GitHub Desktop.
Google apps script for an =openai() function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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