0

我正在使用sessionClient.detectIntent()将文本发送到对话流并且它工作正常,现在我也想用文本发送上下文。我怎样才能做到这一点?

4

2 回答 2

2

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

exports.createContext = async function(contextId, parameters, sessionPath, sessionId, lifespan = 333) {
    let contextPath;
    try {
        contextPath = contextClient.contextPath(projectId, sessionId, contextId);

    } catch (e) {
        console.error("Error => ");
        console.error(e)
    }
    const request = {
        parent: sessionPath,
        context: {
            name: contextPath,
            parameters: struct.encode(parameters),
            lifespanCount: lifespan
        }
    };
    contextClient.createContext(request)
};

当我必须在调用 detectIntent 方法之前创建上下文时,只需调用此方法即可:

bot.createContext('CONTEXT_NAME_GOES_HERE', '{PARAMETER: VALUE}', sessionPath, session_id, lifespan = 1);
于 2020-11-01T06:20:20.117 回答
1

您可以通过将添加queryParams. 请注意,这种通过 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}]
于 2020-11-04T01:35:40.773 回答