Integration of Dialogflow API
To entry Dialogflow CX through API, first we have to have a setup of Gcloud CLI in our system. If you happen to wouldn’t have the setup of Gcloud, please observe the given hyperlink https://cloud.google.com/sdk/docs/install.
After gcloud setup follows these steps to provide authentication permission.
- Choose a venture with given command
gcloud config set venture <ProjectID>
- Now run the next command
gcloud auth application-default login
- You may be prompted with a login web page. “You at the moment are authenticated with the gcloud CLI!” this shall be displayed after you have efficiently logged in.
Then, we’re utilizing the perform given within the Dialogflow API official documentation. The perform used to detect intent will take venture id, session id, texts, and language code as arguments.
from google.cloud.dialogflowcx_v3.providers.classes import SessionsClient
from google.cloud.dialogflowcx_v3.sorts import session
from google.protobuf.json_format import MessageToDict
def detect_intent_disabled_webhook(project_id, location, session_id, agent_id, textual content, language_code):
client_options = None
if location != "international":
api_endpoint = f"{location}-dialogflow.googleapis.com:443"
print(f"API Endpoint: {api_endpoint}n")
client_options = {"api_endpoint": api_endpoint}
session_client = SessionsClient(client_options=client_options)
session_path = session_client.session_path(venture=project_id,location=location,agent=agent_id,session=session_id)
# Put together request
text_input = session.TextInput(textual content=textual content)
query_input = session.QueryInput(textual content=text_input, language_code=language_code)
#If there's a webhook operating within the background, you may disable it by setting 'disable_webhook' to False as an alternative of True.
query_params = session.QueryParameters(disable_webhook = True)
request = session.DetectIntentRequest(session=session_path,query_input=query_input,query_params=query_params)
response = session_client.detect_intent(request=request)
# print(response)
response_dict = MessageToDict(response._pb)
print(response_dict)
project_id = "Your Venture ID"
location_id = "Your Location ID"
agent_id = "Your Agent ID"
session_id = "test_1"
textual content = "Whats up"
language_code = "en-us"
detect_intent_disabled_webhook(project_id, location_id, session_id, agent_id, textual content, language_code)
The place the venture id is the bot id from Dialogflow. We will outline the session id to maintain the session between Dialogflow and the person alive. The question textual content shall be entered as “textual content”, and the “language_code” would be the code for the language through which the bot shall be working.
To set the coaching phrase within the code, we outlined the static variable “textual content.” We’re going to run the perform within the final line of code.
Pattern response
After executing the above perform, the Dialogflow API detects intent based mostly on the textual content entered by the person. As a response to our request, it sends an object.
Beneath is the pattern response generated by the Dialogflow API. To obtain a response to our message, we should get hold of the success textual content from the acquired response object.
{
"responseId": "d91c430d-7b4e-44c1-a5f5-f4563fdd4e6f",
"queryResult": {
"textual content": "Whats up",
"languageCode": "en",
"responseMessages": [
{
"text": {
"text": [
"Welcome to Dialogflow CX."
]
}
}
],
"currentPage": {
"identify": "tasks/appointment-cxx/areas/us-central1/brokers/fcc53e9b-5f20-421c-b836-4df53554526c/flows/00000000-0000-0000-0000-000000000000/pages/START_PAGE",
"displayName": "Begin Web page"
},
"intent": {
"identify": "tasks/appointment-cxx/areas/us-central1/brokers/fcc53e9b-5f20-421c-b836-4df53554526c/intents/00000000-0000-0000-0000-000000000000",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"Transition Targets Chain": [],
"Session Id": "test_1",
"Different Matched Intents": [
{
"Type": "NLU",
"Score": 1,
"DisplayName": "Default Welcome Intent",
"Id": "00000000-0000-0000-0000-000000000000",
"Active": True
}
],
"Execution Sequence": [
{
"Step 1": {
"Type": "INITIAL_STATE",
"InitialState": {
"FlowState": {
"FlowId": "00000000-0000-0000-0000-000000000000",
"Name": "Default Start Flow",
"PageState": {
"Status": "ENTERING_PAGE",
"Name": "Start Page",
"PageId": "START_PAGE"
},
"Version": 0
},
"MatchedIntent": {
"Type": "NLU",
"Score": 1,
"DisplayName": "Default Welcome Intent",
"Active": True,
"Id": "00000000-0000-0000-0000-000000000000"
}
}
}
},
{
"Step 2": {
"FunctionExecution": {
"Responses": [
{
"text": {
"redactedText": [
"Welcome to Dialogflow CX."
],
"textual content": [
"Welcome to Dialogflow CX."
]
},
"responseType": "HANDLER_PROMPT",
"supply": "VIRTUAL_AGENT"
}
]
},
"Kind": "STATE_MACHINE",
"StateMachine": {
"FlowState": {
"FlowId": "00000000-0000-0000-0000-000000000000",
"PageState": {
"Standing": "TRANSITION_ROUTING",
"Identify": "Begin Web page",
"PageId": "START_PAGE"
},
"Model": 0,
"Identify": "Default Begin Circulate"
},
"FlowLevelTransition": True,
"TriggeredIntent": "Default Welcome Intent",
"TriggeredTransitionRouteId": "f48cf8b5-c147-42a2-b967-12d2a3c0fcad"
}
}
},
{
"Step 3": {
"Kind": "STATE_MACHINE",
"StateMachine": {
"FlowState": {
"FlowId": "00000000-0000-0000-0000-000000000000",
"Identify": "Default Begin Circulate",
"PageState": {
"Standing": "TRANSITION_ROUTING",
"Identify": "Begin Web page",
"PageId": "START_PAGE"
},
"Model": 0
}
}
}
}
],
"Triggered Transition Names": [
"f48cf8b5-c147-42a2-b967-12d2a3c0fcad"
]
},
"match": {
"intent": {
"identify": "tasks/appointment-cxx/areas/us-central1/brokers/fcc53e9b-5f20-421c-b836-4df53554526c/intents/00000000-0000-0000-0000-000000000000",
"displayName": "Default Welcome Intent"
},
"resolvedInput": "Whats up",
"matchType": "INTENT",
"confidence": 1
}
},
"responseType": "FINAL"
}
Voice Detection utilizing Dialogflow API
Dialogflow API can be in a position to detect intents on the idea of the Speech audio inputs with assist of their perform given within the documentation.
It takes related inputs because the textual content model, the one change is as an alternative of taking question textual content we go the trail of the audio file which must be processed.
It is ready to take audio recordsdata as an enter and convert the audio to a question textual content which is additional handed on to the Dialogflow. The response is acquired with all of the required responses and the response for our audio enter.
The perform we used to detect the audio file is proven beneath, taken from the Dialogflow API documentation. The audio file have to be in a “wav” format and in a mono channel in any other case code will by means of an error.
Refer beneath script to transform the audio into wav format.
from pydub import AudioSegment
input_audio = AudioSegment.from_wav("YOUR-AUDIO-FILE-PATH")
input_audio = input_audio.set_channels(1)
input_audio.export("YOUR-AUDIO-FILE-PATH", format="wav")
import uuid
from google.cloud.dialogflowcx_v3.providers.brokers import AgentsClient
from google.cloud.dialogflowcx_v3.providers.classes import SessionsClient
from google.cloud.dialogflowcx_v3.sorts import audio_config
from google.cloud.dialogflowcx_v3.sorts import session
def detect_intent_audio(agent, session_id, audio_file_path, language_code):
"""Returns the results of detect intent with an audio file as enter.
Utilizing the identical `session_id` between requests permits continuation
of the dialog."""
session_path = f"{agent}/classes/{session_id}"
print(f"Session path: {session_path}n")
client_options = None
agent_components = AgentsClient.parse_agent_path(agent)
location_id = agent_components["location"]
if location_id != "international":
api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
print(f"API Endpoint: {api_endpoint}n")
client_options = {"api_endpoint": api_endpoint}
session_client = SessionsClient(client_options=client_options)
input_audio_config = audio_config.InputAudioConfig(
audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,
)
with open(audio_file_path, "rb") as audio_file:
input_audio = audio_file.learn()
audio_input = session.AudioInput(config=input_audio_config, audio=input_audio)
query_input = session.QueryInput(audio=audio_input, language_code=language_code)
request = session.DetectIntentRequest(session=session_path, query_input=query_input)
response = session_client.detect_intent(request=request)
print("=" * 20)
print(f"Question textual content: {response.query_result.transcript}")
response_messages = [
" ".join(msg.text.text) for msg in response.query_result.response_messages
]
print(f"Response textual content: {' '.be a part of(response_messages)}n")
project_id = "YOUR-PROJECT-ID"
location_id = "YOUR-LOCATION-ID"
agent_id = "YOUR-AGENT-ID"
agent = f"tasks/{project_id}/areas/{location_id}/brokers/{agent_id}"
session_id = str(uuid.uuid4())
audio_file_path = "YOUR-AUDIO-FILE-PATH"
language_code = "en-us"<br>
detect_intent_audio(agent, session_id, audio_file_path, language_code)
Pattern response for audio
After execution of the above perform, beneath is the pattern response generated from Dialogflow API for the given audio.Question textual content: good day
Response textual content: Welcome to Dialogflow CX.
If you happen to want the JSON response you will get it by printing the response variable. These JSON replies from the Dialogflow API can allow you to combine with different chatbots. We hope that this documentation will help you in utilizing the Dialogflow API with a chatbot.
Please tell us when you’ve got discovered any difficulties in implementing the above capabilities within the feedback part. We might be glad that will help you. In case you are in search of Chatbot Growth or Pure Language Processing providers then do contact us or ship your requirement at letstalk@pragnakalp.com. We might be pleased to supply our skilled providers.