I tried to use OpenAI with Kintone but the error is rate limit with 429 i wanted to summarize the text please check the my codes (function() {
“use strict”;
console.log("Automatic summarization script loaded");
const openAiApiKey = '';
const openAiApiEndpoint = "https://api.openai.com/v1/chat/completions";
// Function to call OpenAI API for generating a summary
async function generateSummary(inputText) {
try {
const response = await fetch(openAiApiEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${openAiApiKey}`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a helpful assistant that summarizes text." },
{ role: "user", content: `Summarize the following text:\n\n${inputText}` }
],
max_tokens: 100
})
});
// Check if the response is ok before accessing the content
if (response.ok) {
const data = await response.json();
console.log("OpenAI response received:", data);
if (data.choices && data.choices.length > 0) {
return data.choices[0].message.content.trim();
} else {
console.error("OpenAI returned an empty or invalid response");
return "Summary not available";
}
} else {
console.error(`API error: ${response.status} ${response.statusText}`);
return "Failed to generate summary.";
}
} catch (error) {
console.error("Error calling OpenAI API:", error);
return "An error occurred while generating the summary.";
}
}
// Event listener for changes in the input_text field
kintone.events.on(['app.record.create.change.input_text', 'app.record.edit.change.input_text'], async function(event) {
const record = event.record;
const inputText = record['input_text']?.value; // Replace 'input_text' with your actual field code
if (!inputText) {
console.log("No input text provided");
return event;
}
console.log("Text detected, summarizing...");
// Generate the summary and update the field in Kintone
const summary = await generateSummary(inputText);
record['summary'].value = summary; // Replace 'summary' with your actual summary field code
console.log("Summary updated in the record");
return event;
});
})();