如何从Node.js对话框包中设置对话框流上下文

问题描述

我正在使用sessionClient.detectIntent()发送文本到dialogflow,并且工作正常,现在我也想随文本发送 context 。我该怎么办?

解决方法

我通常以以下方式创建上下文:

PreparedStatement

在我必须先创建上下文之前,先调用此方法,然后再调用detectIntent方法:

Statement
,

您可以通过在contexts下的上下文数组字段中添加detectIntentqueryParams以及查询文本。请注意,这种通过detectIntent发送上下文的方法将创建(如果未创建)并在执行查询之前激活上下文。

您可以参考下面的代码段:

const dialogflow = require('@google-cloud/dialogflow');

/**
 * Send a query and a context to the Dialogflow agent,and return the query result.
 * @param {string} projectId The project to be used
 */
async function detectIntent(projectId,sessionId,text) {

  // Create a new session
  const sessionClient = new dialogflow.SessionsClient();
  const sessionPath = sessionClient.projectAgentSessionPath(projectId,sessionId);

  // The text query request.
  const request = {
    session: sessionPath,queryParams:{
        //List of context to be sent and activated before the query is executed
        contexts:[
            {
                // The context to be sent and activated or overrated in the session 
                name: `projects/${projectId}/agent/sessions/${sessionId}/contexts/CONTEXT_NAME`,// The lifespan of the context
                lifespanCount: 8
              }
        ]
    },queryInput: {
      text: {
        // The query to send to the dialogflow agent
        text: text,// The language used by the client (en-US)
        languageCode: 'en-US',},};

  // Send request and log result
  const responses = await sessionClient.detectIntent(request);
  console.log('Detected intent');
  const result = responses[0].queryResult;
  console.log(`  Query: ${result.queryText}`);
  console.log(`  Response: ${result.fulfillmentText}`);
  console.log(`  Output Contexts: ${JSON.stringify(result.outputContexts)}`)
}

detectIntent("PROJECT_ID","SESSION_ID","TEXT_QUERY");

输出:

Detected intent
  Query: Hi
  Response: Hello! How can I help you?
  Output Contexts: [{"name":"projects/PROJECT_ID/agent/sessions/SESSION_ID/contexts/CONTEXT_NAME","lifespanCount":7,"parameters":null}]