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): add created_by_id filter to agents listing (#10191)

Sarah Woodersabfc43321d50
diff --git a/alembic/versions/a08c972e781b_add_index_on_agents_organization_id_and_.py b/alembic/versions/a08c972e781b_add_index_on_agents_organization_id_and_.py
new file mode 100644
index 000000000..68af301fb
--- /dev/null
+++ b/alembic/versions/a08c972e781b_add_index_on_agents_organization_id_and_.py
@@ -0,0 +1,40 @@
+"""add index on agents organization_id and created_by_id
+
+Revision ID: a08c972e781b
+Revises: 9fa274fb0b83
+Create Date: 2026-03-22 16:16:30.094739
+
+"""
+
+from typing import Sequence, Union
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "a08c972e781b"
+down_revision: Union[str, None] = "9fa274fb0b83"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ connection = op.get_bind()
+ connection.commit()
+ autocommit_connection = connection.execution_options(isolation_level="AUTOCOMMIT")
+ autocommit_connection.exec_driver_sql(
+ """
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_agents_organization_id_created_by_id
+ ON agents USING btree (organization_id, _created_by_id)
+ """
+ )
+
+
+def downgrade() -> None:
+ connection = op.get_bind()
+ connection.commit()
+ autocommit_connection = connection.execution_options(isolation_level="AUTOCOMMIT")
+ autocommit_connection.exec_driver_sql(
+ """
+ DROP INDEX CONCURRENTLY IF EXISTS ix_agents_organization_id_created_by_id
+ """
+ )
diff --git a/fern/openapi.json b/fern/openapi.json
index a060db865..9d1b48c1b 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -4334,6 +4334,24 @@
"title": "Last Stop Reason"
},
"description": "Filter agents by their last stop reason."
+ },
+ {
+ "name": "created_by_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Filter agents by the user who created them.",
+ "title": "Created By Id"
+ },
+ "description": "Filter agents by the user who created them."
}
],
"responses": {
@@ -4608,6 +4626,24 @@
"title": "Last Stop Reason"
},
"description": "Filter agents by their last stop reason."
+ },
+ {
+ "name": "created_by_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Filter agents by the user who created them.",
+ "title": "Created By Id"
+ },
+ "description": "Filter agents by the user who created them."
}
],
"responses": {
diff --git a/letta/orm/agent.py b/letta/orm/agent.py
index 5a25e2b63..8d84217d3 100644
--- a/letta/orm/agent.py
+++ b/letta/orm/agent.py
@@ -49,6 +49,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixin
Index("ix_agents_created_at", "created_at", "id"),
Index("ix_agents_organization_id_deployment_id", "organization_id", "deployment_id"),
Index("ix_agents_project_id", "project_id"),
+ Index("ix_agents_organization_id_created_by_id", "organization_id", "_created_by_id"),
)
# agent generates its own id
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index 35c2b46bd..b5075d183 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -174,6 +174,7 @@ async def list_agents(
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."),
+ created_by_id: str | None = Query(None, description="Filter agents by the user who created them."),
):
"""
Get a list of all agents.
@@ -209,6 +210,7 @@ async def list_agents(
sort_by=final_sort_by,
show_hidden_agents=show_hidden_agents,
last_stop_reason=last_stop_reason,
+ created_by_id=created_by_id,
)
@@ -232,6 +234,7 @@ async def count_agents(
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."),
+ created_by_id: str | None = Query(None, description="Filter agents by the user who created them."),
server: SyncServer = Depends(get_letta_server),
headers: HeaderParams = Depends(get_headers),
):
@@ -248,7 +251,18 @@ async def count_agents(
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]
+ for param in [
+ name,
+ tags,
+ query_text,
+ project_id,
+ template_id,
+ base_template_id,
+ identity_id,
+ identifier_keys,
+ last_stop_reason,
+ created_by_id,
+ ]
)
and show_hidden_agents
):
@@ -267,6 +281,7 @@ async def count_agents(
identifier_keys=identifier_keys,
show_hidden_agents=show_hidden_agents,
last_stop_reason=last_stop_reason,
+ created_by_id=created_by_id,
)
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index e9a450fde..9692ea559 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -1041,6 +1041,7 @@ class AgentManager:
sort_by: Optional[str] = "created_at",
show_hidden_agents: Optional[bool] = None,
last_stop_reason: Optional[StopReasonType] = None,
+ created_by_id: Optional[str] = None,
) -> List[PydanticAgentState]:
"""
Retrieves agents with optimized filtering and optional field selection.
@@ -1073,7 +1074,7 @@ class AgentManager:
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_filters(query, name, query_text, project_id, template_id, base_template_id, last_stop_reason, created_by_id)
query = _apply_identity_filters(query, identity_id, identifier_keys)
query = _apply_tag_filter(query, tags, match_all_tags)
query = _apply_relationship_filters(query, include_relationships, include)
@@ -1112,6 +1113,7 @@ class AgentManager:
identifier_keys: Optional[List[str]] = None,
show_hidden_agents: Optional[bool] = None,
last_stop_reason: Optional[StopReasonType] = None,
+ created_by_id: Optional[str] = None,
) -> int:
"""
Count agents matching the specified filters using an efficient database-level COUNT query.
@@ -1138,7 +1140,7 @@ class AgentManager:
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_filters(query, name, query_text, project_id, template_id, base_template_id, last_stop_reason, created_by_id)
query = _apply_identity_filters(query, identity_id, identifier_keys)
query = _apply_tag_filter(query, tags, match_all_tags)
diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.py
index 8de18f7b2..e9fef0389 100644
--- a/letta/services/helpers/agent_manager_helper.py
+++ b/letta/services/helpers/agent_manager_helper.py
@@ -741,6 +741,7 @@ def _apply_filters(
template_id: Optional[str],
base_template_id: Optional[str],
last_stop_reason: Optional[StopReasonType] = None,
+ created_by_id: Optional[str] = None,
):
"""
Apply basic filtering criteria to the agent query.
@@ -757,6 +758,7 @@ def _apply_filters(
template_id (Optional[str]): Filter for agents using a specific template.
base_template_id (Optional[str]): Filter for agents using a specific base template.
last_stop_reason (Optional[StopReasonType]): Filter for agents by their last stop reason (e.g., 'requires_approval', 'error').
+ created_by_id (Optional[str]): Filter for agents created by a specific user.
Returns:
The modified query with the applied filters.
@@ -784,6 +786,9 @@ def _apply_filters(
# Filter agents by last stop reason.
if last_stop_reason:
query = query.where(AgentModel.last_stop_reason == last_stop_reason)
+ # Filter agents by created_by_id.
+ if created_by_id:
+ query = query.where(AgentModel._created_by_id == created_by_id)
return query
diff --git a/tests/managers/test_agent_manager.py b/tests/managers/test_agent_manager.py
index b4b1e32f9..90e328e36 100644
--- a/tests/managers/test_agent_manager.py
+++ b/tests/managers/test_agent_manager.py
@@ -23,6 +23,7 @@ from letta.schemas.agent import CreateAgent, InternalTemplateAgentCreate, Update
from letta.schemas.block import CreateBlock
from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.enums import (
+ AgentType,
MessageRole,
)
from letta.schemas.letta_message_content import TextContent
@@ -1442,6 +1443,53 @@ 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_list_agents_by_created_by_id(server: SyncServer, default_user, other_user):
+ """Test filtering agents by created_by_id."""
+ # Create agent as default_user
+ await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name="agent_by_default_user",
+ agent_type=AgentType.letta_v1_agent,
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ memory_blocks=[],
+ include_base_tools=False,
+ ),
+ actor=default_user,
+ )
+
+ # Create agent as other_user
+ await server.agent_manager.create_agent_async(
+ agent_create=CreateAgent(
+ name="agent_by_other_user",
+ agent_type=AgentType.letta_v1_agent,
+ llm_config=LLMConfig.default_config("gpt-4o-mini"),
+ embedding_config=EmbeddingConfig.default_config(provider="openai"),
+ memory_blocks=[],
+ include_base_tools=False,
+ ),
+ actor=other_user,
+ )
+
+ # Filter by default_user's id
+ default_user_agents = await server.agent_manager.list_agents_async(actor=default_user, created_by_id=default_user.id)
+ default_user_names = {agent.name for agent in default_user_agents}
+ assert "agent_by_default_user" in default_user_names
+ assert "agent_by_other_user" not in default_user_names
+
+ # Filter by other_user's id
+ other_user_agents = await server.agent_manager.list_agents_async(actor=other_user, created_by_id=other_user.id)
+ other_user_names = {agent.name for agent in other_user_agents}
+ assert "agent_by_other_user" in other_user_names
+ assert "agent_by_default_user" not in other_user_names
+
+ # No filter - both users' agents visible
+ all_agents = await server.agent_manager.list_agents_async(actor=default_user)
+ all_names = {agent.name for agent in all_agents}
+ assert {"agent_by_default_user", "agent_by_other_user"}.issubset(all_names)
+
+
@pytest.mark.asyncio
async def test_count_agents_with_filters(server: SyncServer, default_user):
"""Test count_agents_async with various filters"""