Fulfillment

Webhook

Setting up a webhook allows you to pass information from a matched intent into a web service and get a result from it.

Request

Your web service receives a POST request from Dialogflow. This is in the form of the response to a user query, matched by intents with webhook enabled. Be sure that your web service meets all the webhook requirements specific to the API version enabled in this agent.

If a request is sent from one of the messaging platforms, the originalRequest field is added to the response to a query.

This format is chosen in order to simplify the response parsing on the service side with the help of Dialogflow SDKs.

The request to the service can have the following fields:

V2 API

Name Type Description
responseId String Unique id for request.
session String Unique session id.
queryResult Object Result of the conversation query or event processing.
queryText String The original text of the query.
parameters Object Consists of parameter_name:parameter_value pairs.
allRequiredParamsPresent Boolean Set to false if required parameters are missing in query.
fulfillmentText String Text to be pronounced to the user or shown on the screen.
fulfillmentMessages Object Collection of rich messages to show the user.
outputContexts Object Collection of output contexts.
intent Object The intent that matched the user's query.
intentDetectionConfidence Number 0-1 Matching score for the intent.
diagnosticInfo Object Free-form diagnostic info.
languageCode String The language that was triggered during intent matching.
originalDetectIntentRequest Object Full request coming from an integrated platform. (Facebook Messenger, Slack, etc.)

V1 API

Name Type Description
originalRequest Object Full request coming from an integrated platform. (Facebook Messenger, Slack, etc.)
id String Unique id of request.
sessionId String Unique session id.
timestamp String Date and time of the request in UTC timezone using ISO-8601 format.
timezone String Time zone from IANA Time Zone Database.
lang String Language of request.
result Object Related information resulting from request.
source String Request source name. (google, facebook, slack, etc.)
resolvedQuery String The query that was used to produce the result.
speech String Text to be pronounced to the user / shown on the screen.
action String Matched Dialogflow intent action name.
actionIncomplete Boolean Whether or not all required parameters were collected.
parameters Object Consists of parameter_name:parameter_value pairs.
contexts Object Array of context objects.
↳- name String The name of the context.
↳- parameters Objects Parameters carried over via context.
↳- lifespan Number Number of requests after which the context will expire.
metadata Object Contains data about matched intent.
↳- intentId String Unique identifier for intent.
↳- webhookUsed Boolean Indicates if webhook is enabled in the matched intent.
↳- webhookForSlotFillingUsed Boolean Indicates if webhook is handling required parameters.
↳- nluResponseTime Number Time to complete request.
↳- intentName String Name of the matched intent.
fulfillment Object Contains data about responses, rich messages, responses from webhook.
↳- speech String Text to be pronounced to the user / shown on the screen.
↳- messages Object Array of message objects.
score Number 0-1 Matching score for the intent.

Sample Request to the Service

V2 API

POST https://my-service.com/action

Headers:
//user defined headers
Content-type: application/json

POST body:
{
  "responseId": "ea3d77e8-ae27-41a4-9e1d-174bd461b68c",
  "session": "projects/your-agents-project-id/agent/sessions/88d13aa8-2999-4f71-b233-39cbf3a824a0",
  "queryResult": {
    "queryText": "user's original query to your agent",
    "parameters": {
      "param": "param value"
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Text defined in Dialogflow's console for the intent that was matched",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Text defined in Dialogflow's console for the intent that was matched"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/your-agents-project-id/agent/sessions/88d13aa8-2999-4f71-b233-39cbf3a824a0/contexts/generic",
        "lifespanCount": 5,
        "parameters": {
          "param": "param value"
        }
      }
    ],
    "intent": {
      "name": "projects/your-agents-project-id/agent/intents/29bcd7f8-f717-4261-a8fd-2d3e451b8af8",
      "displayName": "Matched Intent Name"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {},
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {}
}

V1 API

POST https://my-service.com/action

Headers:
//user defined headers
Content-type: application/json

POST body:

{
  "originalRequest": {},
  "id": "7811ac58-5bd5-4e44-8d06-6cd8c67f5406",
  "sessionId": "1515191296300",
  "timestamp": "2018-01-05T22:35:05.903Z",
  "timezone": "",
  "lang": "en-us",
  "result": {
    "source": "agent",
    "resolvedQuery": "user's original query to your agent",
    "speech": "Text defined in Dialogflow's console for the intent that was matched",
    "action": "Matched Dialogflow intent action name",
    "actionIncomplete": false,
    "parameters": {
      "param": "param value"
    },
    "contexts": [
      {
        "name": "incoming context name",
        "parameters": {},
        "lifespan": 0
      }
    ],
    "metadata": {
      "intentId": "29bcd7f8-f717-4261-a8fd-2d3e451b8af8",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false",
      "nluResponseTime": 6,
      "intentName": "Name of Matched Dialogflow Intent"
    },
    "fulfillment": {
      "speech": "Text defined in Dialogflow's console for the intent that was matched",
      "messages": [
        {
          "type": 0,
          "speech": "Text defined in Dialogflow's console for the intent that was matched"
        }
      ]
    },
    "score": 1
  }
}

See more information in the WebhookRequest doc.

Response

The response from the service should have the following fields:

V2 API

Name Type Description
fulfillmentText String Optional. The text to be shown on the screen. This value is passed directly to QueryResult.fulfillment_text.
fulfillmentMessages[] Object (Message) Optional. The collection of rich messages to present to the user. This value is passed directly to QueryResult.fulfillment_messages.
source String Optional. This value is passed directly to QueryResult.webhook_source.
payload Object (Struct) Optional. This value is passed directly to QueryResult.webhook_payload
outputContexts[] Object (Context) Optional. The collection of output contexts. This value is passed directly to QueryResult.output_contexts.
followupEventInput Object (EventInput) Optional. Makes the platform immediately invoke another sessions.detectIntent call internally with the specified event as input.

V1 API

Name Type Description
speech String Response to the request.
displayText String Text displayed on the user device screen.
data Object Additional data required for performing the action on the client side. The data is sent to the client in the original form and is not processed by Dialogflow.
contextOut Array of context objects Array of context objects set after intent completion.
source String Data source.
followupEvent Object Event name and optional parameters sent from the web service to Dialogflow. Read more

Sample Response from the Service

V2 API

{
  "fulfillmentText": "This is a text response",
  "fulfillmentMessages": [
    {
      "card": {
        "title": "card title",
        "subtitle": "card text",
        "imageUri": "https://assistant.google.com/static/images/molecule/Molecule-Formation-stop.png",
        "buttons": [
          {
            "text": "button text",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    }
  ],
  "source": "example.com",
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "this is a simple response"
            }
          }
        ]
      }
    },
    "facebook": {
      "text": "Hello, Facebook!"
    },
    "slack": {
      "text": "This is a text response for Slack."
    }
  },
  "outputContexts": [
    {
      "name": "projects/${PROJECT_ID}/agent/sessions/${SESSION_ID}/contexts/context name",
      "lifespanCount": 5,
      "parameters": {
        "param": "param value"
      }
    }
  ],
  "followupEventInput": {
    "name": "event name",
    "languageCode": "en-US",
    "parameters": {
      "param": "param value"
    }
  }
}

