Issue with Dialogflow follow up intent

43 Views Asked by At

My index.js code is as follows:

'use strict';
 
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const axios = require('axios');
 
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
 
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
 
  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }
 
  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }
  
  function find(agent) {
    const item = agent.parameters.item;
    const location = agent.parameters.location;
    return new Promise((resolve, reject) => {
      axios.get(`https://sheetdb.io/api/v1/***********/search?item=*${item}*&sheet=${location}`).then(function(res) {
        const where = res.data[0];
        if (where) {
            agent.add(`Location: ${where.location}`);
        } else {
            agent.add('Not found');
        }
        resolve();
        })
        .catch(function (error) {
            console.error('Error fetching data from SheetDB:', error);
            agent.add('Sorry, there was an error while processing your request.');
      });
    });
  }
  
  function instruct(agent) {
    console.log(agent.context.get('FindIntent-followup'));
    const item = agent.context.get('FindIntent-followup').parameters.item;
    const location = agent.context.get('FindIntent-followup').parameters.location; 
    return new Promise((resolve, reject) => {
      axios.get(`https://sheetdb.io/api/v1/**********/search?item=*${item}*&sheet=${location}`).then(function(res) {
        const where = res.data[0];
        if (where.instructions!=="") {
            agent.add(`Instructions are found on ${where.instructions}`);
        } else {
            agent.add('No instructions found');
        }
        resolve();
        })
        .catch(function (error) {
            console.error('Error fetching data from SheetDB:', error);
            agent.add('Sorry, there was an error while processing your request.');
      });
    });
  }
  
  function locate(agent) {
    const area = agent.parameters.area;
    const location = agent.parameters.location;
    
    return new Promise((resolve, reject) => {
      axios.get(`https://sheetdb.io/api/v1/***********/search?location=*${area}*&sheet=${location}`).then(function(res) {
        console.log('SheetDB Response:', res.data);
        const things = res.data;
        if (things.length > 0) {
            let response = 'Items found: \n';
            things.forEach((thing) => {
                response += `\n- ${thing.item}`;
            });
            agent.add(response);
        } 
        else {
            agent.add('Not found');
        }
        resolve();
        })
        .catch(function (error) {
            console.error('Error fetching data from SheetDB:', error);
            agent.add('Sorry, there was an error while processing your request.');
      });
    });
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('FindIntent', find);
  intentMap.set('LocateIntent', locate);
  intentMap.set('InstructIntent', instruct); 
  agent.handleRequest(intentMap);
});

I use webhooks fulfillment for my responses, and my FindIntent and LocateIntent work perfectly fine. However, I added InstructIntent as a followup intent to FindIntent, and it just doesn't work. I get the following errors in my log when I trigger InstructIntent:

ERROR 2023-07-21T09:12:38.125404Z Dialogflow fulfillment error : Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500.
  {
    "textPayload": "Dialogflow fulfillment error : Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500.",
    "insertId": "1sxpjtxf8hdsjz",
    "resource": {
      "type": "global",
      "labels": {
        "project_id": "find-tftv"
      }
    },
    "timestamp": "2023-07-21T09:12:38.125404Z",
    "severity": "ERROR",
    "labels": {
      "protocol": "V2",
      "request_id": "*******",
      "source": "DIALOGFLOW_CONSOLE",
      "type": "dialogflow_fulfillment_error_response"
    },
    "logName": "projects/find-tftv/logs/dialogflow_agent",
    "trace": "*********",
    "receiveTimestamp": "2023-07-21T09:12:38.132775956Z"
  }
