如何通过V2客户端库为节点js创建OutPutContext

时间:2018-11-20 12:37:14

标签: dialogflow

我正在使用v2客户端库的node.js在代理中创建实体和意图。为此,我正在经历git上的sample。它说了一些与会话ID和上下文ID有关的内容。任何人都可以向我解释什么是sessionId和contextId。并提供我可以详细阅读这些内容的链接。

我无法通过遵循这些示例来创建上下文。在创建意图的同时如何创建上下文。

2 个答案:

答案 0 :(得分:1)

以下是创建上下文的代码。您不能在单个API调用中创建上下文和意图,首先需要创建上下文,然后创建使用该上下文的意图。对创建上下文API调用的响应将返回您可以在意图中使用的上下文ID。

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

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

答案 1 :(得分:0)

上下文与SessionID紧密相关。例如,您有一个聊天机器人,它在为两个不同用户服务的两台计算机上旋转。每个用户都有各自的session_id(如果您使用NODE进行编码,则当新用户触发聊天机器人时,您需要确保他/她将获得唯一的session_id)。

现在,每个唯一的会话ID都将具有唯一的上下文。在上面的示例中,假设用户1将初始化一个具有名为'abc'的输入上下文且其生命周期为2的意图,而用户2将初始化另一个具有名为'xyz'的输入上下文且其寿命为5的意图,将记录这些各自的上下文。这些用户各自的会话ID。您可以以编程方式控制(编辑)上下文及其生命周期。与使用GUI相比,这是使用代码实现Dialogflow的最大优势。使用Firebase之类的服务,您还可以保留会话ID及其关联的上下文,因此,下次再次登录同一用户登录时,它们可以从上次离开的地方开始。

我可以从以前的一个项目中共享一个片段,该片段是我以编程方式管理上下文的。初始化脚本如下:

/**
 * @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;
};

然后,以编程方式管理上下文:

/**
 * @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)
  });
}

从这里,您可以引用此github资源来构建自己的上下文-https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js

快乐创造数字灵魂!