Skip to content

Commit

Permalink
Properly order returned conversation statements from mongodb
Browse files Browse the repository at this point in the history
  • Loading branch information
gunthercox committed Jul 11, 2017
1 parent 2bc6d30 commit bf6c6c2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 19 deletions.
6 changes: 3 additions & 3 deletions chatterbot/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def filter_selection(self, chatterbot, session_id):
text_of_recent_responses = []

# TODO: Add a larger quantity of response history
text_of_recent_responses.append(
chatterbot.storage.get_latest_response(session_id)
)
latest_response = chatterbot.storage.get_latest_response(session_id)
if latest_response:
text_of_recent_responses.append(latest_response.text)

# Return the query with no changes if there are no statements to exclude
if not text_of_recent_responses:
Expand Down
43 changes: 27 additions & 16 deletions chatterbot/storage/mongodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,42 +243,53 @@ def create_conversation(self):
"""
Create a new conversation.
"""
conversation_id = self.conversations.insert_one({
'statements': []
}).inserted_id
conversation_id = self.conversations.insert_one({}).inserted_id
return conversation_id

def get_latest_response(self, conversation_id):
"""
Returns the latest response in a conversation if it exists.
Returns None if a matching conversation cannot be found.
"""
conversation = self.conversations.find_one({
'_id': conversation_id
})
from pymongo import DESCENDING

if not conversation['statements']:
return None
statements = list(self.statements.find({
'conversations.id': conversation_id
}).sort('conversations.created_at', DESCENDING))

# TODO: Check if ordering is needed
if not statements:
return None

return conversation['statements'][-2]
return self.mongo_to_object(statements[-2])

def add_to_converation(self, conversation_id, statement, response):
"""
Add the statement and response to the conversation.
"""
self.conversations.update_one(
from datetime import datetime, timedelta
self.statements.update_one(
{
'text': statement.text
},
{
'$push': {
'conversations': {
'id': conversation_id,
'created_at': datetime.utcnow()
}
}
}
)
self.statements.update_one(
{
'id': conversation_id
'text': response.text
},
{
'$push': {
'conversations': {
'$each': [
statement.text,
response.text
]
'id': conversation_id,
# Force the response to be at least one millisecond after the input statement
'created_at': datetime.utcnow() + timedelta(milliseconds=1)
}
}
}
Expand Down

0 comments on commit bf6c6c2

Please sign in to comment.