Memory
For more detailed usage information, please refer to our cookbook: Memory Cookbook
1. Concept
The Memory module in CAMEL provides a flexible and powerful system for storing, retrieving, and managing information for AI agents. It enables agents to maintain context across conversations and retrieve relevant information from past interactions, enhancing the coherence and relevance of AI responses.
2. Get Started
2.1 Basic Usage
Here’s a quick example of how to use the LongtermAgentMemory
:
Adding LongtermAgentMemory
to your ChatAgent
:
3. Core Components
3.1 MemoryRecord
The basic data unit in the CAMEL
memory system.
Attributes:
message
: The main content of the record (BaseMessage
)role_at_backend
: The role this message played at the OpenAI backend (OpenAIBackendRole
)uuid
: A unique identifier for the recordextra_info
: Additional key-value pairs for extra information
Methods:
from_dict()
: Static method to construct aMemoryRecord
from a dictionaryto_dict()
: Convert theMemoryRecord
to a dictionary for serializationto_openai_message()
: Convert the record to anOpenAIMessage
object
3.2 ContextRecord
The result of memory retrieval from AgentMemory
, which is used by ContextCreator
to select records for creating the context for the agent.
Attributes:
memory_record
: AMemoryRecord
score
: A float value representing the relevance or importance of the record
3.3 MemoryBlock (Abstract Base Class)
Serves as the fundamental component within the agent memory system. MemoryBlock
class follows the “Composite Design pattern” so that you can compose objects into tree structures and then work with these structures as if they were individual objects.
write_records()
: Write multiple records to memorywrite_record()
: Write a single record to memoryclear()
: Remove all records from memory
3.4 BaseContextCreator (Abstract Base Class)
Defines the context creation strategies when retrieval messages exceed the model’s context length.
token_counter
: For counting tokens in a messagetoken_limit
: The maximum number of tokens allowed in the generated contextcreate_context()
: Create conversational context from chat history
3.5 AgentMemory (Abstract Base Class)
A specialized form of MemoryBlock designed for direct integration with an agent.
retrieve()
: Get a list ofContextRecords
from memoryget_context_creator()
: Get a context creatorget_context()
: Get chat context with a proper size for the agent
4. Memory Block Implementations
4.1 ChatHistoryBlock
Stores all the chat histories and retrieves with optional window size.
Initialization:
storage
: OptionalBaseKeyValueStorage
(default:InMemoryKeyValueStorage
)keep_rate
: Float value for scoring historical messages (default:0.9
)
Methods:
retrieve()
: Get recent chat history with optional window sizewrite_records()
: Write new records to chat historyclear()
: Remove all chat messages
Use Case: Ideal for maintaining recent conversation context and flow.
4.2 VectorDBBlock
Uses vector embeddings for maintaining and retrieving information.
Initialization:
storage
: Optional BaseVectorStorage (default:QdrantStorage
)embedding
: Optional BaseEmbedding (default:OpenAIEmbedding
)
Methods:
retrieve()
: Get similar records based on a keywordwrite_records()
: Convert and write new records to the vector databaseclear()
: Remove all records from the vector database
Use Case: Better for retrieving semantically relevant information across a large set of messages.
Key Differences:
- Storage Mechanism:
ChatHistoryBlock
uses key-value storage,VectorDBBlock
uses vector database storage. - Retrieval Method:
ChatHistoryBlock
retrieves based on recency,VectorDBBlock
retrieves based on semantic similarity. - Data Representation:
ChatHistoryBlock
stores messages in original form,VectorDBBlock
converts to vector embeddings.
5. Agent Memory Implementations
5.1 ChatHistoryMemory
An AgentMemory implementation that wraps ChatHistoryBlock.
Initialization:
context_creator
:BaseContextCreator
storage
: OptionalBaseKeyValueStorage
window_size
: Optional int for retrieval window
Methods:
retrieve()
: Get recent chat messageswrite_records()
: Write new records to chat historyget_context_creator()
: Get the context creatorclear()
: Remove all chat messages
5.2 VectorDBMemory
An AgentMemory
implementation that wraps VectorDBBlock
.
Initialization:
context_creator
:BaseContextCreator
storage
: OptionalBaseVectorStorage
retrieve_limit
: int for maximum number of retrieved messages (default:3
)
Methods:
retrieve()
: Get relevant messages from the vector databasewrite_records()
: Write new records and update current topicget_context_creator()
: Get the context creator
5.3 LongtermAgentMemory
Combines ChatHistoryMemory and VectorDBMemory for comprehensive memory management.
Initialization:
context_creator
:BaseContextCreator
chat_history_block
: OptionalChatHistoryBlock
vector_db_block
: OptionalVectorDBBlock
retrieve_limit
: int for maximum number of retrieved messages (default:3
)
Methods:
retrieve()
: Get context from both chat history and vector databasewrite_records()
: Write new records to both chat history and vector databaseget_context_creator()
: Get the context creatorclear()
: Remove all records from both memory blocks
5.4 Mem0Storage Integration
Mem0 offers cloud-based memory management capabilities that can be seamlessly integrated with CAMEL.
Initialization params of Mem0Storage
:
api_key
: Optional str for Mem0 API authenticationagent_id
: Optional str to associate memories with an agentuser_id
: Optional str to associate memories with a usermetadata
: Optional dictionary of metadata to include with all memories
The simplest way to use Mem0 is through its Mem0Storage
backend with ChatHistoryMemory
:
This approach provides cloud persistence for chat history while maintaining the simple sequential retrieval of ChatHistoryMemory
. The key features include:
- Cloud persistence of chat history
- Simple setup and configuration
- Sequential retrieval based on conversation order
- Automatic synchronization across sessions
Choose this approach when you need reliable cloud storage for your chat history without complex semantic search requirements.
6. Advanced Topics
6.1 Customizing Context Creator
You can create custom context creators by subclassing BaseContextCreator
:
6.2 Customizing Vector Database Block
For VectorDBBlock
, you can customize it by adjusting the embedding models or vector storages:
6.3 Performance Considerations
- For large-scale applications, consider using persistent storage backends instead of in-memory storage.
- Optimize your context creator to balance between context relevance and token limits.
- When using
VectorDBMemory
, be mindful of the trade-off between retrieval accuracy and speed as the database grows.