Bug description
org.springframework.ai.chat.memory.repository.mongo.MongoChatMemoryRepository is changing the order of the messages to descending during fetch and consequently the LLM is behaving unexpectedly.
I believe this happening because of the descending sort in the below code:
@Override
public List<Message> findByConversationId(String conversationId) {
var messages = this.mongoTemplate.query(Conversation.class)
.matching(Query.query(Criteria.where("conversationId").is(conversationId))
.with(Sort.by("timestamp").descending()));
return messages.stream().map(MongoChatMemoryRepository::mapMessage).collect(Collectors.toList());
}
If we compare the sort with org.springframework.ai.chat.memory.repository.jdbc.PostgresChatMemoryRepositoryDialect, it uses an ascending sort rather than a descending one.
@Override
public String getSelectMessagesSql() {
return "SELECT content, type FROM SPRING_AI_CHAT_MEMORY WHERE conversation_id = ? ORDER BY \"timestamp\"";
}
Environment
Spring AI 1.1.2
Azure CosmosDB with Mongo API
Expected behavior
The order of conversation history should maintain the natural flow of the conversation (USER, ASSISTANT, USER, ASSISTANT.....)