logo

NJP

In Predictive Intelligence how to get predicted data in Portal/Client side

Import · Apr 14, 2023 · article

Predictive Intelligence is a paid plugin that we have to activate manually. To start using this for your organization please make sure you should have followed the below steps.

1- Before starting to train any dataset Please confirm that 'sharedservice.worker' this user should have platform_ml_read , platform_ml_write, platform_ml_create role.

**If 'sharedservice.worker' will not have the above roles then you may get several errors during data training**

2- Once the data training is successful than to test the output the tester should have the ml_admin role.

**If the tester doesn't have that role, then the test section of the output will not appear. **

3- Add the below script in your Script include and call that in the client script to get the output-

3.1- Get Classification Output:

getClassificationOutcome: function() {
        /**
        Get Classification Output
        : {JSON} - input fields data 
        : {string} -Solution Name
        @return : {JSON} - Output values of input data with threshold value and confidence

        ------------
        Input Format
        ------------
        var solutionInput = {
        "short_description": "email",
        "description": "outlook issue"}
        */
        var result = {
            'results': [],
            'inputReceived': solutionInput
        };
        try {
            var solutionInput = this.getParameter('sysparm_fields');
            var solutionName = this.getParameter('sysparm_solutionName');
            var version = this.getActiveVersion(solutionName);
            var mlSolution = sn_ml.ClassificationSolutionStore.get(solutionName);
            var input = [];
            input[0] = JSON.parse(solutionInput);
            var options = {}; // configure optional parameters
            options.top_n = 1;
            options.apply_threshold = false;
            var results = mlSolution.getVersion(version).predict(input, options);
            var obj = JSON.parse(results);
            for (var i = 0; i < obj[Object.keys(obj)].length; i++) {
                var temp = {};
                temp.predictedValue = obj[Object.keys(obj)][i].predictedValue.toString();
                temp.predictedSysId = obj[Object.keys(obj)][i].predictedSysId.toString();
                temp.confidence = obj[Object.keys(obj)][i].confidence;
                result.results.push(temp);
                //this.addToLog('info', 'predictedValue: ' + obj[Object.keys(obj)][i].predictedValue.toString() + ' Confidence: ' + obj[Object.keys(obj)][i].confidence);
            }
            return JSON.stringify(result);
        } catch (ex) {
            result.reason = ex.message.toString();
            //this.addToLog('error', ex.message);
            return JSON.stringify(result);
        }
    }

3.2- Get Similarity output:

getSimilarityOutcome: function() {
        /**
        Get Similarity records Output
        @param1: {JSON} - input fields data
        @param2: {String} -Solution Name
        @return : {JSON} - Output values of input data with threshold value and confidence
        */
        var result = {
            'results': [],
            'inputReceived': solutionInput
        };
        try {
            var solutionInput = this.getParameter('sysparm_fields');
            var solutionName = this.getParameter('sysparm_solutionName');
            var version = this.getActiveVersion(solutionName);
            var mlSolution = sn_ml.SimilaritySolutionStore.get(solutionName);
            var input = [JSON.parse(solutionInput)];
            var options = {}; // configure optional parameters
            options.top_n = 2; //It will return top 2 record if you need one or more record you can add your count
            options.apply_threshold = false;
            var results = mlSolution.getVersion(version).predict(input, options);
            var obj = JSON.parse(results);
            var x;
            var y;
            for (x in obj) {
                for (y in obj[x]) {
                    var temp = {};
                    temp.predictedValue = obj[x][y].predictedValue.toString();
                    temp.predictedSysId = obj[x][y].predictedSysId.toString();
                    temp.confidence = obj[x][y].confidence;
                    temp.kb = this.getKBNumber(obj[x][y].predictedSysId.toString());//please copy and past the below 4th point in this article otherwise it will throw error
                    result.results.push(temp);
                }
            }
            return JSON.stringify(result);
        } catch (ex) {
            result.reason = ex.message.toString();
            //this.addToLog('error', ex.message);
            return JSON.stringify(result);
        }
    }

4- Please add below functions in the same script include:

getKBNumber: function(id) {
        /**
        @parm1: {string} - sys_id of KB record
        @return: {string} - number of the KB
        */
        var kb = new GlideRecord('kb_knowledge');
        kb.get(id);
        return kb.number.toString();
    },
    getActiveVersion: function(solutionName) {
        /*
        @parm1: {string} - sys_id of solution name
        @return: {number} - active version of the solution
        */
        var solution = new GlideRecord('ml_solution');
        solution.addActiveQuery();
        solution.get(solutionName);
        return solution.version;
    }

5- Use below client script as per your requirement:

/**
Input Preparation 
key should be the backend name of your field and you can modify the below solutionInput as per your requiremnet
*/
var solutionInput = {
            "short_description": g_form.getValue('short_description'),
            "description": g_form.getValue('description')
        };
//predict using clasification
        var ga = new GlideAjax('global.predictCustomUtils'); //script include name
        ga.addParam('sysparm_name', 'getClassificationOutcome');
        ga.addParam('sysparm_fields', JSON.stringify(solutionInput));
        ga.addParam('sysparm_solutionName', '<<Your Solution Name>>');
        ga.getXMLAnswer(callBack);

        function callBack(response) {
            var ans = response;
            //alert(ans);
            if (ans == '' || ans == undefined || ans == null) {
                //g_form.addErrorMessage('No similar record found for this combination.' + ans);
            } else {
                var answer = JSON.parse(ans);
                var output = "";
                if (answer.results.length > 0) {
                    for (var i = 0; i < answer.results.length; i++) {
                        alert('The Predicted Value:- '+answer.results[i].predictedValue.toString());
                    }
                }
            }
        }

//Predict using similarity

 var ga = new GlideAjax('global.predictCustomUtils'); //script include name
        ga.addParam('sysparm_name', 'getSimilarityOutcome');
        ga.addParam('sysparm_fields', JSON.stringify(solutionInput));
        ga.addParam('sysparm_solutionName', '<<Your Solution Name>>');
        ga.getXMLAnswer(callBack);

        function callBack(response) {
            var ans = response;
            if (ans == '' || ans == undefined || ans == null) {
                g_form.addErrorMessage('No similar record found for this combination. - ' + ans);
            } else {
                var answer = JSON.parse(ans);
                var output = "";
                if (answer.results.length > 0) {
                    var kb = '';
                    var kbNumbers = '';
                    for (var i = 0; i < answer.results.length; i++) {
                        kb += '<b><a href="/kb_knowledge.do?sys_id=' + answer.results[i].predictedSysId + '" target="_blank">' + answer.results[i].kb + '</a></b> ';
//gs.addInfoMessage(kb); //uncomment this line if you predictimng KB article using above input
                        kbNumbers += answer.results[i].kb + ' ';
                    }
                    if (kbNumbers != '') {
                        alert('Predcited Value : ' + kbNumbers);
                    }
                }
            }
        }

If you need any help Please reach out to me via LinkedIn or send me a message.

Please mark it helpful if somehow it helps you in any manner.

View original source

https://www.servicenow.com/community/ai-intelligence-articles/in-predictive-intelligence-how-to-get-predicted-data-in-portal/ta-p/2534691