首页 > 解决方案 > agent.set.context() 不工作 Dialogflow 实现

问题描述

我们在 Dialogflow 中同时管理多个用户交互时遇到了问题。我们如何在使用自定义事件时管理用户唯一会话,该事件将处理我们的 3rd 方 API,然后向特定用户返回响应。管理用户唯一会话我们尝试使用 Dailogflow Set/Get Context 方法,在用户发出第一个请求时从第一个意图设置具有唯一 ID 的上下文(使用此 ID 将存储对 Redis 服务器的 API 响应)然后将遍历该唯一 ID通过自定义事件。将从上下文中获取唯一 ID,并从我们存储在第一意图中的 Redis 服务器获取数据。我们使用 agent.set.context() 来设置唯一 ID,但此方法不适用于“dialogflow-fulfillment”版本 ^0.5.0,为了完成这项工作,我们已将版本更新为“^0.6.1”。

所需输出:设置了唯一 id 的上下文,将得到正确的响应。当前输出:UnhandledPromiseRejectionWarning:错误:没有为平台定义响应:null

    async function searchFromAPI(agent){

        axios.post('https://testApi.com', searchString.data, {headers: headers})
        .then((resp) => {
                response.data = resp;
                redisClient.set(sessionId, JSON.stringify(response));
            }
        }).catch(error => {
            response.error = true;
            response.message = error.response.statusText;
            redisClient.set(sessionId, JSON.stringify(response));
        });
        await customsleep(2000);
        const sessionId = uuid.v4();
        const contextData = {'name':'userSession','lifespan': 5,'parameters':{'sessionId':sessionId}};
        agent.context.set(contextData);
        console.log(contextData);
        agent.add('We are processing your request, Could you please wait?');
        agent.add(new Suggestion("Yes"));   
        agent.add(new Suggestion("No"));    
    }

    // wait for 4.5sec and call custom event
    async function followOne(agent){    
        await customsleep(4500);
        agent.setFollowupEvent('followUpTwo');
    }
    // wait for 4.7sec then red API response from redis server and return 
    async function followUpTwo(agent){  
        await customsleep(4000);
        sess = session;
        //get context
        const response = agent.context.get('userSession');
        // get the sessionId, Get the data from redis server
        agent.add(response);

    }
    async function PleaseWait(agent){
        await customsleep(3500);
        agent.setFollowupEvent('followUpOne');
    }

标签: dialogflow-esdialogflow-es-fulfillment

解决方案


我找到了通过 context.set(ctx) 重新分配新上下文对象的唯一解决方法。然后它起作用了。

//update context to show full menu
  let context = agent.context.get('user_data');
  if (!context) throw "User_data context ius nod defined in PreferrenceAdd"

  let context2 = new Object();
  context2 = {'name': 'user_data', 'lifespan': 40, 
  'parameters': context.parameters}; 
  console.log("ctx: = " + JSON.stringify(context2));
  context2.parameters.new = false;
  context2.parameters.refresh = true;
  agent.context.set(context2);

推荐阅读