Integrating Google Agent Builder Chat with Dialogflow CX API to Simple Web Flask

Siti Fatimatuzzahro
6 min readJul 24, 2024

--

Just as the title suggests, in this tutorial, I will explain how to integrating Google Agent Builder Chat to a simple web interface using Flask. By the end of this guide, you’ll know how to create your own ‘chatbot’ based on your documents using Google’s Agent Builder.

Google Agent Builder
According to Google, Agent Builder enables developers, including those with limited machine learning expertise, to leverage Google’s foundational models, search capabilities, and conversational AI technologies to develop enterprise-grade generative AI applications.

Simply put, Agent Builder is a Google solution that allows non-AI experts to build their own AI without writing code. Regardless of your background, you can build, configure, and deploy a virtual agent to assist customers with specific questions related to documents or information connected to the agent.

Agent Builder offers four types of applications: search, chat, recommendation, and agent. In this tutorial, we will focus on creating an Agent Builder chat to create your own chatbot.

Agent Builder: Chat
Before starting to build the chat app in Agent Builder, you’ll need the following:

  • Google Cloud Platform Account
  • Documents to be linked to the agent (imported to Google Storage)

After all these ready, you can just starting to set up chat agent with this following steps:

  1. Create an App in Agent Builder
    Go to Agent Builder and select “chat” from the options. Follow the prompts to complete the configuration.
Agent Builder dashboard
New app configuration
New app configuration

2. Connect the Agent to Data Storage

  • If you’ve already created a data storage table, you’ll be directed there. If not, create a new one.
Data storage list dashboard
  • Choose the source of your data. In this tutorial, I’ll use data saved in my bucket.
Data source options
Data source type
Existing data from my existing bucket
Last data storage configuration

After adding your data storage, check the table to see your new data. Select it and complete your app configuration. Once done, your chat app is ready to use. Verify its status in the Agent Builder dashboard.

3. Enable Dialogflow CX API

  • Use Dialogflow CX to integrate your chat bot with your app. Before enabling it, test your agent to ensure readiness.
  • Click ‘Publish’ and configure your API in the pop-up message.
Dialogflow CX
Pop-up message for configurating Dialogflow CX API

After configuration, you’ll receive JavaScript code with your agent’s details (project-id, agent-id, language-code). Simply copy and paste this code onto your website to deploy a chatroom widget instantly. Alternatively, save these details to integrate with your own UI.

Dialogflow CX API details

Integrating Dialogflow CX API with Flask

To integrate the Dialogflow CX API, we will use the Flask framework for our website. Let’s set up the folder structure as follows to neatly separate the code and make it easier to maintain:

/app
/app
__init__.py
/routes
__init__.py
routes.py
/services
__init__.py
gcp_chat.py
__init__.py
/static
/css
style.css
/js
chatroom.js
/templates
chatroom.html
.env
.gitignore
main.py
requirements.txt

For the backend, we will use Flask with the following route:

from flask import jsonify, render_template, request, Blueprint
from app.services.gcp_chat import detect_intent
import uuid
from . import app_routes

@app_routes.route('/')
def index():
return render_template('chatroom.html')

@app_routes.route('/chat', methods=['POST'])
def chat():
user_message = request.json['message']
session_id = request.json.get('session_id', str(uuid.uuid4()))

bot_response = detect_intent(session_id, user_message)

return jsonify({
'response': bot_response,
'session_id': session_id
})

To get response chat from Chat Agent, we will following this function:

from google.cloud import dialogflowcx_v3beta1 as dialogflow

project_id = "your project id"
location_id = o"your location id"
agent_id = "your agent id"
environment = "your environment (default: draft)"
language_code = "your languange code (default: en-us"


def detect_intent(session_id, text):
session_path = (
f"projects/{project_id}/locations/{location_id}/agents/{agent_id}/"
f"environments/{environment}/sessions/{session_id}"
)