V1 API

{
"speech": "this text is spoken out loud if the platform supports voice interactions",
"displayText": "this text is displayed visually",
"messages": {
  "type": 1,
  "title": "card title",
  "subtitle": "card text",
  "imageUrl": "https://assistant.google.com/static/images/molecule/Molecule-Formation-stop.png"
},
"data": {
  "google": {
    "expectUserResponse": true,
    "richResponse": {
      "items": [
        {
          "simpleResponse": {
            "textToSpeech": "this is a simple response"
          }
        }
      ]
    }
  },
  "facebook": {
    "text": "Hello, Facebook!"
  },
  "slack": {
    "text": "This is a text response for Slack."
  }
},
"contextOut": [
  {
    "name": "context name",
    "lifespan": 5,
    "parameters": {
      "param": "param value"
    }
  }
],
"source": "example.com",
"followupEvent": {
  "name": "event name",
  "parameters": {
    "param": "param value"
  }
}

}

See more information in the WebhookResponse doc.

Errors

The service should be able to handle the following errors:

  • 400 Bad Request – The request was invalid or cannot be served.
  • 401 Unauthorized – The request requires user authentication.
  • 403 Forbidden – The server understood the request but refuses to take any further action or the access is not allowed.
  • 404 Not found – There is no resource behind the URI.
  • 500 Server fault – Internal Server Error.
  • 503 Service Unavailable – Internal Server Error.

In case of these or other errors (timeout limit exceeded, service is not available), the “status” in the response sent to the client will contain the following:

"status": {
    "code": 206,
    "errorType": "webhook call failed with %error Code% error"
}

where error Code is the error ID received from the service.

Limits

  • Timeout for service response – 5 seconds.
  • Data received in the response from the service – up to 64K.

Authentication

Authentication can be done in 2 ways:

  • Basic authentication with login and password.
  • Authentication with additional authentication headers.

If the integrated service doesn’t require any authentication, leave the authentication fields blank.

The service must use HTTPS and the URL must be publicly accessible.

Slot Filling

If you want to send requests for required parameters from Dialogflow to your web service, check the option Use webhook for slot filling in the Fulfillment section of the intent.

Example

Check out the second part of our getting started guide, Basic Fulfillment and Conversation Setup, for steps on setting up fulfillment.

Cloud Functions for Firebase

For simple webhook testing and implementation, you can use the Cloud Functions for Firebase area of the Fulfillment page. In most cases the free "Spark" tier of Firebase is all you'll need. Tier limitations and pricing information for the other tiers can be found on the Firebase pricing page.

To enable:

  1. Click on Fulfillment in the left menu.
  2. Click the switch for Inline Editor.

Some basic, functional code provided to help you get started.

To deploy your fulfillment, click the Deploy button under the code editor.

After clicking Deploy, Dialogflow will save your Cloud Function for Firebase and begin the deployment process. When deployment is complete, you'll see a timestamp next to the Deploy button, signifying the last time the function was deployed.

The link under the code editor can be used to visit the function's logs in the Firebase console. This is used to debug issues and get information on your function.

"Graduating" your code

Once you're ready to move your code out of the Fulfillment page, you can use the Download button to get a .ZIP file of your code in it's current state. Using the Firebase CLI, you can unzip your code locally and deploy more complex fulfillment code.

Limitations

Here is a list of things to be aware of when using the Cloud Functions for Firebase option:

  • If you modify your function outside of code editor, you can no longer use the Dialogflow editor to modify your Cloud Function for Firebase. Your function will continue to provide fulfillment for your agent, but if you need to make changes, you will need to do so in the Firebase console.

  • The function must be named "dialogflowFirebaseFulfillment". If you change the name of your function it will not deploy via Dialogflow. If you want to change the name of your function you can download the code, change the function name, and deploy through Firebase's CLI.

  • Code modified in the dialogflow editor cannot be saved or downloaded without being deployed.

  • Dialogflow's editor only supports two files: index.js and package.json (modifying package.json will install any dependencies you specify upon deployment)

  • Network calls originating from your Cloud Function for Firebase to destinations outside Google's network require billing to be enabled for the underlying Google Cloud or Firebase project.