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 manual open/close file endpoints (#3475)

Matthew Zhoufd5d66fad6fa
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index 55f5099ec..7ae0a40ba 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -385,6 +385,77 @@ async def close_all_open_files(
return server.file_agent_manager.close_all_other_files(agent_id=agent_id, keep_file_names=[], actor=actor)
[email protected]("/{agent_id}/files/{file_id}/open", response_model=List[str], operation_id="open_file")
+async def open_file(
+ agent_id: str,
+ file_id: str,
+ server: "SyncServer" = Depends(get_letta_server),
+ actor_id: Optional[str] = Header(None, alias="user_id"),
+):
+ """
+ Opens a specific file for a given agent.
+
+ This endpoint marks a specific file as open in the agent's file state.
+ The file will be included in the agent's working memory view.
+ Returns a list of file names that were closed due to LRU eviction.
+ """
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)
+
+ # Get the agent to access files configuration
+ try:
+ per_file_view_window_char_limit, max_files_open = await server.agent_manager.get_agent_files_config_async(
+ agent_id=agent_id, actor=actor
+ )
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"Agent with id={agent_id} not found")
+
+ # Get file metadata
+ file_metadata = await server.file_manager.get_file_by_id(file_id=file_id, actor=actor, include_content=True)
+ if not file_metadata:
+ raise HTTPException(status_code=404, detail=f"File with id={file_id} not found")
+
+ # Use enforce_max_open_files_and_open for efficient LRU handling
+ closed_files, was_already_open = await server.file_agent_manager.enforce_max_open_files_and_open(
+ agent_id=agent_id,
+ file_id=file_id,
+ file_name=file_metadata.file_name,
+ source_id=file_metadata.source_id,
+ actor=actor,
+ visible_content=file_metadata.content[:per_file_view_window_char_limit] if file_metadata.content else "",
+ max_files_open=max_files_open,
+ )
+
+ return closed_files
+
+
[email protected]("/{agent_id}/files/{file_id}/close", response_model=None, operation_id="close_file")
+async def close_file(
+ agent_id: str,
+ file_id: str,
+ server: "SyncServer" = Depends(get_letta_server),
+ actor_id: Optional[str] = Header(None, alias="user_id"),
+):
+ """
+ Closes a specific file for a given agent.
+
+ This endpoint marks a specific file as closed in the agent's file state.
+ The file will be removed from the agent's working memory view.
+ """
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)
+
+ # Use update_file_agent_by_id to close the file
+ try:
+ await server.file_agent_manager.update_file_agent_by_id(
+ agent_id=agent_id,
+ file_id=file_id,
+ actor=actor,
+ is_open=False,
+ )
+ return JSONResponse(status_code=status.HTTP_200_OK, content={"message": f"File id={file_id} successfully closed"})
+ except NoResultFound:
+ raise HTTPException(status_code=404, detail=f"File association for file_id={file_id} and agent_id={agent_id} not found")
+
+
@router.get("/{agent_id}", response_model=AgentState, operation_id="retrieve_agent")
async def retrieve_agent(
agent_id: str,
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index 920d18109..dec9cbfbe 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -2879,6 +2879,34 @@ class AgentManager:
results = [row[0] for row in result.all()]
return results
+ @enforce_types
+ @trace_method
+ async def get_agent_files_config_async(self, agent_id: str, actor: PydanticUser) -> Tuple[int, int]:
+ """Get per_file_view_window_char_limit and max_files_open for an agent.
+
+ This is a performant query that only fetches the specific fields needed.
+
+ Args:
+ agent_id: The ID of the agent
+ actor: The user making the request
+
+ Returns:
+ Tuple of per_file_view_window_char_limit, max_files_open values
+ """
+ async with db_registry.async_session() as session:
+ result = await session.execute(
+ select(AgentModel.per_file_view_window_char_limit, AgentModel.max_files_open)
+ .where(AgentModel.id == agent_id)
+ .where(AgentModel.organization_id == actor.organization_id)
+ .where(AgentModel.is_deleted == False)
+ )
+ row = result.one_or_none()
+
+ if row is None:
+ raise ValueError(f"Agent {agent_id} not found")
+
+ return row[0], row[1]
+
@enforce_types
@trace_method
async def get_agent_max_files_open_async(self, agent_id: str, actor: PydanticUser) -> int:
@@ -2894,7 +2922,6 @@ class AgentManager:
max_files_open value
"""
async with db_registry.async_session() as session:
- # Direct query for just max_files_open
result = await session.execute(
select(AgentModel.max_files_open)
.where(AgentModel.id == agent_id)
@@ -2923,7 +2950,6 @@ class AgentManager:
per_file_view_window_char_limit value
"""
async with db_registry.async_session() as session:
- # Direct query for just per_file_view_window_char_limit
result = await session.execute(
select(AgentModel.per_file_view_window_char_limit)
.where(AgentModel.id == agent_id)