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: add pagination to tools endpoint (#2893)

cthomasd6a929e83cad
diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.py
index fc196af52..42c89e44e 100644
--- a/letta/server/rest_api/routers/v1/tools.py
+++ b/letta/server/rest_api/routers/v1/tools.py
@@ -1,6 +1,6 @@
import json
from collections.abc import AsyncGenerator
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Literal, Optional, Union
from composio.client import ComposioClientError, HTTPError, NoItemsFound
from composio.client.collections import ActionModel, AppModel
@@ -173,9 +173,18 @@ async def retrieve_tool(
@router.get("/", response_model=List[Tool], operation_id="list_tools")
async def list_tools(
- after: Optional[str] = None,
- limit: Optional[int] = 50,
- name: Optional[str] = None,
+ before: Optional[str] = Query(
+ None, description="Tool ID cursor for pagination. Returns tools that come before this tool ID in the specified sort order"
+ ),
+ after: Optional[str] = Query(
+ None, description="Tool ID cursor for pagination. Returns tools that come after this tool ID in the specified sort order"
+ ),
+ limit: Optional[int] = Query(50, description="Maximum number of tools to return"),
+ order: Literal["asc", "desc"] = Query(
+ "desc", description="Sort order for tools by creation time. 'asc' for oldest first, 'desc' for newest first"
+ ),
+ order_by: Literal["created_at"] = Query("created_at", description="Field to sort by"),
+ name: Optional[str] = Query(None, description="Filter by single tool name"),
names: Optional[List[str]] = Query(None, description="Filter by specific tool names"),
tool_ids: Optional[List[str]] = Query(
None, description="Filter by specific tool IDs - accepts repeated params or comma-separated values"
@@ -190,7 +199,7 @@ async def list_tools(
actor_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
):
"""
- Get a list of all tools available to agents belonging to the org of the user
+ Get a list of all tools available to agents.
"""
try:
# Helper function to parse tool types - supports both repeated params and comma-separated values
@@ -254,8 +263,10 @@ async def list_tools(
# Get the list of tools using unified query
return await server.tool_manager.list_tools_async(
actor=actor,
+ before=before,
after=after,
limit=limit,
+ ascending=(order == "asc"),
tool_types=tool_types_str,
exclude_tool_types=exclude_tool_types_str,
names=final_names,
diff --git a/letta/services/tool_manager.py b/letta/services/tool_manager.py
index 011dd4a81..ac8d8ac54 100644
--- a/letta/services/tool_manager.py
+++ b/letta/services/tool_manager.py
@@ -321,8 +321,10 @@ class ToolManager:
async def list_tools_async(
self,
actor: PydanticUser,
+ before: Optional[str] = None,
after: Optional[str] = None,
limit: Optional[int] = 50,
+ ascending: bool = False,
upsert_base_tools: bool = True,
tool_types: Optional[List[str]] = None,
exclude_tool_types: Optional[List[str]] = None,
@@ -331,11 +333,13 @@ class ToolManager:
search: Optional[str] = None,
return_only_letta_tools: bool = False,
) -> List[PydanticTool]:
- """List all tools with optional pagination."""
+ """List all tools with pagination support."""
tools = await self._list_tools_async(
actor=actor,
+ before=before,
after=after,
limit=limit,
+ ascending=ascending,
tool_types=tool_types,
exclude_tool_types=exclude_tool_types,
names=names,
@@ -359,8 +363,10 @@ class ToolManager:
# Re-fetch the tools list after upserting base tools
tools = await self._list_tools_async(
actor=actor,
+ before=before,
after=after,
limit=limit,
+ ascending=ascending,
tool_types=tool_types,
exclude_tool_types=exclude_tool_types,
names=names,
@@ -376,8 +382,10 @@ class ToolManager:
async def _list_tools_async(
self,
actor: PydanticUser,
+ before: Optional[str] = None,
after: Optional[str] = None,
limit: Optional[int] = 50,
+ ascending: bool = False,
tool_types: Optional[List[str]] = None,
exclude_tool_types: Optional[List[str]] = None,
names: Optional[List[str]] = None,
@@ -416,23 +424,52 @@ class ToolManager:
if return_only_letta_tools:
query = query.where(ToolModel.tool_type.like("letta_%"))
- # Apply pagination if specified
+ # Handle pagination cursors
if after is not None:
after_tool = await session.get(ToolModel, after)
if after_tool:
- query = query.where(
- or_(
- ToolModel.created_at < after_tool.created_at,
- and_(ToolModel.created_at == after_tool.created_at, ToolModel.id < after_tool.id),
+ if ascending:
+ query = query.where(
+ or_(
+ ToolModel.created_at > after_tool.created_at,
+ and_(ToolModel.created_at == after_tool.created_at, ToolModel.id > after_tool.id),
+ )
+ )
+ else:
+ query = query.where(
+ or_(
+ ToolModel.created_at < after_tool.created_at,
+ and_(ToolModel.created_at == after_tool.created_at, ToolModel.id < after_tool.id),
+ )
+ )
+
+ if before is not None:
+ before_tool = await session.get(ToolModel, before)
+ if before_tool:
+ if ascending:
+ query = query.where(
+ or_(
+ ToolModel.created_at < before_tool.created_at,
+ and_(ToolModel.created_at == before_tool.created_at, ToolModel.id < before_tool.id),
+ )
+ )
+ else:
+ query = query.where(
+ or_(
+ ToolModel.created_at > before_tool.created_at,
+ and_(ToolModel.created_at == before_tool.created_at, ToolModel.id > before_tool.id),
+ )
)
- )
# Apply limit
if limit is not None:
query = query.limit(limit)
- # Order by created_at and id for consistent pagination
- query = query.order_by(ToolModel.created_at.desc(), ToolModel.id.desc())
+ # Apply ordering based on ascending parameter
+ if ascending:
+ query = query.order_by(ToolModel.created_at.asc(), ToolModel.id.asc())
+ else:
+ query = query.order_by(ToolModel.created_at.desc(), ToolModel.id.desc())
# Execute query
result = await session.execute(query)