Natural Language Processing
Senior 6 · ICT
Natural Language Processing
Lesson 5 of 5
25 min
Your Python bots match words or similar sentences. A parent who writes "how much does my daughter in senior five pay?" shares few words with any training question, yet clearly wants the S5 fees. Google's Dialogflow uses a machine-learning model trained on huge amounts of language to recognise the intent behind varied wording, and pulls out the details, such as the class, as entities. You design the conversation in a web console; Google runs the understanding; and the finished agent can be placed on a website or a messaging app.
Definition
Dialogflow: Google Cloud's platform for building conversational agents. It has two editions: ES (Essentials), the simpler, intent-based edition used in this lesson, and CX, an advanced edition for large flows, now part of Google Cloud's conversational-agent products.
Agent: one Dialogflow chatbot, with its intents, entities and settings.
Training phrase: an example of what a user might say for an intent. Parameter: a value extracted from the user's words by an entity, stored under a name such as class.
Fulfillment (webhook): a web service that Dialogflow calls when an intent is matched, to look up data or perform an action and return the reply.
The highlighted words in the training phrases are annotated as the entity @class. When a user writes "fees for senior five", the agent matches fees_for_class and fills the parameter class. If the user's message has no class, the required setting makes the agent ask the prompt and wait: this is called slot filling.
| Entity type | Example | Use |
|---|---|---|
| System entity | @sys.date, @sys.number, @sys.time | Built in: understands "next Friday", "twelve", "half past two" |
| Custom entity | @class with entries S1 … S6 and synonyms ("Senior 5", "S.5", "senior five") | Your own vocabulary |
dialogflow.cloud.google.com) with a Google account. Click Create agent, name it SchoolBot, choose English and the time zone (Africa/Kigali), and let it create a Google Cloud project. Two intents already exist: Default Welcome Intent and Default Fallback Intent.class with entries S1 to S6, each with synonyms such as "Senior 5", "S.5" and "senior five". Save.class as required and write its prompt. Add text responses. Create further intents (term_dates, documents, visiting) the same way.Worked example 1: trace a conversation
| Turn | User | Matched intent | Parameters | Agent replies |
|---|---|---|---|---|
| 1 | Muraho | Default Welcome Intent | none | A welcome message |
| 2 | How much does my daughter pay? | fees_for_class | class: missing | "Which class is the student in?" (the required prompt) |
| 3 | senior five | fees_for_class (continued) | class: S5 (synonym of S5) | The fees response with $class = S5 |
| 4 | Is there a swimming pool? | Default Fallback Intent | none | "Sorry, I didn't get that…" |
Turn 3 alone would mean nothing, but because the agent is filling the class slot it knows "senior five" is the answer to its question. Turn 4 matches no intent above the threshold, so the fallback answers instead of guessing.
Fixed text responses are enough for fixed facts. To look something up, for example the exact fee for the class, switch on Enable webhook call for this intent and give Dialogflow the address of your web service under Fulfillment. Dialogflow then sends your service a JSON request containing the matched intent and parameters, and speaks whatever fulfillmentText your service returns. This webhook uses the small web framework Flask:
from flask import Flask, request, jsonify
app = Flask(__name__)
FEES = {"S4": 95000, "S5": 98000, "S6": 98000} # Frw per term (illustrative)
@app.post("/webhook")
def webhook():
body = request.get_json(silent=True) or {}
result = body.get("queryResult", {})
intent = result.get("intent", {}).get("displayName", "")
params = result.get("parameters", {})
if intent == "fees_for_class":
cls = params.get("class", "")
fee = FEES.get(cls)
if fee is None:
text = f"Sorry, I have no fee for {cls or 'that class'}. Please ask the bursar."
else:
text = f"The fee for {cls} is {fee:,} Frw per term."
else:
text = "Sorry, I cannot help with that yet."
return jsonify({"fulfillmentText": text})
if __name__ == "__main__":
app.run(port=8080)
It was tested with Flask's built-in test client, which sends the same JSON shape that Dialogflow ES sends:
from webhook import app
client = app.test_client()
for cls in ["S5", "S2"]:
request_body = {"queryResult": {"queryText": f"How much is {cls}?",
"parameters": {"class": cls},
"intent": {"displayName": "fees_for_class"}}}
print(client.post("/webhook", json=request_body).get_json())
{'fulfillmentText': 'The fee for S5 is 98,000 Frw per term.'}
{'fulfillmentText': 'Sorry, I have no fee for S2. Please ask the bursar.'}To be used by Dialogflow, the webhook must run on a public HTTPS address, for example on a cloud host; a program on your own laptop is not reachable from Google's servers.
Under Integrations, Dialogflow ES offers ready-made connections. The simplest are a Web Demo page with its own link, and Dialogflow Messenger, a chat window you paste into any web page, such as the WordPress site from unit 2 (in a Custom HTML block):
<script src="https://www.gstatic.com/dialogflow-console/fast/messenger/bootstrap.js?v=1"></script>
<df-messenger
intent="WELCOME"
chat-title="SchoolBot"
agent-id="YOUR-AGENT-ID"
language-code="en"
></df-messenger>The console gives you this code with your real agent ID filled in. Other integrations connect the same agent to messaging apps such as Telegram. A Python program can also talk to the agent through the Dialogflow API; this sketch follows Google's client library, but it was not run here, because it needs a Google Cloud project and a service-account key:
# pip install google-cloud-dialogflow (needs a Google Cloud project and credentials)
from google.cloud import dialogflow
def ask(project_id, session_id, text):
client = dialogflow.SessionsClient()
session = client.session_path(project_id, session_id)
query = dialogflow.QueryInput(text=dialogflow.TextInput(text=text, language_code="en"))
response = client.detect_intent(request={"session": session, "query_input": query})
result = response.query_result
return result.intent.display_name, result.intent_detection_confidence, result.fulfillment_textGoogle Cloud Tech: Cloud OnAir, Building Chatbots with Dialogflow. Watch how intents, training phrases, entities and fulfillment fit together. The console in the recording is older than today's, so match the ideas to the steps above rather than the exact buttons.
Worked example 2: Dialogflow or ChatterBot?
A district education office wants a bot for 30,000 parents to ask about school calendars, fees and enrolment, on its website and a messaging app, in English and Kinyarwanda.
Dialogflow is the stronger choice for understanding and reach; ChatterBot is better for a small, offline, fully local project where you control everything.
Warning
Keep keys out of code and classrooms. A Google Cloud service-account key is a password to your project, and charges can follow it. Never paste it into a program you share, upload it to a public repository, or send it in a chat. Delete agents and keys you no longer use.
Tip
Ten phrases, three shapes. For each intent, write training phrases in at least three shapes: a full question ("How much are the S5 fees?"), a short fragment ("S5 fees"), and an indirect one ("my son is going into senior five, what do we pay?"). Variety teaches the model more than repetition.
class entity and four intents from the school office's list, each with at least ten training phrases and a required parameter where needed.Check: at least 13 of your 15 test messages reach the right intent with the right parameters, and an off-topic question reaches the fallback.
Practice
{"fulfillmentText": "The fee for S4 is 95,000 Frw per term."}Further reading
Sources and credits
This lesson adapts CC BY-SA material and is shared under CC BY-SA 4.0.