Dialogflow 检测意图实现

Dialogflow Detect Intent Fulfillment

您好,我已经创建了一个 dialogflow nodejs 后端,它使用 nodejs 的客户端库检测意图。

 const sessionPath = this.sessionClient.sessionPath(this.configService.get('dialogFlowProjectId'), sessionId);

        const request = {
            session: sessionPath,
            queryInput: {
                text: {
                    text: query,
                    languageCode: "en-US"
                }
            }
        };
        // Send request and log result
        Logger.log(request);
        const responses = await this.sessionClient.detectIntent(request);

这很好用,但我也想为某些意图触发实现。

我已经设置了一个 webhook url - 当您在 dialogflow 控制台中使用聊天时,它工作正常。但是当我使用我创建的方法将请求发送到 dialogflow 时,webhook 不会被调用并转到回退意图。我通过 dialogflow 控制台聊天和我自己的 API.

调用相同的意图

如何在使用客户端库时触发 webhook 调用 API?

首先,请记住您不会 "call an Intent",无论是通过测试控制台还是通过 API。您可以做的是发送应与 Intent 匹配的查询文本。

如果您设置了 Intent 以便它应该调用 Fulfillment webhook,那么无论来源如何,只要 Intent 本身被触发,这都应该发生。

Fallback Intent 被触发反而表明查询文本的某些内容与您认为应该匹配的 Intent 不匹配。我会检查以确保您在 query 中发送的文本应该与相关 Intent 的训练短语相匹配,您没有输入上下文,并且您的代理设置为 "en-US" 语言代码。

为了通过 webhook 路由多个意图,您需要一个 handler.js 文件,其中包含一个快速路由器...

const def = require('./intents/default')
const compression = require('compression')

const serverless = require('serverless-http')
const bodyParser = require('body-parser')

const { WebhookClient } = require('dialogflow-fulfillment')

const express = require('express')
const app = express()

// register middleware
app.use(bodyParser.json({ strict: false }))
app.use(function (err, req, res, next) {
  res.status(500)
  res.send(err)
})
app.use(compression())
app.post('/', async function (req, res) {
  // Instantiate agent
  const agent = new WebhookClient({ request: req, response: res })
  const intentMap = new Map()

  intentMap.set('Default Welcome Intent', def.defaultWelcome)

  await agent.handleRequest(intentMap)
})

module.exports.server = serverless(app)

如您所见,这个 handler.js 使用的是 serverless-http 和 express。

您的 intent.js 函数可能看起来像这样...

module.exports.defaultWelcome = async function DefaultWelcome (agent) {

  const responses = [
    'Hi! How are you doing?',
    'Hello! How can I help you?',
    'Good day! What can I do for you today?',
    'Hello, welcoming to the Dining Bot. Would you like to know what\'s being served? Example: \'What\'s for lunch at cronkhite?\'',
    'Greetings from Dining Bot, what can I do for you?(Hint, you can ask things like: \'What\'s for breakfast at Annenberg etc..\' or \'What time is breakfast at Anennberg?\')',
    'greetings',
    'hey',
    'long time no see',
    'hello',
    "lovely day isn't it"
  ]
  const index = Math.floor((Math.random() * responses.length) + 1)
  console.log(responses[index].text)
  agent.add(responses[index].text)
}

这为您提供了通过 webhook 路由多个请求的基本框架。希望这有帮助。