You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dialogflow现有会话中触发意图并推送响应到对应会话

问题根因

你当前的代码仅调用了Dialogflow的detectIntent接口完成意图检测,该接口只会将识别结果返回给接口调用方(也就是你的Cloud Function),不会主动将响应推送给对应会话的Web客户端。你传入的sessionId已经正确关联了会话上下文,只是缺少了将响应推送到前端会话窗口的步骤。

解决方案

如果你使用的是Dialogflow官方的Dialogflow Messenger Web集成,可通过调用Dialogflow的会话消息推送接口,将获取到的响应主动推送到指定会话的前端窗口,修改步骤如下:

  1. 首先为你调用接口的服务账号添加权限:Dialogflow Conversation Manager 或 Dialogflow API Client,确保拥有推送消息的权限。
  2. 调整代码逻辑,在获取到queryResult.fulfillmentText后,新增推送消息到会话的逻辑,参考修改后的代码如下:
const { SessionsClient, ConversationsClient } = require('@google-cloud/dialogflow');

const triggerCallback = async (sessionId, message) => {
  const sessionClient = new SessionsClient({projectId: projectId, keyFilename: keypath});
  const conversationsClient = new ConversationsClient({projectId: projectId, keyFilename: keypath});
  
  // 注意如果你的Dialogflow Agent部署在非global区域,需要替换下面的location参数
  const location = 'global';
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);
  const request = {
    session: sessionPath,
    queryInput: {
      event: {
        name: eventName,  
        languageCode: LANGUAGE_CODE
      },
    },
  };
  const [response] = await sessionClient.detectIntent(request);
  const result = response.queryResult;
  if(result.fulfillmentText) {
    // 推送消息到对应会话的前端窗口
    const conversationPath = conversationsClient.conversationPath(projectId, location, sessionId);
    await conversationsClient.createMessage({
      parent: conversationPath,
      message: {
        text: {
          text: [result.fulfillmentText]
        },
        languageCode: LANGUAGE_CODE,
        participant: 'PARTICIPANT_TYPE_AGENT'
      }
    });
    return result.fulfillmentText;
  } else {
    return 'no intent found';
  }
};

exports.Callback = async (req, res) => {
  try {
    let sessionId = req.query.sessionId || req.body.sessionId || '';
    let message = req.query.message || req.body.message || 'Hello World!';
    const response = await triggerCallback(sessionId, message);
    res.status(200).send(response);
  } catch(error) {
    console.error('Trigger bot error! ', JSON.stringify(error));
    res.status(400).send(error.message);
  }
};
  1. 验证你传入的sessionId和前端Dialogflow Messenger实际使用的会话ID完全一致,可打开浏览器开发者工具,查看Dialogflow Messenger的网络请求中携带的会话ID,确保传参无错。
额外说明

如果你使用的是自行开发的Web前端而非官方Dialogflow Messenger集成,也可以选择在前端调用你的Cloud Function接口,拿到返回的响应后,直接插入到自定义的会话窗口UI中,无需调用Dialogflow的推送接口。

内容的提问来源于stack exchange,提问作者Bill Software Engineer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:27:03