gpt4 book ai didi

dialogflow-es - 从意图异步触发实现 webhook?

转载 作者:行者123 更新时间:2023-12-05 05:12:29 25 4
gpt4 key购买 nike

我有一些意图需要触发 fulfillment webhook 并且不关心响应。 webhook 响应的时间比超时时间长,因此我希望仅用“感谢聊天”进行响应,然后在实际触发 webhook 时关闭对话。

感觉很简单,但我错过了一些东西。我也是 dialogflow 的新手。

我可以用任何语言做到这一点,但这里有一个 Javascript 的例子:

fdk.handle(function (input) {
// Some code here that takes 20 seconds.

return {'fulfillmentText': 'i can respond but I will never make it here.'}
});

编辑 1 - 尝试异步

当我使用异步函数时,POST 请求永远不会发生。所以在下面的代码中:

fdk.handle(function (input) {
callFlow(input);
return { 'fulfillmentText': 'here is the response from the webhook!!' }
});

async function callFlow(input) {
console.log("input is --> " + input)

var url = "some_url"

console.log("Requesting " + url)

request(url, { json: true, headers: {'Access-Control-Allow-Origin' : '*'} }, (err, res, body) => {
if (err) { return console.log(err); }
console.log("body is...")
console.log(body)
});
}

我在日志中看到了两个 console.log 输出,但请求中没有任何内容。而且请求似乎也没有发生,因为我没有在我的端点看到它。

解决方案

感谢 Prisoner 的提示。似乎我需要通过 callFlow() 和 handle() 函数返回履行 JSON。现在 Google Home 不会超时,并且会生成 HTTP 调用和响应。

const fdk = require('@fnproject/fdk');
const request = require('request');

fdk.handle(function (input) {
return callFlow(input);
});

async function callFlow(input) {
var searchPhrase = input || "cats"
var url = "some url"

return new Promise((resolve, reject) => {
request.post(url, {
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: searchPhrase
},
function (err, resp, body) {
if (err) { return console.log(err) }
r = { 'fulfillmentText': `OK I've triggered the flow function with search term ${searchPhrase}` }
resolve(r)
}
);
});

}

最佳答案

您不能异步触发履行。在对话模型中,预计履行将执行一些决定响应的逻辑。

但是,您可以在返回结果之前未完成的实现中执行异步操作。

如果您使用的是足够现代的节点版本(版本 8 及更高版本),您可以通过将函数声明为 async 函数来实现,但调用它带有 await 关键字。 (如果您使用 await 调用它,它会在继续之前等待异步操作完成。)

因此,根据您的示例,这样的事情应该可行:

async function doSomethingLong(){
// This takes 20 seconds
}

fdk.handle(function (input) {
doSomethingLong();

return {'fulfillmentText': 'This might respond before doSomethingLong finishes.'}
});

根据您的代码示例更新 1

您报告说对 request 的调用似乎根本没有完成,这似乎很奇怪,但有一些奇怪的事情可能会导致它。

首先,request 本身不是异步函数。它使用回调模型,async 函数不会自动等待调用这些回调。所以你的 callFlow() 函数调用 console.log() 几次,调用 request() 并在回调被回调之前返回.

您可能应该将 request 替换为类似 request-promise-native 的内容打包并等待您从电话中获得的 promise 。这使得 callFlow() 真正异步(并且您可以在它完成调用时进行记录)。

其次,我要指出您显示的代码没有执行 POST 操作。它默认执行 GET。如果您或您正在调用的 API 期待 POST,那可能是错误的来源。但是,我希望填充 err 参数,并且您的代码看起来确实会检查并记录此内容。

整个设置中的一个未知数,对我来说,是我不知道 fdk 是如何处理异步函数的,而且我粗略地阅读了文档也没有教我。我已经使用其他框架完成了此操作,这不是问题,但我不知道 fdk 处理程序是否超时或执行其他操作以在发送回复后终止调用。

关于dialogflow-es - 从意图异步触发实现 webhook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com