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 filters to count_agents endpoint [LET-5380] [LET-5497] (#6008)

Christina Tongc76bc9e2164a
diff --git a/fern/openapi.json b/fern/openapi.json
index b6f8a58de..fdf0fd06d 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -4201,9 +4201,190 @@
"get": {
"tags": ["agents"],
"summary": "Count Agents",
- "description": "Get the total number of agents.",
+ "description": "Get the total number of agents with optional filtering.\nSupports the same filters as list_agents for consistent querying.",
"operationId": "count_agents",
- "parameters": [],
+ "parameters": [
+ {
+ "name": "name",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Name of the agent",
+ "title": "Name"
+ },
+ "description": "Name of the agent"
+ },
+ {
+ "name": "tags",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "List of tags to filter agents by",
+ "title": "Tags"
+ },
+ "description": "List of tags to filter agents by"
+ },
+ {
+ "name": "match_all_tags",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "description": "If True, only counts agents that match ALL given tags. Otherwise, counts agents that have ANY of the passed-in tags.",
+ "default": false,
+ "title": "Match All Tags"
+ },
+ "description": "If True, only counts agents that match ALL given tags. Otherwise, counts agents that have ANY of the passed-in tags."
+ },
+ {
+ "name": "query_text",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Search agents by name",
+ "title": "Query Text"
+ },
+ "description": "Search agents by name"
+ },
+ {
+ "name": "project_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Search agents by project ID - this will default to your default project on cloud",
+ "title": "Project Id"
+ },
+ "description": "Search agents by project ID - this will default to your default project on cloud"
+ },
+ {
+ "name": "template_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Search agents by template ID",
+ "title": "Template Id"
+ },
+ "description": "Search agents by template ID"
+ },
+ {
+ "name": "base_template_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Search agents by base template ID",
+ "title": "Base Template Id"
+ },
+ "description": "Search agents by base template ID"
+ },
+ {
+ "name": "identity_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Search agents by identity ID",
+ "title": "Identity Id"
+ },
+ "description": "Search agents by identity ID"
+ },
+ {
+ "name": "identifier_keys",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Search agents by identifier keys",
+ "title": "Identifier Keys"
+ },
+ "description": "Search agents by identifier keys"
+ },
+ {
+ "name": "last_stop_reason",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/StopReasonType"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Filter agents by their last stop reason.",
+ "title": "Last Stop Reason"
+ },
+ "description": "Filter agents by their last stop reason."
+ }
+ ],
"responses": {
"200": {
"description": "Successful Response",
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index f081aa112..e550c843a 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -165,14 +165,57 @@ async def list_agents(
@router.get("/count", response_model=int, operation_id="count_agents")
async def count_agents(
+ name: str | None = Query(None, description="Name of the agent"),
+ tags: list[str] | None = Query(None, description="List of tags to filter agents by"),
+ match_all_tags: bool = Query(
+ False,
+ description="If True, only counts agents that match ALL given tags. Otherwise, counts agents that have ANY of the passed-in tags.",
+ ),
+ query_text: str | None = Query(None, description="Search agents by name"),
+ project_id: str | None = Query(None, description="Search agents by project ID - this will default to your default project on cloud"),
+ template_id: str | None = Query(None, description="Search agents by template ID"),
+ base_template_id: str | None = Query(None, description="Search agents by base template ID"),
+ identity_id: str | None = Query(None, description="Search agents by identity ID"),
+ identifier_keys: list[str] | None = Query(None, description="Search agents by identifier keys"),
+ show_hidden_agents: bool | None = Query(
+ False,
+ include_in_schema=False,
+ description="If set to True, include agents marked as hidden in the results.",
+ ),
+ last_stop_reason: Optional[StopReasonType] = Query(None, description="Filter agents by their last stop reason."),
server: SyncServer = Depends(get_letta_server),
headers: HeaderParams = Depends(get_headers),
):
"""
- Get the total number of agents.
+ Get the total number of agents with optional filtering.
+ Supports the same filters as list_agents for consistent querying.
"""
actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)
- return await server.agent_manager.size_async(actor=actor)
+
+ # If no filters are provided, use the simpler size_async method
+ if (
+ all(
+ param is None or param is False
+ for param in [name, tags, query_text, project_id, template_id, base_template_id, identity_id, identifier_keys, last_stop_reason]
+ )
+ and not show_hidden_agents
+ ):
+ return await server.agent_manager.size_async(actor=actor)
+
+ return await server.agent_manager.count_agents_async(
+ actor=actor,
+ name=name,
+ tags=tags,
+ match_all_tags=match_all_tags,
+ query_text=query_text,
+ project_id=project_id,
+ template_id=template_id,
+ base_template_id=base_template_id,
+ identity_id=identity_id,
+ identifier_keys=identifier_keys,
+ show_hidden_agents=show_hidden_agents,
+ last_stop_reason=last_stop_reason,
+ )
class IndentedORJSONResponse(Response):
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index ab616e6b0..274c60a8b 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -925,6 +925,58 @@ class AgentManager:
*[agent.to_pydantic_async(include_relationships=include_relationships, include=include) for agent in agents]
)
+ @trace_method
+ async def count_agents_async(
+ self,
+ actor: PydanticUser,
+ name: Optional[str] = None,
+ tags: Optional[List[str]] = None,
+ match_all_tags: bool = False,
+ query_text: Optional[str] = None,
+ project_id: Optional[str] = None,
+ template_id: Optional[str] = None,
+ base_template_id: Optional[str] = None,
+ identity_id: Optional[str] = None,
+ identifier_keys: Optional[List[str]] = None,
+ show_hidden_agents: Optional[bool] = None,
+ last_stop_reason: Optional[StopReasonType] = None,
+ ) -> int:
+ """
+ Count agents matching the specified filters using an efficient database-level COUNT query.
+
+ Args:
+ actor: The User requesting the count
+ name (Optional[str]): Filter by agent name.
+ tags (Optional[List[str]]): Filter agents by tags.
+ match_all_tags (bool): If True, only count agents that match ALL given tags.
+ query_text (Optional[str]): Search agents by name.
+ project_id (Optional[str]): Filter by project ID.
+ template_id (Optional[str]): Filter by template ID.
+ base_template_id (Optional[str]): Filter by base template ID.
+ identity_id (Optional[str]): Filter by identifier ID.
+ identifier_keys (Optional[List[str]]): Search agents by identifier keys.
+ show_hidden_agents (bool): If True, include agents marked as hidden in the results.
+ last_stop_reason (Optional[str]): Filter by the agent's last stop reason (e.g., 'requires_approval', 'error').
+
+ Returns:
+ int: The count of agents matching the filters.
+ """
+ async with db_registry.async_session() as session:
+ query = select(func.count()).select_from(AgentModel)
+ query = AgentModel.apply_access_predicate(query, actor, ["read"], AccessType.ORGANIZATION)
+
+ # Apply filters
+ query = _apply_filters(query, name, query_text, project_id, template_id, base_template_id, last_stop_reason)
+ query = _apply_identity_filters(query, identity_id, identifier_keys)
+ query = _apply_tag_filter(query, tags, match_all_tags)
+
+ # Apply hidden filter
+ if not show_hidden_agents:
+ query = query.where((AgentModel.hidden.is_(None)) | (AgentModel.hidden == False))
+
+ result = await session.execute(query)
+ return result.scalar_one()
+
@enforce_types
@trace_method
async def list_agents_matching_tags_async(
diff --git a/tests/managers/test_agent_manager.py b/tests/managers/test_agent_manager.py
index da5a4921f..96056cc39 100644
--- a/tests/managers/test_agent_manager.py
+++ b/tests/managers/test_agent_manager.py
@@ -901,6 +901,114 @@ async def test_list_agents_by_last_stop_reason(server: SyncServer, default_user)
assert {"agent_requires_approval", "agent_error", "agent_no_stop_reason"}.issubset(all_names)
+async def test_count_agents_with_filters(server: SyncServer, default_user):
+ """Test count_agents_async with various filters"""
+ # Create agents with different attributes
+ agent1 = await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name="agent_requires_approval",
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ memory_blocks=[],
+ include_base_tools=False,
+ tags=["inbox", "test"],
+ ),
+ actor=default_user,
+ )
+ await server.agent_manager.update_agent_async(
+ agent_id=agent1.id,
+ agent_update=UpdateAgent(last_stop_reason=StopReasonType.requires_approval),
+ actor=default_user,
+ )
+
+ agent2 = await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name="agent_error",
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ memory_blocks=[],
+ include_base_tools=False,
+ tags=["error", "test"],
+ ),
+ actor=default_user,
+ )
+ await server.agent_manager.update_agent_async(
+ agent_id=agent2.id,
+ agent_update=UpdateAgent(last_stop_reason=StopReasonType.error),
+ actor=default_user,
+ )
+
+ agent3 = await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name="agent_completed",
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ memory_blocks=[],
+ include_base_tools=False,
+ tags=["completed"],
+ ),
+ actor=default_user,
+ )
+ await server.agent_manager.update_agent_async(
+ agent_id=agent3.id,
+ agent_update=UpdateAgent(last_stop_reason=StopReasonType.end_turn),
+ actor=default_user,
+ )
+
+ agent4 = await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name="agent_no_stop_reason",
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ memory_blocks=[],
+ include_base_tools=False,
+ tags=["test"],
+ ),
+ actor=default_user,
+ )
+
+ # Test count with no filters - should return total count
+ total_count = await server.agent_manager.count_agents_async(actor=default_user)
+ assert total_count >= 4
+
+ # Test count by last_stop_reason - requires_approval (inbox use case)
+ approval_count = await server.agent_manager.count_agents_async(
+ actor=default_user, last_stop_reason=StopReasonType.requires_approval.value
+ )
+ assert approval_count == 1
+
+ # Test count by last_stop_reason - error
+ error_count = await server.agent_manager.count_agents_async(actor=default_user, last_stop_reason=StopReasonType.error.value)
+ assert error_count == 1
+
+ # Test count by last_stop_reason - end_turn
+ completed_count = await server.agent_manager.count_agents_async(actor=default_user, last_stop_reason=StopReasonType.end_turn.value)
+ assert completed_count == 1
+
+ # Test count by tags
+ test_tag_count = await server.agent_manager.count_agents_async(actor=default_user, tags=["test"])
+ assert test_tag_count == 3
+
+ # Test count by tags with match_all_tags
+ inbox_test_count = await server.agent_manager.count_agents_async(actor=default_user, tags=["inbox", "test"], match_all_tags=True)
+ assert inbox_test_count == 1
+
+ # Test count by name
+ name_count = await server.agent_manager.count_agents_async(actor=default_user, name="agent_requires_approval")
+ assert name_count == 1
+
+ # Test count by query_text
+ query_count = await server.agent_manager.count_agents_async(actor=default_user, query_text="error")
+ assert query_count >= 1
+
+ # Test combined filters: last_stop_reason + tags
+ combined_count = await server.agent_manager.count_agents_async(
+ actor=default_user, last_stop_reason=StopReasonType.requires_approval.value, tags=["inbox"]
+ )
+ assert combined_count == 1
+
+
@pytest.mark.asyncio
async def test_list_agents_ordering_and_pagination(server: SyncServer, default_user):
names = ["alpha_agent", "beta_agent", "gamma_agent"]