内存#

如需更详细的使用信息,请参阅我们的操作指南:Memory Cookbook

1. 概念#

CAMEL中的Memory模块提供了一个灵活而强大的系统,用于存储、检索和管理AI代理的信息。它使代理能够跨对话保持上下文,并从过去的交互中检索相关信息,从而增强AI响应的连贯性和相关性。

2. 开始使用#

2.1 基本用法#

这里有一个快速示例展示如何使用LongtermAgentMemory

from camel.memories import (
    ChatHistoryBlock,
    LongtermAgentMemory,
    MemoryRecord,
    ScoreBasedContextCreator,
    VectorDBBlock,
)
from camel.messages import BaseMessage
from camel.types import ModelType, OpenAIBackendRole
from camel.utils import OpenAITokenCounter

# Initialize the memory
memory = LongtermAgentMemory(
    context_creator=ScoreBasedContextCreator(
        token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),
        token_limit=1024,
    ),
    chat_history_block=ChatHistoryBlock(),
    vector_db_block=VectorDBBlock(),
)

# Create and write new records
records = [
    MemoryRecord(
        message=BaseMessage.make_user_message(
            role_name="User",
            meta_dict=None,
            content="What is CAMEL AI?",
        ),
        role_at_backend=OpenAIBackendRole.USER,
    ),
    MemoryRecord(
        message=BaseMessage.make_assistant_message(
            role_name="Agent",
            meta_dict=None,
            content="CAMEL-AI.org is the 1st LLM multi-agent framework and "
                    "an open-source community dedicated to finding the scaling law "
                    "of agents.",
        ),
        role_at_backend=OpenAIBackendRole.ASSISTANT,
    ),
]
memory.write_records(records)

# Get context for the agent
context, token_count = memory.get_context()

print(context)
print(f"Retrieved context (token count: {token_count}):")
for message in context:
    print(f"{message}")
>>> Retrieved context (token count: 49):
{'role': 'user', 'content': 'What is AI?'}
{'role': 'assistant', 'content': 'AI refers to systems that mimic human intelligence.'}

为你的ChatAgent添加LongtermAgentMemory功能:

from camel.agents import ChatAgent

# Define system message for the agent
sys_msg = BaseMessage.make_assistant_message(
    role_name='Agent',
    content='You are a curious agent wondering about the universe.',
)

# Initialize agent
agent = ChatAgent(system_message=sys_msg)

# Set memory to the agent
agent.memory = memory


# Define a user message
usr_msg = BaseMessage.make_user_message(
    role_name='User',
    content="Tell me which is the 1st LLM multi-agent framework based on what we have discussed",
)

# Sending the message to the agent
response = agent.step(usr_msg)

# Check the response (just for illustrative purpose)
print(response.msgs[0].content)
>>> CAMEL AI is recognized as the first LLM (Large Language Model) multi-agent framework. It is an open-source community initiative focused on exploring the scaling laws of agents, enabling the development and interaction of multiple AI agents in a collaborative environment. This framework allows researchers and developers to experiment with various configurations and interactions among agents, facilitating advancements in AI capabilities and understanding.

3. 核心组件#

3.1 内存记录#

CAMEL 内存系统中的基本数据单元。

属性:

  • message: 记录的主要内容 (BaseMessage)

  • role_at_backend: 该消息在OpenAI后端扮演的角色 (OpenAIBackendRole)

  • uuid: 记录的唯一标识符

  • extra_info: 用于额外信息的键值对

方法:

  • from_dict(): 静态方法,用于从字典构造一个MemoryRecord

  • to_dict(): 将MemoryRecord转换为字典以便序列化

  • to_openai_message(): 将记录转换为OpenAIMessage对象

3.2 ContextRecord#

AgentMemory获取的内存检索结果,由ContextCreator用来选择记录以创建代理的上下文。

属性:

  • memory_record: 一个 MemoryRecord

  • score: 一个浮点数值,表示记录的相关性或重要性

