I created a custom function in Google App Script to call the OpenAI API. It was functioning properly, but I am currently transitioning to the Azure OpenAI API service for improved performance and stability. However, I encountered issues when attempting to recode the Apps Script according to the Azure OpenAI instructions. The current version of the script is as follows:
const api_key = "azure openai api key1";
const max_tokens = 500;
function gpt(userprompt, userrole = "user", temperature = 1) {
const gptprompt = [{role:userrole,content:userprompt},
];
const url = "azure openai endpoint";
const payload = {
engine:"gpt-35-turbo",
messages: gptprompt,
temperature: temperature,
max_tokens: max_tokens,
};
// Use 'method' property with value 'POST' instead of default 'GET' method
const options = {
method: "POST",
contentType: "application/json",
headers: { Authorization: "Bearer " + api_key },
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
try {
const response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText());
const results = JSON.parse(response.getContentText());
console.log(results);
const text = results?.choices?.[0]?.message?.text?.trim() ?? "No text generated"; // Update this line to use 'choices' and 'message'
console.log(text);
return text;
} catch (error) {
// Log error message and return a custom error message
console.error("Error: ", error);
return "Error: Unable to fetch data.";
}
}
but return error according to log:
6:52:23 AM Notice Execution started
6:52:23 AM Info { "statusCode": 401, "message": "Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired." }
6:52:23 AM Info { statusCode: 401, message: 'Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired.' }
6:52:23 AM Info No text generated 6:52:24 AM Notice Execution completed
I have checked the API key and endpoint is work in python Am I missed some part in the apps script?