0% found this document useful (0 votes)
13 views

Miniproject

Uploaded by

Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Miniproject

Uploaded by

Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

ABSTRACT

As a result of rapid technological advancements and the evolving concept of automated


customer service, specialized frameworks have emerged to facilitate the creation and
development of chatbots. By leveraging artificial intelligence, these chatbots integrate machine
learning, allowing them to adapt and become more effective across various service-oriented
fields. In this project, we have developed a chatbot for a restaurant setting, aimed at
streamlining the process of placing and tracking orders, checking promotional offers, and
providing operational information.

The motivation behind this project stems from a need to enhance the dining experience by
reducing wait times and improving service efficiency, particularly during peak hours. Unlike
other systems typically found in restaurant management, this chatbot targets a broader audience
including casual diners and regular customers who seek a quick and interactive way to order
their meals.

This project is significant as it not only answers frequent and common queries related to menu
options and restaurant services but also provides these answers promptly at any time desired
by the user.

This alignment with advanced technological methodologies ensures that the restaurant chatbot
can effectively handle interactions, making it a valuable tool for modern restaurant
management and customer service.
TABLE OF CONTENT

1. INTRODUCTION 1

1.1. INTRODUCTION 2

1.2. PROBLEM STATEMENT 2

1.3. OBJECTIVES 3

2. CHATBOTS 4

2.1. CHATBOT 5

2.2. TYPES 5

2.3. HOW DO THEY WORK? 5

2.4. HOW TO BUILD ONE? 6

2.5. SELECTED PLATFORM 7

3. REQUIREMENTS 9

3.1. FUNCTIONAL REQUIREMENTS 10

3.2. NON-FUNCTIONAL REQUIREMENTS: 10

4. SYSTEM ARCHITECUTRE 12

4.1. ARCHITECTURE 13

4.2. DIAGRAMMATIC REPRESENTATION 16

4.3. FLOW CHART 17

5. IMPLEMENTATION 18

5.1. CREATING INTENTS IN DIALOGFLOW: 19

5.2. TRAINING 20

5.3. ENTITY CREATION & MAPPING 22

5.4. BACKEND INTEGRATION 25

6. TESTING & VALIDATION 27

6.1. TESTING CRITERIA 28

6.2. TESTING PLAN 30


7. CONCLUSION 31

8. REFRENCES 33

9. APPENDIX 35

9.1. CONVERSATIONS SCREENSHOT 36

9.2. DATABASE SCREENSHOTS 38

9.3. CODE OVERVIEW 39


1. INTRODUCTION
1
1.1. INTRODUCTION
A chatbot is a software application designed to simulate conversation with human users
over the internet. These interactive agents use natural language processing (NLP) to understand
and respond to user inputs, making them effective tools for automating customer service and
other communication tasks. In the hospitality industry, chatbots are increasingly being
leveraged to enhance customer engagement, streamline service processes, and improve
operational efficiencies.

In this context, our project focuses on developing a restaurant chatbot that assists customers by
facilitating order placement, offering promotions and discounts, checking operational hours,
and tracking order statuses. By integrating principles of natural language processing (NLP) and
natural language understanding (NLU), this chatbot is capable of understanding and interacting
in a conversational manner, closely mimicking human-like interactions.

1.2. PROBLEM STATEMENT


In the fast-paced restaurant industry, traditional methods of order taking and customer
service often lead to inefficiencies and challenges during peak hours. Restaurant staff are
frequently overwhelmed by the influx of customer inquiries and orders, resulting in longer wait
times, order errors, and a diminished dining experience. Additionally, the lack of a dedicated
digital solution leaves restaurants struggling to meet evolving customer expectations for
convenience and instant access to information.

To address these challenges, our project aims to develop a restaurant chatbot—a


sophisticated digital assistant powered by artificial intelligence and natural language
processing. This chatbot will revolutionize the way restaurants interact with customers,
providing a seamless conversational interface for order placement, inquiries, and assistance.
By enhancing customer satisfaction, streamlining order management processes, and improving
operational efficiencies, the restaurant chatbot will modernize and elevate the dining
experience, ensuring restaurants can effectively meet the evolving needs of their customers in
today's digital landscape.

2
1.3. OBJECTIVES
a) Enable customers to place orders, track them, and make inquiries seamlessly through
the chatbot, saving time and simplifying the ordering process.
b) Automate the ordering process to reduce workload on restaurant staff and minimize
errors, thereby improving overall service quality.
c) Offer customers real-time updates on the status of their orders from preparation through
to delivery, ensuring transparency and improving service satisfaction.

3
2. CHATBOTS

