How to create OutPutContext via V2 client library for node js












0















I am working on entity and intents creation in my agent using v2 client library for node.js . And for that i am going through this sample which is on git. And it says something related to session id and context id. Can anyone explain me what is sessionId and contextId. And also provide me link where i can read those thing in details.



I am unable to create context by following those example. How can i create context while creating intent at the same time.










share|improve this question

























  • what's the code you are using currently for creating the intent? please provide the exact code, i was able to provide context as well, need to see your code to suggest modifications.

    – sid8491
    Nov 20 '18 at 13:17











  • for creating the intent you will be calling createIntent() method only which you have provided in the link. anyway, you can see this for reference: github.com/googleapis/dialogflow-python-client-v2/issues/62 its in python but you can easily convert it into node js

    – sid8491
    Nov 20 '18 at 13:51











  • you basically need to add one line.

    – sid8491
    Nov 20 '18 at 13:51
















0















I am working on entity and intents creation in my agent using v2 client library for node.js . And for that i am going through this sample which is on git. And it says something related to session id and context id. Can anyone explain me what is sessionId and contextId. And also provide me link where i can read those thing in details.



I am unable to create context by following those example. How can i create context while creating intent at the same time.










share|improve this question

























  • what's the code you are using currently for creating the intent? please provide the exact code, i was able to provide context as well, need to see your code to suggest modifications.

    – sid8491
    Nov 20 '18 at 13:17











  • for creating the intent you will be calling createIntent() method only which you have provided in the link. anyway, you can see this for reference: github.com/googleapis/dialogflow-python-client-v2/issues/62 its in python but you can easily convert it into node js

    – sid8491
    Nov 20 '18 at 13:51











  • you basically need to add one line.

    – sid8491
    Nov 20 '18 at 13:51














0












0








0








I am working on entity and intents creation in my agent using v2 client library for node.js . And for that i am going through this sample which is on git. And it says something related to session id and context id. Can anyone explain me what is sessionId and contextId. And also provide me link where i can read those thing in details.



I am unable to create context by following those example. How can i create context while creating intent at the same time.










share|improve this question
















I am working on entity and intents creation in my agent using v2 client library for node.js . And for that i am going through this sample which is on git. And it says something related to session id and context id. Can anyone explain me what is sessionId and contextId. And also provide me link where i can read those thing in details.



I am unable to create context by following those example. How can i create context while creating intent at the same time.







dialogflow






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 5:35







FaisalAhmed

















asked Nov 20 '18 at 12:37









FaisalAhmedFaisalAhmed

97611834




97611834













  • what's the code you are using currently for creating the intent? please provide the exact code, i was able to provide context as well, need to see your code to suggest modifications.

    – sid8491
    Nov 20 '18 at 13:17











  • for creating the intent you will be calling createIntent() method only which you have provided in the link. anyway, you can see this for reference: github.com/googleapis/dialogflow-python-client-v2/issues/62 its in python but you can easily convert it into node js

    – sid8491
    Nov 20 '18 at 13:51











  • you basically need to add one line.

    – sid8491
    Nov 20 '18 at 13:51



















  • what's the code you are using currently for creating the intent? please provide the exact code, i was able to provide context as well, need to see your code to suggest modifications.

    – sid8491
    Nov 20 '18 at 13:17











  • for creating the intent you will be calling createIntent() method only which you have provided in the link. anyway, you can see this for reference: github.com/googleapis/dialogflow-python-client-v2/issues/62 its in python but you can easily convert it into node js

    – sid8491
    Nov 20 '18 at 13:51











  • you basically need to add one line.

    – sid8491
    Nov 20 '18 at 13:51

















what's the code you are using currently for creating the intent? please provide the exact code, i was able to provide context as well, need to see your code to suggest modifications.

– sid8491
Nov 20 '18 at 13:17





what's the code you are using currently for creating the intent? please provide the exact code, i was able to provide context as well, need to see your code to suggest modifications.

– sid8491
Nov 20 '18 at 13:17













for creating the intent you will be calling createIntent() method only which you have provided in the link. anyway, you can see this for reference: github.com/googleapis/dialogflow-python-client-v2/issues/62 its in python but you can easily convert it into node js

– sid8491
Nov 20 '18 at 13:51





for creating the intent you will be calling createIntent() method only which you have provided in the link. anyway, you can see this for reference: github.com/googleapis/dialogflow-python-client-v2/issues/62 its in python but you can easily convert it into node js

– sid8491
Nov 20 '18 at 13:51













you basically need to add one line.

– sid8491
Nov 20 '18 at 13:51





you basically need to add one line.

– sid8491
Nov 20 '18 at 13:51












2 Answers
2






active

oldest

votes


















1














The following is code to create a context. You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent that uses the context. The response to the create context API call will return a context ID you can use in your intent.



  const dialogflow = require('dialogflow');

// Instantiates clients
const entityTypesClient = new dialogflow.EntityTypesClient();

// The path to the agent the created entity type belongs to.
const agentPath = entityTypesClient.projectAgentPath(projectId);

const createEntityTypeRequest = {
parent: agentPath,
entityType: {
displayName: displayName,
kind: kind,
},
};

entityTypesClient
.createEntityType(createEntityTypeRequest)
.then(responses => {
console.log(`Created ${responses[0].name} entity type`);
})
.catch(err => {
console.error('Failed to create size entity type:', err);
});


Source: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js






share|improve this answer
























  • above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

    – FaisalAhmed
    Nov 21 '18 at 5:15











  • As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

    – FaisalAhmed
    Nov 21 '18 at 5:20













  • Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

    – matthewayne
    Nov 21 '18 at 22:45











  • Can you replace code in your answer with code related to context. Code which you have provided is for entity

    – FaisalAhmed
    Nov 23 '18 at 6:04











  • @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

    – Alex Riquelme
    Nov 26 '18 at 16:28



















0














Contexts are very closely associated with SessionID. Say for eg, you have a chatbot that gets spun up on two computers serving two different user's. Each user will have a respective session_id (If you're coding in NODE, when a new user fires the chatbot, you need to ensure he/she will get a unique session_id).



Now, every unique session id will have unique contexts. From above example, let's say user 1 will initialize an intent that has input context named 'abc' with lifespan of 2 and user 2 will initialize another intent that has input context named 'xyz' with lifespan of 5, these respective contexts gets recorded against each of these user's individual session id's. You can programatically control (edit) contexts and its lifecycle. This is the biggest advantage of code facilitated Dialogflow as opposed to using GUI. Using services like Firebase, you can also preserve session id's and its associated contexts so, next time same user sign's in again, they can start from where they had last left.



I can share a snippet from one of my previous projects where I was managing contexts programatically. Initialization script is as follows:



/**
* @author Pruthvi Kumar
* @email pruthvikumar.123@gmail.com
* @create date 2018-08-15 04:42:22
* @modify date 2018-08-15 04:42:22
* @desc Dialogflow config for chatbot.
*/

const dialogflow_config = {
projectId: 'xxx',
sessionId: 'chatbot-session-id', //This is default assignment. This will hve to be overridden by sessionId as obtained from client in order to main context per sessionId.
languageCode: 'en-US'
};

exports.configStoreSingleton = (function () {
let instanceStacks;
let instanceSessionId;

let contextStack = {};
let intentsStack = {};
let successfulIntentResponseStack = {};

function init() {
contextStack[dialogflow_config['sessionId']] = ;
intentsStack[dialogflow_config['sessionId']] = ;
successfulIntentResponseStack[dialogflow_config['sessionId']] = ;

return {
contextStack: contextStack,
intentsStack: intentsStack,
successfulIntentResponseStack: successfulIntentResponseStack
};
}

return {
init: function () {
if (!instanceStacks || (instanceSessionId !== dialogflow_config['sessionId'] && (!intentsStack[dialogflow_config['sessionId']]))) {
console.log('[dialogflow_config]: Singleton is not instantiated previously or New userSession is triggered! Fresh instance stack will be provisioned');
instanceStacks = init();
instanceSessionId = dialogflow_config['sessionId'];
}
return instanceStacks;
}
};
})();

exports.updateSessionIdOfDialogflowConfig = function (sessionId) {
if (typeof (sessionId) === 'string') {
dialogflow_config['sessionId'] = sessionId;
return true;
} else {
console.warn('[dialogflow_config]: SessionId must be of type STRING!');
return;
}
};

exports.getDialogflowConfig = function () {
return dialogflow_config;
};


And then, to programmatically manage contexts:



