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: deprecate shared_block_ids, and add groups, blocks [LET-4430] (#5746)

Ari Webb787740e3cbaf
diff --git a/fern/openapi.json b/fern/openapi.json
index 5b882d00c..29cb4eed6 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -8698,6 +8698,114 @@
}
}
},
+ "/v1/groups/{group_id}/blocks/attach/{block_id}": {
+ "patch": {
+ "tags": ["groups"],
+ "summary": "Attach Block To Group",
+ "description": "Attach a block to a group.\nThis will add the block to the group and all agents within the group.",
+ "operationId": "attach_block_to_group",
+ "parameters": [
+ {
+ "name": "block_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "Block Id"
+ }
+ },
+ {
+ "name": "group_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 42,
+ "maxLength": 42,
+ "pattern": "^group-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
+ "description": "The ID of the group in the format 'group-<uuid4>'",
+ "examples": ["group-123e4567-e89b-42d3-8456-426614174000"],
+ "title": "Group Id"
+ },
+ "description": "The ID of the group in the format 'group-<uuid4>'"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/v1/groups/{group_id}/blocks/detach/{block_id}": {
+ "patch": {
+ "tags": ["groups"],
+ "summary": "Detach Block From Group",
+ "description": "Detach a block from a group.\nThis will remove the block from the group and all agents within the group.",
+ "operationId": "detach_block_from_group",
+ "parameters": [
+ {
+ "name": "block_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "Block Id"
+ }
+ },
+ {
+ "name": "group_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 42,
+ "maxLength": 42,
+ "pattern": "^group-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
+ "description": "The ID of the group in the format 'group-<uuid4>'",
+ "examples": ["group-123e4567-e89b-42d3-8456-426614174000"],
+ "title": "Group Id"
+ },
+ "description": "The ID of the group in the format 'group-<uuid4>'"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/v1/identities/": {
"get": {
"tags": ["identities", "identities"],
@@ -24536,7 +24644,8 @@
"type": "array",
"title": "Shared Block Ids",
"description": "",
- "default": []
+ "default": [],
+ "deprecated": true
},
"manager_agent_id": {
"anyOf": [
@@ -24720,7 +24829,8 @@
"type": "array",
"title": "Shared Block Ids",
"description": "",
- "default": []
+ "default": [],
+ "deprecated": true
},
"hidden": {
"anyOf": [
@@ -24807,7 +24917,8 @@
"type": "array",
"title": "Shared Block Ids",
"description": "",
- "default": []
+ "default": [],
+ "deprecated": true
},
"hidden": {
"anyOf": [
@@ -24924,7 +25035,8 @@
}
],
"title": "Shared Block Ids",
- "description": ""
+ "description": "",
+ "deprecated": true
}
},
"type": "object",
@@ -26390,7 +26502,8 @@
"type": "array",
"title": "Shared Block Ids",
"description": "",
- "default": []
+ "default": [],
+ "deprecated": true
},
"hidden": {
"anyOf": [
diff --git a/letta/schemas/group.py b/letta/schemas/group.py
index a5c06c0cf..0006c17e5 100644
--- a/letta/schemas/group.py
+++ b/letta/schemas/group.py
@@ -34,7 +34,7 @@ class Group(GroupBase):
template_id: Optional[str] = Field(None, description="The id of the template.")
base_template_id: Optional[str] = Field(None, description="The base template id.")
deployment_id: Optional[str] = Field(None, description="The id of the deployment.")
- shared_block_ids: List[str] = Field([], description="")
+ shared_block_ids: List[str] = Field([], description="", deprecated=True)
# Pattern fields
manager_agent_id: Optional[str] = Field(None, description="")
termination_token: Optional[str] = Field(None, description="")
@@ -174,7 +174,7 @@ class GroupCreate(BaseModel):
description: str = Field(..., description="")
manager_config: ManagerConfigUnion = Field(RoundRobinManager(), description="")
project_id: Optional[str] = Field(None, description="The associated project id.")
- shared_block_ids: List[str] = Field([], description="")
+ shared_block_ids: List[str] = Field([], description="", deprecated=True)
hidden: Optional[bool] = Field(
None,
description="If set to True, the group will be hidden.",
@@ -194,4 +194,4 @@ class GroupUpdate(BaseModel):
description: Optional[str] = Field(None, description="")
manager_config: Optional[ManagerConfigUpdateUnion] = Field(None, description="")
project_id: Optional[str] = Field(None, description="The associated project id.")
- shared_block_ids: Optional[List[str]] = Field(None, description="")
+ shared_block_ids: Optional[List[str]] = Field(None, description="", deprecated=True)
diff --git a/letta/server/rest_api/routers/v1/groups.py b/letta/server/rest_api/routers/v1/groups.py
index fd703fbd0..190767836 100644
--- a/letta/server/rest_api/routers/v1/groups.py
+++ b/letta/server/rest_api/routers/v1/groups.py
@@ -284,3 +284,43 @@ async def reset_group_messages(
"""
actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)
await server.group_manager.reset_messages_async(group_id=group_id, actor=actor)
+
+
[email protected]("/{group_id}/blocks/attach/{block_id}", response_model=None, operation_id="attach_block_to_group")
+async def attach_block_to_group(
+ block_id: str,
+ group_id: GroupId,
+ server: "SyncServer" = Depends(get_letta_server),
+ headers: HeaderParams = Depends(get_headers),
+):
+ """
+ Attach a block to a group.
+ This will add the block to the group and all agents within the group.
+ """
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)
+ await server.group_manager.attach_block_async(
+ group_id=group_id,
+ block_id=block_id,
+ actor=actor,
+ )
+ return None
+
+
[email protected]("/{group_id}/blocks/detach/{block_id}", response_model=None, operation_id="detach_block_from_group")
+async def detach_block_from_group(
+ block_id: str,
+ group_id: GroupId,
+ server: "SyncServer" = Depends(get_letta_server),
+ headers: HeaderParams = Depends(get_headers),
+):
+ """
+ Detach a block from a group.
+ This will remove the block from the group and all agents within the group.
+ """
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)
+ await server.group_manager.detach_block_async(
+ group_id=group_id,
+ block_id=block_id,
+ actor=actor,
+ )
+ return None
diff --git a/letta/services/archive_manager.py b/letta/services/archive_manager.py
index 7f477d3f2..57fbca414 100644
--- a/letta/services/archive_manager.py
+++ b/letta/services/archive_manager.py
@@ -14,6 +14,7 @@ from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.enums import PrimitiveType, VectorDBProvider
from letta.schemas.user import User as PydanticUser
from letta.server.db import db_registry
+from letta.services.helpers.agent_manager_helper import validate_agent_exists_async
from letta.settings import DatabaseChoice, settings
from letta.utils import enforce_types
from letta.validators import raise_on_invalid_id
@@ -157,6 +158,12 @@ class ArchiveManager:
) -> None:
"""Attach an agent to an archive."""
async with db_registry.async_session() as session:
+ # Verify agent exists and user has access to it
+ await validate_agent_exists_async(session, agent_id, actor)
+
+ # Verify archive exists and user has access to it
+ await ArchiveModel.read_async(db_session=session, identifier=archive_id, actor=actor)
+
# Check if relationship already exists
existing = await session.execute(
select(ArchivesAgents).where(
@@ -194,6 +201,12 @@ class ArchiveManager:
) -> None:
"""Detach an agent from an archive."""
async with db_registry.async_session() as session:
+ # Verify agent exists and user has access to it
+ await validate_agent_exists_async(session, agent_id, actor)
+
+ # Verify archive exists and user has access to it
+ await ArchiveModel.read_async(db_session=session, identifier=archive_id, actor=actor)
+
# Delete the relationship directly
result = await session.execute(
delete(ArchivesAgents).where(
diff --git a/letta/services/group_manager.py b/letta/services/group_manager.py
index a16b942ea..4dbdb149c 100644
--- a/letta/services/group_manager.py
+++ b/letta/services/group_manager.py
@@ -5,8 +5,10 @@ from sqlalchemy import and_, asc, delete, desc, or_, select
from sqlalchemy.orm import Session
from letta.orm.agent import Agent as AgentModel
+from letta.orm.block import Block
from letta.orm.errors import NoResultFound
from letta.orm.group import Group as GroupModel
+from letta.orm.groups_blocks import GroupsBlocks
from letta.orm.message import Message as MessageModel
from letta.otel.tracing import trace_method
from letta.schemas.enums import PrimitiveType
@@ -410,6 +412,48 @@ class GroupManager:
for block in blocks:
session.add(BlocksAgents(agent_id=manager_agent.id, block_id=block.id, block_label=block.label))
+ @enforce_types
+ @trace_method
+ @raise_on_invalid_id(param_name="group_id", expected_prefix=PrimitiveType.GROUP)
+ @raise_on_invalid_id(param_name="block_id", expected_prefix=PrimitiveType.BLOCK)
+ async def attach_block_async(self, group_id: str, block_id: str, actor: PydanticUser) -> None:
+ """Attach a block to a group."""
+ async with db_registry.async_session() as session:
+ # Verify group exists and user has access
+ await GroupModel.read_async(db_session=session, identifier=group_id, actor=actor)
+
+ # Verify block exists AND user has access to it
+ await Block.read_async(db_session=session, identifier=block_id, actor=actor)
+
+ # Check if block is already attached to the group
+ check_query = select(GroupsBlocks).where(and_(GroupsBlocks.group_id == group_id, GroupsBlocks.block_id == block_id))
+ result = await session.execute(check_query)
+ if result.scalar_one_or_none():
+ # Block already attached, no-op
+ return
+
+ # Add block to group
+ session.add(GroupsBlocks(group_id=group_id, block_id=block_id))
+ await session.commit()
+
+ @enforce_types
+ @trace_method
+ @raise_on_invalid_id(param_name="group_id", expected_prefix=PrimitiveType.GROUP)
+ @raise_on_invalid_id(param_name="block_id", expected_prefix=PrimitiveType.BLOCK)
+ async def detach_block_async(self, group_id: str, block_id: str, actor: PydanticUser) -> None:
+ """Detach a block from a group."""
+ async with db_registry.async_session() as session:
+ # Verify group exists and user has access
+ await GroupModel.read_async(db_session=session, identifier=group_id, actor=actor)
+
+ # Verify block exists AND user has access to it
+ await Block.read_async(db_session=session, identifier=block_id, actor=actor)
+
+ # Remove block from group
+ delete_group_block = delete(GroupsBlocks).where(and_(GroupsBlocks.group_id == group_id, GroupsBlocks.block_id == block_id))
+ await session.execute(delete_group_block)
+ await session.commit()
+
@staticmethod
def ensure_buffer_length_range_valid(
max_value: Optional[int],