In our previous tutorial, we have demonstrated how to create chatbots using Python for various channels such as:

Now, all those bots would be good but they will have one limitation. They don’t have NLP capabilities. So, based upon user’s inputs, we’ll be able to provide fixed answers only. But what if we want to add NLP capabilities to our bots?

Well, we can use NLP enabled chatbot platform like Dialogflow.

Dialogflow is a Natural language processing (NLP) platform that makes it simple to build chatbots. For each query and its responses, we may build a chatbot step by step. You may develop, train, and deploy your bot using Dialogflow’s console. Also, Dialogflow comes with its own API so we can programmatically connect the Dialogflow agent with our application.

So, let’s check out how to integrate Dialogflow API with our bot to make it more intelligent.

Integration of Dialogflow API

To access Dialogflow via API, we first need to create a service account with Dialogflow API enabled for the project. We must obtain an authentication key from GCP in order to authenticate our project using the Dialogflow API. Then, we need to use the service account key file in our environment.

Now we are considering the example for the intent of the below screenshot, we have added training phrases to the “camera” intent. To detect this intent, we will use the Dialogflow API.

Then, we are using the function given in the Dialogflow API official documentation. The function used to detect intent will take project id, session id, texts, and language code as arguments.

from google.cloud import dialogflow

def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    # for text in texts:
    text_input = dialogflow.TextInput(text=texts, language_code=language_code)

    query_input = dialogflow.QueryInput(text=text_input)

    response = session_client.detect_intent(
        request={"session": session, "query_input": query_input}
    )

    print("=" * 20)
    print("Query text: {}".format(response.query_result.query_text))
    print(
        "Detected intent: {} (confidence: {})\n".format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence,
        )
    )
    print("Fulfillment text: {}\n".format(response.query_result.fulfillment_messages))
    print("Fulfillment parameters: {}\n".format(response.query_result.parameters))
    print(response)

project_id="photography-9bhm"
session_id="test1"
texts = "which company camera do you use ?"
language_code="en"

detect_intent_texts(project_id, session_id, texts, language_code)

Where the project id is the bot id from Dialogflow. We can define the session id to keep the session between Dialogflow and the user alive. The query text will be entered as “texts”, and the “language_code” will be the code for the language in which the bot will be working.

To set the training phrase in the code, we defined the static variable “texts.” We are going to run the function in the last line of code.

Sample response

After executing the above function, the Dialogflow API detects intent based on the text entered by the user. As a response to our request, it sends an object.

Below is the sample response generated by returned by the Dialogflow API. To receive a response to our message, we must obtain the fulfillment text from the received response object.

{response_id: "99437676-e057-4d98-beac-30858e13c770-d678412e"
query_result {
  query_text: "which company camera do you use ?"
  parameters {
    fields {
      key: "suggestions"
      value {
        list_value {
          values {
            string_value: "[\"sony\",\"nikon\"]"
          }
        }
      }
    }
  }
  all_required_params_present: true
  fulfillment_text: "Mobile camera"
  fulfillment_messages {
    text {
      text: "Canon"
    }
  }
  fulfillment_messages {
    text {
      text: "Mobile camera"
    }
  }
  output_contexts {
    name: "projects/photography-9bhm/agent/sessions/test1/contexts/camera-followup"
    lifespan_count: 2
    parameters {
      fields {
        key: "suggestions"
        value {
          list_value {
            values {
              string_value: "[\"sony\",\"nikon\"]"
            }
          }
        }
      }
      fields {
        key: "suggestions.original"
        value {
          list_value {
          }
        }
      }
    }
  }
  intent {
    name: "projects/photography-9bhm/agent/intents/db7eb6b6-5eaf-4076-81f6-67ea7b02d936"
    display_name: "camera"
  }
  intent_detection_confidence: 1.0
  language_code: "en"
}

Voice Detection using Dialogflow API

Dialogflow API is also able to detect intents on basis of the Speech audio inputs with help of their function given in the documentation.

It takes similar inputs as the text version, the only change is instead of taking query text we pass the path of the audio file which needs to be processed.

It is able to take audio files as an input and convert the audio to a query text which is further passed on to the Dialogflow. The response is received with all the required responses and the response for our audio input.

The function we used to detect the audio file is shown below, taken from the Dialogflow API documentation. The audio file and the python script file must be in the same directory for the following code to work; otherwise, the audio file will not be detected.

def detect_intent_audio(project_id, session_id, audio_file_path, language_code):
    """Returns the result of detect intent with an audio file as input.
    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    # Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
    audio_encoding = dialogflow.AudioEncoding.AUDIO_ENCODING_LINEAR_16
    sample_rate_hertz = 48000

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    with open(audio_file_path, "rb") as audio_file:
        input_audio = audio_file.read()

    audio_config = dialogflow.InputAudioConfig(
        audio_encoding=audio_encoding,
        language_code=language_code,
        sample_rate_hertz=sample_rate_hertz,
    )
    query_input = dialogflow.QueryInput(audio_config=audio_config)

    request = dialogflow.DetectIntentRequest(
        session=session, query_input=query_input, input_audio=input_audio,
    )
    response = session_client.detect_intent(request=request)

    print("=" * 20)
    print("Query text: {}".format(response.query_result.query_text))
    print(
        "Detected intent: {} (confidence: {})\n".format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence,
        )
    )
    print("Fulfillment text: {}\n".format(response))

project_id="photography-9bhm"
session_id="test1"
audio_file_path = "Record-001.wav"
language_code="en"

detect_intent_audio(project_id, session_id, audio_file_path, language_code)

Sample response for audio

After execution of the above function, below is the sample response generated from Dialogflow API for the given audio.

{query_result {
  query_text: "hello"
  speech_recognition_confidence: 1.0
  parameters {
  }
  all_required_params_present: true
  fulfillment_text: "Hey there, Sugar pie ;) Trust me, I\342\200\231m not drunk; I\342\200\231m just intoxicated by you!"
  fulfillment_messages {
    text {
      text: "Hey there, Sugar pie ;) Trust me, I\342\200\231m not drunk; I\342\200\231m just intoxicated by you!"
    }
  }
  intent {
    name: "projects/photography-9bhm/agent/intents/d1558f1f-c431-4dfd-a81f-c3927642d0b2"
    display_name: "greeting"
    end_interaction: true
  }
  intent_detection_confidence: 1.0
  diagnostic_info {
    fields {
      key: "end_conversation"
      value {
        bool_value: true
      }
    }
    fields {
      key: "webhook_latency_ms"
      value {
        number_value: 4894.0
      }
    }
  }
  language_code: "en"
}

These JSON replies from the Dialogflow API can enable you to integrate with other chatbots. We hope that this documentation will assist you in using the Dialogflow API with a chatbot. Please let us know if you have found any difficulties in implementing the above functions in the comments section.

We have already created a blog post series where we have provided a tutorial on how to create a chatbot for different platforms. You can explore these blogs and learn how you can set different kinds of rich responses which can increase user engagement on your chatbot.

Telegram: Create Telegram Bot Using Python Tutorial With Examples

Facebook Messanger: Create Facebook Messenger Bot Using Python Tutorial With Examples

Whatsapp: Create WhatsApp Bot With Twilio Using Python Tutorial With Examples

Slack: Create Slack Bot Using Python Tutorial With Examples

Discord: Create Discord Bot Using Python Tutorial With Examples

Categories: Chatbots Development Dialogflow Dialogflow Tutorial NLP Python

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*