Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

feat(core): sort conversations by last_message_at (#10190)

Sarah Wooders5148af867766
diff --git a/alembic/versions/1c28e167b74f_add_last_message_at_to_conversations.py b/alembic/versions/1c28e167b74f_add_last_message_at_to_conversations.py
new file mode 100644
index 000000000..36d1c3e46
--- /dev/null
+++ b/alembic/versions/1c28e167b74f_add_last_message_at_to_conversations.py
@@ -0,0 +1,47 @@
+"""add last_message_at to conversations
+
+Revision ID: 1c28e167b74f
+Revises: a08c972e781b
+Create Date: 2026-03-22 19:07:27.266449
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "1c28e167b74f"
+down_revision: Union[str, None] = "a08c972e781b"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+
+ conversation_columns = {column["name"] for column in inspector.get_columns("conversations")}
+ if "last_message_at" not in conversation_columns:
+ op.add_column("conversations", sa.Column("last_message_at", sa.DateTime(timezone=True), nullable=True))
+
+ conversation_indexes = {index["name"] for index in inspector.get_indexes("conversations")}
+ if "ix_conversations_org_agent_last_message_at" not in conversation_indexes:
+ op.create_index(
+ "ix_conversations_org_agent_last_message_at", "conversations", ["organization_id", "agent_id", "last_message_at"], unique=False
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+
+ conversation_indexes = {index["name"] for index in inspector.get_indexes("conversations")}
+ if "ix_conversations_org_agent_last_message_at" in conversation_indexes:
+ op.drop_index("ix_conversations_org_agent_last_message_at", table_name="conversations")
+
+ conversation_columns = {column["name"] for column in inspector.get_columns("conversations")}
+ if "last_message_at" in conversation_columns:
+ op.drop_column("conversations", "last_message_at")
diff --git a/fern/openapi.json b/fern/openapi.json
index 9d1b48c1b..41c9d98b0 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -8841,7 +8841,7 @@
"in": "query",
"required": false,
"schema": {
- "enum": ["created_at", "last_run_completion"],
+ "enum": ["created_at", "last_run_completion", "last_message_at"],
"type": "string",
"description": "Field to sort by",
"default": "created_at",
@@ -32959,6 +32959,19 @@
],
"title": "Model Settings",
"description": "The model settings for this conversation (overrides agent's model settings)."
+ },
+ "last_message_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Last Message At",
+ "description": "Timestamp of the most recent message request sent to this conversation."
}
},
"additionalProperties": false,
@@ -49331,6 +49344,19 @@
],
"title": "Model Settings",
"description": "The model settings for this conversation (overrides agent's model settings)."
+ },
+ "last_message_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Last Message At",
+ "description": "Timestamp of the most recent message request sent to this conversation."
}
},
"type": "object",
diff --git a/letta/orm/conversation.py b/letta/orm/conversation.py
index 7e41f575f..60d6581d6 100644
--- a/letta/orm/conversation.py
+++ b/letta/orm/conversation.py
@@ -1,8 +1,9 @@
import uuid
+from datetime import datetime
from typing import TYPE_CHECKING, List, Optional
from pydantic import TypeAdapter
-from sqlalchemy import JSON, ForeignKey, Index, String
+from sqlalchemy import JSON, DateTime, ForeignKey, Index, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from letta.orm.mixins import OrganizationMixin
@@ -26,6 +27,7 @@ class Conversation(SqlalchemyBase, OrganizationMixin):
__table_args__ = (
Index("ix_conversations_agent_id", "agent_id"),
Index("ix_conversations_org_agent", "organization_id", "agent_id"),
+ Index("ix_conversations_org_agent_last_message_at", "organization_id", "agent_id", "last_message_at"),
)
id: Mapped[str] = mapped_column(String, primary_key=True, default=lambda: f"conv-{uuid.uuid4()}")
@@ -37,6 +39,9 @@ class Conversation(SqlalchemyBase, OrganizationMixin):
model_settings: Mapped[Optional[dict]] = mapped_column(
JSON, nullable=True, doc="Model settings override for this conversation (provider-specific settings)"
)
+ last_message_at: Mapped[Optional[datetime]] = mapped_column(
+ DateTime(timezone=True), nullable=True, doc="Timestamp of the most recent message request to this conversation"
+ )
# Relationships
agent: Mapped["Agent"] = relationship("Agent", back_populates="conversations", lazy="raise")
@@ -67,4 +72,5 @@ class Conversation(SqlalchemyBase, OrganizationMixin):
isolated_block_ids=[b.id for b in self.isolated_blocks] if self.isolated_blocks else [],
model=self.model,
model_settings=_model_settings_adapter.validate_python(self.model_settings) if self.model_settings else None,
+ last_message_at=self.last_message_at,
)
diff --git a/letta/schemas/conversation.py b/letta/schemas/conversation.py
index 0f6bf7f88..0a0676dba 100644
--- a/letta/schemas/conversation.py
+++ b/letta/schemas/conversation.py
@@ -1,3 +1,4 @@
+from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field, field_validator
@@ -28,6 +29,10 @@ class Conversation(OrmMetadataBase):
None,
description="The model settings for this conversation (overrides agent's model settings).",
)
+ last_message_at: Optional[datetime] = Field(
+ None,
+ description="Timestamp of the most recent message request sent to this conversation.",
+ )
class CreateConversation(BaseModel):
@@ -73,6 +78,10 @@ class UpdateConversation(BaseModel):
None,
description="The model settings for this conversation (overrides agent's model settings).",
)
+ last_message_at: Optional[datetime] = Field(
+ None,
+ description="Timestamp of the most recent message request sent to this conversation.",
+ )
@field_validator("model")
@classmethod
diff --git a/letta/server/rest_api/routers/v1/conversations.py b/letta/server/rest_api/routers/v1/conversations.py
index 1386de1fe..0f6170d51 100644
--- a/letta/server/rest_api/routers/v1/conversations.py
+++ b/letta/server/rest_api/routers/v1/conversations.py
@@ -70,7 +70,7 @@ async def list_conversations(
order: Literal["asc", "desc"] = Query(
"desc", description="Sort order for conversations. 'asc' for oldest first, 'desc' for newest first"
),
- order_by: Literal["created_at", "last_run_completion"] = Query("created_at", description="Field to sort by"),
+ order_by: Literal["created_at", "last_run_completion", "last_message_at"] = Query("created_at", description="Field to sort by"),
server: SyncServer = Depends(get_letta_server),
headers: HeaderParams = Depends(get_headers),
):
@@ -405,6 +405,13 @@ async def send_conversation_message(
actor=actor,
)
+ # Mark conversation message activity at request time
+ conversation = await conversation_manager.update_conversation(
+ conversation_id=conversation_id,
+ conversation_update=UpdateConversation(last_message_at=get_utc_time()),
+ actor=actor,
+ )
+
# Streaming mode (default)
if request.streaming:
# Convert to LettaStreamingRequest for StreamingService compatibility
diff --git a/letta/services/conversation_manager.py b/letta/services/conversation_manager.py
index 98d6318f5..b0aae27bb 100644
--- a/letta/services/conversation_manager.py
+++ b/letta/services/conversation_manager.py
@@ -236,7 +236,7 @@ class ConversationManager:
after: Cursor for pagination (conversation ID)
summary_search: Optional text to search for within the summary field
ascending: Sort order (True for oldest first, False for newest first)
- sort_by: Field to sort by ("created_at" or "last_run_completion")
+ sort_by: Field to sort by ("created_at", "last_run_completion", or "last_message_at")
Returns:
List of conversations matching the criteria
@@ -258,6 +258,10 @@ class ConversationManager:
)
sort_column = latest_run_subquery.c.last_run_completion
sort_nulls_last = True
+ elif sort_by == "last_message_at":
+ stmt = select(ConversationModel)
+ sort_column = ConversationModel.last_message_at
+ sort_nulls_last = True
else:
# Simple query for created_at
stmt = select(ConversationModel)
@@ -330,6 +334,43 @@ class ConversationManager:
and_(sort_column == after_sort_value, ConversationModel.id < after_id),
)
)
+ elif sort_by == "last_message_at":
+ after_conv = await ConversationModel.read_async(
+ db_session=session,
+ identifier=after,
+ actor=actor,
+ )
+ after_sort_value = after_conv.last_message_at
+ after_id = after_conv.id
+ if after_sort_value is None:
+ if ascending:
+ stmt = stmt.where(
+ or_(
+ and_(ConversationModel.last_message_at.is_(None), ConversationModel.id > after_id),
+ ConversationModel.last_message_at.isnot(None),
+ )
+ )
+ else:
+ stmt = stmt.where(and_(ConversationModel.last_message_at.is_(None), ConversationModel.id < after_id))
+ else:
+ if ascending:
+ stmt = stmt.where(
+ and_(
+ ConversationModel.last_message_at.isnot(None),
+ or_(
+ ConversationModel.last_message_at > after_sort_value,
+ and_(ConversationModel.last_message_at == after_sort_value, ConversationModel.id > after_id),
+ ),
+ )
+ )
+ else:
+ stmt = stmt.where(
+ or_(
+ ConversationModel.last_message_at.is_(None),
+ ConversationModel.last_message_at < after_sort_value,
+ and_(ConversationModel.last_message_at == after_sort_value, ConversationModel.id < after_id),
+ )
+ )
else:
# Simple created_at cursor
after_conv = await ConversationModel.read_async(
diff --git a/tests/integration_test_conversations_sdk.py b/tests/integration_test_conversations_sdk.py
index 3c99b3b2b..70e2fd2a1 100644
--- a/tests/integration_test_conversations_sdk.py
+++ b/tests/integration_test_conversations_sdk.py
@@ -108,6 +108,31 @@ class TestConversationsSDK:
assert conv1.id in conv_ids
assert conv2.id in conv_ids
+ def test_list_conversations_sort_by_last_message_at(self, client: Letta, agent):
+ """Test listing conversations sorted by last_message_at."""
+ conv_older = client.conversations.create(agent_id=agent.id)
+ conv_newer = client.conversations.create(agent_id=agent.id)
+
+ list(
+ client.conversations.messages.create(
+ conversation_id=conv_older.id,
+ messages=[{"role": "user", "content": "hello older conversation"}],
+ )
+ )
+ list(
+ client.conversations.messages.create(
+ conversation_id=conv_newer.id,
+ messages=[{"role": "user", "content": "hello newer conversation"}],
+ )
+ )
+
+ sorted_desc = client.conversations.list(agent_id=agent.id, order_by="last_message_at", order="desc")
+ sorted_ids = [c.id for c in sorted_desc]
+
+ assert conv_older.id in sorted_ids
+ assert conv_newer.id in sorted_ids
+ assert sorted_ids.index(conv_newer.id) < sorted_ids.index(conv_older.id)
+
def test_retrieve_conversation(self, client: Letta, agent):
"""Test retrieving a specific conversation."""
# Create a conversation
diff --git a/tests/integration_test_send_message_v2.py b/tests/integration_test_send_message_v2.py
index 8f08d8c52..c7a54326d 100644
--- a/tests/integration_test_send_message_v2.py
+++ b/tests/integration_test_send_message_v2.py
@@ -6,6 +6,7 @@ import os
import threading
import time
import uuid
+from datetime import datetime
from typing import Any, List, Tuple
import pytest
@@ -1012,6 +1013,13 @@ async def test_conversation_streaming_raw_http(
)
assert stream_response.status_code == 200, f"Failed to send message: {stream_response.text}"
+ # Verify last_message_at is populated and parseable
+ retrieve_after_send_response = await http_client.get(f"/v1/conversations/{conversation['id']}")
+ assert retrieve_after_send_response.status_code == 200
+ retrieved_after_send = retrieve_after_send_response.json()
+ assert retrieved_after_send["last_message_at"] is not None
+ datetime.fromisoformat(retrieved_after_send["last_message_at"].replace("Z", "+00:00"))
+
# Parse SSE response and accumulate messages
messages = await accumulate_chunks(stream_response.text)
print("MESSAGES:", messages)
diff --git a/tests/managers/test_conversation_manager.py b/tests/managers/test_conversation_manager.py
index ee7c7b0c7..93e65dcf2 100644
--- a/tests/managers/test_conversation_manager.py
+++ b/tests/managers/test_conversation_manager.py
@@ -2,6 +2,8 @@
Tests for ConversationManager.
"""
+from datetime import datetime, timedelta, timezone
+
import pytest
from letta.orm.errors import NoResultFound
@@ -385,6 +387,58 @@ async def test_delete_conversation_excluded_from_summary_search(conversation_man
assert len(results) == 1
+async def test_list_conversations_sort_by_last_message_at(conversation_manager, server: SyncServer, sarah_agent, default_user):
+ """Test sorting conversations by last_message_at with nulls last."""
+ conv_old = await conversation_manager.create_conversation(
+ agent_id=sarah_agent.id,
+ conversation_create=CreateConversation(summary="old"),
+ actor=default_user,
+ )
+ conv_new = await conversation_manager.create_conversation(
+ agent_id=sarah_agent.id,
+ conversation_create=CreateConversation(summary="new"),
+ actor=default_user,
+ )
+ conv_null = await conversation_manager.create_conversation(
+ agent_id=sarah_agent.id,
+ conversation_create=CreateConversation(summary="null"),
+ actor=default_user,
+ )
+
+ now = datetime.now(timezone.utc)
+ await conversation_manager.update_conversation(
+ conversation_id=conv_old.id,
+ conversation_update=UpdateConversation(last_message_at=now - timedelta(minutes=5)),
+ actor=default_user,
+ )
+ await conversation_manager.update_conversation(
+ conversation_id=conv_new.id,
+ conversation_update=UpdateConversation(last_message_at=now),
+ actor=default_user,
+ )
+
+ desc_conversations = await conversation_manager.list_conversations(
+ agent_id=sarah_agent.id,
+ actor=default_user,
+ sort_by="last_message_at",
+ ascending=False,
+ )
+ desc_ids = [c.id for c in desc_conversations]
+ assert desc_ids.index(conv_new.id) < desc_ids.index(conv_old.id)
+ assert desc_ids.index(conv_old.id) < desc_ids.index(conv_null.id)
+
+ asc_conversations = await conversation_manager.list_conversations(
+ agent_id=sarah_agent.id,
+ actor=default_user,
+ sort_by="last_message_at",
+ ascending=True,
+ )
+ asc_ids = [c.id for c in asc_conversations]
+ assert asc_ids.index(conv_old.id) < asc_ids.index(conv_new.id)
+ assert asc_ids.index(conv_new.id) < asc_ids.index(conv_null.id)
+
+
@pytest.mark.asyncio
async def test_conversation_isolation_by_agent(conversation_manager, server: SyncServer, sarah_agent, charles_agent, default_user):
"""Test that conversations are isolated by agent."""