SlideShare a Scribd company logo
Integrating DialogFlow (API.ai) into
Qiscus SDK Chat Application
Just recently on October 10th, Google announced a change in name of API.AI into DialogFlow. There
are a couple of new features following this change. Regardless of what has been changed, in this
post we are going to share a simple way of how to integrate your agents that is created using
DialogFlow into any Qiscus SDK chat application.
As DialogFlow doesn't have a famous 'one-click integration' feature for Qiscus (yet), we need to
make a workaround to do so. Fortunately, DialogFlow provides some integration ways through its
SDK options, here in the image, you can see several programming languages that you can use for
your agent integration.
Image of DialogFlow SDK for integration
For our simplicity purpose, we are going to use our last article on how to create a simple chat
application using QiscusSDK and how to integrate a simple echo bot into it as prior requirement to
this post. You can find the codes here. Since it uses Python as the webhook, in this article we are
going to use DialogFlow SDK for Python as well called apiai (this might changes later as the effect
of name change).
Another thing to note is that we assume you already have an agent or two created in DialogFlow, if
not please refer to the basic tuts to create one.
1. Add DialogFlow SDK Python Package
Alright, let's get started! First thing first, let's add DialogFlow SDK python package (apiai) into our
project, come on open setup.py file, and add it,
from setuptools import setup, find_packages
setup(
name='simplebot',
version='1.0',
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'apiai',
'flask',
'requests'
],
)
and let's import that package into our simplebot/views.py file then instantiate new object
from this package,
import apiai
import json
import requests
from flask import render_template, request
from simplebot import app
app_id = "YOUR_APP_ID"
secret_key = "YOUR_SECRET_KEY"
sender_email = "YOUR_BOT_EMAIL"
bot_name = "YOUR_BOT_NAME"
qiscus_sdk_url = "https://{}.qiscus.com".format(app_id)
client_access_token = "YOUR_DIALOGFLOW_CLIENT_ACCESS_TOKEN"
ai = apiai.ApiAI(client_access_token)
...
.
Notice in the code above, we need client_access_token to initiate new object from the
package. So please make sure you already got this token from your agent DialogFlow console
dashboard and assign it to the client_access_token, you may want to see this image to locate
where it is.
image of console
2. Incoming Message and Agent Response
After you got this package set, let's implement it in our index() function. First we will need to get
query from Qiscus chat app to be passed to the DialogFlow agent before we send it to get the
response from agent.
...
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
payload = request.get_json().get('payload')
room_id = payload.get("room").get("id")
message = payload.get("message").get("text")
# let's prepare the incoming message (query) we want
to send to dialogflow agent
conv = ai.text_request()
conv.session_id =
"ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)"
conv.query = message
# and let's get the response from dialogflow agent
response = conv.getresponse()
response_json =
json.loads(response.read().decode('utf-8'))

Recommended for you

Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications

The document provides tips for building API-heavy Ruby on Rails applications. It discusses using APIs from Instagram, CafePress, Spreadsheets, Google Docs, and others. It covers authentication challenges, using background jobs, effective testing strategies like mocking HTTP requests, and different approaches to OAuth authentication used by APIs like Instagram, Freshbooks, Xero, and Evernote. Code examples are provided for common API patterns like making requests, parsing responses, and implementing OAuth flows.

