Search code examples
firebaseapi-ai

append contextOut array to firebase webhook response with api.ai


I'm trying to add a contextOut array to the response given by my firebase webhook for api.ai as documented here.

My simplified firebase code is as follows:

exports.myEndPoint = functions.https.onRequest((req, res) => {

  const assistant = new Assistant({ request: req, response: res });

  function firstHandler(assistant) {
    const i = Math.floor(Math.random() * 200);

    // I want to append contextOut to the response for api.ai here 

    assistant.ask(message generated using i);
  }

  function secondHandler(assistant) {

    // I want to retrieve i from the request from api.ai here

    assistant.tell(a different message generated using i from earlier);
  }

  const actionMap = new Map();
  actionMap.set('first', firstHandler);
  actionMap.set('second', secondHandler);
  assistant.handleRequest(actionMap);

});

I have tried res.contextOut, res.data before creating an instance of assistant as well as assistant.contextOut and assistant.data after the instance is made. I can't see the variable in the json response in the api.ai console.

Can anyone tell me what I'm missing? Thanks!


Solution

  • I managed a work around for my question.

    Here is the simplified code:

    exports.myEndPoint = functions.https.onRequest((req, res) => {
    
      const assistant = new Assistant({ request: req, response: res });
    
      function firstHandler(assistant) {
        const i = Math.floor(Math.random() * 200);
        const obj = {
          "index": i,
        }
    
        // I create my own context here.         
    
        assistant.setContext('index', 2, obj);
    
        assistant.ask(message generated using i);
      }
    
      function secondHandler(assistant) {
    
        // Use the created context here.
    
        const context = assistant.getContext('index');
        const i = context.parameters.index;
    
        assistant.tell(a different message generated using i from earlier);
      }
    
      const actionMap = new Map();
      actionMap.set('first', firstHandler);
      actionMap.set('second', secondHandler);
      assistant.handleRequest(actionMap);
    
    });
    

    Solution uses documentation found here.

    I'm fairly sure that I could also use the existing context I have with api.ai to do this but I haven't tested it yet.