拒否への対応
ユーザーに提案をしたとき、それが気に入られなかったらどうなるでしょうか?同じ提案をすぐに繰り返してしまうと、ボットの印象が悪くなります。
ここでは、respond() 関数を修正して、4つの引数を受け取り、4つの値を返すようにします。
- ユーザーのメッセージを引数として受け取り、ボットの応答を最初の戻り値とします。
- ユーザーが指定したエンティティを含む辞書
params。 prev_suggestionsリスト。respond()に渡すときは、直前のボットメッセージで行った提案を格納します。respond()が返すときは、現在の提案を格納します。excludedリスト。ユーザーがすでに明示的に拒否した結果をすべて格納します。
この関数は、"deny" インテントを受け取った際に直前の提案を除外リストに追加し、応答から除外済みの提案を取り除く処理も行う必要があります。
この演習はコースの一部です
Python でチャットボットを作る
演習の手順
- 4つの引数(
message、params、prev_suggestions、excluded)を持つrespond()関数を定義してください。 messageを解析し、結果をparse_dataに格納してください。parse_dataの"intent"キーの値は、キーと値のペアを持つ辞書です。parse_data["intent"]["name"]をintentに、parse_data["entities"]をentitiesに代入してください。intentが"deny"の場合は、excludedリストの.extend()メソッドを使ってprev_suggestionsを追加してください。- 空の
params辞書と、空のsuggestionsリストおよびexcludedリストを初期化してください。その後、回答を送信してボットにメッセージを送りましょう。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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))