始める無料で始める

拒否への対応

ユーザーに提案をしたとき、それが気に入られなかったらどうなるでしょうか?同じ提案をすぐに繰り返してしまうと、ボットの印象が悪くなります。

ここでは、respond() 関数を修正して、4つの引数を受け取り、4つの値を返すようにします。

  • ユーザーのメッセージを引数として受け取り、ボットの応答を最初の戻り値とします。
  • ユーザーが指定したエンティティを含む辞書 params
  • prev_suggestions リスト。respond() に渡すときは、直前のボットメッセージで行った提案を格納します。respond() が返すときは、現在の提案を格納します。
  • excluded リスト。ユーザーがすでに明示的に拒否した結果をすべて格納します。

この関数は、"deny" インテントを受け取った際に直前の提案を除外リストに追加し、応答から除外済みの提案を取り除く処理も行う必要があります。

この演習はコースの一部です

Python でチャットボットを作る

コースを見る

演習の手順

  • 4つの引数(messageparamsprev_suggestionsexcluded)を持つ 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))
コードを編集して実行