如何在文本型Dialogflow CX V3聊天机器人中使用Return Partial Response
文本型Dialogflow CX V3使用Return Partial Response的方案
核心方案:用streamingDetectIntent处理文本请求
别被名字限制,streamingDetectIntent并非只支持音频,完全可以处理文本会话。它能在流程执行过程中实时返回Partial Response和最终结果,刚好适配你需要先推送前置消息、再等待webhook完成的场景。
具体实现步骤
构造流式请求
- 初始化流式会话客户端,第一个请求包需包含会话信息、文本输入,同时设置
query_params.return_partial_responses = true,开启Partial Response支持。 - 文本输入只需一次性发送初始请求包即可,无需后续追加内容。
- 初始化流式会话客户端,第一个请求包需包含会话信息、文本输入,同时设置
处理流式返回结果
- 客户端会收到多轮响应:先返回
response_type: PARTIAL的结果,对应你在控制台配置的前置消息,可直接推送给用户; - 待webhook执行完成后,会收到
response_type: FINAL的最终结果,包含webhook返回的内容。
- 客户端会收到多轮响应:先返回
代码示例(Node.js)
const { SessionsClient } = require('@google-cloud/dialogflow-cx'); async function sendStreamingTextQuery() { const client = new SessionsClient({ apiEndpoint: 'REGION-dialogflow.googleapis.com' }); const sessionPath = client.projectLocationAgentSessionPath( 'PROJECT_ID', 'LOCATION', 'AGENT_ID', 'SESSION_ID' ); const request = { session: sessionPath, queryInput: { text: { text: '用户输入的文本内容' }, languageCode: 'zh-CN', }, queryParams: { returnPartialResponses: true, // 开启Partial Response特性 }, }; const stream = client.streamingDetectIntent(); stream.write(request); for await (const response of stream) { if (response.responseType === 'PARTIAL') { // 推送Partial Response给用户 console.log('前置消息:', response.queryResult.responseMessages); } else if (response.responseType === 'FINAL') { // 处理webhook返回的最终结果 console.log('最终回复:', response.queryResult.responseMessages); } } } sendStreamingTextQuery();
关键注意事项
- 会话ID一致性:整个会话流程中
SESSION_ID需保持不变,否则会被判定为新会话,无法关联Partial和Final结果。 - 权限配置:确保客户端拥有
dialogflow.sessions.detectIntent的权限,和普通detectIntent的权限要求一致。 - 控制台配置校验:确认已在代理路由中正确配置
Return Partial Response的前置消息,触发条件设置无误。
内容的提问来源于stack exchange,提问作者emrys57
相关产品推荐
相关产品推荐

