diff --git a/libs/langchain/langchain/chat_loaders/imessage.py b/libs/langchain/langchain/chat_loaders/imessage.py index df2ed95577..ff9a06142c 100644 --- a/libs/langchain/langchain/chat_loaders/imessage.py +++ b/libs/langchain/langchain/chat_loaders/imessage.py @@ -108,8 +108,13 @@ class IMessageChatLoader(chat_loaders.BaseChatLoader): ) from e cursor = conn.cursor() - # Fetch the list of chat IDs - cursor.execute("SELECT ROWID FROM chat") + # Fetch the list of chat IDs sorted by time (most recent first) + query = """SELECT chat_id + FROM message + JOIN chat_message_join ON message.ROWID = chat_message_join.message_id + GROUP BY chat_id + ORDER BY MAX(date) DESC;""" + cursor.execute(query) chat_ids = [row[0] for row in cursor.fetchall()] for chat_id in chat_ids: