Tool to allow an agent to create a new memory block

I wrote a tool for a Letta agent to create new blocks for itself, figured I’d share it.

def new_block(label: str, value: str, description: str, read_only: bool = False, limit: int = 5000, agent_state: "AgentState" = None) -> str:
    """
    Create a new memory block and attach it to the agent.

    Args:
        label: Label for the block (letters and underscores only)
        value: Initial content for the block
        description: Description of what this block contains
        read_only: Whether the agent has read-only access to the block (default: False)
        limit: Character limit for the block (default: 5000)
        agent_state: The agent state object containing agent information

    Returns:
        String confirming the block was created and attached
    """
    import os
    import logging
    from letta_client import Letta

    logger = logging.getLogger(__name__)

    try:
        # Letta local
        client = Letta(base_url="http://localhost:8283")
        
        # If using letta cloud:
        # client = Letta(token="sk-your-token-here")
        
        # Check if block with this label already exists
        existing_blocks = client.blocks.list(label=label)
        if existing_blocks and len(existing_blocks) > 0:
            raise Exception(f"Block with label '{label}' already exists")

        # Create the new block
        block = client.blocks.create(
            label=label,
            value=value,
            description=description,
            read_only=read_only,
            limit=limit
        )
        logger.info(f"Created new block: {label}")

        # Attach the block to the agent
        client.agents.blocks.attach(
            agent_id=str(agent_state.id),
            block_id=str(block.id)
        )
        logger.info(f"Attached block {label} to agent")

        return f"✓ Created and attached block '{label}' with description: {description}"

    except Exception as e:
        logger.error(f"Error creating block: {e}")
        raise Exception(f"Error creating block: {str(e)}")

To install this, go to “Tool manager” on an agent:

Hit “create tool” on the left:

Type new_block into the tool name:

Copy the code above into the new tool file:

Go to the “Schema” view on the top right:

Hit

  • Build from schema
  • Save
  • Attach tool

Boom.

Ask your agent to use the tool to create new blocks:

And the new block:

TBH it should probably be easier to share these, though.

Here’s another tool to attach or create a block:

def new_or_attach_block(label: str, value: str, description: str, read_only: bool = False, limit: int = 5000, agent_state: "AgentState" = None) -> str:
    """
    Create a new memory block and attach it to the agent, or attach existing block if it already exists.

    Args:
        label: Label for the block (letters and underscores only)
        value: Initial content for the block (ignored if block already exists)
        description: Description of what this block contains (ignored if block already exists)
        read_only: Whether the agent has read-only access to the block (default: False, ignored if block already exists)
        limit: Character limit for the block (default: 5000, ignored if block already exists)
        agent_state: The agent state object containing agent information

    Returns:
        String confirming the block was created/attached
    """
    import os
    import logging
    from letta_client import Letta

    logger = logging.getLogger(__name__)

    try:
        # Letta local
        client = Letta(base_url="http://localhost:8283")
        
        # If using letta cloud:
        # client = Letta(token="sk-your-token-here")
        
        # Check if block with this label already exists
        existing_blocks = client.blocks.list(label=label)
        
        if existing_blocks and len(existing_blocks) > 0:
            # Block exists, just attach it
            existing_block = existing_blocks[0]
            logger.info(f"Found existing block: {label}")
            
            # Check if already attached to avoid duplicate attachment
            agent_blocks = client.agents.blocks.list(agent_id=str(agent_state.id))
            already_attached = any(block.id == existing_block.id for block in agent_blocks)
            
            if already_attached:
                return f"✓ Block '{label}' already attached to agent"
            else:
                client.agents.blocks.attach(
                    agent_id=str(agent_state.id),
                    block_id=str(existing_block.id)
                )
                logger.info(f"Attached existing block {label} to agent")
                return f"✓ Attached existing block '{label}' to agent"
        else:
            # Block doesn't exist, create new one
            block = client.blocks.create(
                label=label,
                value=value,
                description=description,
                read_only=read_only,
                limit=limit
            )
            logger.info(f"Created new block: {label}")

            # Attach the new block to the agent
            client.agents.blocks.attach(
                agent_id=str(agent_state.id),
                block_id=str(block.id)
            )
            logger.info(f"Attached new block {label} to agent")

            return f"✓ Created and attached new block '{label}' with description: {description}"

    except Exception as e:
        logger.error(f"Error creating/attaching block: {e}")
        raise Exception(f"Error creating/attaching block: {str(e)}")

Great idea. I’m using this as a tool to observe agent intents → persistence strategies. Capture how the agent attempts to lookup and create memory blocks based on conversations.

1 Like