Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add remaining identities routes (#1049)
cthomas0def2b875fa9
diff --git a/letta/schemas/identity.py b/letta/schemas/identity.pyindex 00db9e879..5796685b6 100644--- a/letta/schemas/identity.py+++ b/letta/schemas/identity.py@@ -27,4 +27,18 @@ class Identity(IdentityBase):name: str = Field(..., description="The name of the identity.")identity_type: IdentityType = Field(..., description="The type of the identity.")project_id: Optional[str] = Field(None, description="The project id of the identity, if applicable.")- agents: List[AgentState] = Field(..., description="The ids of the agents associated with the identity.")+ agents: List[AgentState] = Field(..., description="The agents associated with the identity.")+++class IdentityCreate(LettaBase):+ identifier_key: str = Field(..., description="External, user-generated identifier key of the identity.")+ name: str = Field(..., description="The name of the identity.")+ identity_type: IdentityType = Field(..., description="The type of the identity.")+ project_id: Optional[str] = Field(None, description="The project id of the identity, if applicable.")+ agent_ids: Optional[List[str]] = Field(None, description="The agent ids that are associated with the identity.")+++class IdentityUpdate(LettaBase):+ name: Optional[str] = Field(None, description="The name of the identity.")+ identity_type: Optional[IdentityType] = Field(None, description="The type of the identity.")+ agent_ids: Optional[List[str]] = Field(None, description="The agent ids that are associated with the identity.")diff --git a/letta/server/rest_api/routers/v1/identities.py b/letta/server/rest_api/routers/v1/identities.pyindex 5646e7b21..fa155e13c 100644--- a/letta/server/rest_api/routers/v1/identities.py+++ b/letta/server/rest_api/routers/v1/identities.py@@ -1,8 +1,8 @@from typing import TYPE_CHECKING, List, Optional-from fastapi import APIRouter, Depends, HTTPException, Query+from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query-from letta.schemas.identity import Identity, IdentityType+from letta.schemas.identity import Identity, IdentityCreate, IdentityType, IdentityUpdatefrom letta.server.rest_api.utils import get_letta_serverif TYPE_CHECKING:@@ -33,3 +33,60 @@ def list_identities(except Exception as e:raise HTTPException(status_code=500, detail=f"{e}")return identities++[email protected]("/{identifier_key}", tags=["identities"], response_model=Identity, operation_id="get_identity_from_identifier_key")+def retrieve_identity(+ identifier_key: str,+ server: "SyncServer" = Depends(get_letta_server),+):+ try:+ return server.identity_manager.get_identity_by_identifier_key(identifier_key=identifier_key)+ except NoResultFound as e:+ raise HTTPException(status_code=404, detail=str(e))++[email protected]("/", tags=["identities"], response_model=Identity, operation_id="create_identity")+def create_identity(+ identity: IdentityCreate = Body(...),+ server: "SyncServer" = Depends(get_letta_server),+ user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present+ project_slug: Optional[str] = Header(None, alias="project-slug"), # Only handled by next js middleware+):+ actor = server.user_manager.get_user_or_default(user_id=user_id)+ return server.identity_manager.create_identity(identity=identity, actor=actor)++[email protected]("/", tags=["identities"], response_model=Identity, operation_id="upsert_identity")+def upsert_identity(+ identity: IdentityCreate = Body(...),+ server: "SyncServer" = Depends(get_letta_server),+ user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present+ project_slug: Optional[str] = Header(None, alias="project-slug"), # Only handled by next js middleware+):+ actor = server.user_manager.get_user_or_default(user_id=user_id)+ return server.identity_manager.upsert_identity(identity=identity, actor=actor)++[email protected]("/{identifier_key}", tags=["identities"], response_model=Identity, operation_id="update_identity")+def modify_identity(+ identifier_key: str,+ identity: IdentityUpdate = Body(...),+ server: "SyncServer" = Depends(get_letta_server),+ user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present+):+ actor = server.user_manager.get_user_or_default(user_id=user_id)+ return server.identity_manager.update_identity_by_key(identifier_key=identifier_key, identity=identity, actor=actor)++[email protected]("/{identifier_key}", tags=["identities"], operation_id="delete_identity")+def delete_identity(+ identifier_key: str,+ server: "SyncServer" = Depends(get_letta_server),+ user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present+):+ """+ Delete an identity by its identifier key+ """+ actor = server.user_manager.get_user_or_default(user_id=user_id)+ server.identity_manager.delete_identity_by_key(identifier_key=identifier_key, actor=actor)diff --git a/letta/services/identity_manager.py b/letta/services/identity_manager.pyindex bf237419f..7372a34cd 100644--- a/letta/services/identity_manager.py+++ b/letta/services/identity_manager.py@@ -1,8 +1,13 @@from typing import Optional+from fastapi import HTTPException+from sqlalchemy.orm import Session++from letta.orm.agent import Agent as AgentModelfrom letta.orm.identity import Identity as IdentityModelfrom letta.schemas.identity import Identity as PydanticIdentity-from letta.schemas.identity import IdentityType+from letta.schemas.identity import IdentityCreate, IdentityType, IdentityUpdate+from letta.schemas.user import User as PydanticUserfrom letta.utils import enforce_types@@ -44,3 +49,94 @@ class IdentityManager:with self.session_maker() as session:identity = IdentityModel.read(db_session=session, identifier_key=identifier_key)return identity.to_pydantic()++ @enforce_types+ def create_identity(self, identity: IdentityCreate, actor: PydanticUser) -> PydanticIdentity:+ with self.session_maker() as session:+ agents = self._get_agents_from_ids(session=session, agent_ids=identity.agent_ids, actor=actor)++ identity = IdentityModel.create(+ db_session=session,+ name=identity.name,+ identifier_key=identity.identifier_key,+ identity_type=identity.identity_type,+ project_id=identity.project_id,+ organization_id=actor.organization_id,+ agents=agents,+ )+ return identity.to_pydantic()++ @enforce_types+ def upsert_identity(self, identity: IdentityCreate, actor: PydanticUser) -> PydanticIdentity:+ with self.session_maker() as session:+ existing_identity = IdentityModel.read(db_session=session, identifier_key=identifier_key)+ if existing_identity is None:+ identity = self.create_identity(identity=identity, actor=actor)+ else:+ if existing_identity.identifier_key != identity.identifier_key:+ raise HTTPException(status_code=400, detail="Identifier key is an immutable field")+ if existing_identity.project_id != identity.project_id:+ raise HTTPException(status_code=400, detail="Project id is an immutable field")+ if existing_identity.organization_id != identity.organization_id:+ raise HTTPException(status_code=400, detail="Organization id is an immutable field")+ identity_update = IdentityUpdate(name=identity.name, identity_type=identity.identity_type, agent_ids=identity.agent_ids)+ identity = self.update_identity_by_key(identity.identifier_key, identity_update, actor)+ identity.commit(session)+ return identity.to_pydantic()++ @enforce_types+ def update_identity_by_key(self, identifier_key: str, identity: IdentityUpdate, actor: PydanticUser) -> PydanticIdentity:+ with self.session_maker() as session:+ try:+ existing_identity = IdentityModel.read(db_session=session, identifier_key=identifier_key)+ except NoResultFound:+ raise HTTPException(status_code=404, detail="Identity not found")+ if identity.organization_id != existing_identity.organization_id or identity.organization_id != actor.organization_id:+ raise HTTPException(status_code=403, detail="Forbidden")++ agents = None+ if identity.agent_ids:+ agents = self._get_agents_from_ids(session=session, agent_ids=identity.agent_ids, actor=actor)++ existing_identity.name = identity.name if identity.name is not None else existing_identity.name+ existing_identity.identity_type = (+ identity.identity_type if identity.identity_type is not None else existing_identity.identity_type+ )+ existing_identity.agents = agents if agents is not None else existing_identity.agents+ existing_identity.commit(session)+ return existing_identity.to_pydantic()++ @enforce_types+ def delete_identity_by_key(self, identifier_key: str, actor: PydanticUser) -> None:+ with self.session_maker() as session:+ identity = IdentityModel.read(db_session=session, identifier_key=identifier_key)+ if identity is None:+ raise HTTPException(status_code=404, detail="Identity not found")+ if identity.organization_id != actor.organization_id:+ raise HTTPException(status_code=403, detail="Forbidden")+ session.delete(identity)++ def _get_agents_from_ids(self, session: Session, agent_ids: list[str], actor: PydanticUser) -> list[AgentModel]:+ """Helper method to get agents from their IDs and verify permissions.++ Args:+ session: The database session+ agent_ids: List of agent IDs to fetch+ actor: The user making the request++ Returns:+ List of agent models++ Raises:+ HTTPException: If agents not found or user doesn't have permission+ """+ agents = AgentModel.list(db_session=session, ids=agent_ids)+ if len(agents) != len(agent_ids):+ found_ids = {agent.id for agent in agents}+ missing_ids = [id for id in agent_ids if id not in found_ids]+ raise HTTPException(status_code=404, detail=f"Agents not found: {', '.join(missing_ids)}")++ if any(agent.organization_id != actor.organization_id for agent in agents):+ raise HTTPException(status_code=403, detail="Forbidden")++ return agents