Shared Memory
Multiple agents can access the same memory block, enabling collaboration and information sharing
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:
By the end of this guide, you’ll understand how to build simple multi-agent systems where agents work together by sharing memory.
You will need to install letta-client to interface with a Letta server:
bash TypeScript npm install @letta-ai/letta-client bash Python pip install letta-client
import { LettaClient } from "@letta-ai/letta-client";
// Initialize the Letta client using LETTA_API_KEY environment variableconst client = new LettaClient({ token: process.env.LETTA_API_KEY });
// If self-hosting, specify the base URL:// const client = new LettaClient({ baseUrl: "http://localhost:8283" });from letta_client import Lettaimport os
# Initialize the Letta client using LETTA_API_KEY environment variableclient = Letta(token=os.getenv("LETTA_API_KEY"))
# If self-hosting, specify the base URL:# client = Letta(base_url="http://localhost:8283")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.
// Create a memory block that will be shared between agents// API Reference: https://docs.letta.com/api-reference/blocks/createconst block = await client.blocks.create({ label: "organization", value: "Organization: Letta", limit: 4000,});
console.log(`Created shared block: ${block.id}\n`);# Create a memory block that will be shared between agents# API Reference: https://docs.letta.com/api-reference/blocks/createblock = client.blocks.create( label="organization", value="Organization: Letta", limit=4000,)
print(f"Created shared block: {block.id}\n")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.
// Create first agent with block attached during creation// API Reference: https://docs.letta.com/api-reference/agents/createconst 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 afterwardconst 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/attachawait client.agents.blocks.attach(agent2.id, block.id);console.log(`Attached block to agent2\n`);# Create first agent with block attached during creation# API Reference: https://docs.letta.com/api-reference/agents/createagent1 = 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 afterwardagent2 = 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/attachagent2 = client.agents.blocks.attach( agent_id=agent2.id, block_id=block.id,)print(f"Attached block to agent2: {agent2.id}")Now let’s have both agents research different topics and contribute their findings to the shared memory block.
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:).
// Agent1 searches for information about memory blocks// API Reference: https://docs.letta.com/api-reference/agents/messages/createconst 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: ".`, }, ], }, { timeoutInSeconds: 120, // Web search can take time },);
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 originconst 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: ".`, }, ], }, { timeoutInSeconds: 120, // Web search can take time },);
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)})`, ); }}# Agent1 searches for information about memory blocks# API Reference: https://docs.letta.com/api-reference/agents/messages/createresponse = 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 originresponse = 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})")Let’s retrieve the shared memory block to see both agents’ contributions:
// Retrieve the shared block to see what both agents learned// API Reference: https://docs.letta.com/api-reference/blocks/retrieveconst updatedBlock = await client.blocks.retrieve(block.id);
console.log("==== Updated block ====");console.log(updatedBlock.value);console.log("=======================\n");# Retrieve the shared block to see what both agents learned# API Reference: https://docs.letta.com/api-reference/blocks/retrieveupdated_block = client.blocks.retrieve(block.id)
print(f"==== Updated block ====")print(updated_block.value)print(f"=======================")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.
Read-only blocks are useful for sharing policies, system information, or terms of service that agents should reference but not modify.
// Create a read-only block for policies or system information// API Reference: https://docs.letta.com/api-reference/blocks/createconst 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 agentconst 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}`);# Create a read-only block for policies or system information# API Reference: https://docs.letta.com/api-reference/blocks/createread_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 agentread_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}")Here’s the full code in one place that you can run:
import { LettaClient } from "@letta-ai/letta-client";
async function main() { // 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, 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: ".`, }, ], }, { timeoutInSeconds: 120, // Web search can take time }, );
// 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: ".`, }, ], }, { timeoutInSeconds: 120, // Web search can take time }, );
// 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}`);}
main();from letta_client import Lettaimport os
# Initialize clientclient = Letta(token=os.getenv("LETTA_API_KEY"))
# Create shared blockblock = client.blocks.create( label="organization", value="Organization: Letta", limit=4000,)
print(f"Created shared block: {block.id}\n")
# Create agents with shared blockagent1 = 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 informationresponse = 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 informationresponse = 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 memoryupdated_block = client.blocks.retrieve(block.id)print(f"==== Updated block ====")print(updated_block.value)print(f"=======================")
# Create read-only blockread_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}")Shared Memory
Multiple agents can access the same memory block, enabling collaboration and information sharing
Flexible Attachment
Blocks can be attached during agent creation with block_ids or later using the attach method
Concurrent Updates
Memory tools handle concurrent updates differently - insert is additive, replace validates, rethink overwrites
Read-Only Blocks
Prevent agent modifications while still providing shared context like policies or system information
Have multiple agents research different topics and contribute findings to a shared knowledge base.
Create read-only blocks with company policies, terms of service, or system guidelines that all agents reference.
Use shared blocks as a coordination layer where agents update task status and communicate progress.
Enable agents with different specializations to work together by sharing context and intermediate results.
Memory Blocks Guide
Learn more about memory blocks, including managing and updating them
Attaching and Detaching Blocks
Understand how to dynamically control agent access to memory blocks