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.

fix: missing cursor kwargs (#5763)

Kian Jones60226ad20357
diff --git a/letta/services/source_manager.py b/letta/services/source_manager.py
index 9ef2cb6fd..d79e3c1cd 100644
--- a/letta/services/source_manager.py
+++ b/letta/services/source_manager.py
@@ -326,13 +326,25 @@ class SourceManager:
@enforce_types
@trace_method
@raise_on_invalid_id(param_name="source_id", expected_prefix=PrimitiveType.SOURCE)
- async def get_agents_for_source_id(self, source_id: str, actor: PydanticUser) -> List[str]:
+ async def get_agents_for_source_id(
+ self,
+ source_id: str,
+ actor: PydanticUser,
+ before: Optional[str] = None,
+ after: Optional[str] = None,
+ limit: Optional[int] = 50,
+ ascending: bool = True,
+ ) -> List[str]:
"""
Get all agent IDs associated with a given source ID.
Args:
source_id: ID of the source to find agents for
actor: User performing the action
+ before: Agent ID cursor for pagination (upper bound)
+ after: Agent ID cursor for pagination (lower bound)
+ limit: Maximum number of agent IDs to return
+ ascending: Sort direction by creation time
Returns:
List[str]: List of agent IDs that have this source attached
@@ -341,8 +353,84 @@ class SourceManager:
# Verify source exists and user has permission to access it
await self._validate_source_exists_async(session, source_id, actor)
- # Query the junction table directly for performance
- query = select(SourcesAgents.agent_id).where(SourcesAgents.source_id == source_id)
+ # Get reference objects for pagination
+ before_obj = None
+ after_obj = None
+
+ if before:
+ before_obj = await session.get(AgentModel, before)
+ if not before_obj:
+ from letta.orm.errors import NoResultFound
+
+ raise NoResultFound(f"No Agent found with id {before}")
+
+ if after:
+ after_obj = await session.get(AgentModel, after)
+ if not after_obj:
+ from letta.orm.errors import NoResultFound
+
+ raise NoResultFound(f"No Agent found with id {after}")
+
+ # Build query with join to AgentModel for ordering and pagination
+ query = (
+ select(AgentModel.id)
+ .join(SourcesAgents, AgentModel.id == SourcesAgents.agent_id)
+ .where(
+ SourcesAgents.source_id == source_id,
+ AgentModel.organization_id == actor.organization_id,
+ AgentModel.is_deleted == False,
+ )
+ )
+
+ # Apply pagination conditions
+ if before_obj or after_obj:
+ from sqlalchemy import and_, or_
+
+ conditions = []
+
+ if before_obj and after_obj:
+ # Window-based query
+ conditions.append(
+ or_(
+ AgentModel.created_at < before_obj.created_at,
+ and_(AgentModel.created_at == before_obj.created_at, AgentModel.id < before_obj.id),
+ )
+ )
+ conditions.append(
+ or_(
+ AgentModel.created_at > after_obj.created_at,
+ and_(AgentModel.created_at == after_obj.created_at, AgentModel.id > after_obj.id),
+ )
+ )
+ else:
+ if before_obj:
+ conditions.append(
+ or_(
+ AgentModel.created_at < before_obj.created_at
+ if ascending
+ else AgentModel.created_at > before_obj.created_at,
+ and_(AgentModel.created_at == before_obj.created_at, AgentModel.id < before_obj.id),
+ )
+ )
+ if after_obj:
+ conditions.append(
+ or_(
+ AgentModel.created_at > after_obj.created_at if ascending else AgentModel.created_at < after_obj.created_at,
+ and_(AgentModel.created_at == after_obj.created_at, AgentModel.id > after_obj.id),
+ )
+ )
+
+ if conditions:
+ query = query.where(and_(*conditions))
+
+ # Apply ordering
+ if ascending:
+ query = query.order_by(AgentModel.created_at.asc(), AgentModel.id.asc())
+ else:
+ query = query.order_by(AgentModel.created_at.desc(), AgentModel.id.desc())
+
+ # Apply limit
+ query = query.limit(limit)
result = await session.execute(query)
agent_ids = result.scalars().all()
diff --git a/tests/managers/test_source_manager.py b/tests/managers/test_source_manager.py
index 509567e50..5d13fdbf2 100644
--- a/tests/managers/test_source_manager.py
+++ b/tests/managers/test_source_manager.py
@@ -238,6 +238,92 @@ async def test_list_attached_agents_nonexistent_source(server: SyncServer, defau
await server.source_manager.list_attached_agents(source_id="nonexistent-source-id", actor=default_user)
+async def test_get_agents_for_source_id_pagination(server: SyncServer, default_source, default_user):
+ """Test pagination functionality of get_agents_for_source_id."""
+ # Create multiple agents
+ agents = []
+ for i in range(5):
+ agent = await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name=f"Test Agent {i}",
+ memory_blocks=[],
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ include_base_tools=False,
+ ),
+ actor=default_user,
+ )
+ agents.append(agent)
+ # Add delay for SQLite to ensure distinct created_at timestamps
+ if USING_SQLITE and i < 4:
+ time.sleep(CREATE_DELAY_SQLITE)
+
+ # Attach all agents to the source
+ for agent in agents:
+ await server.agent_manager.attach_source_async(agent_id=agent.id, source_id=default_source.id, actor=default_user)
+
+ # Test 1: Get all agents (no pagination)
+ all_agent_ids = await server.source_manager.get_agents_for_source_id(
+ source_id=default_source.id,
+ actor=default_user,
+ )
+ assert len(all_agent_ids) == 5
+
+ # Test 2: Pagination with limit
+ first_page = await server.source_manager.get_agents_for_source_id(
+ source_id=default_source.id,
+ actor=default_user,
+ limit=2,
+ )
+ assert len(first_page) == 2
+
+ # Test 3: Get next page using 'after' cursor
+ second_page = await server.source_manager.get_agents_for_source_id(
+ source_id=default_source.id,
+ actor=default_user,
+ after=first_page[-1],
+ limit=2,
+ )
+ assert len(second_page) == 2
+ # Verify no overlap between pages
+ assert first_page[-1] not in second_page
+ assert first_page[0] not in second_page
+
+ # Test 4: Get previous page using 'before' cursor
+ prev_page = await server.source_manager.get_agents_for_source_id(
+ source_id=default_source.id,
+ actor=default_user,
+ before=second_page[0],
+ limit=2,
+ )
+ assert len(prev_page) == 2
+ # The previous page should contain agents from first_page
+ assert any(agent_id in first_page for agent_id in prev_page)
+
+ # Test 5: Ascending order (oldest first)
+ ascending_ids = await server.source_manager.get_agents_for_source_id(
+ source_id=default_source.id,
+ actor=default_user,
+ ascending=True,
+ )
+ assert len(ascending_ids) == 5
+
+ # Test 6: Descending order (newest first)
+ descending_ids = await server.source_manager.get_agents_for_source_id(
+ source_id=default_source.id,
+ actor=default_user,
+ ascending=False,
+ )
+ assert len(descending_ids) == 5
+ # Descending should be reverse of ascending
+ assert descending_ids == list(reversed(ascending_ids))
+
+ # Test 7: Verify all agent IDs are correct
+ created_agent_ids = {agent.id for agent in agents}
+ assert set(all_agent_ids) == created_agent_ids
+
+
# ======================================================================================================================
# SourceManager Tests - Sources
# ======================================================================================================================