设置输入或输出上下文对话流nodejs v2

时间:2019-01-26 16:03:55

标签: node.js dialogflow

我正在使用dialogflow NPM模块,并且想发送input/output context,但是我不确定该怎么做。 我知道我可以在google-assistant NPM中使用 我可以使用以下方法将contexts设置为parameter

 const parameters = { // Custom parameters to pass with context
     welcome: true,
 };
 conv.contexts.set('welcome-context', 5, parameters);

3 个答案:

答案 0 :(得分:2)

为了使用Dialogflow NPM模块发送上下文,您必须首先使用dialogflow.ContextsClient创建上下文,然后在查询中发送它。

要将参数转换为Dialogflow所需的格式,您将需要使用以下模块:pb-util

const dialogflow = require('dialogflow');
const { struct } = require('pb-util');  

const projectId = 'projectId';
const contextsClient = new dialogflow.ContextsClient();
const sessionClient = new dialogflow.SessionsClient();

async function createContext(sessionId, contextId, parameters, lifespanCount = 5) {

    const sessionPath = contextsClient.sessionPath(projectId, sessionId);
    const contextPath = contextsClient.contextPath(
        projectId,
        sessionId,
        contextId
    );

    const request = {
        parent: sessionPath,
        context: {
            name: contextPath,
            parameters: struct.encode(parameters)
            lifespanCount
        }
    };

    const [context] = await contextsClient.createContext(request);

    return context;
}


function sendQuery(sessionId, query, context) {

    const session = sessionClient.sessionPath(projectId, sessionId);

    const request = {
        session,
        queryInput: {
            text: {
                text: query
            }
        },
        queryParams: {
            contexts: [context] // You can pass multiple contexts if you wish
        }
    };

    return sessionClient.detectIntent(request);
}

(async() => {
    const parameters = { // Custom parameters to pass with context
       welcome: true
    };

    const sessionId = 'my-session';
    const context = await createContext(sessionId, 'welcome-context', parameters);

    const response = await sendQuery(sessionId, 'Hi', context);

    console.log(response);

})();

请记住,您发送输入上下文。输出上下文是在意图中生成的。

如果您在验证客户端SessionClientContextClient时遇到问题,可以检查以下其他问题:Dialogflow easy way for authorization

答案 1 :(得分:2)

首先,对包装进行一些澄清

  • google-assistant软件包是一个人的Assistant SDK的实现/包装程序,可让您将Assistant嵌入任何程序或设备中。这就像建立自己的Google Home。 (该软件包不是来自Google,而是包装了正式的protobuf API,因此您不必自己对其进行编译。)
  • actions-on-google软件包用于制作可与Action SDK或Dialogflow配合使用的webhook。这是为了制作一个与助手一起使用并发送回响应的程序。 (即-用于编写响应“嘿Google,与我的应用对话”的代码)
  • dialogflow软件包使您可以使用Dialogflow代理,包括配置它们并将查询发送给他们,以查看哪些Intent与查询匹配。这与“ google-assistant”程序包非常相似,但功能更多。
  • dialogflow-fulfillment软件包用于制作一个Webhook,该Webhook为Dialogflow支持的任何平台提供逻辑和响应。这等效于Google动作包。

您提供的代码片段看起来像是来自“ Google行动”程序包中的代码,并且将输出上下文设置为答复的一部分。

使用“ dialogflow-fulfillment”软件包的代码等同于

 const parameters = { // Custom parameters to pass with context
     welcome: true,
 };
 agent.context.set('welcome-context', 5, parameters);

请注意,它是“上下文”,在此程序包中没有“ s”。

类似地,要获取输入上下文,您将使用

agent.context.get('name-of-context;);

(您可能会看到一些使用诸如agent.setContext()之类的示例。为了支持上述目的,不推荐使用这些方法。)

答案 2 :(得分:0)

基于Marco的出色回答-这是一个简单的版本:

package.json

{
  "name": "credtest",
  "version": "1.0.0",
  "dependencies": {
    "dialogflow": "^1.2.0",
    "pb-util": "^0.1.3"
  }
}

index.js

const {ContextsClient} = require('dialogflow')
const { struct } = require('pb-util');  

// REPLACE THESE:

/*
1. Service Account Credential file (KEEP SAFE)
// where/how to get this key: https://cloud.google.com/iam/docs/creating-managing-service-account-keys
// For different auth options, see Marco Casagrande's explainer: https://stackoverflow.com/questions/50545943/dialogflow-easy-way-for-authorization/50546430#50546430)
// Note: JSON hard-coded below for copy/paste, just import/require in when using for real
*/

const credential = {
    "type": "__REPLACE__ME___",
    "project_id": "__REPLACE__ME___",
    "private_key_id": "__REPLACE__ME___",
    "private_key": "__REPLACE__ME___",
    "client_email": "__REPLACE__ME___",
    "client_id": "__REPLACE__ME___",
    "auth_uri": "__REPLACE__ME___",
    "token_uri": "__REPLACE__ME___",
    "auth_provider_x509_cert_url": "__REPLACE__ME___",
    "client_x509_cert_url": "__REPLACE__ME___"
  }
  
/*
2. Project ID, Google cloud project id
Tip: notice the service-account naturally already has your product id
*/
const project_id = '__REPLACE__ME___' // This is your google cloud project


const client = new ContextsClient({
    credentials: credential
});


createContext('123456789', {name: 'bongo_context', lifespanCount: 3, parameters: {a:1, b:2, c:3 }} )


function createContext(sessionID, {name, lifespanCount, parameters = {} } = {} ) {
    const formattedParent = client.sessionPath(project_id, sessionID);
    const formattedContextName = `projects/${project_id}/agent/sessions/${sessionID}/contexts/${name}`
    const context = {
        "name": formattedContextName,
        "lifespanCount": 2,
        "parameters": struct.encode(parameters)
    }

    const request = {
        parent: formattedParent,
        context: context,
    }

    client.createContext(request)
          .then(responses => {
            const response = responses[0];
            console.log('context now active:', response)
          })
          .catch(err => {
            console.error(err);
          });

}