INFO 2023-07-21T09:12:38.128867Z Dialogflow Response : id: "*********" lang: "en" session_id: "********" timestamp: "2023-07-21T09:12:37.879152Z" result { source: "agent" resolved_query: "What are the instructions" action: "FindIntent.FindIntent-custom" score: 1.0 parameters { } contexts { name: "findintent-followup" lifespan: 1 parameters { fields { key: "item" value { string_value: "projector" } } fields { key: "item.original" value { string_value: "projector" } } fields { key: "location" value { string_value: "ryan" } } fields { key: "location.original" value { string_value: "ryan" } } } } metadata { intent_id: "*****" webhook_response_time: 230 intent_name: "InstructIntent" original_webhook_payload: "{\n \"responseId\": \"*********\",\n \"queryResult\": {\n \"queryText\": \"What are the instructions\",\n \"action\": \"FindIntent.FindIntent-custom\",\n \"parameters\": {\n },\n \"allRequiredParamsPresent\": true,\n \"fulfillmentMessages\": [{\n \"text\": {\n \"text\": [\"\"]\n }\n }],\n \"outputContexts\": [{\n \"name\": \"projects/find-tftv/agent/sessions/339ff93a-32a6-30c4-9711-03698393a2a3/contexts/findintent-followup\",\n \"lifespanCount\": 1,\n \"parameters\": {\n \"item\": \"projector\",\n \"item.original\": \"projector\",\n \"location\": \"ryan\",\n \"location.original\": \"ryan\"\n }\n }, {\n \"name\": \"projects/find-tftv/agent/sessions/339ff93a-32a6-30c4-9711-03698393a2a3/contexts/__system_counters__\",\n \"parameters\": {\n \"no-input\": 0.0,\n \"no-match\": 0.0\n }\n }],\n \"intent\": {\n \"name\": \"projects/find-tftv/agent/intents/********",\n \"displayName\": \"InstructIntent\"\n },\n \"intentDetectionConfidence\": 1.0,\n \"languageCode\": \"en\"\n },\n \"originalDetectIntentRequest\": {\n \"source\": \"DIALOGFLOW_CONSOLE\",\n \"payload\": {\n }\n },\n \"session\": \"projects/find-tftv/agent/sessions/*******\"\n}" webhook_used: "true" webhook_for_slot_filling_used: "false" is_fallback_in…
  {
    "textPayload": "Dialogflow Response : id: \"********\"\nlang: \"en\"\nsession_id: \"*******\"\ntimestamp: \"2023-07-21T09:12:37.879152Z\"\nresult {\n  source: \"agent\"\n  resolved_query: \"What are the instructions\"\n  action: \"FindIntent.FindIntent-custom\"\n  score: 1.0\n  parameters {\n  }\n  contexts {\n    name: \"findintent-followup\"\n    lifespan: 1\n    parameters {\n      fields {\n        key: \"item\"\n        value {\n          string_value: \"projector\"\n        }\n      }\n      fields {\n        key: \"item.original\"\n        value {\n          string_value: \"projector\"\n        }\n      }\n      fields {\n        key: \"location\"\n        value {\n          string_value: \"ryan\"\n        }\n      }\n      fields {\n        key: \"location.original\"\n        value {\n          string_value: \"ryan\"\n        }\n      }\n    }\n  }\n  metadata {\n    intent_id: \"*********\"\n    webhook_response_time: 230\n    intent_name: \"InstructIntent\"\n    original_webhook_payload: \"{\\n  \\\"responseId\\\": \\\"********\\\",\\n  \\\"queryResult\\\": {\\n    \\\"queryText\\\": \\\"What are the instructions\\\",\\n    \\\"action\\\": \\\"FindIntent.FindIntent-custom\\\",\\n    \\\"parameters\\\": {\\n    },\\n    \\\"allRequiredParamsPresent\\\": true,\\n    \\\"fulfillmentMessages\\\": [{\\n      \\\"text\\\": {\\n        \\\"text\\\": [\\\"\\\"]\\n      }\\n    }],\\n    \\\"outputContexts\\\": [{\\n      \\\"name\\\": \\\"projects/find-tftv/agent/sessions/******/contexts/findintent-followup\\\",\\n      \\\"lifespanCount\\\": 1,\\n      \\\"parameters\\\": {\\n        \\\"item\\\": \\\"projector\\\",\\n        \\\"item.original\\\": \\\"projector\\\",\\n        \\\"location\\\": \\\"ryan\\\",\\n        \\\"location.original\\\": \\\"ryan\\\"\\n      }\\n    }, {\\n      \\\"name\\\": \\\"projects/find-tftv/agent/sessions/*******/contexts/__system_counters__\\\",\\n      \\\"parameters\\\": {\\n        \\\"no-input\\\": 0.0,\\n        \\\"no-match\\\": 0.0\\n      }\\n    }],\\n    \\\"intent\\\": {\\n      \\\"name\\\": \\\"projects/find-tftv/agent/intents/*****\\\",\\n      \\\"displayName\\\": \\\"InstructIntent\\\"\\n    },\\n    \\\"intentDetectionConfidence\\\": 1.0,\\n    \\\"languageCode\\\": \\\"en\\\"\\n  },\\n  \\\"originalDetectIntentRequest\\\": {\\n    \\\"source\\\": \\\"DIALOGFLOW_CONSOLE\\\",\\n    \\\"payload\\\": {\\n    }\\n  },\\n  \\\"session\\\": \\\"projects/find-tftv/agent/sessions/*****\\\"\\n}\"\n    webhook_used: \"true\"\n    webhook_for_slot_filling_used: \"false\"\n    is_fallback_intent: \"false\"\n  }\n  fulfillment {\n    messages {\n      lang: \"en\"\n      type {\n        number_value: 0.0\n      }\n      speech {\n        string_value: \"\"\n      }\n    }\n  }\n}\nstatus {\n  code: 200\n  error_type: \"success\"\n}\nsentiment_analysis_result {\n  query_text_sentiment {\n  }\n}\n",
    "insertId": "ezyogzf1nru1r",
    "resource": {
      "type": "global",
      "labels": {
        "project_id": "find-tftv"
      }
    },
    "timestamp": "2023-07-21T09:12:38.128867Z",
    "severity": "INFO",
    "labels": {
      "type": "dialogflow_response",
      "source": "DIALOGFLOW_CONSOLE",
      "request_id": "********",
      "protocol": "V2"
    },
    "logName": "projects/find-tftv/logs/dialogflow_agent",
    "trace": "*********",
    "receiveTimestamp": "2023-07-21T09:12:38.134975348Z"
  }
ERROR 2023-07-21T09:12:39.110784Z [resource.labels.functionName: dialogflowFirebaseFulfillment] [labels.executionId: mlwkhtvmlfot] TypeError: Cannot read property 'get' of undefined at instruct (/workspace/index.js:65:53) at WebhookClient.handleRequest (/workspace/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:303:44) at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/workspace/index.js:141:9) at cloudFunction (/workspace/node_modules/firebase-functions/lib/providers/https.js:57:9) at process.nextTick (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/function_wrappers.js:98:17) at process._tickCallback (internal/process/next_tick.js:61:11)
  {
    "textPayload": "TypeError: Cannot read property 'get' of undefined\n    at instruct (/workspace/index.js:65:53)\n    at WebhookClient.handleRequest (/workspace/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:303:44)\n    at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/workspace/index.js:141:9)\n    at cloudFunction (/workspace/node_modules/firebase-functions/lib/providers/https.js:57:9)\n    at process.nextTick (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/function_wrappers.js:98:17)\n    at process._tickCallback (internal/process/next_tick.js:61:11)",
    "insertId": "********",
    "resource": {
      "type": "cloud_function",
      "labels": {
        "function_name": "dialogflowFirebaseFulfillment",
        "region": "us-central1",
        "project_id": "find-tftv"
      }
    },
    "timestamp": "2023-07-21T09:12:39.110784Z",
    "severity": "ERROR",
    "labels": {
      "instance_id": "******8",
      "execution_id": "******"
    },
    "logName": "projects/find-tftv/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
    "trace": "projects/find-tftv/traces/******",
    "receiveTimestamp": "2023-07-21T09:12:39.270252642Z"
  }

This is after my get call works perfectly fine for my main intent (FindIntent) and it correctly identifies and sets the parameters in find(agent). Any idea what could be going wrong? I tried changing instruct(agent) to

function instruct(agent) {
    console.log(agent.get.context('FindIntent-followup').parameters.area);
    console.log(agent.get.context('FindIntent-followup').parameters.location);
}

and I got the exact same error trace, even though I removed the webhooks call, and nothing added to the log. The context name is correct as well. Any idea what might be going wrong?

0

There are 0 best solutions below