LangMem学习第二天 记忆管理

Memory Manager

Memory Manager 是一个利用LLM从对话中提取关键信息,并将其作为长期记忆进行管理的API。

提供以下功能:

  • 添加新的记忆
  • 更新现有记忆
  • 删除不需要的记忆
LangMem学习第二天 记忆管理

目前的代码

from pydantic import BaseModel, Field, conint
from langmem import create_memory_manager
import os
import f_common
# create_memory_manager 是生成 Memory Manager 的 API。
# 用于长期记忆的结构(schemas)可以像上面这样使用 Pydantic 指定任意的 schema。
# 默认情况下,记忆被视为字符串,但通过定义具体的数据结构,可以使代理更容易地整理信息。
# 这里创建并应用了表示用户饮食偏好的 UserFoodPreference schema。
#
# Memory Manager 使用LLM的工具调用来更新长期记忆。
# 因此,需要将LLM模型作为第一个参数传入。
# 根据选择的模型,长期记忆的准确性会有很大差异。经过多次尝试,在一些轻量级模型下信息摘要可能不够充分的情况也出现过。
class UserFoodPreference(BaseModel):
    """用户饮食偏好的详细信息"""food_name: str = Field(..., description="菜名")
    cuisine: str | None = Field(
        None, description="料理类型(和食、洋食、中餐等)"
    )
    preference: conint(ge=0, le=100) | None = Field(
        None, description="喜好程度(以0~100的分数表示)")
    description: str | None = Field(
        None, description="其他补充说明(例如,特定的调味或配料等)"
    )


# 生成 Memory Manager
manager = create_memory_manager(
     #"openai:gpt-4o-2024-11-20",  # 用于记忆提取和更新的模型
    f_common.my_grok_llm,
    schemas=[UserFoodPreference],
    instructions="请详细提取用户的偏好。如果将偏好中的`preference`更新为0,则从记忆中删除(RemoveDoc)",
    enable_inserts=True,  # 添加记忆: 默认为True
    enable_updates=True,  # 更新记忆: 默认为True
    enable_deletes=True,  # 删除记忆: 默认为False
)
# 继续

def print_memory(num: int, memories: list):
    """输出长期记忆"""print(f"### conversation:{num}")
    for m in memories:
        print(m)

# 添加
conversation = [
    {"role": "user", "content": "我非常喜欢拉面!!"},
    {"role": "user", "content": "我也喜欢意面"},
]
# 长期记忆反映
memories = manager.invoke({"messages": conversation})
print_memory(1, memories)

# 更新 or 删除
conversation = [
    {"role": "user", "content": "我喜欢味噌拉面"},
    {"role": "user", "content": "我不喜欢意面了"},
]
# 长期记忆反映(更新/删除现有长期记忆)
memories = manager.invoke({"messages": conversation, "existing": memories})
print_memory(2, memories)

使用Grok的LLM,输出和应该输出的貌似有点偏差,

LangMem学习第二天 记忆管理

应该输出类似

LangMem学习第二天 记忆管理

可以看出更新和删除操作已按预期执行。

请注意:

由于长期记忆的更新使用了LLM的工具调用,因此执行结果不一定相同。

另外,删除只是被标记为RemoveDoc,并不代表实际删除。删除方法(物理或逻辑)由使用API的一方决定。

Paragoger衍生者AI训练营。发布者:稻草人,转载请注明出处:https://www.shxcj.com/archives/9697

(0)
上一篇 10小时前
下一篇 2025-02-15 1:30 下午

相关推荐

发表回复

登录后才能评论
本文授权以下站点有原版访问授权 https://www.shxcj.com https://www.2img.ai https://www.2video.cn