AOAI integration

  1. Upload a Word file with 10,000 characters of text to kintone and have the AI ​​learn from it.
  2. When you ask the AI ​​a question in kintone, the AI ​​will display an answer from the text learned in step 1.

see how my codes look like

(function () {
    'use strict';

    const FILE_FIELD_CODE = "File_Upload";        
    const TEXT_AREA_FIELD_CODE = "Extracted_Text";
    const QUESTION_FIELD_CODE = "Question";
    const ANSWER_FIELD_CODE = "Answer";

    // Function to read and return text from a plain text file
    async function extractTextFromFile(fileKey) {
        try {
            console.log("Starting text extraction for file key:", fileKey);
            const fileResponse = await kintone.api(kintone.api.url('/k/v1/file', true), 'GET', { fileKey: fileKey });
            const fileBlob = await fileResponse.blob();
            const fileText = await fileBlob.text();
            console.log("Extracted text from file:", fileText);
            return fileText;
        } catch (error) {
            console.error("Error reading text from file:", error);
            return "Failed to read text.";
        }
    }

    // Function to call OpenAI and get the answer
    async function generateAnswerFromAI(question, extractedText) {
        try {
            console.log("Sending request to OpenAI with question:", question);
            console.log("Extracted text:", extractedText);

            const response = await fetch("https://api.openai.com/v1/chat/completions", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": `Bearer OPENAI_API_KEY`
                },
                body: JSON.stringify({
                    model: "gpt-3.5-turbo",
                    messages: [{ "role": "user", "content": `Answer the following question based on this content:\n\n${extractedText}\n\nQuestion: ${question}\nAnswer:` }],
                    max_tokens: 100
                })
            });

            const data = await response.json();
            console.log("Response from OpenAI:", data);
            return data.choices && data.choices[0].message.content ? data.choices[0].message.content.trim() : "No answer available.";
        } catch (error) {
            console.error("Error generating answer from OpenAI:", error);
            return "Failed to generate answer.";
        }
    }

    // Event: Trigger text extraction on file upload
    kintone.events.on('app.record.create.change.' + FILE_FIELD_CODE, async function(event) {
        const record = event.record;
        const fileField = record[FILE_FIELD_CODE];

        if (fileField && fileField.value && fileField.value.length > 0) {
            const fileKey = fileField.value[0].fileKey;
            console.log("File key found:", fileKey);

            const extractedText = await extractTextFromFile(fileKey);
            console.log("Storing extracted text in record...");
            record[TEXT_AREA_FIELD_CODE].value = extractedText;

            kintone.app.record.set({ record: record });  /
        } else {
            console.log("No file uploaded or file key is missing.");
        }
        return event;
    });

    // Event: Generate answer when question is entered
    kintone.events.on(['app.record.create.submit', 'app.record.edit.submit'], async function(event) {
        const record = event.record;
        const question = record[QUESTION_FIELD_CODE].value;
        const extractedText = record[TEXT_AREA_FIELD_CODE].value;

        console.log("Question field value:", question);
        console.log("Extracted text field value:", extractedText);

        if (question && extractedText) {
            console.log("Both question and extracted text are present. Generating answer...");
            const answer = await generateAnswerFromAI(question, extractedText);
            record[ANSWER_FIELD_CODE].value = answer;
            kintone.app.record.set({ record: record }); 
        } else {
            console.log("Either the question or the extracted text is missing.");
        }
        return event;
    });

    console.log("Script loaded and initialized.");
})(); 

but the codes return nothing kindly help me

1 Like

Thanks for the question, @Mpumuro!

Could you please elaborate on the question? For example, what does your Console error message say in the Inspector mode? :smiley:

in console return Either the question or the extracted text is missing.

Thank you for your response.

After checking the code on the above page, it was found that the slash (/) on line 65 was causing multiple errors.

kintone.app.record.set({ record: record });  /

Furthermore, since the value can be set to the record with return event; , the value-setting process on line 85 seems unnecessary.

kintone.app.record.set({ record: record });

After removing the slash (/ ) and commenting out the process of the kintone.app.record.set function, it appears that the system works properly if the OpenAI API can be executed.

I apologize for the inconvenience, but could you please set a valid value for OPENAI_API_KEY in the app used for operation verification to check whether it works as expected?

In our testing, when the slash was removed and the process of the kintone.app.record.set function was commented out, the system seemed to work correctly as long as the OpenAI API could be executed.

In addition, one point of concern is that in the event triggered when a field value is changed on the record addition screen, the "Attachment" field is not included.

Here is a link to fields that can be specified with field codes (japanese only):

In your code, there is an event handling changes to the "Attachment" field, but this process does not seem to work.

Please be aware you cannot get information from the attachment field.

Additionally, in your latest response you mentioned the console returns either the "Question" or the "extracted_text". This indicates that the else branch of the process is being executed.

It would be appreciated if you could check once again whether the fields "Extracted_Text" and "Question" are set with values when the record is saved.

I hope this helps.