[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기

This document summarizes a presentation on smart SharePoint development. It discusses REST/OData APIs, the Client-Side Object Model, and SOAP web services. For REST/OData, it covers architecture, operations, and advantages of using URIs and HTTP methods. For CSOM, it outlines the architecture, object models, and advantages of familiar .NET development. For SOAP, it describes the standard and lists SharePoint web services supported across versions. Code examples demonstrate creating a site using REST and adding permissions using JavaScript CSOM.

The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started

Jeff Scudder, Eric Bidelman The number of APIs made available for Google products has exploded from a handful to a slew! Get the big picture on what is possible with the APIs for everything from YouTube, to Spreadsheets, to Search, to Translate. We'll go over a few tools to help you get started and the things these APIs share in common. After this session picking up new Google APIs will be a snap.

googleajax apisgoogle data
response_messages =
response_json.get("result").get("fulfillment").get("messages")
post_url =
"{}/api/v2/rest/post_comment".format(qiscus_sdk_url)
headers = {"QISCUS_SDK_SECRET": secret_key}
data = {
"sender_email": sender_email,
"room_id": room_id,
"message": message,
"type": "text",
"payload": {}
}
req = requests.post(post_url, headers=headers,
params=data)
...
What we need to do next is just to send back any response we got from agent to the Qiscus chat
app. This can be anything: plain text or any additional payload. So, before we return it back, we need
to know the structure of payload that is returned by our agent at DialogFlow, please have a look at
JSON code below, this JSON code is the payload that is returned from our agent in DialogFlow.
{
"id": "354eaf3c-c40e-42e4-acf6-fc2ef0e71799",
"timestamp": "2017-10-26T08:11:58.239Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "yo",
"action": "hi",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
"intentId": "fe8dbb22-43bf-4cb4-b634-48c3a2af98ae",
"webhookUsed": "false",
"webhookForSlotFillingUsed": "false",
"intentName": "hi"
},
"fulfillment": {
"speech": "Hi! How are you doing?",
"messages": [
{
"type": 0,
"id": "948f5dad-550c-4fa1-93ba-3819d8e42fbb",
"speech": "Hi! How are you doing?"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "d70073ae-0cdb-4bc4-b7d9-d8d0b16b98af"
}
From JSON code above, there is a fulfillment field. It has additional children fields that are
actual responses from our agent which we are interested in.
Also read: "Making your Apps “Chatable”"
Notice the messages field? its value is a list. So we may assume our agent could return one or
more messages when we make a request to DialogFlow. This could be another text or additional
custom payload, such as payload for button or card. However, to simplify this process, let's handle
text message only.
Ok, let's modify our index() function in views.py file again.
...
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
payload = request.get_json().get('payload')
room_id = payload.get("room").get("id")
message = payload.get("message").get("text")
# let's prepare the incoming message (query) we want
to send to dialogflow agent
conv = ai.text_request()
conv.session_id =
"ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)"
conv.query = message
# and let's get the response from dialogflow agent
response = conv.getresponse()
response_json =
json.loads(response.read().decode('utf-8'))
response_messages =
response_json.get("result").get("fulfillment").get("messages")
post_url =
"{}/api/v2/rest/post_comment".format(qiscus_sdk_url)
headers = {"QISCUS_SDK_SECRET": secret_key}
for msg in response_messages:
data = {
"sender_email": sender_email,
"room_id": room_id,
"message": msg.get("speech"),
"type": "text",
"payload": {}
}
try:
requests.post(post_url, headers=headers,
params=data)
except requests.exceptions.RequestException as e:
print(e)
return "Something went wrong!", 401
return "OK", 200
else:
return render_template('index.html', appId=app_d,
senderEmail=sender_email)
...
save and let's run our webhook, and you may open http://locahost:5000 in your browser.
$ make run
3. Webhook
Since we've been developing this integration locally, Qiscus SDK won't recognise our webhook even
though we are trying to add our local webhook address to the Qiscus SDK. So to help making our
webhook open to the internet, we are going to use ngrok and add the generated temporary
subdomain addresses into our Qiscus SDK, please refer to this for ngrok.
After you do that, please try to have a chat again through generated subdomain address in your
browser. Voila, you got a reply from your agent in DialogFlow!
Accompanying codes can be found at https://github.com/qiscus/qiscus-dialogflow. You can also
experience directly at https://qiscusdialog.herokuapp.com/.
Closing
To sum up, this article is only focusing on how we integrate our agent that is created in DialogFlow
which returns plain text only. In order to leverage your agent capability, you may want to add
additional custom payload as additional fulfillment response. For example you may want to return
message that contains image and buttons from DialogFlow. You can refer to Qiscus docs for any type
of comments that is supported by Qiscus as well as how to add custom payload in DialogFlow for
more information.

Recommended for you

Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample

Apache Aries is an open source project for building enterprise OSGi applications. It provides several integration components like Blueprint container, JPA integration, and JNDI integration. The Aries project was created in 2009 and is currently used by projects like Apache Geronimo, Apache Felix, and JBoss OSGi. It aims to develop more application-centric features in the future like message-driven blueprint components and declarative security.

apache arieszoe slattery
The RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with OracleThe RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with Oracle

It transforms and caches any SOA based application in REST. A proxy "soap to rest" is provided, using Oracle Service Bus and Oracle Coherence.

coherencerest2soapsoa
Generating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdeviceGenerating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdevice

IoT Device (Raspberry Pi) + .NET 6.0 + .NET IoT Libraries + C# Source Code Generator + Azure IoT Hub + Azure IoT Client SDK for C# + VS Code

azureiotc#

More Related Content

What's hot

RESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkRESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP Framework
Bo-Yi Wu
 
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & morePower your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
wesley chun
 
Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)
Ville Seppänen
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
Tim Cull
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
lanslote
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started
guest1af57e
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample
Skills Matter
 
The RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with OracleThe RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with Oracle
Emiliano Pecis
 
Generating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdeviceGenerating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdevice
Alon Fliess
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with Parse
DroidConTLV
 
Parse Advanced
Parse AdvancedParse Advanced
Parse Advanced
Tushar Acharya
 
DF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and HerokuDF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and Heroku
afawcett
 
TDC2016SP - Trilha Android
TDC2016SP - Trilha AndroidTDC2016SP - Trilha Android
TDC2016SP - Trilha Android
tdc-globalcode
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
Rob Windsor
 
google drive and the google drive sdk
google drive and the google drive sdkgoogle drive and the google drive sdk
google drive and the google drive sdk
firenze-gtug
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
madhavforu
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote Authentication
Adil Ansari
 
Search APIs & Universal Links
Search APIs & Universal LinksSearch APIs & Universal Links
Search APIs & Universal Links
Yusuke Kita
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Eric Shupps
 

What's hot (20)

RESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkRESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP Framework
 
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & morePower your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
 
Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample
 
The RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with OracleThe RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with Oracle
 
Generating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdeviceGenerating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdevice
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with Parse
 
Parse Advanced
Parse AdvancedParse Advanced
Parse Advanced
 
DF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and HerokuDF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and Heroku
 
TDC2016SP - Trilha Android
TDC2016SP - Trilha AndroidTDC2016SP - Trilha Android
TDC2016SP - Trilha Android
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
google drive and the google drive sdk
google drive and the google drive sdkgoogle drive and the google drive sdk
google drive and the google drive sdk
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote Authentication
 
Search APIs & Universal Links
Search APIs & Universal LinksSearch APIs & Universal Links
Search APIs & Universal Links
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
 

Similar to Integrating dialog flow (api.ai) into qiscus sdk chat application

AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
Marvin Heng
 
Exploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with PythonExploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with Python
wesley chun
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
Katy Slemon
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin Görner
European Innovation Academy
 
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resourcesJavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
Corley S.r.l.
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)
Andrey Volobuev
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Red Hat Developers
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
Kiril Iliev
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api's
Ortus Solutions, Corp
 
[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit
Tomomi Imura
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Gavin Pickin
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
Katy Slemon
 
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidMobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Alberto Ruibal
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
維佋 唐
 
2012: ql.io and Node.js
2012: ql.io and Node.js2012: ql.io and Node.js
2012: ql.io and Node.js
Jonathan LeBlanc
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0
Eugenio Romano
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...
Appear
 
Micro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMicro app-framework - NodeLive Boston
Micro app-framework - NodeLive Boston
Michael Dawson
 
Micro app-framework
Micro app-frameworkMicro app-framework
Micro app-framework
Michael Dawson
 

Similar to Integrating dialog flow (api.ai) into qiscus sdk chat application (20)

AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
 
Exploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with PythonExploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with Python
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin Görner
 
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resourcesJavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api's
 
[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidMobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
2012: ql.io and Node.js
2012: ql.io and Node.js2012: ql.io and Node.js
2012: ql.io and Node.js
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...
 
Micro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMicro app-framework - NodeLive Boston
Micro app-framework - NodeLive Boston
 
Micro app-framework
Micro app-frameworkMicro app-framework
Micro app-framework
 

Recently uploaded

WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
Toru Tamaki
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
Awais Yaseen
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
SynapseIndia
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 

Recently uploaded (20)

WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 

Integrating dialog flow (api.ai) into qiscus sdk chat application

  • 1. Integrating DialogFlow (API.ai) into Qiscus SDK Chat Application Just recently on October 10th, Google announced a change in name of API.AI into DialogFlow. There are a couple of new features following this change. Regardless of what has been changed, in this post we are going to share a simple way of how to integrate your agents that is created using DialogFlow into any Qiscus SDK chat application. As DialogFlow doesn't have a famous 'one-click integration' feature for Qiscus (yet), we need to make a workaround to do so. Fortunately, DialogFlow provides some integration ways through its SDK options, here in the image, you can see several programming languages that you can use for your agent integration.
  • 2. Image of DialogFlow SDK for integration For our simplicity purpose, we are going to use our last article on how to create a simple chat application using QiscusSDK and how to integrate a simple echo bot into it as prior requirement to this post. You can find the codes here. Since it uses Python as the webhook, in this article we are going to use DialogFlow SDK for Python as well called apiai (this might changes later as the effect of name change). Another thing to note is that we assume you already have an agent or two created in DialogFlow, if not please refer to the basic tuts to create one. 1. Add DialogFlow SDK Python Package Alright, let's get started! First thing first, let's add DialogFlow SDK python package (apiai) into our project, come on open setup.py file, and add it, from setuptools import setup, find_packages setup( name='simplebot', version='1.0', long_description=__doc__, packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'apiai',
  • 3. 'flask', 'requests' ], ) and let's import that package into our simplebot/views.py file then instantiate new object from this package, import apiai import json import requests from flask import render_template, request from simplebot import app app_id = "YOUR_APP_ID" secret_key = "YOUR_SECRET_KEY" sender_email = "YOUR_BOT_EMAIL" bot_name = "YOUR_BOT_NAME" qiscus_sdk_url = "https://{}.qiscus.com".format(app_id) client_access_token = "YOUR_DIALOGFLOW_CLIENT_ACCESS_TOKEN" ai = apiai.ApiAI(client_access_token) ... . Notice in the code above, we need client_access_token to initiate new object from the package. So please make sure you already got this token from your agent DialogFlow console dashboard and assign it to the client_access_token, you may want to see this image to locate where it is.
  • 4. image of console 2. Incoming Message and Agent Response After you got this package set, let's implement it in our index() function. First we will need to get query from Qiscus chat app to be passed to the DialogFlow agent before we send it to get the response from agent. ... @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': payload = request.get_json().get('payload') room_id = payload.get("room").get("id") message = payload.get("message").get("text") # let's prepare the incoming message (query) we want to send to dialogflow agent conv = ai.text_request() conv.session_id = "ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)" conv.query = message # and let's get the response from dialogflow agent response = conv.getresponse() response_json = json.loads(response.read().decode('utf-8'))
  • 5. response_messages = response_json.get("result").get("fulfillment").get("messages") post_url = "{}/api/v2/rest/post_comment".format(qiscus_sdk_url) headers = {"QISCUS_SDK_SECRET": secret_key} data = { "sender_email": sender_email, "room_id": room_id, "message": message, "type": "text", "payload": {} } req = requests.post(post_url, headers=headers, params=data) ... What we need to do next is just to send back any response we got from agent to the Qiscus chat app. This can be anything: plain text or any additional payload. So, before we return it back, we need to know the structure of payload that is returned by our agent at DialogFlow, please have a look at JSON code below, this JSON code is the payload that is returned from our agent in DialogFlow. { "id": "354eaf3c-c40e-42e4-acf6-fc2ef0e71799", "timestamp": "2017-10-26T08:11:58.239Z", "lang": "en", "result": { "source": "agent", "resolvedQuery": "yo", "action": "hi", "actionIncomplete": false, "parameters": {}, "contexts": [], "metadata": { "intentId": "fe8dbb22-43bf-4cb4-b634-48c3a2af98ae", "webhookUsed": "false", "webhookForSlotFillingUsed": "false", "intentName": "hi" }, "fulfillment": { "speech": "Hi! How are you doing?", "messages": [ {
  • 6. "type": 0, "id": "948f5dad-550c-4fa1-93ba-3819d8e42fbb", "speech": "Hi! How are you doing?" } ] }, "score": 1 }, "status": { "code": 200, "errorType": "success" }, "sessionId": "d70073ae-0cdb-4bc4-b7d9-d8d0b16b98af" } From JSON code above, there is a fulfillment field. It has additional children fields that are actual responses from our agent which we are interested in. Also read: "Making your Apps “Chatable”" Notice the messages field? its value is a list. So we may assume our agent could return one or more messages when we make a request to DialogFlow. This could be another text or additional custom payload, such as payload for button or card. However, to simplify this process, let's handle text message only. Ok, let's modify our index() function in views.py file again. ... @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': payload = request.get_json().get('payload') room_id = payload.get("room").get("id") message = payload.get("message").get("text") # let's prepare the incoming message (query) we want to send to dialogflow agent conv = ai.text_request() conv.session_id = "ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)" conv.query = message # and let's get the response from dialogflow agent response = conv.getresponse() response_json =
  • 7. json.loads(response.read().decode('utf-8')) response_messages = response_json.get("result").get("fulfillment").get("messages") post_url = "{}/api/v2/rest/post_comment".format(qiscus_sdk_url) headers = {"QISCUS_SDK_SECRET": secret_key} for msg in response_messages: data = { "sender_email": sender_email, "room_id": room_id, "message": msg.get("speech"), "type": "text", "payload": {} } try: requests.post(post_url, headers=headers, params=data) except requests.exceptions.RequestException as e: print(e) return "Something went wrong!", 401 return "OK", 200 else: return render_template('index.html', appId=app_d, senderEmail=sender_email) ... save and let's run our webhook, and you may open http://locahost:5000 in your browser. $ make run
  • 8. 3. Webhook Since we've been developing this integration locally, Qiscus SDK won't recognise our webhook even though we are trying to add our local webhook address to the Qiscus SDK. So to help making our webhook open to the internet, we are going to use ngrok and add the generated temporary subdomain addresses into our Qiscus SDK, please refer to this for ngrok. After you do that, please try to have a chat again through generated subdomain address in your browser. Voila, you got a reply from your agent in DialogFlow! Accompanying codes can be found at https://github.com/qiscus/qiscus-dialogflow. You can also experience directly at https://qiscusdialog.herokuapp.com/. Closing To sum up, this article is only focusing on how we integrate our agent that is created in DialogFlow which returns plain text only. In order to leverage your agent capability, you may want to add additional custom payload as additional fulfillment response. For example you may want to return message that contains image and buttons from DialogFlow. You can refer to Qiscus docs for any type of comments that is supported by Qiscus as well as how to add custom payload in DialogFlow for more information.