Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add pagination to agent blocks endpoint (#5087)
cthomas7c03288c05a8
diff --git a/fern/openapi.json b/fern/openapi.jsonindex d2bca489d..bf303be18 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -5159,6 +5159,87 @@"type": "string","title": "Agent Id"}+ },+ {+ "name": "before",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Block ID cursor for pagination. Returns blocks that come before this block ID in the specified sort order",+ "title": "Before"+ },+ "description": "Block ID cursor for pagination. Returns blocks that come before this block ID in the specified sort order"+ },+ {+ "name": "after",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Block ID cursor for pagination. Returns blocks that come after this block ID in the specified sort order",+ "title": "After"+ },+ "description": "Block ID cursor for pagination. Returns blocks that come after this block ID in the specified sort order"+ },+ {+ "name": "limit",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "description": "Maximum number of blocks to return",+ "default": 100,+ "title": "Limit"+ },+ "description": "Maximum number of blocks to return"+ },+ {+ "name": "order",+ "in": "query",+ "required": false,+ "schema": {+ "enum": ["asc", "desc"],+ "type": "string",+ "description": "Sort order for blocks by creation time. 'asc' for oldest first, 'desc' for newest first",+ "default": "desc",+ "title": "Order"+ },+ "description": "Sort order for blocks by creation time. 'asc' for oldest first, 'desc' for newest first"+ },+ {+ "name": "order_by",+ "in": "query",+ "required": false,+ "schema": {+ "const": "created_at",+ "type": "string",+ "description": "Field to sort by",+ "default": "created_at",+ "title": "Order By"+ },+ "description": "Field to sort by"}],"responses": {diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex da62df82a..a5e675c99 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -900,16 +900,34 @@ async def list_blocks(agent_id: str,server: "SyncServer" = Depends(get_letta_server),headers: HeaderParams = Depends(get_headers),+ before: Optional[str] = Query(+ None, description="Block ID cursor for pagination. Returns blocks that come before this block ID in the specified sort order"+ ),+ after: Optional[str] = Query(+ None, description="Block ID cursor for pagination. Returns blocks that come after this block ID in the specified sort order"+ ),+ limit: Optional[int] = Query(100, description="Maximum number of blocks to return"),+ order: Literal["asc", "desc"] = Query(+ "desc", description="Sort order for blocks by creation time. 'asc' for oldest first, 'desc' for newest first"+ ),+ order_by: Literal["created_at"] = Query("created_at", description="Field to sort by"),):"""Retrieve the core memory blocks of a specific agent."""actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)+try:- agent = await server.agent_manager.get_agent_by_id_async(agent_id=agent_id, include_relationships=["memory"], actor=actor)- return agent.memory.blocks- except NoResultFound as e:- raise HTTPException(status_code=404, detail=str(e))+ return await server.agent_manager.list_agent_blocks_async(+ agent_id=agent_id,+ actor=actor,+ before=before,+ after=after,+ limit=limit,+ ascending=(order == "asc"),+ )+ except NoResultFound:+ raise HTTPException(status_code=404, detail="Agent not found")@router.patch("/{agent_id}/core-memory/blocks/{block_label}", response_model=Block, operation_id="modify_core_memory_block")diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.pyindex c69197eff..81f283a5e 100644--- a/letta/services/agent_manager.py+++ b/letta/services/agent_manager.py@@ -2634,6 +2634,63 @@ class AgentManager:tools = result.scalars().all()return [tool.to_pydantic() for tool in tools]+ @enforce_types+ @trace_method+ async def list_agent_blocks_async(+ self,+ agent_id: str,+ actor: PydanticUser,+ before: Optional[str] = None,+ after: Optional[str] = None,+ limit: Optional[int] = None,+ ascending: bool = False,+ ) -> List[PydanticBlock]:+ """+ List all blocks for a specific agent with pagination.++ Args:+ agent_id: ID of the agent to find blocks for.+ actor: User performing the action.+ before: Block ID cursor for pagination. Returns blocks that come before this block ID.+ after: Block ID cursor for pagination. Returns blocks that come after this block ID.+ limit: Maximum number of blocks to return.+ ascending: Sort order by creation time.++ Returns:+ List[PydanticBlock]: List of blocks for the agent.+ """+ async with db_registry.async_session() as session:+ # First verify agent exists and user has access+ await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)++ # Build query to get blocks for this agent with pagination+ query = (+ select(BlockModel)+ .join(BlocksAgents, BlockModel.id == BlocksAgents.block_id)+ .where(BlocksAgents.agent_id == agent_id, BlockModel.organization_id == actor.organization_id)+ )++ # Apply cursor-based pagination+ if before:+ query = query.where(BlockModel.id < before)+ if after:+ query = query.where(BlockModel.id > after)++ # Apply sorting - use id instead of created_at for core memory blocks+ if ascending:+ query = query.order_by(BlockModel.id.asc())+ else:+ query = query.order_by(BlockModel.id.desc())++ # Apply limit+ if limit:+ query = query.limit(limit)++ result = await session.execute(query)+ blocks = result.scalars().all()++ return [block.to_pydantic() for block in blocks]+@enforce_types@trace_methodasync def list_groups_async(@@ -2662,9 +2719,6 @@ class AgentManager:List[PydanticGroup]: List of groups containing the agent."""async with db_registry.async_session() as session:- from letta.orm.group import Group as GroupModel- from letta.orm.sqlalchemy_base import GroupsAgents-query = (select(GroupModel).join(GroupsAgents, GroupModel.id == GroupsAgents.group_id)