Skip to content

Instantly share code, notes, and snippets.

@estevecastells
Created July 2, 2024 20:44
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-3.5-turbo-0125",
messages: [
{"role": "user", "content": userMessage}
],
temperature: 0.6,
max_tokens: 10000,
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