使用 api.ai 将 contextOut 数组附加到 firebase webhook 响应

append contextOut array to firebase webhook response with api.ai

我正在尝试将 contextOut 数组添加到我的 firebase webhook 为 api.ai as documented here.

给出的响应中

我简化的firebase代码如下:

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);

});

我在创建助手实例之前尝试了res.contextOutres.data,在创建实例之后还尝试了assistant.contextOutassistant.data。我在 api.ai 控制台的 json 响应中看不到变量。

谁能告诉我我错过了什么?谢谢!

我设法解决了我的问题。

这里是简化的代码:

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);

});

解决方案使用文档 found here

我很确定我也可以使用现有的上下文 api.ai 来做到这一点,但我还没有测试过。