4
2.1. CHATBOT
A chatbot is a computer program that can simulate a conversation or chat with a user in natural
language through messaging applications, website, or mobile applications and interact with
users according to their input and should be available 24/7. Chatbots are developed and became
so popular due to the increased use of smart devices and IoT technology.

2.2. TYPES
a. Base-line chatbot: It is a chatbot that is based on a database and uses if / then logic to
create a conversation flow and that takes a lot of time to ensure the understanding of
the question and the answer needed.[1]
b. AI chatbot: This type of chatbot is more complex than base-line but it is more
interactive and personalized and needs big data training to be impressive if the problem
is matched to their capabilities.[2]
c. Hybrid Model: A hybrid approach mixes the Base-line & AI chatbot to make it smart
and his behavior more expected by depending on database and Ai algorithm to work
together.[3]

2.3. How do they work?


A chatbot is an AI-based software program designed to interact with users via text or speech
in a conversational manner. Here's how a typical chatbot works:

a) User Input: The interaction begins when a user sends a message or query to the chatbot.
This input can be in the form of text typed into a chat interface or spoken words captured
by a speech recognition system.
b) Natural Language Processing (NLP): The chatbot's underlying system processes the
user input using natural language processing (NLP) algorithms. NLP enables the
chatbot to understand the meaning and context of the user's message, including parsing
text for keywords, identifying intent, and extracting relevant information.
c) Intent Recognition: Based on the user input, the chatbot determines the user's intent
or what action they want to perform. Intent recognition involves categorizing the user's
message into predefined categories or actions, such as placing an order, asking a
question, or requesting assistance.

5
d) Response Generation: Once the user's intent is identified, the chatbot generates a
response to address the user's query or fulfill their request. This response can be pre-
programmed text, dynamically generated content, or a combination of both, tailored to
provide relevant information or assistance based on the context of the conversation.

2.4. How to build one?


a) From Scratch
At first, we have to identify the opportunities for our chatbot and decide its
field and scope to achieve efficiency and accuracy. and a precise understanding
of the customer needs is required to solve the operational challenges. Then the
design of the bot comes to be a significant stage to decide the user engagement
with your app or website. and we can categorize chatbot interactions as
structured and unstructured interactions.

• Structured interaction. You already know about this kind of interaction.


You know what your customers will ask and can design it easily — it's
just like an FAQ section of your app or website [4]. This information
will link to your contact information, services, products, etc.
• Unstructured interaction. The unstructured conversation flow includes
freestyle plain text. It's hard to predict what queries will emerge and it
looks like an extempore speech competition for your chatbot. the role
of AI comes to lights here, it decodes the context of the text based on
NLP analysis. while the same NLP will provide a voice to the
chatbot.[5]

The later choice will need specialized chatbot developers with an


understanding of programming languages, machine learning, and AI. We can
use some of the code-based frameworks to build and handle the chatbot like
wit.ai and api.ai.

b) Using Platforms
It is similar to scratch chatbots but the only difference is that you do not have
to hire a specialized developer and use the chatbot builder platforms like
Google Dialogflow, IBM Watson, Botsify and Rasa, it’s not hard or impossible

6
to achieve it. but it’s not possible to create an NLP-enabled chatbot that can
deal with unstructured data.

• IBM Watson: is touted as a question-and-answer system that can be


used to build applications and chatbots. The IBM Watson platform
allows us to create an application that shares a dialog interaction
between our chatbot and users on Quick n’ Easy Projector Rentals. The
IBM interface is simple to use, and no back-end coding is shown at first
glance. The chatbot can be easily integrated into other applications such
as Slack, Facebook, and Twilio.

• Google Dialogflow: is an easy-to-understand conversational agent.


Theoretically, we can have a bot up and running by understanding 3
core concepts: intents, entities, and dialog control. As stated earlier,
these general concepts are followed across a majority of the chatbot
platforms we played with.
• Rasa: is an open source chatbot that is equipped with a natural language
processing tool. The open-source tool is called Rasa NLU. You can
tweak and customize the machine learning algorithm that Rasa uses so
that you can create a model that provides the results you desire. Rasa
NLU can be run wherever you want it to, and none of your training data
has to be passed over to Google, Microsoft, Amazon, or Facebook to
train your chatbot.

2.5. Selected Platform

We selected Google Dialogflow as the cornerstone of our chatbot development


strategy. Dialogflow's robust features, advanced natural language understanding
capabilities, and seamless integration options align closely with our project
requirements and objectives.

7
Advantages of Google Dialogflow:

• High Customizability: Dialogflow offers a high degree of customizability,


allowing us to tailor the chatbot's behavior and functionality to meet our
specific needs. With support for various pipelines, we can employ different
strategies for processing user dialogues, ensuring optimal performance and
responsiveness.
• Flexible Deployment Options: Dialogflow provides seamless integration
options, enabling deployment as a simple HTTP server or programmatically
via Python APIs. This versatility facilitates smooth integration with existing
systems and workflows, enhancing overall efficiency and effectiveness.
• Robust NLU Capabilities: Dialogflow's advanced natural language
understanding (NLU) engine empowers us to achieve sophisticated language
understanding and intent recognition. With state-of-the-art machine learning
algorithms, we can mimic other commercial NLP platforms and seamlessly
transition existing applications to Dialogflow's ecosystem.

Disadvantages of Google Dialogflow

• Resource Intensive: Dialogflow may require significant server resources,


particularly when utilizing memory-intensive components like the Spacy
library. This can pose challenges in terms of server requirements and resource
allocation.

• Learning Curve: The installation, configuration, and training phases of


Dialogflow may require machine learning expertise, presenting a learning
curve for users without prior experience. This could potentially impact the ease
of adoption and implementation of the platform.
• Limited Contextual Support: Dialogflow may lack out-of-the-box support
for context-based conversation, necessitating additional programming to
maintain context within the chat service. This could introduce complexity and
overhead in managing conversational context effectively.

8
3. REQUIREMENTS
9
3.1. Functional Requirements

a) The chatbot system must provide a menu of available food items, including
descriptions, prices, and dietary information.
b) The chatbot should facilitate the ordering process by guiding users through
menu options and assisting with selection confirmation.
c) The system should support the addition and removal of items from the user's
order, allowing for real-time adjustments before finalizing the purchase.
d) The system should allow users to track the status of their orders, providing
updates on preparation, cooking, and delivery progress as applicable.
e) The system should generate order confirmation messages upon successful
completion of a transaction, including order details and receipt information for
user reference.

3.2. Non-Functional Requirements:

a) The chatbot system must respond promptly to user interactions, minimizing


response times to enhance user satisfaction and efficiency during the ordering
process.
b) The chatbot should simulate natural conversation flow by incorporating delays
in responses, creating a conversational experience that feels engaging and
human-like.
c) The system should maintain an accurate and up-to-date database of menu items,
prices, and promotions, ensuring that users receive reliable information during
interactions.
d) The chatbot's training data should be tailored to food-related inquiries, focusing
on menu descriptions, order processing logic, and customer service scenarios
relevant to the food industry.

10
e) The system should employ filters or algorithms to detect and filter out
inappropriate language or content, preserving a family-friendly and respectful
environment for users.
f) The system should be designed with scalability in mind, accommodating
potential future expansions such as additional menu items, seasonal
promotions, or integration with third-party delivery services.

11
4. SYSTEM ARCHITECUTRE
12
4.1. Architecture

Figure 1

a) Agents: A Dialogflow agent is a virtual agent that handles concurrent conversations


with your end-users. It is a natural language understanding module that understands the
nuances of human language. Dialogflow translates end-user text or audio during a
conversation to structured data that your apps and services can understand. You design
and build a Dialogflow agent to handle the types of conversations required for your
system.
b) Intents: An intent categorizes an end-user's intention for one conversation turn. For
each agent, you define many intents, where your combined intents can handle a
complete conversation. When an end-user writes or says something, referred to as
an end-user expression, Dialogflow matches the end-user expression to the best intent
in your agent. Matching an intent is also known as intent classification.

Figure 2

A basic intent contains the following:


• Training phrases: These are example phrases for what end-users might say.
When an end-user expression resembles one of these phrases, Dialogflow
matches the intent. You don't have to define every possible example, because

13
Dialogflow's built-in machine learning expands on your list with other, similar
phrases.
• Action: You can define an action for each intent. When an intent is matched,
Dialogflow provides the action to your system, and you can use the action to
trigger certain actions defined in your system.
• Parameters: When an intent is matched at runtime, Dialogflow provides the
extracted values from the end-user expression as parameters. Each parameter
has a type, called the entity type, which dictates exactly how the data is
extracted. Unlike raw end-user input, parameters are structured data that can
easily be used to perform some logic or generate responses.
• Responses: You define text, speech, or visual responses to return to the end-
user. These may provide the end-user with answers, ask the end-user for more
information, or terminate the conversation.

The following diagram shows the basic flow for intent matching and responding to the
end-user:

Figure 3

c) Fulfillment is the last piece in the puzzle, it is the code that you write to interface with
backend services to respond to a dynamic request. Dialogflow has inbuilt integration with
Google Cloud Functions to interface with your backend. You can also provide any other
custom HTTPS endpoint to connect Dialogflow to your backend.

14
Figure 4

d) Entities
There is a type of every intent parameter, which is known as an Entity type. The task
performed by the end-user is to explain how data can be extracted from the end-user
expression. The Dialogflow offers you a various system entity which are predefined,
which is able to match various types of common data. For example, there are various
types of system entities for matching email addresses, colors, time, date, etc. For
matching custom data, we can also make our custom entities. For example: we can
define a fruit entity that matches the kinds of the fruits which are available to buy with
the agent of a grocery store.

e) Context

The context of Dialogflow is the same as a natural language context. When a person
tells you, "they are blue," you have to grasp the context to know which they are referring
to. In the same way, for Dialogflow, in order to handle an end-user expression, the
Dialogflow context must be provided to match an intent appropriately.

To handle the flow of the conversation, contexts are used. By setting input and output
contexts, that are recognized by the string names, we can configure the contexts for the
intents. If the intent is matched, then for that intent, any configured output context will
15
be active. When the contexts are in the active state then the Dialogflow try to match
intent configured to the input contexts which is corresponding to the contexts which are
presently active.

4.2. Diagrammatic Representation

Diagrammatic Representation of the complete architecture we used for this project:

Figure 5

16
4.3. Flow Chart

Figure 6

17
5. IMPLEMENTATION

18
5.1. Creating Intents in Dialogflow:

a. Welcome Intent: This intent is triggered when a user initiates a conversation with the
chatbot. Its purpose is to greet the user and provide a friendly welcome message, setting
the tone for the interaction.

b. Fallback Intent: This intent is triggered when the chatbot is unable to understand the
user's input or when the user's message does not match any existing intents. Its purpose
is to handle unexpected or ambiguous user inputs gracefully and guide the user back on
track.

c. order.add - context: ongoing-order: This intent is triggered when the user wants to add
items to their order. Its purpose is to handle the process of adding food items to the
current order being created by the user.

d. order.remove - context: ongoing-order: This intent is triggered when the user wants to
remove items from their order. Its purpose is to manage the process of removing specific
food items from the current order.

e. order.complete - context: ongoing-order: This intent is triggered when the user indicates
that they have finished adding items to their order and want to complete the ordering
process. Its purpose is to finalize the order, save it to the database, and provide
confirmation to the user.

f. track.order - context: ongoing-tracking: This intent is triggered when the user wants to
track the status of their order. Its purpose is to retrieve information about the current
status of the user's order from the database and provide it to the user.

g. check.operational.hours: This intent is triggered when the user inquires about the
operational hours of the restaurant or food establishment. Its purpose is to provide
information about the opening and closing hours of the restaurant on a given day.

19
h. Each intent serves a specific function within the chatbot's conversation flow, allowing
users to interact with the system to place orders, make inquiries, and track their orders
effectively.

Figure 7

5.2. Training
Training the intents involves providing sufficient examples of user queries or
utterances that correspond to each intent. This process allows the chatbot to learn and
understand the different ways users may express their intentions during interactions. Here's
how training is typically done for each intent:

a) Welcome Intent: Include variations of greetings and opening phrases that users may use
to start a conversation, such as "Hi", "Hello", "Good morning", or "Hey there".

20
b) Fallback Intent: Include a diverse set of examples representing common
misunderstandings, typos, or ambiguous inputs that users might provide. These examples
help the chatbot recognize when it needs to trigger the fallback response.

c) Order.Add - Context: Ongoing-Order: Provide examples of user requests to add items to


their order, such as "I'd like to order a pizza", "Can I add fries to my order?", or "Add a
soda to my order".

d) Order.Remove - Context: Ongoing-Order: Offer examples of user requests to remove


items from their order, such as "Remove the salad from my order", "I changed my mind
about the dessert", or "Take off the extra cheese from my pizza".

e) Order.Complete - Context: Ongoing-Order: Include examples of user statements


indicating they have finished adding items to their order and are ready to complete the
ordering process, such as "I'm done ordering", "That's all for my order", or "Place my
order now".

f) Track.Order - Context: Ongoing-Tracking: Provide examples of user queries to track the


status of their order, such as "Where is my order?", "Can you check the status of my
delivery?", or "I'd like to know when my food will arrive".

g) Check.Operational.Hours: Offer examples of user inquiries about the operational hours


of the restaurant or food establishment, such as "What time do you open?", "Are you open
on weekends?", or "When does the kitchen close?".

During training, it's essential to include a diverse range of examples that capture the
different ways users may express similar intents. This helps the chatbot generalize and
respond accurately to a variety of user inputs during real interactions. Additionally, ongoing
monitoring and refinement of the training data based on user feedback and observed
interactions can further improve the chatbot's performance over time.

21
Figure 8

5.3. Entity Creation & Mapping

a) Creation

Entities are essential components in understanding and processing user inputs


accurately. In the context of our food ordering chatbot project, the following entities are
crucial:

• Food Items: Create entities for various food items available for ordering, such as
"pizza", "burger", "sushi", "salad", "sandwich", "pasta", "smoothie", etc. Include
synonyms and variations to ensure robust recognition.

• Quantities: Define an entity for quantities to capture the number of servings or items
ordered, such as "one", "two", "three", "small", "medium", "large", etc. Consider
including numerical values as entities for precise quantity extraction.

22
• Order Actions: Create entities to represent actions related to ordering, such as "add",
"remove", "cancel", or "modify". These entities help the chatbot understand the
user's intent regarding their order management.

b) Entity Mapping:

Mapping entities to intents and slot types is essential for the chatbot to comprehend
user inputs accurately and fulfill their requests effectively. Here's how we can map entities
in our food ordering chatbot:

▪ Intent Mapping: Associate each entity with the intents where they are relevant. For
example:
• Map food item entities to the "order.add" intent for adding items to the order.
• Map quantities entities to the "order.add" intent to specify the quantity of
each food item.
• Map special request entities to intents such as "order.add" or "order.modify"
to accommodate customizations.

▪ Context Management: Use entity mapping to manage conversation context


effectively. Ensure that entities are mapped appropriately to ongoing contexts to
maintain coherence in user interactions. For example:
• Maintain context during order modification or customization to track
changes accurately.
• Use entity mapping to handle follow-up questions or prompts based on
previous user inputs.

▪ Fallback Handling: Utilize entity mapping to facilitate fallback responses when


entities cannot be extracted accurately. If critical entities are missing or ambiguous,
prompt the user for clarification or provide default actions based on context to
ensure a seamless user experience.

23
By meticulously designing and mapping entities in our food ordering chatbot, we can
enhance its ability to understand user inputs, facilitate smoother interactions, and
ultimately deliver a satisfying ordering experience for users.

Food-item is our entity consisting


of multiple food items which are
available in the restaurant

Figure 9

Here, In the order.add intent, the


training phrases are highlighted
with yellow and orange colors
indicating the entities are mapped
accordingly.
The orange texts are food item,
while the default entity sys-
number is used for ‘quantity’.

Figure 10

24
5.4. Backend Integration
Backend integration with Python and a Database Management System (DBMS) using
fulfillment and webhooks is crucial for the functionality of a chatbot. Here's an
explanation of how it works:

a) Python Backend:
i. Python serves as the backend programming language for implementing
the business logic and handling user requests in the chatbot application.
ii. In the context of our food ordering chatbot, the Python backend receives
user inputs and processes them to determine the appropriate responses.
iii. The backend interacts with the DBMS to fetch or update data related to
food items, orders, user preferences, etc.
iv. Python frameworks such as FastAPI or Flask are commonly used to
build the backend infrastructure for handling HTTP requests and
responses.
b) DBMS Integration:
i. The DBMS (e.g., MySQL, PostgreSQL) stores and manages the data
required for the chatbot application, such as food item details, order
information, user profiles, etc.
ii. The Python backend interacts with the DBMS through database
connectors or ORMs (Object-Relational Mapping) to perform CRUD
(Create, Read, Update, Delete) operations on the database.
iii. Queries are constructed in Python to retrieve or manipulate data in the
DBMS based on user requests and application logic.

c) Fulfillment:
i. Fulfillment refers to the process of generating responses to user queries
or actions in the chatbot application.
ii. In our scenario, the fulfillment logic is implemented in Python backend
functions or methods.
iii. When a user interacts with the chatbot and triggers an intent (e.g.,
placing an order, querying operational hours), the corresponding
fulfillment function is executed to generate a response.

25
iv. The fulfillment function may involve querying the database to retrieve
relevant information (e.g., food item details, order status) and formatting
the response for the user.

d) Webhooks:
i. Webhooks are endpoints in the backend application that receive HTTP
POST requests from external services, such as chatbot platforms like
Dialogflow.
ii. In the context of our chatbot, Dialogflow sends user queries to the
webhook endpoint configured in the fulfillment section.
iii. The Python backend processes the webhook request, extracts relevant
information (e.g., user input, parameters), executes the appropriate logic
(e.g., intent handling, database operations), and sends back a response
to Dialogflow.
iv. Webhooks facilitate real-time communication between the chatbot
platform and the backend application, enabling dynamic interaction and
response generation based on user inputs.

By integrating Python backend with a DBMS using fulfillment and webhooks, we


establish a robust architecture for our chatbot application, enabling seamless user interactions,
efficient data management, and personalized responses tailored to user queries and actions.

26
6. TESTING & VALIDATION

27
6.1. Testing Criteria
a) Chatbot Testing Criteria

Building a reliable and engaging chatbot requires thorough testing. Here are key criteria to
consider:

1. Data Quality and Validation:


a. Pre-training Checks: Similar to Rasa's data validation, ensure your training
data is clean and free of errors. Utilize built-in validation tools or develop
custom checks for inconsistencies.
b. Strict Validation: Consider enabling stricter validation options to catch even
minor issues before training. This helps prevent potential training failures or
subpar performance.
2. Test Conversations:
a. Simulations: Leverage built-in simulators or dedicated testing platforms to
hold simulated conversations with your chatbot. This allows manual exploration
of various scenarios and identification of weaknesses.
b. Scripted Test Cases: Develop pre-defined conversations with expected
responses. These "test cases" serve as benchmarks to evaluate the chatbot's
ability to handle specific situations.
3. Conversation Flow Evaluation:
a. Intent Recognition Accuracy: Test how effectively the chatbot understands
user queries phrased differently. Use synonyms, variations, and natural
language to ensure robust intent detection.
b. Response Speed and Relevance: Assess the speed of the chatbot's responses
and ensure they are directly relevant to the user's questions. Ideally, responses
should be near-instantaneous and provide accurate information.
c. Multiple Questions Handling: Verify how the chatbot handles follow-up
questions within a conversation. The chatbot should maintain context and guide
the user towards a resolution without needing repeated information.
d. User Engagement: Observe if the chatbot uses conversational techniques to
keep users engaged. This might include prompts, questions, or informative
messages to encourage further interaction.

28
4. Domain-Specific Testing:
a. Industry-Tailored Questions: Develop a comprehensive list of questions
specific to your chatbot's domain or industry. Test the chatbot's ability to answer
these questions using relevant terminology.
5. Error Handling and Robustness:
a. Ambiguity Management: Evaluate the chatbot's ability to handle ambiguous
phrases or questions with multiple interpretations. Ideally, the chatbot should
clarify or offer different possibilities.
b. Unknown Information Handling: Test how the chatbot reacts to out-of-
vocabulary words, typos, or unexpected user inputs. It should provide
informative responses or offer to escalate the issue to a human agent.
6. Continuous Improvement:
Regularly test and refine your chatbot throughout development. Analyze real
user interactions to identify areas for improvement. Test edge cases that may
not be common but could still occur. By iteratively testing and refining, you can
ensure your chatbot delivers an exceptional user experience.

b) Classic Criteria
The classic criteria in the software test. By testing the software at and around critical
points, and what it accepts and what it does not accept. The software is also presented to a
group of people to be tested and examined based on interactions and data with humans.

29
6.2. Testing Plan

a) Features to be tested
Tested features will be those features that the bot has been trained on and given all the
necessary information and data about these features.

User input/intent Bot Action


Welcome Intent Response_Welcome Intent

Fall Back Intent Response_Fall Back Intent

new.order intent Response_new.order intent

Order.add intent Response_Order.add intent

Order.complete Response_Order.complete

Order.remove Response_Order.remove

Track.order Response_Track.order

Operational-hours Response_Operational-hours

Check.operational hours Response_Check.operational


hours

b) Testing Environment
The testing of the bot was completed on the local host environment by hosting
the bot using NG Rock software, which creates a link that enables users outside the
local environment to access and interact with the bot.

30
7. CONCLUSION
31
This chatbot was designed to streamline the food ordering process for customers, providing
a user-friendly interface that simplifies menu browsing and order customization. By
integrating with a backend database and utilizing webhooks for real-time updates, the bot
efficiently manages incoming orders, updates kitchen workflows, and tracks order status,
ensuring that customers receive timely and accurate updates about their food.

The system not only enhances customer interaction by providing details about the
restaurant's operational hours and responding to frequently asked questions but also
supports the restaurant staff by reducing the workload associated with phone orders and
manual order tracking. Through the integration of the Dialogflow platform and FastAPI,
the chatbot ensures seamless communication between the customers and the restaurant’s
management system, thus improving overall service delivery.

Additionally, the chatbot provides a platform for the restaurant to expand its digital
presence, facilitating easy scalability and updates to the menu and services as the business
evolves. It introduces potential efficiencies in handling peak traffic times and special
promotions, contributing positively to the restaurant's operational capabilities.

In conclusion, this project not only showcases the application of artificial intelligence in
enhancing customer service in the restaurant industry but also sets a foundation for future
enhancements such as integration with more sophisticated AI features for personalized
recommendations based on customer preferences and order history. This initiative not only
elevates the customer experience but also supports the restaurant's staff in maintaining high
service standards, ultimately contributing to increased customer satisfaction and business
growth.

Future Improvements: The project scope for the food ordering chatbot could be expanded
to include features such as voice command capabilities, integration with kitchen
management systems, and support for digital payments to streamline the entire dining
experience. Future enhancements might also involve personalization algorithms for dish
recommendations based on user preferences, multilingual support for diverse customer
bases, and the integration of loyalty programs to enhance user engagement and satisfaction.

32
8. REFRENCES
33
1. “Dialogflow ES basics.”
https://cloud.google.com/dialogflow/es/docs/basics
2. “Dialogflow Architecture.”
https://medium.com/google-cloud/deconstructing-chatbots-getting-started-with-
dialogflow-4f91deb32135
3. “Natural Language Processing.”
https://www.geeksforgeeks.org/natural-language-processing-nlp-tutorial/
4. “CodeBasics NLP – Tutorial.”
https://youtube.com/playlist?list=PLeo1K3hjS3uuvuAXhYjV2lMEShq2UYSwX&si=fgN
qZuFM16vlYYu3
5. “Gemini.”
https://gemini.google.com/
6. Installation:
https://www.mysql.com/products/workbench/
https://dialogflow.cloud.google.com/

34
9. APPENDIX

35
9.1. Conversations Screenshot
a) Ordering

36
b) Track Order

c) Operational hours

37
9.2. Database Screenshots
a) Table - food_items

b) Table – orders

c) Table – orders_tracking

38
9.3. Code Overview
a) main.py

from fastapi import FastAPI


from fastapi import Request
from fastapi.responses import JSONResponse
import db_helper
import generic_helper
from datetime import datetime, time

app = FastAPI()

inprogress_orders = {}

@app.post("/")
async def handle_request(request: Request):
# Retrieve the JSON data from the request
payload = await request.json()

# Extract the necessary information from the payload


# based on the structure of the WebhookRequest from Dialougflow
intent = payload['queryResult']['intent']['displayName']
parameters = payload['queryResult']['parameters']
output_contexts = payload['queryResult']['outputContexts']
session_id = generic_helper.extract_session_id(output_contexts[0]["name"])

intent_handler_dict = {
'order.add - context: ongoing-order': add_to_order,
'order.remove - context: ongoing-order': remove_from_order,
'order.complete - context: ongoing-order': complete_order,
'track.order - context: ongoing-tracking': track_order,
'check.operational.hours': check_operational_hours
}

39
return intent_handler_dict[intent](parameters, session_id)

open_time = time(9, 0) # Opens at 9 AM


close_time = time(23, 0) # Closes at 11 PM

def check_operational_hours(parameters: dict, session_id: str):


now = datetime.now().time() # Get current time
# Check if current time is within operational hours
if open_time <= now <= close_time:
message = "Yes, we are open now!"
else:
message = "Sorry, we are closed now. We open every day from 9 AM to 11 PM."

return JSONResponse(content={
"fulfillmentText": message
})

def save_to_db(order: dict):


next_order_id = db_helper.get_next_order_id()

# Insert individual items along with quantity in orders table


for food_item, quantity in order.items():
rcode = db_helper.insert_order_item(
food_item,
quantity,
next_order_id
)

if rcode == -1:
return -1

# Now insert order tracking status


db_helper.insert_order_tracking(next_order_id, "in progress")
40
return next_order_id

def complete_order(parameters: dict, session_id: str):


if session_id not in inprogress_orders:
fulfillment_text = "I'm having a trouble finding your order. Sorry! Can you place
a new order please?"
else:
order = inprogress_orders[session_id]
order_id = save_to_db(order)
if order_id == -1:
fulfillment_text = "Sorry, I couldn't process your order due to a backend error.
"\
"Please place a new order again"
else:
order_total = db_helper.get_total_order_price(order_id)

fulfillment_text = f"Awesome. We have placed your order. " \


f"Here is your order id # {order_id}. " \
f"Your order total is {order_total} which you can pay at the time of
delivery!"

del inprogress_orders[session_id]

return JSONResponse(content={
"fulfillmentText": fulfillment_text
})

def add_to_order(parameters: dict, session_id: str):


food_items = parameters["food-item"]
quantities = parameters["number"]

if len(food_items) != len(quantities):
41
fulfillment_text = "Sorry I didn't understand. Can you please specify food items
and quantities clearly?"
else:
new_food_dict = dict(zip(food_items, quantities))

if session_id in inprogress_orders:
current_food_dict = inprogress_orders[session_id]
current_food_dict.update(new_food_dict)
inprogress_orders[session_id] = current_food_dict
else:
inprogress_orders[session_id] = new_food_dict

order_str =
generic_helper.get_str_from_food_dict(inprogress_orders[session_id])
fulfillment_text = f"So far you have: {order_str}. Do you need anything else?"

return JSONResponse(content={
"fulfillmentText": fulfillment_text
})

def remove_from_order(parameters: dict, session_id: str):


if session_id not in inprogress_orders:
return JSONResponse(content={
"fulfillmentText": "I'm having a trouble finding your order. Sorry! Can you
place a new order please?"
})

food_items = parameters["food-item"]
current_order = inprogress_orders[session_id]

removed_items = []
no_such_items = []

42
for item in food_items:
if item not in current_order:
no_such_items.append(item)
else:
removed_items.append(item)
del current_order[item]

if len(removed_items) > 0:
fulfillment_text = f'Removed {",".join(removed_items)} from your order!'

if len(no_such_items) > 0:
fulfillment_text = f' Your current order does not have {",".join(no_such_items)}'

if len(current_order.keys()) == 0:
fulfillment_text += " Your order is empty!"
else:
order_str = generic_helper.get_str_from_food_dict(current_order)
fulfillment_text += f" Here is what is left in your order: {order_str}"

return JSONResponse(content={
"fulfillmentText": fulfillment_text
})

def track_order(parameters: dict, session_id: str):


order_id = int(parameters['order_id'])
order_status = db_helper.get_order_status(order_id)
if order_status:
fulfillment_text = f"The order status for order id: {order_id} is: {order_status}"
else:
fulfillment_text = f"No order found with order id: {order_id}"

return JSONResponse(content={
"fulfillmentText": fulfillment_text
43
})

b) db_handler.py

import mysql.connector
global cnx

cnx = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="kichudb"
)

# Function to call the MySQL stored procedure and insert an order item
def insert_order_item(food_item, quantity, order_id):
try:
cursor = cnx.cursor()

# Calling the stored procedure


cursor.callproc('insert_order_item', (food_item, quantity, order_id))

# Committing the changes


cnx.commit()

# Closing the cursor


cursor.close()

print("Order item inserted successfully!")

return 1
44
except mysql.connector.Error as err:
print(f"Error inserting order item: {err}")

# Rollback changes if necessary


cnx.rollback()

return -1

except Exception as e:
print(f"An error occurred: {e}")
# Rollback changes if necessary
cnx.rollback()

return -1

# Function to insert a record into the order_tracking table


def insert_order_tracking(order_id, status):
cursor = cnx.cursor()

# Inserting the record into the order_tracking table


insert_query = "INSERT INTO order_tracking (order_id, status) VALUES (%s,
%s)"
cursor.execute(insert_query, (order_id, status))

# Committing the changes


cnx.commit()

# Closing the cursor


cursor.close()

def get_total_order_price(order_id):
cursor = cnx.cursor()

45
# Executing the SQL query to get the total order price
query = f"SELECT get_total_order_price({order_id})"
cursor.execute(query)

# Fetching the result


result = cursor.fetchone()[0]

# Closing the cursor


cursor.close()

return result

# Function to get the next available order_id


def get_next_order_id():
cursor = cnx.cursor()

# Executing the SQL query to get the next available order_id


query = "SELECT MAX(order_id) FROM orders"
cursor.execute(query)

# Fetching the result


result = cursor.fetchone()[0]

# Closing the cursor


cursor.close()

# Returning the next available order_id


if result is None:
return 1
else:
return result + 1

# Function to fetch the order status from the order_tracking table


def get_order_status(order_id):
46
cursor = cnx.cursor()

# Executing the SQL query to fetch the order status


query = f"SELECT status FROM order_tracking WHERE order_id = {order_id}"
cursor.execute(query)

# Fetching the result


result = cursor.fetchone()

# Closing the cursor


cursor.close()

# Returning the order status


if result:
return result[0]
else:
return None

if __name__ == "__main__":
# print(get_total_order_price(56))
# insert_order_item('Samosa', 3, 99)
# insert_order_item('Pav Bhaji', 1, 99)
# insert_order_tracking(99, "in progress")
print(get_next_order_id())

c) session_handler.py

import re

def get_str_from_food_dict(food_dict: dict):


result = ", ".join([f"{int(value)} {key}" for key, value in food_dict.items()])
return result

47
def extract_session_id(session_str: str):
match = re.search(r"/sessions/(.*?)/contexts/", session_str)
if match:
extracted_string = match.group(0)
return extracted_string

return ""

48

You might also like