Academy ↓
OpenAI API Prompt and Response
Send a text prompt to OpenAI API using GPT 3.5 Turbo.
Here's how the code works:
Basically the function is named "ai" and then a text variable is used to fill in for the prompt you can enter in the function in sheets. Any text you add in the function in side of your cell will be used as "prompt" inside the function.
We'll get the apikey for the API call from the cell A1 in the tab named "apikey"
Then we'll add the settings like max_tokens and top_p as data. Then we'll create the payload and the headers for the API call. In this case we're using a POST api call to essentially add the prompt text to OpenAI and we'll end up getting a response that's text.
We execute the API call with UrlFetchApp.fetch() along with the options we stated earlier.
Then we'll get the response, get the text, and parse it with JSON.
Finally we'll return just the message content from the JSON we get back to we can read the text the AI gives us back.
function ai(prompt) {
var apikey = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("apikey").getRange("A1").getValue();
var role = ""
var data = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "system", "content": role},
{"role": "user", "content": prompt }],
"temperature": 1,
"max_tokens": 500,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}
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
}