/**
* @author Pruthvi Kumar
* @email pruthvikumar.123@gmail.com
* @create date 2018-08-15 04:37:15
* @modify date 2018-08-15 04:37:15
* @desc Operate on Dialogflow Contexts
*/

const dialogflow = require('dialogflow');
const dialogflowConfig = require('../modules/dialogflow_config');
const structjson = require('./dialogflow_structjson');
const util = require('util');

const contextsClient = new dialogflow.ContextsClient();

exports.setContextHistory = function (sessionId, intent_name, context_payload, preservedContext=false) {
/* maintain context stack per session */
/* context_payload = {input_contexts: , output_contexts = }
*/
const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;

if (intent_name) {
contextStack[sessionId].push({
intent: intent_name,
contexts: context_payload,
preserveContext: preservedContext
});
} else {
console.warn('[dialogflow_contexts]: Intent name is not provided OR Nothing in context_payload to add to history!');
}

};

exports.getContextHistory = function () {
const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
return contextStack;
}

exports.preserveContext = function () {
const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
//Traverse contextStack, get the last contexts.
let context_to_be_preserved = contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']][contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']].length - 1];
//console.log(`context to be preserved is: ${util.inspect(context_to_be_preserved)}`);
return context_to_be_preserved['contexts'].map((context, index) => {
let context_id = exports.getContextId(context);
return exports.updateContext(context_id, true)
});
}


From here, you can reference this github resource to build your own contexts - https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js



