Skip to content

Instantly share code, notes, and snippets.

@estevecastells
Last active August 13, 2024 11:46
Show Gist options
  • Save estevecastells/a0097df89a914f60c394e974d2eae067 to your computer and use it in GitHub Desktop.
Save estevecastells/a0097df89a914f60c394e974d2eae067 to your computer and use it in GitHub Desktop.
Use OpenAI API in a Google Spreadsheets as an Apps Script function
function queryOpenAIChatCompletion(userMessage) {
var apiKey = 'API_KEY'; // Replace with your actual API key
var url = 'https://api.openai.com/v1/chat/completions';
var payload = {
model: "gpt-4o-mini",
messages: [
{"role": "user", "content": userMessage}
],
temperature: 0.4,
max_tokens: 3000,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'headers': {
'Authorization': 'Bearer ' + apiKey
},
'payload': JSON.stringify(payload)
};
try {
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
return data.choices[0].message.content;
} catch (e) {
Logger.log(e.toString());
return "Error: " + e.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment