Dealing with rejection
What happens if you make a suggestion to your user and they don't like it? Your bot will look really silly if it makes the same suggestion again right away.
Here, you're going to modify your respond() function so that it accepts and returns 4 arguments:
- The user message as an argument, and the bot response as the first return value.
- A dictionary
paramsincluding the entities the user has specified. - A
prev_suggestionslist. When passed torespond(), this should contain the suggestions made in the previous bot message. When returned byrespond(), it should contain the current suggestions. - An
excludedlist, which contains all of the results your user has already explicitly rejected.
Your function should add the previous suggestions to the excluded list whenever it receives a "deny" intent. It should also filter out excluded suggestions from the response.
This exercise is part of the course
Building Chatbots in Python
Exercise instructions
- Define a
respond()function with 4 arguments:message,params,prev_suggestions, andexcluded. - Interpret the
messageand store the result inparse_data. - The value of the
"intent"key ofparse_datais itself a dictionary of key-value pairs. Assignparse_data["intent"]["name"]tointent, andparse_data["entities"]toentities. - If the
intentis"deny", use the.extend()method of theexcludedlist to addprev_suggestionsto it. - Initialize the empty
paramsdictionary and emptysuggestionsandexcludedlists. Then, hit 'Submit Answer' to send the messages to the bot.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define respond()
def ____:
# Interpret the message
parse_data = ____
# Extract the intent
intent = ____
# Extract the entities
entities = ____
# Add the suggestion to the excluded list if intent is "deny"
if ____ == "____":
____
# Fill the dictionary with entities
for ent in entities:
params[ent["entity"]] = str(ent["value"])
# Find matching hotels
results = [
r
for r in find_hotels(params, excluded)
if r[0] not in excluded
]
# Extract the suggestions
names = [r[0] for r in results]
n = min(len(results), 3)
suggestions = names[:2]
return responses[n].format(*names), params, suggestions, excluded
# Initialize the empty dictionary and lists
params, suggestions, excluded = {}, [], []
# Send the messages
for message in ["I want a mid range hotel", "no that doesn't work for me"]:
print("USER: {}".format(message))
response, params, suggestions, excluded = respond(message, params, suggestions, excluded)
print("BOT: {}".format(response))