【问题标题】:set input or output context dialogflow nodejs v2设置输入或输出上下文对话流 nodejs v2
【发布时间】:2019-06-20 03:56:19
【问题描述】:

我正在使用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);

【问题讨论】:

    标签: node.js dialogflow-es


    【解决方案1】:

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

    【讨论】:

    • 您已将thebongocontext 硬连线到那里的上下文中。
    【解决方案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

    【讨论】:

    • 记得在 request.queryInput.text 中添加 'languageCode' 参数
    • 亲爱的@Jonathan 和 Marcos,我遇到了 languageCode 错误,但你能更好地向我解释一下我必须把这个参数放在哪里吗?谢谢。
    • 对话流 UI 中的上下文看起来只是一个文本字符串,这就是我们在这里谈论的内容吗?谷歌肯定喜欢把事情复杂化,一堆 3rd 方库来格式化字符串......
    • 我得到contextsClient.sessionPath is not a function ...
    【解决方案3】:

    首先,关于包的一些说明

    • google-assistant 包是一个人对 Assistant SDK 的实现/包装,允许您将 Assistant 嵌入到任何程序或设备中。这就像构建您自己的 Google Home。 (这个包似乎不是来自谷歌,但确实包装了官方的 protobuf API,所以你不必自己编译。)
    • actions-on-google 包用于制作可与 Action SDK 或 Dialogflow 一起使用的 webhook。这是为了制作一个与助手一起工作并发回响应的程序。 (即 - 用于编写响应“Hey Google,与我的应用程序对话”的代码)
    • dialogflow 包允许您使用 Dialogflow 代理,包括配置它们并向它们发送查询以查看哪些意图与查询匹配。这是“google-assistant”包的一个非常粗略的等价物,但功能更多。
    • dialogflow-fulfillment 包用于制作一个 Webhook,为 Dialogflow 支持的任何平台提供逻辑和响应。它相当于 actions-on-google 包。

    您提供的代码片段看起来像是来自“actions-on-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() 之类的示例。这些方法已被弃用,取而代之的是上述方法。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多