Academy ↓
OpenAI API Custom Function
Call OpenAI's API with this simple custom function. Use your own API Key with this seemingly native function.
/**
* @customfunction
* @param {string} prompt - the prompt text
* @param {string} apikey - Your API Key from Open AI
* @param {string} model - AI Model
* @param {string} max_tokens - Maximum tokens to spend
* @param {number} temperature - Between 0 and 1
* @param {number} top_p - Between 0 and 1
* @param {number} frequency_penalty - Between 0 and 1
* @param {number} presence_penalty - Between 0 and 1
* @param {string} role - [OPTIONAL] System Role
*/
function OPENAI(prompt,apikey,model,temperature,max_tokens,top_p,frequency_penalty,presence_penalty,role="") {
var data = {
"model": model,
"messages": [{"role": "system", "content": role},
{"role": "user", "content": prompt }],
"temperature": temperature,
"max_tokens": max_tokens,
"top_p": top_p,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty
}
var options = {
'method': 'POST',
'contentType': 'application/json',
'headers': {
'Authorization' : 'Bearer ' + apikey
},
'payload': JSON.stringify(data)
}
var answer = UrlFetchApp.fetch("https://api.openai.com/v1/chat/completions",options)
var response = answer.getContentText()
var json = JSON.parse(response)
return json.choices[0].message.content
}