diff --git a/chatterbot/logic/best_match.py b/chatterbot/logic/best_match.py index fa6e98999..5a9a4bb2d 100644 --- a/chatterbot/logic/best_match.py +++ b/chatterbot/logic/best_match.py @@ -1,5 +1,6 @@ from chatterbot.logic import LogicAdapter from chatterbot import filters +import random class BestMatch(LogicAdapter): @@ -36,6 +37,14 @@ def process(self, input_statement, additional_response_selection_parameters=None if result.confidence >= self.maximum_similarity_threshold: break + # If closest_match and the next result have equal cofidence, then choose either randomly. + if result.confidence == closest_match.confidence: + closest_match = random.choice([result, closest_match]) + + # If our new result is better than our previous closest_match, choose closest_match instead. + elif result.confidence > closest_match.confidence: + closest_match = result + self.chatbot.logger.info('Using "{}" as a close match to "{}" with a confidence of {}'.format( closest_match.text, input_statement.text, closest_match.confidence ))