Happy creating digital souls!






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393153%2fhow-to-create-outputcontext-via-v2-client-library-for-node-js%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The following is code to create a context. You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent that uses the context. The response to the create context API call will return a context ID you can use in your intent.



      const dialogflow = require('dialogflow');

    // Instantiates clients
    const entityTypesClient = new dialogflow.EntityTypesClient();

    // The path to the agent the created entity type belongs to.
    const agentPath = entityTypesClient.projectAgentPath(projectId);

    const createEntityTypeRequest = {
    parent: agentPath,
    entityType: {
    displayName: displayName,
    kind: kind,
    },
    };

    entityTypesClient
    .createEntityType(createEntityTypeRequest)
    .then(responses => {
    console.log(`Created ${responses[0].name} entity type`);
    })
    .catch(err => {
    console.error('Failed to create size entity type:', err);
    });


    Source: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js






    share|improve this answer
























    • above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

      – FaisalAhmed
      Nov 21 '18 at 5:15











    • As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

      – FaisalAhmed
      Nov 21 '18 at 5:20













    • Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

      – matthewayne
      Nov 21 '18 at 22:45











    • Can you replace code in your answer with code related to context. Code which you have provided is for entity

      – FaisalAhmed
      Nov 23 '18 at 6:04











    • @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

      – Alex Riquelme
      Nov 26 '18 at 16:28
















    1














    The following is code to create a context. You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent that uses the context. The response to the create context API call will return a context ID you can use in your intent.



      const dialogflow = require('dialogflow');

    // Instantiates clients
    const entityTypesClient = new dialogflow.EntityTypesClient();

    // The path to the agent the created entity type belongs to.
    const agentPath = entityTypesClient.projectAgentPath(projectId);

    const createEntityTypeRequest = {
    parent: agentPath,
    entityType: {
    displayName: displayName,
    kind: kind,
    },
    };

    entityTypesClient
    .createEntityType(createEntityTypeRequest)
    .then(responses => {
    console.log(`Created ${responses[0].name} entity type`);
    })
    .catch(err => {
    console.error('Failed to create size entity type:', err);
    });


    Source: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js






    share|improve this answer
























    • above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

      – FaisalAhmed
      Nov 21 '18 at 5:15











    • As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

      – FaisalAhmed
      Nov 21 '18 at 5:20













    • Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

      – matthewayne
      Nov 21 '18 at 22:45











    • Can you replace code in your answer with code related to context. Code which you have provided is for entity

      – FaisalAhmed
      Nov 23 '18 at 6:04











    • @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

      – Alex Riquelme
      Nov 26 '18 at 16:28














    1












    1








    1







    The following is code to create a context. You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent that uses the context. The response to the create context API call will return a context ID you can use in your intent.



      const dialogflow = require('dialogflow');

    // Instantiates clients
    const entityTypesClient = new dialogflow.EntityTypesClient();

    // The path to the agent the created entity type belongs to.
    const agentPath = entityTypesClient.projectAgentPath(projectId);

    const createEntityTypeRequest = {
    parent: agentPath,
    entityType: {
    displayName: displayName,
    kind: kind,
    },
    };

    entityTypesClient
    .createEntityType(createEntityTypeRequest)
    .then(responses => {
    console.log(`Created ${responses[0].name} entity type`);
    })
    .catch(err => {
    console.error('Failed to create size entity type:', err);
    });


    Source: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js






    share|improve this answer













    The following is code to create a context. You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent that uses the context. The response to the create context API call will return a context ID you can use in your intent.



      const dialogflow = require('dialogflow');

    // Instantiates clients
    const entityTypesClient = new dialogflow.EntityTypesClient();

    // The path to the agent the created entity type belongs to.
    const agentPath = entityTypesClient.projectAgentPath(projectId);

    const createEntityTypeRequest = {
    parent: agentPath,
    entityType: {
    displayName: displayName,
    kind: kind,
    },
    };

    entityTypesClient
    .createEntityType(createEntityTypeRequest)
    .then(responses => {
    console.log(`Created ${responses[0].name} entity type`);
    })
    .catch(err => {
    console.error('Failed to create size entity type:', err);
    });


    Source: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 '18 at 15:20









    matthewaynematthewayne

    2,723814




    2,723814













    • above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

      – FaisalAhmed
      Nov 21 '18 at 5:15











    • As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

      – FaisalAhmed
      Nov 21 '18 at 5:20













    • Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

      – matthewayne
      Nov 21 '18 at 22:45











    • Can you replace code in your answer with code related to context. Code which you have provided is for entity

      – FaisalAhmed
      Nov 23 '18 at 6:04











    • @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

      – Alex Riquelme
      Nov 26 '18 at 16:28



















    • above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

      – FaisalAhmed
      Nov 21 '18 at 5:15











    • As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

      – FaisalAhmed
      Nov 21 '18 at 5:20













    • Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

      – matthewayne
      Nov 21 '18 at 22:45











    • Can you replace code in your answer with code related to context. Code which you have provided is for entity

      – FaisalAhmed
      Nov 23 '18 at 6:04











    • @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

      – Alex Riquelme
      Nov 26 '18 at 16:28

















    above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

    – FaisalAhmed
    Nov 21 '18 at 5:15





    above code which you have given in your answer is related entity creation. I am confused. how this can help me in context creation.

    – FaisalAhmed
    Nov 21 '18 at 5:15













    As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

    – FaisalAhmed
    Nov 21 '18 at 5:20







    As you said that You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent. I didn't find such thing mentioned anywhere in docs. Can you please share some links where i can read those thing in details

    – FaisalAhmed
    Nov 21 '18 at 5:20















    Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

    – matthewayne
    Nov 21 '18 at 22:45





    Its not in the docs explicitly, but is a fact of how you create intents and contexts via the API. If you create an intent and wish to have a context attached to it you need to refer to the context by ID. A context ID is created for a context when it is created by Dialogflow and cannot be known before the context is created. Thus since a intent requires a context ID and and context ID is not generated until the context is created a context must be created before an intent is created.

    – matthewayne
    Nov 21 '18 at 22:45













    Can you replace code in your answer with code related to context. Code which you have provided is for entity

    – FaisalAhmed
    Nov 23 '18 at 6:04





    Can you replace code in your answer with code related to context. Code which you have provided is for entity

    – FaisalAhmed
    Nov 23 '18 at 6:04













    @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

    – Alex Riquelme
    Nov 26 '18 at 16:28





    @FaisalAhmed here you have some context functions to insert in your code: github.com/googleapis/nodejs-dialogflow/blob/…

    – Alex Riquelme
    Nov 26 '18 at 16:28













    0














    Contexts are very closely associated with SessionID. Say for eg, you have a chatbot that gets spun up on two computers serving two different user's. Each user will have a respective session_id (If you're coding in NODE, when a new user fires the chatbot, you need to ensure he/she will get a unique session_id).



    Now, every unique session id will have unique contexts. From above example, let's say user 1 will initialize an intent that has input context named 'abc' with lifespan of 2 and user 2 will initialize another intent that has input context named 'xyz' with lifespan of 5, these respective contexts gets recorded against each of these user's individual session id's. You can programatically control (edit) contexts and its lifecycle. This is the biggest advantage of code facilitated Dialogflow as opposed to using GUI. Using services like Firebase, you can also preserve session id's and its associated contexts so, next time same user sign's in again, they can start from where they had last left.



    I can share a snippet from one of my previous projects where I was managing contexts programatically. Initialization script is as follows:



    /**
    * @author Pruthvi Kumar
    * @email pruthvikumar.123@gmail.com
    * @create date 2018-08-15 04:42:22
    * @modify date 2018-08-15 04:42:22
    * @desc Dialogflow config for chatbot.
    */

    const dialogflow_config = {
    projectId: 'xxx',
    sessionId: 'chatbot-session-id', //This is default assignment. This will hve to be overridden by sessionId as obtained from client in order to main context per sessionId.
    languageCode: 'en-US'
    };

    exports.configStoreSingleton = (function () {
    let instanceStacks;
    let instanceSessionId;

    let contextStack = {};
    let intentsStack = {};
    let successfulIntentResponseStack = {};

    function init() {
    contextStack[dialogflow_config['sessionId']] = ;
    intentsStack[dialogflow_config['sessionId']] = ;
    successfulIntentResponseStack[dialogflow_config['sessionId']] = ;

    return {
    contextStack: contextStack,
    intentsStack: intentsStack,
    successfulIntentResponseStack: successfulIntentResponseStack
    };
    }

    return {
    init: function () {
    if (!instanceStacks || (instanceSessionId !== dialogflow_config['sessionId'] && (!intentsStack[dialogflow_config['sessionId']]))) {
    console.log('[dialogflow_config]: Singleton is not instantiated previously or New userSession is triggered! Fresh instance stack will be provisioned');
    instanceStacks = init();
    instanceSessionId = dialogflow_config['sessionId'];
    }
    return instanceStacks;
    }
    };
    })();

    exports.updateSessionIdOfDialogflowConfig = function (sessionId) {
    if (typeof (sessionId) === 'string') {
    dialogflow_config['sessionId'] = sessionId;
    return true;
    } else {
    console.warn('[dialogflow_config]: SessionId must be of type STRING!');
    return;
    }
    };

    exports.getDialogflowConfig = function () {
    return dialogflow_config;
    };


    And then, to programmatically manage contexts:



    /**
    * @author Pruthvi Kumar
    * @email pruthvikumar.123@gmail.com
    * @create date 2018-08-15 04:37:15
    * @modify date 2018-08-15 04:37:15
    * @desc Operate on Dialogflow Contexts
    */

    const dialogflow = require('dialogflow');
    const dialogflowConfig = require('../modules/dialogflow_config');
    const structjson = require('./dialogflow_structjson');
    const util = require('util');

    const contextsClient = new dialogflow.ContextsClient();

    exports.setContextHistory = function (sessionId, intent_name, context_payload, preservedContext=false) {
    /* maintain context stack per session */
    /* context_payload = {input_contexts: , output_contexts = }
    */
    const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;

    if (intent_name) {
    contextStack[sessionId].push({
    intent: intent_name,
    contexts: context_payload,
    preserveContext: preservedContext
    });
    } else {
    console.warn('[dialogflow_contexts]: Intent name is not provided OR Nothing in context_payload to add to history!');
    }

    };

    exports.getContextHistory = function () {
    const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
    return contextStack;
    }

    exports.preserveContext = function () {
    const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
    //Traverse contextStack, get the last contexts.
    let context_to_be_preserved = contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']][contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']].length - 1];
    //console.log(`context to be preserved is: ${util.inspect(context_to_be_preserved)}`);
    return context_to_be_preserved['contexts'].map((context, index) => {
    let context_id = exports.getContextId(context);
    return exports.updateContext(context_id, true)
    });
    }


    From here, you can reference this github resource to build your own contexts - https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js



    Happy creating digital souls!






    share|improve this answer




























      0














      Contexts are very closely associated with SessionID. Say for eg, you have a chatbot that gets spun up on two computers serving two different user's. Each user will have a respective session_id (If you're coding in NODE, when a new user fires the chatbot, you need to ensure he/she will get a unique session_id).



      Now, every unique session id will have unique contexts. From above example, let's say user 1 will initialize an intent that has input context named 'abc' with lifespan of 2 and user 2 will initialize another intent that has input context named 'xyz' with lifespan of 5, these respective contexts gets recorded against each of these user's individual session id's. You can programatically control (edit) contexts and its lifecycle. This is the biggest advantage of code facilitated Dialogflow as opposed to using GUI. Using services like Firebase, you can also preserve session id's and its associated contexts so, next time same user sign's in again, they can start from where they had last left.



      I can share a snippet from one of my previous projects where I was managing contexts programatically. Initialization script is as follows:



      /**
      * @author Pruthvi Kumar
      * @email pruthvikumar.123@gmail.com
      * @create date 2018-08-15 04:42:22
      * @modify date 2018-08-15 04:42:22
      * @desc Dialogflow config for chatbot.
      */

      const dialogflow_config = {
      projectId: 'xxx',
      sessionId: 'chatbot-session-id', //This is default assignment. This will hve to be overridden by sessionId as obtained from client in order to main context per sessionId.
      languageCode: 'en-US'
      };

      exports.configStoreSingleton = (function () {
      let instanceStacks;
      let instanceSessionId;

      let contextStack = {};
      let intentsStack = {};
      let successfulIntentResponseStack = {};

      function init() {
      contextStack[dialogflow_config['sessionId']] = ;
      intentsStack[dialogflow_config['sessionId']] = ;
      successfulIntentResponseStack[dialogflow_config['sessionId']] = ;

      return {
      contextStack: contextStack,
      intentsStack: intentsStack,
      successfulIntentResponseStack: successfulIntentResponseStack
      };
      }

      return {
      init: function () {
      if (!instanceStacks || (instanceSessionId !== dialogflow_config['sessionId'] && (!intentsStack[dialogflow_config['sessionId']]))) {
      console.log('[dialogflow_config]: Singleton is not instantiated previously or New userSession is triggered! Fresh instance stack will be provisioned');
      instanceStacks = init();
      instanceSessionId = dialogflow_config['sessionId'];
      }
      return instanceStacks;
      }
      };
      })();

      exports.updateSessionIdOfDialogflowConfig = function (sessionId) {
      if (typeof (sessionId) === 'string') {
      dialogflow_config['sessionId'] = sessionId;
      return true;
      } else {
      console.warn('[dialogflow_config]: SessionId must be of type STRING!');
      return;
      }
      };

      exports.getDialogflowConfig = function () {
      return dialogflow_config;
      };


      And then, to programmatically manage contexts:



      /**
      * @author Pruthvi Kumar
      * @email pruthvikumar.123@gmail.com
      * @create date 2018-08-15 04:37:15
      * @modify date 2018-08-15 04:37:15
      * @desc Operate on Dialogflow Contexts
      */

      const dialogflow = require('dialogflow');
      const dialogflowConfig = require('../modules/dialogflow_config');
      const structjson = require('./dialogflow_structjson');
      const util = require('util');

      const contextsClient = new dialogflow.ContextsClient();

      exports.setContextHistory = function (sessionId, intent_name, context_payload, preservedContext=false) {
      /* maintain context stack per session */
      /* context_payload = {input_contexts: , output_contexts = }
      */
      const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;

      if (intent_name) {
      contextStack[sessionId].push({
      intent: intent_name,
      contexts: context_payload,
      preserveContext: preservedContext
      });
      } else {
      console.warn('[dialogflow_contexts]: Intent name is not provided OR Nothing in context_payload to add to history!');
      }

      };

      exports.getContextHistory = function () {
      const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
      return contextStack;
      }

      exports.preserveContext = function () {
      const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
      //Traverse contextStack, get the last contexts.
      let context_to_be_preserved = contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']][contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']].length - 1];
      //console.log(`context to be preserved is: ${util.inspect(context_to_be_preserved)}`);
      return context_to_be_preserved['contexts'].map((context, index) => {
      let context_id = exports.getContextId(context);
      return exports.updateContext(context_id, true)
      });
      }


      From here, you can reference this github resource to build your own contexts - https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js



      Happy creating digital souls!






      share|improve this answer


























        0












        0








        0







        Contexts are very closely associated with SessionID. Say for eg, you have a chatbot that gets spun up on two computers serving two different user's. Each user will have a respective session_id (If you're coding in NODE, when a new user fires the chatbot, you need to ensure he/she will get a unique session_id).



        Now, every unique session id will have unique contexts. From above example, let's say user 1 will initialize an intent that has input context named 'abc' with lifespan of 2 and user 2 will initialize another intent that has input context named 'xyz' with lifespan of 5, these respective contexts gets recorded against each of these user's individual session id's. You can programatically control (edit) contexts and its lifecycle. This is the biggest advantage of code facilitated Dialogflow as opposed to using GUI. Using services like Firebase, you can also preserve session id's and its associated contexts so, next time same user sign's in again, they can start from where they had last left.



        I can share a snippet from one of my previous projects where I was managing contexts programatically. Initialization script is as follows:



        /**
        * @author Pruthvi Kumar
        * @email pruthvikumar.123@gmail.com
        * @create date 2018-08-15 04:42:22
        * @modify date 2018-08-15 04:42:22
        * @desc Dialogflow config for chatbot.
        */

        const dialogflow_config = {
        projectId: 'xxx',
        sessionId: 'chatbot-session-id', //This is default assignment. This will hve to be overridden by sessionId as obtained from client in order to main context per sessionId.
        languageCode: 'en-US'
        };

        exports.configStoreSingleton = (function () {
        let instanceStacks;
        let instanceSessionId;

        let contextStack = {};
        let intentsStack = {};
        let successfulIntentResponseStack = {};

        function init() {
        contextStack[dialogflow_config['sessionId']] = ;
        intentsStack[dialogflow_config['sessionId']] = ;
        successfulIntentResponseStack[dialogflow_config['sessionId']] = ;

        return {
        contextStack: contextStack,
        intentsStack: intentsStack,
        successfulIntentResponseStack: successfulIntentResponseStack
        };
        }

        return {
        init: function () {
        if (!instanceStacks || (instanceSessionId !== dialogflow_config['sessionId'] && (!intentsStack[dialogflow_config['sessionId']]))) {
        console.log('[dialogflow_config]: Singleton is not instantiated previously or New userSession is triggered! Fresh instance stack will be provisioned');
        instanceStacks = init();
        instanceSessionId = dialogflow_config['sessionId'];
        }
        return instanceStacks;
        }
        };
        })();

        exports.updateSessionIdOfDialogflowConfig = function (sessionId) {
        if (typeof (sessionId) === 'string') {
        dialogflow_config['sessionId'] = sessionId;
        return true;
        } else {
        console.warn('[dialogflow_config]: SessionId must be of type STRING!');
        return;
        }
        };

        exports.getDialogflowConfig = function () {
        return dialogflow_config;
        };


        And then, to programmatically manage contexts:



        /**
        * @author Pruthvi Kumar
        * @email pruthvikumar.123@gmail.com
        * @create date 2018-08-15 04:37:15
        * @modify date 2018-08-15 04:37:15
        * @desc Operate on Dialogflow Contexts
        */

        const dialogflow = require('dialogflow');
        const dialogflowConfig = require('../modules/dialogflow_config');
        const structjson = require('./dialogflow_structjson');
        const util = require('util');

        const contextsClient = new dialogflow.ContextsClient();

        exports.setContextHistory = function (sessionId, intent_name, context_payload, preservedContext=false) {
        /* maintain context stack per session */
        /* context_payload = {input_contexts: , output_contexts = }
        */
        const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;

        if (intent_name) {
        contextStack[sessionId].push({
        intent: intent_name,
        contexts: context_payload,
        preserveContext: preservedContext
        });
        } else {
        console.warn('[dialogflow_contexts]: Intent name is not provided OR Nothing in context_payload to add to history!');
        }

        };

        exports.getContextHistory = function () {
        const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
        return contextStack;
        }

        exports.preserveContext = function () {
        const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
        //Traverse contextStack, get the last contexts.
        let context_to_be_preserved = contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']][contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']].length - 1];
        //console.log(`context to be preserved is: ${util.inspect(context_to_be_preserved)}`);
        return context_to_be_preserved['contexts'].map((context, index) => {
        let context_id = exports.getContextId(context);
        return exports.updateContext(context_id, true)
        });
        }


        From here, you can reference this github resource to build your own contexts - https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js



        Happy creating digital souls!






        share|improve this answer













        Contexts are very closely associated with SessionID. Say for eg, you have a chatbot that gets spun up on two computers serving two different user's. Each user will have a respective session_id (If you're coding in NODE, when a new user fires the chatbot, you need to ensure he/she will get a unique session_id).



        Now, every unique session id will have unique contexts. From above example, let's say user 1 will initialize an intent that has input context named 'abc' with lifespan of 2 and user 2 will initialize another intent that has input context named 'xyz' with lifespan of 5, these respective contexts gets recorded against each of these user's individual session id's. You can programatically control (edit) contexts and its lifecycle. This is the biggest advantage of code facilitated Dialogflow as opposed to using GUI. Using services like Firebase, you can also preserve session id's and its associated contexts so, next time same user sign's in again, they can start from where they had last left.



        I can share a snippet from one of my previous projects where I was managing contexts programatically. Initialization script is as follows:



        /**
        * @author Pruthvi Kumar
        * @email pruthvikumar.123@gmail.com
        * @create date 2018-08-15 04:42:22
        * @modify date 2018-08-15 04:42:22
        * @desc Dialogflow config for chatbot.
        */

        const dialogflow_config = {
        projectId: 'xxx',
        sessionId: 'chatbot-session-id', //This is default assignment. This will hve to be overridden by sessionId as obtained from client in order to main context per sessionId.
        languageCode: 'en-US'
        };

        exports.configStoreSingleton = (function () {
        let instanceStacks;
        let instanceSessionId;

        let contextStack = {};
        let intentsStack = {};
        let successfulIntentResponseStack = {};

        function init() {
        contextStack[dialogflow_config['sessionId']] = ;
        intentsStack[dialogflow_config['sessionId']] = ;
        successfulIntentResponseStack[dialogflow_config['sessionId']] = ;

        return {
        contextStack: contextStack,
        intentsStack: intentsStack,
        successfulIntentResponseStack: successfulIntentResponseStack
        };
        }

        return {
        init: function () {
        if (!instanceStacks || (instanceSessionId !== dialogflow_config['sessionId'] && (!intentsStack[dialogflow_config['sessionId']]))) {
        console.log('[dialogflow_config]: Singleton is not instantiated previously or New userSession is triggered! Fresh instance stack will be provisioned');
        instanceStacks = init();
        instanceSessionId = dialogflow_config['sessionId'];
        }
        return instanceStacks;
        }
        };
        })();

        exports.updateSessionIdOfDialogflowConfig = function (sessionId) {
        if (typeof (sessionId) === 'string') {
        dialogflow_config['sessionId'] = sessionId;
        return true;
        } else {
        console.warn('[dialogflow_config]: SessionId must be of type STRING!');
        return;
        }
        };

        exports.getDialogflowConfig = function () {
        return dialogflow_config;
        };


        And then, to programmatically manage contexts:



        /**
        * @author Pruthvi Kumar
        * @email pruthvikumar.123@gmail.com
        * @create date 2018-08-15 04:37:15
        * @modify date 2018-08-15 04:37:15
        * @desc Operate on Dialogflow Contexts
        */

        const dialogflow = require('dialogflow');
        const dialogflowConfig = require('../modules/dialogflow_config');
        const structjson = require('./dialogflow_structjson');
        const util = require('util');

        const contextsClient = new dialogflow.ContextsClient();

        exports.setContextHistory = function (sessionId, intent_name, context_payload, preservedContext=false) {
        /* maintain context stack per session */
        /* context_payload = {input_contexts: , output_contexts = }
        */
        const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;

        if (intent_name) {
        contextStack[sessionId].push({
        intent: intent_name,
        contexts: context_payload,
        preserveContext: preservedContext
        });
        } else {
        console.warn('[dialogflow_contexts]: Intent name is not provided OR Nothing in context_payload to add to history!');
        }

        };

        exports.getContextHistory = function () {
        const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
        return contextStack;
        }

        exports.preserveContext = function () {
        const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
        //Traverse contextStack, get the last contexts.
        let context_to_be_preserved = contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']][contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']].length - 1];
        //console.log(`context to be preserved is: ${util.inspect(context_to_be_preserved)}`);
        return context_to_be_preserved['contexts'].map((context, index) => {
        let context_id = exports.getContextId(context);
        return exports.updateContext(context_id, true)
        });
        }


        From here, you can reference this github resource to build your own contexts - https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js



        Happy creating digital souls!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 6:36









        Pruthvi KumarPruthvi Kumar

        59729




        59729






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393153%2fhow-to-create-outputcontext-via-v2-client-library-for-node-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Can I use Tabulator js library in my java Spring + Thymeleaf project?