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 shared memory block tutorial, update memory block guide (#5503)

Cameron Pfiffer31cb8de60692
diff --git a/fern/docs.yml b/fern/docs.yml
index 2f0d4ac6d..1668be00e 100644
--- a/fern/docs.yml
+++ b/fern/docs.yml
@@ -606,9 +606,11 @@ navigation:
- page: Overview
path: pages/cookbooks_simple.mdx
- page: Your First Agent
- path: pages/examples/hello_world.mdx
+ path: pages/tutorials/hello_world.mdx
- page: Attaching and Detaching Memory Blocks
- path: pages/examples/attaching_detaching_blocks.mdx
+ path: pages/tutorials/attaching_detaching_blocks.mdx
+ - page: Shared Memory Blocks
+ path: pages/tutorials/shared-memory-blocks.mdx
- section: Multi-Agent
contents:
- page: Async Multi-Agent
diff --git a/fern/pages/agents/memory_blocks.mdx b/fern/pages/agents/memory_blocks.mdx
new file mode 100644
index 000000000..8dfff8c24
--- /dev/null
+++ b/fern/pages/agents/memory_blocks.mdx
@@ -0,0 +1,415 @@
+---
+title: Memory Blocks
+subtitle: Understanding the building blocks of agent memory
+slug: guides/agents/memory-blocks
+---
+
+<Info>
+Interested in learning more about the origin of memory blocks? Read our [blog post](https://www.letta.com/blog/memory-blocks).
+</Info>
+
+## What are memory blocks?
+
+Memory blocks are structured sections of the agent's context window that persist across all interactions. They are always visible - no retrieval needed.
+
+**Memory blocks are Letta's core abstraction.** Create a block with a descriptive label and the agent learns how to use it. This simple mechanism enables capabilities impossible with traditional context management.
+
+**Key properties:**
+- **Agent-managed** - Agents autonomously organize information based on block labels
+- **Flexible** - Use for any purpose: knowledge, guidelines, state tracking, scratchpad space
+- **Shareable** - Multiple agents can access the same block; update once, visible everywhere
+- **Always visible** - Blocks stay in context, never need retrieval
+
+**Examples:**
+- Store tool usage guidelines so agents avoid past mistakes
+- Maintain working memory in a scratchpad block
+- Mirror external state (user's current document) for real-time awareness
+- Share read-only policies across all agents from a central source
+- Coordinate multi-agent systems: parent agents watch subagent result blocks update in real-time
+- Enable emergent behavior: add `performance_tracking` or `emotional_state` and watch agents start using them
+
+Memory blocks aren't just storage - they're a coordination primitive that enables sophisticated agent behavior.
+
+## Memory block structure
+
+Memory blocks represent a section of an agent's context window. An agent may have multiple memory blocks, or none at all. A memory block consists of:
+* A `label`, which is a unique identifier for the block
+* A `description`, which describes the purpose of the block
+* A `value`, which is the contents/data of the block
+* A `limit`, which is the size limit (in characters) of the block
+
+## The importance of the `description` field
+
+When making memory blocks, it's crucial to provide a good `description` field that accurately describes what the block should be used for.
+The `description` is the main information used by the agent to determine how to read and write to that block. Without a good description, the agent may not understand how to use the block.
+
+Because `persona` and `human` are two popular block labels, Letta autogenerates default descriptions for these blocks if you don't provide them. If you provide a description for a memory block labelled `persona` or `human`, the default description will be overridden.
+
+For `persona`, a good default is:
+> The persona block: Stores details about your current persona, guiding how you behave and respond. This helps you to maintain consistency and personality in your interactions.
+
+For `human`, a good default is:
+> The human block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversation.
+
+## Read-only blocks
+
+Memory blocks are read-write by default (so the agent can update the block using memory tools), but can be set to read-only by setting the `read_only` field to `true`. When a block is read-only, the agent cannot update the block.
+
+Read-only blocks are useful when you want to give an agent access to information (for example, a shared memory block about an organization), but you don't want the agent to be able to make potentially destructive changes to the block.
+
+## Creating an agent with memory blocks
+
+When you create an agent, you can specify memory blocks to also be created with the agent. For most chat applications, we recommend create a `human` block (to represent memories about the user) and a `persona` block (to represent the agent's persona).
+<CodeGroup>
+```typescript TypeScript maxLines=50
+// install letta-client with `npm install @letta-ai/letta-client`
+import { LettaClient } from '@letta-ai/letta-client'
+
+// create a client to connect to your local Letta server
+const client = new LettaClient({
+ baseUrl: "http://localhost:8283"
+});
+
+// create an agent with two basic self-editing memory blocks
+const agentState = await client.agents.create({
+ memoryBlocks: [
+ {
+ label: "human",
+ value: "The human's name is Bob the Builder.",
+ limit: 5000
+ },
+ {
+ label: "persona",
+ value: "My name is Sam, the all-knowing sentient AI.",
+ limit: 5000
+ }
+ ],
+ model: "openai/gpt-4o-mini",
+ embedding: "openai/text-embedding-3-small"
+});
+```
+```python title="python" maxLines=50
+# install letta_client with `pip install letta-client`
+from letta_client import Letta
+
+# create a client to connect to your local Letta server
+client = Letta(
+ base_url="http://localhost:8283"
+)
+
+# create an agent with two basic self-editing memory blocks
+agent_state = client.agents.create(
+ memory_blocks=[
+ {
+ "label": "human",
+ "value": "The human's name is Bob the Builder.",
+ "limit": 5000
+ },
+ {
+ "label": "persona",
+ "value": "My name is Sam, the all-knowing sentient AI.",
+ "limit": 5000
+ }
+ ],
+ model="openai/gpt-4o-mini",
+ embedding="openai/text-embedding-3-small"
+)
+```
+</CodeGroup>
+When the agent is created, the corresponding blocks are also created and attached to the agent, so that the block value will be in the context window.
+
+## Creating and attaching memory blocks
+You can also directly create blocks and attach them to an agent. This can be useful if you want to create blocks that are shared between multiple agents. If multiple agents are attached to a block, they will all have the block data in their context windows (essentially providing shared memory).
+
+Below is an example of creating a block directory, and attaching the block to two agents by specifying the `block_ids` field.
+<CodeGroup>
+```typescript TypeScript maxLines=50
+// create a persisted block, which can be attached to agents
+const block = await client.blocks.create({
+ label: "organization",
+ description: "A block to store information about the organization",
+ value: "Organization: Letta",
+ limit: 4000,
+});
+
+// create an agent with both a shared block and its own blocks
+const sharedBlockAgent1 = await client.agents.create({
+ name: "shared_block_agent1",
+ memoryBlocks: [
+ {
+ label: "persona",
+ value: "I am agent 1"
+ },
+ ],
+ blockIds: [block.id],
+ model: "openai/gpt-4o-mini",
+ embedding: "openai/text-embedding-3-small"
+
+});
+
+// create another agent sharing the block
+const sharedBlockAgent2 = await client.agents.create({
+ name: "shared_block_agent2",
+ memoryBlocks: [
+ {
+ label: "persona",
+ value: "I am agent 2"
+ },
+ ],
+ blockIds: [block.id],
+ model: "openai/gpt-4o-mini",
+ embedding: "openai/text-embedding-3-small"
+});
+```
+```python title="python" maxLines=50
+# create a persisted block, which can be attached to agents
+block = client.blocks.create(
+ label="organization",
+ description="A block to store information about the organization",
+ value="Organization: Letta",
+ limit=4000,
+)
+
+# create an agent with both a shared block and its own blocks
+shared_block_agent1 = client.agents.create(
+ name="shared_block_agent1",
+ memory_blocks=[
+ {
+ "label": "persona",
+ "value": "I am agent 1"
+ },
+ ],
+ block_ids=[block.id],
+ model="openai/gpt-4o-mini",
+ embedding="openai/text-embedding-3-small"
+)
+
+# create another agent sharing the block
+shared_block_agent2 = client.agents.create(
+ name="shared_block_agent2",
+ memory_blocks=[
+ {
+ "label": "persona",
+ "value": "I am agent 2"
+ },
+ ],
+ block_ids=[block.id],
+ model="openai/gpt-4o-mini",
+ embedding="openai/text-embedding-3-small"
+)
+```
+</CodeGroup>
+You can also attach blocks to existing agents:
+<CodeGroup>
+```typescript TypeScript
+await client.agents.blocks.attach(agent.id, block.id);
+```
+```python Python
+client.agents.blocks.attach(agent_id=agent.id, block_id=block.id)
+```
+</CodeGroup>
+You can see all agents attached to a block by using the `block_id` field in the [blocks retrieve](/api-reference/blocks/retrieve) endpoint.
+
+## Managing blocks
+
+### Retrieving a block
+You can retrieve the contents of a block by ID. This is useful when blocks store finalized reports, code outputs, or other data you want to extract for use outside the agent.
+
+<CodeGroup>
+```typescript TypeScript
+const block = await client.blocks.retrieve(block.id);
+console.log(block.value); // access the block's content
+```
+```python Python
+block = client.blocks.retrieve(block.id)
+print(block.value) # access the block's content
+```
+</CodeGroup>
+
+### Listing blocks
+You can list all blocks, optionally filtering by label or searching by label text. This is useful for finding blocks across your project.
+
+<CodeGroup>
+```typescript TypeScript
+// list all blocks
+const blocks = await client.blocks.list();
+
+// filter by label
+const humanBlocks = await client.blocks.list({
+ label: "human"
+});
+
+// search by label text
+const searchResults = await client.blocks.list({
+ labelSearch: "organization"
+});
+```
+```python Python
+# list all blocks
+blocks = client.blocks.list()
+
+# filter by label
+human_blocks = client.blocks.list(label="human")
+
+# search by label text
+search_results = client.blocks.list(label_search="organization")
+```
+</CodeGroup>
+
+### Modifying a block
+You can directly modify a block's content, limit, description, or other properties. This is particularly useful for:
+- External scripts that provide up-to-date information to agents (e.g., syncing a text file to a block)
+- Updating shared blocks that multiple agents reference
+- Programmatically managing block content outside of agent interactions
+
+<CodeGroup>
+```typescript TypeScript
+// update the block's value - completely replaces the content
+await client.blocks.modify(block.id, {
+ value: "Updated organization information: Letta - Building agentic AI"
+});
+
+// update multiple properties
+await client.blocks.modify(block.id, {
+ value: "New content",
+ limit: 6000,
+ description: "Updated description"
+});
+```
+```python Python
+# update the block's value - completely replaces the content
+client.blocks.modify(
+ block.id,
+ value="Updated organization information: Letta - Building agentic AI"
+)
+
+# update multiple properties
+client.blocks.modify(
+ block.id,
+ value="New content",
+ limit=6000,
+ description="Updated description"
+)
+```
+</CodeGroup>
+
+<Warning>
+**Setting `value` completely replaces the entire block content** - it is not an append operation. If multiple processes (agents or external scripts) modify the same block concurrently, the last write wins and overwrites all earlier changes. To avoid data loss:
+- Set blocks to **read-only** if you don't want agents to modify them
+- Only modify blocks directly in controlled scenarios where overwriting is acceptable
+- Ensure your application logic accounts for full replacements, not merges
+</Warning>
+
+### Deleting a block
+You can delete a block when it's no longer needed. Note that deleting a block will remove it from all agents that have it attached.
+
+<CodeGroup>
+```typescript TypeScript
+await client.blocks.delete(block.id);
+```
+```python Python
+client.blocks.delete(block_id=block.id)
+```
+</CodeGroup>
+
+### Inspecting block usage
+See which agents have a block attached:
+
+<CodeGroup>
+```typescript TypeScript
+// list all agents that use this block
+const agentsWithBlock = await client.blocks.agents.list(block.id);
+console.log(`Used by ${agentsWithBlock.length} agents:`);
+for (const agent of agentsWithBlock) {
+ console.log(` - ${agent.name}`);
+}
+
+// with pagination
+const agentsPage = await client.blocks.agents.list(block.id, {
+ limit: 10,
+ order: "asc"
+});
+```
+```python Python
+# list all agents that use this block
+agents_with_block = client.blocks.agents.list(block_id=block.id)
+print(f"Used by {len(agents_with_block)} agents:")
+for agent in agents_with_block:
+ print(f" - {agent.name}")
+
+# with pagination
+agents_page = client.blocks.agents.list(
+ block_id=block.id,
+ limit=10,
+ order="asc"
+)
+```
+</CodeGroup>
+
+## Agent-scoped block operations
+
+### Listing an agent's blocks
+You can retrieve all blocks attached to a specific agent. This shows you the complete memory configuration for that agent.
+
+<CodeGroup>
+```typescript TypeScript
+const agentBlocks = await client.agents.blocks.list(agent.id);
+```
+```python Python
+agent_blocks = client.agents.blocks.list(agent_id=agent.id)
+```
+</CodeGroup>
+
+### Retrieving an agent's block by label
+Instead of using a block ID, you can retrieve a block from a specific agent using its label. This is useful when you want to inspect what the agent currently knows about a specific topic.
+
+<CodeGroup>
+```typescript TypeScript
+// get the agent's current knowledge about the human
+const humanBlock = await client.agents.blocks.retrieve(
+ agent.id,
+ "human"
+);
+console.log(humanBlock.value);
+```
+```python Python
+# get the agent's current knowledge about the human
+human_block = client.agents.blocks.retrieve(
+ agent_id=agent.id,
+ block_label="human"
+)
+print(human_block.value)
+```
+</CodeGroup>
+
+### Modifying an agent's block
+You can modify a block through the agent-scoped endpoint using the block's label. This is useful for updating agent-specific memory without needing to know the block ID.
+
+<CodeGroup>
+```typescript TypeScript
+// update the agent's human block
+await client.agents.blocks.modify(agent.id, "human", {
+ value: "The human's name is Alice. She prefers Python over TypeScript."
+});
+```
+```python Python
+# update the agent's human block
+client.agents.blocks.modify(
+ agent_id=agent.id,
+ block_label="human",
+ value="The human's name is Alice. She prefers Python over TypeScript."
+)
+```
+</CodeGroup>
+
+### Detaching blocks from agents
+You can detach a block from an agent's context window. This removes the block from the agent's memory without deleting the block itself.
+
+<CodeGroup>
+```typescript TypeScript
+await client.agents.blocks.detach(agent.id, block.id);
+```
+```python Python
+client.agents.blocks.detach(agent_id=agent.id, block_id=block.id)
+```
+</CodeGroup>
diff --git a/fern/pages/agents/prebuilt_tools.mdx b/fern/pages/agents/prebuilt_tools.mdx
new file mode 100644
index 000000000..fd498f503
--- /dev/null
+++ b/fern/pages/agents/prebuilt_tools.mdx
@@ -0,0 +1,47 @@
+---
+title: Pre-built Tools
+subtitle: Understanding the pre-built tools in the Letta server
+slug: guides/agents/prebuilt-tools
+---
+
+Letta provides a set of pre-built tools that are available to all agents. These tools include memory management tools (for reading and writing to memory blocks), file editing tools, multi-agent tools, and general utility tools like web search and code execution.
+
+## Default Memory Tools
+
+By default, agents in Letta are created with a set of default tools including `send_message` (which generates a message to send to the user), core memory tools (allowing the agent to edit its memory blocks), and external memory tools (to read/write from archival memory, and to access recall memory, aka the conversation history):
+
+| Tool | Description |
+|--------------------------------------------|------------------------------------------------------|
+| `send_message` | Sends a message to the human user. |
+| `memory_insert` | Insert content into a block in core memory. |
+| `memory_replace` | Replace content in a block in core memory. |
+| `memory_rethink` | Reflect on and reorganize core memory contents. |
+| `memory_finish_edits` | Finalize memory editing operations. |
+| `core_memory_append` _(Deprecated)_ | Append to the contents of a block in core memory. |
+| `core_memory_replace` _(Deprecated)_ | Replace the contents of a block in core memory. |
+| `conversation_search` | Search prior conversation history (recall memory) |
+| `archival_memory_insert` | Add a memory to archival memory |
+| `archival_memory_search` | Search archival memory via embedding search |
+
+You can disable the default tools by setting `include_base_tools` to `false` during agent creation. Note that disabling the `send_message` tool may cause agent messages (intended for the user) to appear as "reasoning" messages in the API and ADE.
+
+## Multi-Agent Tools
+
+Letta also includes a set of pre-made tools designed for multi-agent interaction.
+See [our guide on multi-agent](/guides/agents/multi-agent) for more information.
+
+## Web Search
+
+The `web_search` tool allows agents to search the web for information.
+
+<Info>
+On [Letta Cloud](/guides/cloud/overview), this tool works out of the box, but when using this tool on a self-hosted Letta server, you must set a `EXA_API_KEY` environment variable either in during server startup or in your agent's [tool execution environment](/guides/agents/tool-variables).
+</Info>
+
+## Code Interpreter
+
+The `run_code` tool allows agents to run code (in a sandbox), for example to do data analysis or calculations. Supports Python, Javascript, Typescript, R, and Java.
+
+<Info>
+On [Letta Cloud](/guides/cloud/overview), this tool works out of the box, but when using this tool on a self-hosted Letta server, you must set a `E2B_API_KEY` environment variable either in during server startup or in your agent's [tool execution environment](/guides/agents/tool-variables).
+</Info>
diff --git a/fern/pages/agents/shared-memory-blocks-guide.mdx b/fern/pages/agents/shared-memory-blocks-guide.mdx
new file mode 100644
index 000000000..c30692af8
--- /dev/null
+++ b/fern/pages/agents/shared-memory-blocks-guide.mdx
@@ -0,0 +1,837 @@
+---
+title: Shared Memory Blocks Guide
+subtitle: Complete guide to using shared memory for multi-agent coordination
+slug: guides/agents/shared-memory-blocks
+---
+
+Shared memory blocks enable multiple agents to access and update the same memory, creating powerful multi-agent systems with seamless coordination.
+
+## Overview
+
+**Shared memory blocks** allow you to attach the same memory block to multiple agents. When one agent updates the block, all other agents with access immediately see the changes. This enables:
+
+- **Real-time coordination** without explicit agent-to-agent messaging
+- **Consistent information** across teams and departments
+- **Hierarchical access control** based on roles and responsibilities
+- **Privacy boundaries** for sensitive information
+- **Knowledge sharing** across specialized agents
+
+<Note>
+Shared memory blocks are different from agent-to-agent messaging (like `send_message_to_agent_async`). With shared memory, agents coordinate **asynchronously** through shared state rather than direct communication.
+</Note>
+
+## Core Concepts
+
+### What is a Shared Memory Block?
+
+A memory block becomes "shared" when you attach it to multiple agents using the same `block_id`. All agents with access see the same content in real-time.
+
+```python
+from letta import Letta
+
+client = Letta()
+
+# Step 1: Create a memory block
+shared_block = client.blocks.create(
+ label="team_knowledge",
+ description="Shared knowledge base for the team",
+ value="Team policies and procedures...",
+ limit=5000
+)
+
+# Step 2: Attach to multiple agents
+agent1 = client.agents.create(
+ name="Agent_1",
+ block_ids=[shared_block.id], # Attach shared block
+ # ... other config
+)
+
+agent2 = client.agents.create(
+ name="Agent_2",
+ block_ids=[shared_block.id], # Same block ID = shared memory
+ # ... other config
+)
+
+# Now agent1 and agent2 share the same memory block!
+```
+
+### Block Types
+
+| Type | Description | Use Case |
+|---|---|---|
+| **Read-Only** | Agents can read but not modify | Company policies, reference data |
+| **Read/Write** | Agents can read and update | Task queues, shared notes |
+| **Private** | Single agent only | Personal work logs, private notes |
+
+### Access Patterns
+
+Letta supports multiple access patterns for organizing shared memory:
+
+1. **Hierarchical**: Tier 1 < Tier 2 < Tier 3 (access increases up the hierarchy)
+2. **Team-Based**: All team members share the same blocks
+3. **Overlapping**: Each agent has a unique combination of blocks
+4. **Organizational**: Department → Cross-Department → Executive levels
+
+## Architecture Patterns
+
+### Pattern 1: Hierarchical Access (Support Tiers)
+
+```
+Tier 1 Agents → company_policies [R]
+Tier 2 Agents → company_policies [R], escalation_procedures [R]
+Tier 3 Agents → company_policies [R], escalation_procedures [R], team_metrics [R/W]
+```
+
+**Use Cases:**
+- Customer support with tier levels
+- Knowledge bases with sensitivity levels
+- Organizations with clearance levels
+
+**Example:** [Read-Only Organizational Knowledge Tutorial](/cookbooks/shared-memory-read-only)
+
+### Pattern 2: Team Coordination (Shared Queues)
+
+```
+All Team Members → task_queue [R/W], completed_work [R/W]
+Supervisor Only → team_metrics [R/W]
+Each Worker → private_work_log [R/W]
+```
+
+**Use Cases:**
+- Task coordination across workers
+- Project management teams
+- Shared deliverables tracking
+
+**Example:** [Task Coordination Tutorial](/cookbooks/shared-memory-task-coordination)
+
+### Pattern 3: Specialized Agents (Overlapping Access)
+
+```
+Coordinator → ALL blocks (user_profile, preferences, interaction_history, calendar, financial)
+Email Agent → user_profile, preferences, interaction_history, calendar
+Research Agent → user_profile, preferences, interaction_history
+Calendar Agent → user_profile, preferences, calendar
+Finance Agent → user_profile, preferences, financial
+```
+
+**Use Cases:**
+- Personal AI assistant networks
+- Specialized service agents
+- Multi-domain customer support
+
+**Example:** [Multi-Agent User Assistant Tutorial](/cookbooks/shared-memory-user-assistant)
+
+### Pattern 4: Enterprise Hierarchy (Departments)
+
+```
+Company-Wide [R] → ALL agents (mission, policies)
+Department Blocks [R/W] → Department members only
+Cross-Dept Block [R/W] → All directors + CEO
+Executive Dashboard [R/W] → CEO only
+```
+
+**Use Cases:**
+- Enterprise organizations
+- Multi-department companies
+- Regulated industries with compliance requirements
+
+**Example:** [Enterprise Multi-Team Tutorial](/cookbooks/shared-memory-enterprise)
+
+## Best Practices
+
+### 1. Use Read-Only Blocks for Critical Information
+
+Protect policies, procedures, and reference data from accidental modification:
+
+```python
+company_policies = client.blocks.create(
+ label="company_policies",
+ value="Our company policies...",
+ # Read-only ensures consistency
+)
+```
+
+<Warning>
+Even though Letta doesn't currently enforce read-only at the API level, agents will respect read-only semantics and refuse to modify these blocks when instructed not to in their persona.
+</Warning>
+
+### 2. Implement the Principle of Least Privilege
+
+Only give agents access to blocks they need:
+
+```python
+# ❌ Bad: Sales agent with access to HR data
+sales_agent = client.agents.create(
+ block_ids=[sales_knowledge.id, hr_employee_data.id] # Too much access
+)
+
+# ✓ Good: Sales agent with only sales data
+sales_agent = client.agents.create(
+ block_ids=[sales_knowledge.id] # Appropriate access
+)
+```
+
+### 3. Use Clear Naming Conventions
+
+Make block purposes obvious:
+
+```python
+# ✓ Good names
+"company_policies" # Clear scope and content
+"sales_team_knowledge" # Clear ownership
+"cross_dept_projects" # Clear purpose
+"ceo_executive_dashboard" # Clear access level
+
+# ❌ Bad names
+"data" # Too generic
+"block1" # Not descriptive
+"temp" # Purpose unclear
+```
+
+### 4. Set Appropriate Character Limits
+
+Balance between enough space and memory constraints:
+
+```python
+# Reference data: smaller
+company_policies = client.blocks.create(
+ limit=5000 # Policies don't change often
+)
+
+# Active coordination: larger
+task_queue = client.blocks.create(
+ limit=10000 # Tasks accumulate over time
+)
+
+# Detailed logs: largest
+interaction_history = client.blocks.create(
+ limit=12000 # Many interactions to track
+)
+```
+
+<Tip>
+If a block frequently hits its character limit, consider archiving old content or splitting into multiple blocks (e.g., `current_tasks` vs `completed_tasks`).
+</Tip>
+
+### 5. Document Block Access in Agent Personas
+
+Make agents aware of their access:
+
+```python
+agent = client.agents.create(
+ memory_blocks=[{
+ "label": "persona",
+ "value": """I am a Sales Representative.
+
+My access:
+- company_policies (read-only): Company-wide policies
+- sales_knowledge (read/write): Shared with sales team
+- my_leads (private): My personal lead tracking
+
+I do NOT have access to:
+- engineering_specs (Engineering team only)
+- hr_employee_data (HR team only)
+"""
+ }]
+)
+```
+
+### 6. Use Descriptive Block Descriptions
+
+Help with debugging and management:
+
+```python
+block = client.blocks.create(
+ label="sales_knowledge",
+ description="Sales team knowledge base: pricing, playbooks, targets. Read/write access for Sales Director, Rep 1, Rep 2.",
+ # Good description includes: content, access, and purpose
+)
+```
+
+## Common Use Cases
+
+### Use Case 1: Customer Support with Tiers
+
+**Problem:** Support agents at different levels need different information.
+
+**Solution:** Hierarchical blocks with increasing access
+
+```
+support_tier1/ → Basic policies
+support_tier2/ → Advanced troubleshooting + escalation procedures
+support_tier3/ → Full system access + team metrics
+```
+
+**Benefits:**
+- Consistent policy information across all tiers
+- Sensitive escalation procedures protected
+- Supervisors track team performance privately
+
+### Use Case 2: Project Management Team
+
+**Problem:** Multiple workers need to coordinate on tasks.
+
+**Solution:** Shared task queue + completion log
+
+```
+task_queue (R/W) → All team members claim and update tasks
+completed_work (R/W) → All team members share findings
+team_metrics (R/W) → Supervisor only tracks performance
+```
+
+**Benefits:**
+- Real-time task claiming without conflicts
+- Knowledge sharing through completed work
+- Supervisor oversight without micromanagement
+
+### Use Case 3: Personal AI Assistant Network
+
+**Problem:** User needs specialized agents that understand full context.
+
+**Solution:** Overlapping block access with privacy boundaries
+
+```
+Universal: user_profile, user_preferences → All agents
+Coordination: interaction_history → Coordinator, Email, Research
+Domain-specific: calendar_data → Calendar, Email agents only
+Restricted: financial_data → Finance agent only
+```
+
+**Benefits:**
+- Seamless handoffs between specialists
+- Consistent user experience
+- Privacy protection for sensitive data
+
+### Use Case 4: Enterprise Organization
+
+**Problem:** Large company with departments needs coordination.
+
+**Solution:** Multi-tier hierarchy with isolation
+
+```
+Company-wide (R) → All employees see mission/policies
+Department (R/W) → Each dept has private knowledge
+Cross-dept (R/W) → Directors coordinate projects
+Executive (R/W) → CEO tracks company metrics
+```
+
+**Benefits:**
+- Department autonomy and isolation
+- Async cross-department coordination
+- Executive oversight without bottlenecks
+- Compliance with data privacy regulations
+
+## API Reference
+
+### Creating Shared Blocks
+
+```python
+block = client.blocks.create(
+ label="block_name", # Required: identifier
+ description="What this is", # Recommended: for management
+ value="Initial content", # Required: starting content
+ limit=5000 # Optional: character limit
+)
+```
+
+### Attaching to Agents (at Creation)
+
+```python
+agent = client.agents.create(
+ name="Agent_Name",
+ block_ids=[block1.id, block2.id], # Attach existing blocks
+ memory_blocks=[ # Create new private blocks
+ {"label": "persona", "value": "..."}
+ ],
+ # ... other config
+)
+```
+
+### Attaching to Existing Agents
+
+```python
+# Attach a block to an existing agent
+client.agents.blocks.attach(
+ agent_id=agent.id,
+ block_id=block.id
+)
+
+# Detach a block from an agent
+client.agents.blocks.detach(
+ agent_id=agent.id,
+ block_id=block.id
+)
+```
+
+### Listing Blocks
+
+Find blocks across your project with optional filtering:
+
+<CodeGroup>
+```python Python
+# List all blocks in project
+all_blocks = client.blocks.list()
+
+# Filter by label
+team_blocks = client.blocks.list(label="team_knowledge")
+
+# Search by label text
+search_results = client.blocks.list(label_search="sales")
+```
+```typescript TypeScript
+// List all blocks in project
+const allBlocks = await client.blocks.list();
+
+// Filter and search
+const teamBlocks = await client.blocks.list({
+ label: "team_knowledge",
+ labelSearch: "sales"
+});
+```
+</CodeGroup>
+
+### Retrieving a Block
+
+Get complete block information by ID:
+
+<CodeGroup>
+```python Python
+block = client.blocks.retrieve(block.id)
+print(f"Block: {block.label}")
+print(f"Value: {block.value}")
+```
+```typescript TypeScript
+const block = await client.blocks.retrieve(block.id);
+console.log(`Block: ${block.label}`);
+console.log(`Value: ${block.value}`);
+```
+</CodeGroup>
+
+### Modifying Blocks Directly
+
+Update block content without going through an agent. Useful for external scripts syncing data to agents:
+
+<CodeGroup>
+```python Python
+# Update block content - completely replaces the value
+client.blocks.modify(
+ block.id,
+ value="Updated team knowledge: New procedures..."
+)
+
+# Update multiple properties
+client.blocks.modify(
+ block.id,
+ value="New content",
+ limit=8000,
+ description="Updated description"
+)
+
+# Make block read-only
+client.blocks.modify(block.id, read_only=True)
+```
+```typescript TypeScript
+// Update block content - completely replaces the value
+await client.blocks.modify(block.id, {
+ value: "Updated team knowledge: New procedures..."
+});
+
+// Update multiple properties
+await client.blocks.modify(block.id, {
+ value: "New content",
+ limit: 8000,
+ description: "Updated description"
+});
+
+// Make block read-only
+await client.blocks.modify(block.id, { readOnly: true });
+```
+</CodeGroup>
+
+<Warning>
+**Setting `value` completely replaces the entire block content** - it is not an append operation. When you modify a shared block directly, all agents with access will see the changes immediately.
+
+**Race condition risk**: If two processes (agents or external scripts) modify the same block concurrently, the last write wins and completely overwrites all earlier changes. To avoid data loss:
+- Set blocks to **read-only** if you don't want agents or other processes to modify them
+- Only allow direct modifications in controlled scenarios where overwriting is acceptable
+- Ensure your application logic accounts for the fact that block updates are full replacements, not merges
+</Warning>
+
+### Deleting Blocks
+
+Remove blocks when no longer needed. This detaches the block from all agents:
+
+<CodeGroup>
+```python Python
+client.blocks.delete(block_id=block.id)
+```
+```typescript TypeScript
+await client.blocks.delete(block.id);
+```
+</CodeGroup>
+
+### Agent-Scoped Operations
+
+#### List an Agent's Blocks
+
+See all memory blocks attached to a specific agent:
+
+<CodeGroup>
+```python Python
+# List all blocks for an agent
+agent_blocks = client.agents.blocks.list(agent_id=agent.id)
+
+# With pagination
+agent_blocks = client.agents.blocks.list(
+ agent_id=agent.id,
+ limit=10,
+ order="asc"
+)
+
+for block in agent_blocks:
+ print(f"{block.label}: {block.value[:50]}...")
+```
+```typescript TypeScript
+// List all blocks for an agent
+const agentBlocks = await client.agents.blocks.list(agent.id);
+
+// With pagination
+const agentBlocksPaginated = await client.agents.blocks.list(agent.id, {
+ limit: 10,
+ order: "asc"
+});
+
+for (const block of agentBlocks) {
+ console.log(`${block.label}: ${block.value.slice(0, 50)}...`);
+}
+```
+</CodeGroup>
+
+#### Retrieve Agent's Block by Label
+
+Get a specific block from an agent using its label instead of ID:
+
+<CodeGroup>
+```python Python
+# Get agent's human block
+human_block = client.agents.blocks.retrieve(
+ agent_id=agent.id,
+ block_label="human"
+)
+print(human_block.value)
+
+# Get shared task queue from specific agent
+task_queue = client.agents.blocks.retrieve(
+ agent_id=worker_agent.id,
+ block_label="task_queue"
+)
+```
+```typescript TypeScript
+// Get agent's human block
+const humanBlock = await client.agents.blocks.retrieve(
+ agent.id,
+ "human"
+);
+console.log(humanBlock.value);
+
+// Get shared task queue from specific agent
+const taskQueue = await client.agents.blocks.retrieve(
+ workerAgent.id,
+ "task_queue"
+);
+```
+</CodeGroup>
+
+#### Modify Agent's Block by Label
+
+Update a specific agent's block without needing the block ID:
+
+<CodeGroup>
+```python Python
+# Update agent's knowledge about the human
+client.agents.blocks.modify(
+ agent_id=agent.id,
+ block_label="human",
+ value="Updated user information: Alice, prefers email over chat"
+)
+
+# Update shared block via specific agent
+client.agents.blocks.modify(
+ agent_id=worker.id,
+ block_label="task_queue",
+ value="Updated task queue with new items..."
+)
+```
+```typescript TypeScript
+// Update agent's knowledge about the human
+await client.agents.blocks.modify(agent.id, "human", {
+ value: "Updated user information: Alice, prefers email over chat"
+});
+
+// Update shared block via specific agent
+await client.agents.blocks.modify(worker.id, "task_queue", {
+ value: "Updated task queue with new items..."
+});
+```
+</CodeGroup>
+
+### Inspecting Block Usage
+
+See which agents have a block attached:
+
+<CodeGroup>
+```python Python
+# List all agents that use this block
+agents_with_block = client.blocks.agents.list(block_id=block.id)
+print(f"Used by {len(agents_with_block)} agents:")
+for agent in agents_with_block:
+ print(f" - {agent.name}")
+
+# With pagination
+agents_page = client.blocks.agents.list(
+ block_id=block.id,
+ limit=10,
+ order="asc"
+)
+```
+```typescript TypeScript
+// List all agents that use this block
+const agentsWithBlock = await client.blocks.agents.list(block.id);
+console.log(`Used by ${agentsWithBlock.length} agents:`);
+for (const agent of agentsWithBlock) {
+ console.log(` - ${agent.name}`);
+}
+
+// With pagination
+const agentsPage = await client.blocks.agents.list(block.id, {
+ limit: 10,
+ order: "asc"
+});
+```
+</CodeGroup>
+
+### Updating Blocks via Agents
+
+Agents update blocks using memory tools during conversations:
+
+<CodeGroup>
+```python Python
+# Agent updates shared block content
+client.agents.messages.create(
+ agent_id=agent.id,
+ messages=[{
+ "role": "user",
+ "content": "Update the task queue to mark task-001 as complete"
+ }]
+)
+
+# Agent uses core_memory_replace or core_memory_append tools
+# Changes are immediately visible to all agents with access
+```
+```typescript TypeScript
+// Agent updates shared block content
+await client.agents.messages.create(agent.id, {
+ messages: [{
+ role: "user",
+ content: "Update the task queue to mark task-001 as complete"
+ }]
+});
+
+// Agent uses core_memory_replace or core_memory_append tools
+// Changes are immediately visible to all agents with access
+```
+</CodeGroup>
+
+## Troubleshooting
+
+### Problem: Agent Can't See Block Updates
+
+**Symptoms:** Agent reads old content after another agent updated it.
+
+**Solutions:**
+1. Verify both agents have the same `block_id` attached
+2. Check that updates are being committed (agent finished its turn)
+3. Ensure character limit hasn't been exceeded (updates may fail silently)
+
+```python
+# Debug: Check which agents share the block
+block_info = client.blocks.retrieve(block_id=block.id)
+print(f"Agents with access: {block_info.agent_ids}")
+```
+
+### Problem: Block Character Limit Exceeded
+
+**Symptoms:** Updates not applying, content truncated.
+
+**Solutions:**
+1. Increase block limit: `client.blocks.update(block_id=block.id, limit=10000)`
+2. Archive old content: Move completed items to a separate block
+3. Summarize content: Have an agent periodically summarize and condense
+
+```python
+# Check current usage
+block = client.blocks.retrieve(block_id=block.id)
+print(f"Characters: {len(block.value)} / {block.limit}")
+```
+
+### Problem: Privacy Violation
+
+**Symptoms:** Agent accessing data it shouldn't see.
+
+**Solutions:**
+1. Review block attachments: `client.agents.retrieve(agent_id).block_ids`
+2. Detach inappropriate blocks: `client.agents.blocks.detach()`
+3. Update agent persona to clarify access boundaries
+4. Consider splitting one block into multiple with different access
+
+### Problem: Race Conditions on Concurrent Updates
+
+**Symptoms:** Two agents try to claim the same task, conflicts occur.
+
+**Solutions:**
+1. Design blocks to minimize conflicts (separate sections for each agent)
+2. Use timestamps and agent IDs in updates
+3. Implement retry logic for failed updates
+4. Consider optimistic concurrency control
+
+```python
+# Good: Each agent updates their own section
+"""
+TASK-001:
+ Status: In Progress
+ Claimed by: Worker_1
+ Timestamp: 2024-10-08 14:30
+
+TASK-002:
+ Status: In Progress
+ Claimed by: Worker_2
+ Timestamp: 2024-10-08 14:31
+"""
+```
+
+## Performance Considerations
+
+### Block Size and Agent Performance
+
+- **Smaller blocks (<5K chars)**: Faster loading, more focused context
+- **Larger blocks (>10K chars)**: More context but slower processing
+- **Optimal**: Keep blocks focused on single purpose, split large blocks
+
+### Number of Blocks per Agent
+
+- **Recommended**: 3-7 blocks per agent
+- **Each block adds**: Context in agent's working memory
+- **Too many blocks**: May dilute agent focus
+- **Too few blocks**: May limit coordination capabilities
+
+### Update Frequency
+
+- **High-frequency updates** (many agents, frequent changes): Consider separate blocks to reduce contention
+- **Low-frequency updates** (policies, references): Larger consolidated blocks are fine
+
+## Security and Compliance
+
+### Data Privacy
+
+Shared memory blocks enable compliance with data privacy regulations:
+
+```python
+# GDPR/HIPAA Example: Isolate sensitive data
+hr_employee_data = client.blocks.create(
+ label="hr_employee_data",
+ description="CONFIDENTIAL - HR Department only. Contains PII."
+)
+
+# Only attach to authorized agents
+hr_director = client.agents.create(
+ block_ids=[hr_employee_data.id] # Only HR has access
+)
+
+# Sales/Engineering agents do NOT get access
+sales_agent = client.agents.create(
+ block_ids=[sales_knowledge.id] # No HR data access
+)
+```
+
+### Audit Trail
+
+Track block access for compliance:
+
+```python
+# Check block usage
+block_info = client.blocks.retrieve(block_id=sensitive_block.id)
+print(f"Accessed by: {block_info.agent_ids}")
+
+# Log all agents with access
+for agent_id in block_info.agent_ids:
+ agent = client.agents.retrieve(agent_id=agent_id)
+ print(f" {agent.name} - {agent.created_at}")
+```
+
+### Access Revocation
+
+Remove access when no longer needed:
+
+```python
+# Employee leaves company - revoke agent access
+client.agents.blocks.detach(
+ agent_id=former_employee_agent.id,
+ block_id=company_confidential.id
+)
+
+# Or delete the agent entirely
+client.agents.delete(agent_id=former_employee_agent.id)
+```
+
+## Tutorials
+
+Learn shared memory patterns through hands-on tutorials:
+
+<CardGroup cols={2}>
+<Card title="Part 1: Read-Only Knowledge" icon="lock" href="/cookbooks/shared-memory-read-only">
+Build a hierarchical support team with shared company policies
+</Card>
+
+<Card title="Part 2: Task Coordination" icon="list-check" href="/cookbooks/shared-memory-task-coordination">
+Create a data analysis team with shared task queues
+</Card>
+
+<Card title="Part 3: User Assistant Network" icon="users" href="/cookbooks/shared-memory-user-assistant">
+Build specialized agents with overlapping block access
+</Card>
+
+<Card title="Part 4: Enterprise System" icon="building" href="/cookbooks/shared-memory-enterprise">
+Implement a complete enterprise with departments and hierarchies
+</Card>
+</CardGroup>
+
+## Related Guides
+
+<CardGroup cols={2}>
+<Card title="Memory Blocks Overview" icon="database" href="/guides/agents/memory-blocks">
+Understanding memory blocks and core memory
+</Card>
+
+<Card title="Multi-Agent Systems" icon="diagram-project" href="/guides/agents/multi-agent">
+Overview of multi-agent architectures in Letta
+</Card>
+
+<Card title="Agent-to-Agent Messaging" icon="comments" href="/cookbooks/multi-agent-async">
+Alternative coordination pattern using async messaging
+</Card>
+
+<Card title="API Reference" icon="code" href="/api-reference/agents/core-memory">
+Complete API documentation for blocks and memory
+</Card>
+</CardGroup>
+
+## Key Takeaways
+
+✓ **Shared memory blocks** enable seamless multi-agent coordination without explicit messaging
+✓ **Access patterns** range from simple (all agents) to complex (hierarchical organizations)
+✓ **Privacy boundaries** protect sensitive data while enabling collaboration
+✓ **Real-time sync** ensures all agents see updates immediately
+✓ **Scales** from 2 agents to enterprise systems with 10+ agents
+✓ **Complements** agent-to-agent messaging for complete multi-agent systems
+
+Shared memory blocks are a powerful primitive for building sophisticated multi-agent systems. Start with simple patterns (Tutorial 1) and progress to complex architectures (Tutorial 4) as your needs grow.
diff --git a/fern/pages/examples/attaching_detaching_blocks.mdx b/fern/pages/tutorials/attaching_detaching_blocks.mdx
similarity index 100%
rename from fern/pages/examples/attaching_detaching_blocks.mdx
rename to fern/pages/tutorials/attaching_detaching_blocks.mdx
diff --git a/fern/pages/examples/hello_world.mdx b/fern/pages/tutorials/hello_world.mdx
similarity index 100%
rename from fern/pages/examples/hello_world.mdx
rename to fern/pages/tutorials/hello_world.mdx
diff --git a/fern/pages/tutorials/shared-memory-blocks.mdx b/fern/pages/tutorials/shared-memory-blocks.mdx
new file mode 100644
index 000000000..91ba3ad5e
--- /dev/null
+++ b/fern/pages/tutorials/shared-memory-blocks.mdx
@@ -0,0 +1,541 @@
+---
+title: "Shared Memory Blocks"
+subtitle: Enable multi-agent collaboration through shared memory
+slug: tutorials/shared-memory-blocks
+---
+
+## Overview
+
+Memory blocks can be shared between multiple agents, enabling powerful multi-agent collaboration patterns. When a block is shared, all attached agents can read and write to it, creating a common workspace for coordinating information and tasks.
+
+This tutorial demonstrates how to:
+- Create memory blocks that multiple agents can access
+- Build collaborative workflows where agents contribute different information
+- Use read-only blocks to provide shared context without allowing modifications
+- Understand how memory tools handle concurrent updates
+
+By the end of this guide, you'll understand how to build simple multi-agent systems where agents work together by sharing memory.
+
+<Note>
+**This tutorial uses Letta Cloud.** Generate an API key at [app.letta.com/api-keys](https://app.letta.com/api-keys) and set it as `LETTA_API_KEY` in your environment. Self-hosted servers only need an API key if authentication is enabled.
+
+The `web_search` tool used in this tutorial requires an `EXA_API_KEY` environment variable when self-hosting. You can learn more about self-hosting [here](/guides/selfhosting).
+</Note>
+
+## What You'll Learn
+
+- Creating standalone memory blocks for sharing
+- Attaching the same block to multiple agents
+- Building collaborative workflows with shared memory
+- Using read-only blocks for policies and system information
+- Understanding how memory tools handle concurrent updates
+
+## Prerequisites
+
+You will need to install `letta-client` to interface with a Letta server:
+
+<CodeGroup>
+```bash TypeScript
+npm install @letta-ai/letta-client
+```
+```bash Python
+pip install letta-client
+```
+</CodeGroup>
+
+## Steps
+
+### Step 1: Initialize Client
+
+<CodeGroup>
+```typescript TypeScript
+import { LettaClient } from '@letta-ai/letta-client';
+
+// Initialize the Letta client using LETTA_API_KEY environment variable
+const client = new LettaClient({ token: process.env.LETTA_API_KEY });
+
+// If self-hosting, specify the base URL:
+// const client = new LettaClient({ baseUrl: "http://localhost:8283" });
+```
+```python Python
+from letta_client import Letta
+import os
+
+# Initialize the Letta client using LETTA_API_KEY environment variable
+client = Letta(token=os.getenv("LETTA_API_KEY"))
+
+# If self-hosting, specify the base URL:
+# client = Letta(base_url="http://localhost:8283")
+```
+</CodeGroup>
+
+### Step 2: Create a Shared Memory Block
+
+Create a standalone memory block that will be shared between multiple agents. This block will serve as a collaborative workspace where both agents can contribute information.
+
+We're going to give the block the label "organization" to indicate that it contains information about some organization. The starting value of this block is "Organization: Letta" to give the agents a starting point to work from.
+
+<CodeGroup>
+```typescript TypeScript
+// Create a memory block that will be shared between agents
+// API Reference: https://docs.letta.com/api-reference/blocks/create
+const block = await client.blocks.create({
+ label: "organization",
+ value: "Organization: Letta",
+ limit: 4000,
+});
+
+console.log(`Created shared block: ${block.id}\n`);
+```
+```python Python
+# Create a memory block that will be shared between agents
+# API Reference: https://docs.letta.com/api-reference/blocks/create
+block = client.blocks.create(
+ label="organization",
+ value="Organization: Letta",
+ limit=4000,
+)
+
+print(f"Created shared block: {block.id}\n")
+```
+</CodeGroup>
+
+### Step 3: Create Agents with Shared Block
+
+Create two agents that will both have access to the same memory block. You can attach blocks during creation using `block_ids` or later using the `attach` method.
+
+We'll provide each agent with the `web_search` tool to search the web for information. This tool is built-in to Letta. If you are self-hosting, you will need to set an `EXA_API_KEY` environment variable for either the server or the agent to use this tool.
+
+<CodeGroup>
+```typescript TypeScript
+// Create first agent with block attached during creation
+// API Reference: https://docs.letta.com/api-reference/agents/create
+const agent1 = await client.agents.create({
+ name: "agent1",
+ model: "openai/gpt-4o-mini",
+ blockIds: [block.id],
+ tools: ["web_search"],
+});
+console.log(`Created agent1: ${agent1.id}`);
+
+// Create second agent and attach block afterward
+const agent2 = await client.agents.create({
+ name: "agent2",
+ model: "openai/gpt-4o-mini",
+ tools: ["web_search"],
+});
+console.log(`Created agent2: ${agent2.id}`);
+
+// Attach the shared block to agent2
+// API Reference: https://docs.letta.com/api-reference/agents/blocks/attach
+await client.agents.blocks.attach(agent2.id, { blockId: block.id });
+console.log(`Attached block to agent2\n`);
+```
+```python Python
+# Create first agent with block attached during creation
+# API Reference: https://docs.letta.com/api-reference/agents/create
+agent1 = client.agents.create(
+ name="agent1",
+ model="openai/gpt-4o-mini",
+ block_ids=[block.id],
+ tools=["web_search"],
+)
+print(f"Created agent1: {agent1.id}")
+
+# Create second agent and attach block afterward
+agent2 = client.agents.create(
+ name="agent2",
+ model="openai/gpt-4o-mini",
+ tools=["web_search"],
+)
+print(f"Created agent2: {agent2.id}")
+
+# Attach the shared block to agent2
+# API Reference: https://docs.letta.com/api-reference/agents/blocks/attach
+agent2 = client.agents.blocks.attach(
+ agent_id=agent2.id,
+ block_id=block.id,
+)
+print(f"Attached block to agent2: {agent2.id}")
+```
+</CodeGroup>
+
+### Step 4: Have Agents Collaborate via Shared Memory
+
+Now let's have both agents research different topics and contribute their findings to the shared memory block.
+
+- **Agent 1**: Searches for information about the connection between memory blocks and Letta.
+- **Agent 2**: Searches for information about the origin of Letta.
+
+We're going to ask each agent to search for different information and insert what they learn into the shared memory block, prepended with the agent's name (either `Agent1:` or `Agent2:`).
+
+<CodeGroup>
+```typescript TypeScript
+// Agent1 searches for information about memory blocks
+// API Reference: https://docs.letta.com/api-reference/agents/messages/create
+const response1 = await client.agents.messages.create(agent1.id, {
+ messages: [{
+ role: "user",
+ content: `Find information about the connection between memory blocks and Letta.
+Insert what you learn into the memory block, prepended with "Agent1: ".`
+ }]
+});
+
+for (const msg of response1.messages) {
+ if (msg.messageType === "assistant_message") {
+ console.log(`Agent1 response: ${msg.content}`);
+ }
+ if (msg.messageType === "tool_call_message") {
+ console.log(`Tool call: ${msg.toolCall.name}(${JSON.stringify(msg.toolCall.arguments)})`);
+ }
+}
+
+// Agent2 searches for information about Letta's origin
+const response2 = await client.agents.messages.create(agent2.id, {
+ messages: [{
+ role: "user",
+ content: `Find information about the origin of Letta.
+Insert what you learn into the memory block, prepended with "Agent2: ".`
+ }]
+});
+
+for (const msg of response2.messages) {
+ if (msg.messageType === "assistant_message") {
+ console.log(`Agent2 response: ${msg.content}`);
+ }
+ if (msg.messageType === "tool_call_message") {
+ console.log(`Tool call: ${msg.toolCall.name}(${JSON.stringify(msg.toolCall.arguments)})`);
+ }
+}
+```
+```python Python
+# Agent1 searches for information about memory blocks
+# API Reference: https://docs.letta.com/api-reference/agents/messages/create
+response = client.agents.messages.create(
+ agent_id=agent1.id,
+ messages=[{"role": "user", "content": """
+ Find information about the connection between memory blocks and Letta.
+ Insert what you learn into the memory block, prepended with "Agent1: ".
+"""}],
+)
+
+for msg in response.messages:
+ if msg.message_type == "assistant_message":
+ print(f"Agent1 response: {msg.content}")
+ if msg.message_type == "tool_call_message":
+ print(f"Tool call: {msg.tool_call.name}({msg.tool_call.arguments})")
+
+# Agent2 searches for information about Letta's origin
+response = client.agents.messages.create(
+ agent_id=agent2.id,
+ messages=[{"role": "user", "content": """
+ Find information about the origin of Letta.
+ Insert what you learn into the memory block, prepended with "Agent2: ".
+"""}],
+)
+
+for msg in response.messages:
+ if msg.message_type == "assistant_message":
+ print(f"Agent2 response: {msg.content}")
+ if msg.message_type == "tool_call_message":
+ print(f"Tool call: {msg.tool_call.name}({msg.tool_call.arguments})")
+```
+</CodeGroup>
+
+### Step 5: Inspect the Shared Memory
+
+Let's retrieve the shared memory block to see both agents' contributions:
+
+<CodeGroup>
+```typescript TypeScript
+// Retrieve the shared block to see what both agents learned
+// API Reference: https://docs.letta.com/api-reference/blocks/retrieve
+const updatedBlock = await client.blocks.retrieve(block.id);
+
+console.log("==== Updated block ====");
+console.log(updatedBlock.value);
+console.log("=======================\n");
+```
+```python Python
+# Retrieve the shared block to see what both agents learned
+# API Reference: https://docs.letta.com/api-reference/blocks/retrieve
+updated_block = client.blocks.retrieve(block.id)
+
+print(f"==== Updated block ====")
+print(updated_block.value)
+print(f"=======================")
+```
+</CodeGroup>
+
+The output should be something like this:
+
+> Organization: Letta
+>
+> Agent1: Memory blocks are integral to the Letta framework for managing context in large language models (LLMs). They serve as structured units that enhance an agent's ability to maintain long-term memory and coherence across interactions. Specifically, Letta utilizes memory blocks to organize context into discrete categories, such as "human" memory (user preferences and facts) and "persona" memory (the agent's self-concept and traits). This structured approach allows agents to edit and persist important information, improving performance, personalization, and controllability. By effectively managing the context window through these memory blocks, Letta enhances the overall functionality and adaptability of its LLM agents.
+>
+> Agent2: Letta originated as MemGPT, a research project focused on building
+> stateful AI agents with long-term memory capabilities. It evolved into a
+> platform for building and deploying production-ready agents.
+
+Note that each agent has placed their information into the block, prepended with their name. This is a simple way to identify who contributed what to the block. You don't have to prepend agent identifiers to the block, we only did this for demonstration purposes.
+
+<Note>
+**Understanding concurrent updates**: Memory tools handle concurrent updates differently:
+- `memory_insert` is additive and the most robust for multi-agent systems. Multiple agents can insert content simultaneously without conflicts, as each insert simply appends to the block.
+- `memory_replace` validates that the exact old content exists before replacing it. If another agent modifies the content being replaced, the tool call fails with a validation error, preventing accidental overwrites.
+- `memory_rethink` performs a complete rewrite of the entire block and follows "most recent write wins." This is a destructive operation - use cautiously in multi-agent systems as it can overwrite other agents' contributions.
+</Note>
+
+### Step 6: Using Read-Only Blocks
+
+Read-only blocks are useful for sharing policies, system information, or terms of service that agents should reference but not modify.
+
+<CodeGroup>
+```typescript TypeScript
+// Create a read-only block for policies or system information
+// API Reference: https://docs.letta.com/api-reference/blocks/create
+const readOnlyBlock = await client.blocks.create({
+ label: "read_only_block",
+ value: "This is a read-only block.",
+ readOnly: true,
+});
+
+// Attach the read-only block to an agent
+const readOnlyAgent = await client.agents.create({
+ name: "read_only_agent",
+ model: "openai/gpt-4o-mini",
+ blockIds: [readOnlyBlock.id],
+});
+
+console.log(`Created read-only agent: ${readOnlyAgent.id}`);
+```
+```python Python
+# Create a read-only block for policies or system information
+# API Reference: https://docs.letta.com/api-reference/blocks/create
+read_only_block = client.blocks.create(
+ label="read_only_block",
+ value="This is a read-only block.",
+ read_only=True,
+)
+
+# Attach the read-only block to an agent
+read_only_agent = client.agents.create(
+ name="read_only_agent",
+ model="openai/gpt-4o-mini",
+ block_ids=[read_only_block.id],
+)
+
+print(f"Created read-only agent: {read_only_agent.id}")
+```
+</CodeGroup>
+
+<Note>
+Agents can see read-only blocks in their context but cannot modify them using memory tools. This is useful for organizational policies, system configuration, or any information that should be reference-only.
+</Note>
+
+## Complete Example
+
+Here's the full code in one place that you can run:
+
+<CodeGroup>
+```typescript TypeScript
+import { LettaClient } from '@letta-ai/letta-client';
+
+// Initialize client
+const client = new LettaClient({ token: process.env.LETTA_API_KEY });
+
+// Create shared block
+const block = await client.blocks.create({
+ label: "organization",
+ value: "Organization: Letta",
+ limit: 4000,
+});
+
+console.log(`Created shared block: ${block.id}\n`);
+
+// Create agents with shared block
+const agent1 = await client.agents.create({
+ name: "agent1",
+ model: "openai/gpt-4o-mini",
+ blockIds: [block.id],
+ tools: ["web_search"],
+});
+
+const agent2 = await client.agents.create({
+ name: "agent2",
+ model: "openai/gpt-4o-mini",
+ tools: ["web_search"],
+});
+
+await client.agents.blocks.attach(agent2.id, { blockId: block.id });
+
+console.log(`Created agents: ${agent1.id}, ${agent2.id}\n`);
+
+// Agent1 contributes information
+const response1 = await client.agents.messages.create(agent1.id, {
+ messages: [{
+ role: "user",
+ content: `Find information about the connection between memory blocks and Letta.
+Insert what you learn into the memory block, prepended with "Agent1: ".`
+ }]
+});
+
+// Agent2 contributes information
+const response2 = await client.agents.messages.create(agent2.id, {
+ messages: [{
+ role: "user",
+ content: `Find information about the origin of Letta.
+Insert what you learn into the memory block, prepended with "Agent2: ".`
+ }]
+});
+
+// Inspect the shared memory
+const updatedBlock = await client.blocks.retrieve(block.id);
+console.log("==== Updated block ====");
+console.log(updatedBlock.value);
+console.log("=======================\n");
+
+// Create read-only block
+const readOnlyBlock = await client.blocks.create({
+ label: "policies",
+ value: "Company Policy: Always be helpful and respectful.",
+ readOnly: true,
+});
+
+const readOnlyAgent = await client.agents.create({
+ name: "policy_agent",
+ model: "openai/gpt-4o-mini",
+ blockIds: [readOnlyBlock.id],
+});
+
+console.log(`Created read-only agent: ${readOnlyAgent.id}`);
+```
+```python Python
+from letta_client import Letta
+import os
+
+# Initialize client
+client = Letta(token=os.getenv("LETTA_API_KEY"))
+
+# Create shared block
+block = client.blocks.create(
+ label="organization",
+ value="Organization: Letta",
+ limit=4000,
+)
+
+print(f"Created shared block: {block.id}\n")
+
+# Create agents with shared block
+agent1 = client.agents.create(
+ name="agent1",
+ model="openai/gpt-4o-mini",
+ block_ids=[block.id],
+ tools=["web_search"],
+)
+
+agent2 = client.agents.create(
+ name="agent2",
+ model="openai/gpt-4o-mini",
+ tools=["web_search"],
+)
+
+agent2 = client.agents.blocks.attach(
+ agent_id=agent2.id,
+ block_id=block.id,
+)
+
+print(f"Created agents: {agent1.id}, {agent2.id}\n")
+
+# Agent1 contributes information
+response = client.agents.messages.create(
+ agent_id=agent1.id,
+ messages=[{"role": "user", "content": """
+ Find information about the connection between memory blocks and Letta.
+ Insert what you learn into the memory block, prepended with "Agent1: ".
+"""}],
+)
+
+# Agent2 contributes information
+response = client.agents.messages.create(
+ agent_id=agent2.id,
+ messages=[{"role": "user", "content": """
+ Find information about the origin of Letta.
+ Insert what you learn into the memory block, prepended with "Agent2: ".
+"""}],
+)
+
+# Inspect the shared memory
+updated_block = client.blocks.retrieve(block.id)
+print(f"==== Updated block ====")
+print(updated_block.value)
+print(f"=======================")
+
+# Create read-only block
+read_only_block = client.blocks.create(
+ label="policies",
+ value="Company Policy: Always be helpful and respectful.",
+ read_only=True,
+)
+
+read_only_agent = client.agents.create(
+ name="policy_agent",
+ model="openai/gpt-4o-mini",
+ block_ids=[read_only_block.id],
+)
+
+print(f"Created read-only agent: {read_only_agent.id}")
+```
+</CodeGroup>
+
+## Key Concepts
+
+<CardGroup cols={2}>
+<Card title="Shared Memory" icon="share-nodes">
+Multiple agents can access the same memory block, enabling collaboration and information sharing
+</Card>
+
+<Card title="Flexible Attachment" icon="link">
+Blocks can be attached during agent creation with block_ids or later using the attach method
+</Card>
+
+<Card title="Concurrent Updates" icon="rotate">
+Memory tools handle concurrent updates differently - insert is additive, replace validates, rethink overwrites
+</Card>
+
+<Card title="Read-Only Blocks" icon="lock">
+Prevent agent modifications while still providing shared context like policies or system information
+</Card>
+</CardGroup>
+
+## Use Cases
+
+<AccordionGroup>
+<Accordion title="Multi-Agent Research">
+Have multiple agents research different topics and contribute findings to a shared knowledge base.
+</Accordion>
+
+<Accordion title="Organizational Policies">
+Create read-only blocks with company policies, terms of service, or system guidelines that all agents reference.
+</Accordion>
+
+<Accordion title="Task Coordination">
+Use shared blocks as a coordination layer where agents update task status and communicate progress.
+</Accordion>
+
+<Accordion title="Collaborative Problem Solving">
+Enable agents with different specializations to work together by sharing context and intermediate results.
+</Accordion>
+</AccordionGroup>
+
+## Next Steps
+
+<CardGroup cols={2}>
+<Card title="Memory Blocks Guide" icon="database" href="/guides/agents/memory-blocks">
+Learn more about memory blocks, including managing and updating them
+</Card>
+
+<Card title="Attaching and Detaching Blocks" icon="link" href="/examples/attaching-detaching-blocks">
+Understand how to dynamically control agent access to memory blocks
+</Card>
+</CardGroup>