session_client = dialogflow.SessionsClient()
text_input = dialogflow.TextInput(text=text)
query_input = dialogflow.QueryInput(text=text_input, language_code=language_code)
request = dialogflow.DetectIntentRequest(
session=session_path, query_input=query_input
)
response = session_client.detect_intent(request=request)
return response.query_result.response_messages[0].text.text[0]

For the frontend, we will use a simple UI with basic HTML, CSS, and JavaScript:

<!-- HTML code -->
<body>
<div id="body-chat">
<div id="chat-container">
<div id="navbar-chat">Test Agent</div>
<div id="chat-messages"></div>
<div id="user-input">
<input type="text" id="message-input" placeholder="Type your question...">
<div class="button-send" onclick="sendMessage()">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#C8E6C9" class="size-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12Zm0 0h7.5" />
</svg>
</div>
</div>
</div>
</div>
<script src="{{ url_for('static', filename='js/session.js') }}"></script>
</body>
/* CSS code */
@import url('https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css');

body {
font-family: 'Google Sans', Arial, sans-serif;
background-color: #EEF7EE;
margin: 0;
padding: 0;
}
#body-chat {
font-family: "Google Sans",Arial, sans-serif;
background-color: #EEF7EE;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#chat-container {
width: 400px;
height: 700px;
border: 1px solid #ccc;
border-radius: 12px;
display: flex;
flex-direction: column;
background-color: white;
}
#chat-messages {
flex: 1;
overflow-y: auto;
padding: 10px;
display: flex;
flex-direction: column;
}
#user-input {
display: flex;
padding: 10px 20px;
}
#user-input input {
flex: 1;
padding: 5px 10px;
border: 1px solid #ccc;
border-radius: 20px;
}
#user-input .button-send {
margin-left: 8px;
width: 40px;
cursor: pointer;
}
.message {
max-width: 70%;
padding: 8px 12px;
margin-bottom: 10px;
border-radius: 20px;
font-size: 14px;
line-height: 1.4;
}
.user {
background-color: #EEF7EE;
color: black;
align-self: flex-end;
border-bottom-right-radius: 0;
}
.bot {
background-color: #f1f1f1;
color: black;
align-self: flex-start;
border-bottom-left-radius: 0;
}
#chat-container #navbar-chat{
width: 400px;
background-color: #C8E6C9;
text-align: center;
padding: 20px 0px;
font-size: 18px;
font-weight: bold;
border-radius: 12px 12px 0px 0px;
}
// JavaScript code
let sessionId = null;

function addMessage(message, isUser) {
const chatMessages = document.getElementById('chat-messages');
const messageElement = document.createElement('div');
messageElement.classList.add('message');
messageElement.classList.add(isUser ? 'user' : 'bot');
messageElement.textContent = message;
chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
}

function sendMessage() {
const messageInput = document.getElementById('message-input');
const message = messageInput.value.trim();
if (message) {
addMessage(message, true);
messageInput.value = '';

fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
session_id: sessionId
}),
})
.then(response => response.json())
.then(data => {
addMessage(data.response, false);
sessionId = data.session_id;
})
.catch(error => {
console.error('Error:', error);
addMessage('Sorry, an error occurred.', false);
});
}
}

document.getElementById('message-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});

Here’s What You Get After Coding

After completing the code, here is the result: The Google Chat responds with default answers in English, even though the source content is in Indonesian. However, it can also understand questions asked in Indonesian because we used the default settings from the Agent.

Simple web for chatbot

Conclusion

That’s all for this tutorial, you can find the source code for this tutorial at this repository on GitHub. We can easily integrate the Dialogflow CX API into our website with a custom UI. Although the agent uses default settings and we can’t customize the prompts for different languages, the Agent Builder Chat is quite capable for handling basic Q&A tasks related to our documents.

--

--

Siti Fatimatuzzahro

Hi there! I'm an AI/ML enthusiast with a passion for pixels! 🎨✨ You'll often find me diving into cool AI projects or having fun with other tech stuff 😄🚀