3.3 MemoryBlock (抽象基类)#

作为智能体内存系统中的基础组件。MemoryBlock类遵循"组合设计模式",使您能够将对象组合成树状结构,然后像操作单个对象一样操作这些结构。

  • write_records(): 将多条记录写入内存

  • write_record(): 将单条记录写入内存

  • clear(): 从内存中移除所有记录

3.4 BaseContextCreator (抽象基类)#

定义当检索消息超过模型上下文长度时的上下文创建策略。

  • token_counter: 用于计算消息中的token数量

  • token_limit: 生成上下文中允许的最大token数量

  • create_context(): 从聊天记录创建对话上下文

3.5 AgentMemory (抽象基类)#

一种专门设计的MemoryBlock形式,用于直接与代理集成。

  • retrieve(): 从内存中获取一个ContextRecords列表

  • get_context_creator(): 获取上下文创建器

  • get_context(): 获取适合agent大小的聊天上下文

4. 内存块实现#

4.1 聊天历史区块#

存储所有聊天记录,并可通过可选窗口大小进行检索。

初始化:

  • storage: 可选的 BaseKeyValueStorage (默认: InMemoryKeyValueStorage)

  • keep_rate: 用于评分历史消息的浮点数值(默认值:0.9

方法:

  • retrieve(): 获取最近的聊天记录,可指定窗口大小

  • write_records(): 将新记录写入聊天历史

  • clear(): 移除所有聊天消息

使用场景:非常适合维护最近的对话上下文和流程。

4.2 VectorDBBlock#

使用向量嵌入来维护和检索信息。

初始化:

  • storage: 可选的BaseVectorStorage(默认:QdrantStorage

  • embedding: 可选的BaseEmbedding(默认值:OpenAIEmbedding

方法:

  • retrieve(): 根据关键词获取相似记录

  • write_records(): 转换并将新记录写入向量数据库

  • clear(): 从向量数据库中移除所有记录

使用场景:更适合在大量消息中检索语义相关的信息。

关键区别:

  1. 存储机制:ChatHistoryBlock使用键值存储,VectorDBBlock使用向量数据库存储。

  2. 检索方法:ChatHistoryBlock基于最近性检索,VectorDBBlock基于语义相似性检索。

  3. 数据表示:ChatHistoryBlock以原始形式存储消息,VectorDBBlock转换为向量嵌入。

5. Agent 内存实现#

5.1 ChatHistoryMemory#

一个封装ChatHistoryBlock的AgentMemory实现。

初始化:

  • context_creator: BaseContextCreator

  • storage: 可选的 BaseKeyValueStorage

  • window_size: 可选的整数,用于检索窗口

方法:

  • retrieve(): 获取最近的聊天消息

  • write_records(): 将新记录写入聊天历史

  • get_context_creator(): 获取上下文创建器

  • clear(): 移除所有聊天消息

5.2 VectorDBMemory#

一个封装VectorDBBlockAgentMemory实现。

初始化:

  • context_creator: BaseContextCreator

  • storage: 可选的 BaseVectorStorage

  • retrieve_limit: 检索消息的最大数量,整数类型(默认值:3

方法:

  • retrieve(): 从向量数据库中获取相关消息

  • write_records(): 写入新记录并更新当前主题

  • get_context_creator(): 获取上下文创建器

5.3 长期代理记忆#

结合ChatHistoryMemory和VectorDBMemory实现全面的内存管理。

初始化:

  • context_creator: BaseContextCreator

  • chat_history_block: 可选的 ChatHistoryBlock

  • vector_db_block: 可选的 VectorDBBlock

  • retrieve_limit: 检索消息的最大数量,类型为整数(默认值:3

方法:

  • retrieve(): 从聊天记录和向量数据库中获取上下文

  • write_records(): 将新记录写入聊天历史和向量数据库

  • get_context_creator(): 获取上下文创建器

  • clear(): 从两个内存块中移除所有记录

5.4 Mem0Storage 集成#

Mem0 提供基于云的内存管理功能,可以与CAMEL无缝集成。

Mem0Storage的初始化参数:

  • api_key: 可选的字符串,用于Mem0 API认证

  • agent_id: 可选的字符串,用于将记忆与代理关联

  • user_id: 可选的字符串,用于将记忆与用户关联

  • metadata: 可选字典,包含要与所有记忆一起存储的元数据

使用Mem0的最简单方式是通过其Mem0Storage后端与ChatHistoryMemory配合使用:

from camel.memories import ChatHistoryMemory, ScoreBasedContextCreator
from camel.storages import Mem0Storage
from camel.types import ModelType
from camel.utils import OpenAITokenCounter

# Initialize ChatHistoryMemory with Mem0Storage
memory = ChatHistoryMemory(
    context_creator=ScoreBasedContextCreator(
        token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),
        token_limit=1024,
    ),
    storage=Mem0Storage(
        api_key="your_mem0_api_key",  # Or set MEM0_API_KEY environment variable
        agent_id="agent123"  # Unique identifier for this agent
    ),
    agent_id="agent123"  # Should match the storage agent_id
)

# Create and write new records
records = [
    MemoryRecord(
        message=BaseMessage.make_user_message(
            role_name="User",
            content="What is CAMEL AI?",
        ),
        role_at_backend=OpenAIBackendRole.USER,
    ),
    MemoryRecord(
        message=BaseMessage.make_assistant_message(
            role_name="Agent",
            content="CAMEL-AI.org is the 1st LLM multi-agent framework and "
                    "an open-source community dedicated to finding the scaling law "
                    "of agents.",
        ),
        role_at_backend=OpenAIBackendRole.ASSISTANT,
    ),
]
memory.write_records(records)


# Get context for the agent
context, token_count = memory.get_context()

print(context)
print(f"Retrieved context (token count: {token_count}):")
for message in context:
    print(f"{message}")
>>> Retrieved context (token count: 49):
{'role': 'user', 'content': 'What is CAMEL AI?'}
{'role': 'assistant', 'content': 'CAMEL-AI.org is the 1st LLM multi-agent framework and an open-source community dedicated to finding the scaling law of agents.'}

这种方法为聊天记录提供了云端持久化存储,同时保持了ChatHistoryMemory简单的顺序检索功能。主要特点包括:

  1. 聊天记录的云端持久化存储

  2. 简单设置和配置

  3. 基于对话顺序的连续检索

  4. 跨会话自动同步

当您需要为聊天记录提供可靠的云存储,且无需复杂的语义搜索功能时,请选择此方法。

6. 高级主题#

6.1 自定义上下文创建器#

您可以通过继承BaseContextCreator来创建自定义上下文生成器:

from camel.memories import BaseContextCreator

class MyCustomContextCreator(BaseContextCreator):
    @property
    def token_counter(self):
        # Implement your token counting logic
        return 

    @property
    def token_limit(self):
        return 1000  # Or any other limit

    def create_context(self, records):
        # Implement your context creation logic
        pass

6.2 自定义向量数据库块#

对于VectorDBBlock,您可以通过调整嵌入模型或向量存储来自定义它:

from camel.embeddings import OpenAIEmbedding
from camel.memories import VectorDBBlock
from camel.storages import QdrantStorage

vector_db = VectorDBBlock(
    embedding=OpenAIEmbedding(),
    storage=QdrantStorage(vector_dim=OpenAIEmbedding().get_output_dim()),
)

6.3 性能注意事项#

  • 对于大规模应用,建议考虑使用持久化存储后端而非内存存储。

  • 优化您的上下文创建器,在上下文相关性和令牌限制之间取得平衡。

  • 使用VectorDBMemory时,请注意随着数据库增长,检索准确性和速度之间的权衡。