LangChain1.0智能体开发:长期记忆

阅读本文您将获得:

  • LangChain长期记忆store的实现
  • LangGraph持久化功能的存储结构
  • 智能体使用工具读取长期记忆
  • 智能体使用工具写入长期记忆

1、概述

LangChain智能体借助LangGraph的持久化功能实现长期记忆。LangChain长期记忆属于高阶的主题,使用时需具备LangGraph相关知识。

2、记忆存储

LangGraph将长期记忆以JSON文档的形式存储在存储系统中。 每个记忆都归属于一个自定义命名空间(类似文件夹),并对应一个唯一键(类似文件名)。命名空间中通常包含用户ID、组织ID或其他标识,这些信息能让记忆的整理更便捷。 这种结构支持对记忆进行层级化组织,同时可通过内容筛选器实现跨命名空间检索。

python 复制代码
from langgraph.store.memory import InMemoryStore

def embed(texts: list[str]) -> list[list[float]]:
    # Replace with an actual embedding function or LangChain embeddings object
    return [[1.0, 2.0] * len(texts)]

# InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production use.
store = InMemoryStore(index={"embed": embed, "dims": 2}) 
user_id = "my-user"
application_context = "chitchat"
namespace = (user_id, application_context) 
store.put( 
    namespace,
    "a-memory",
    {
        "rules": [
            "User likes short, direct language",
            "User only speaks English & python",
        ],
        "my-key": "my-value",
    },
)
# get the "memory" by ID
item = store.get(namespace, "a-memory") 
# search for "memories" within this namespace, filtering on content equivalence, sorted by vector similarity
items = store.search( 
    namespace, filter={"my-key": "my-value"}, query="language preferences"
)

3、在工具中读取长期记忆

python 复制代码
from dataclasses import dataclass
from langchain_core.runnables import RunnableConfig
from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
store = InMemoryStore() 

# Write sample data to the store using the put method
store.put( 
    ("users",),  # Namespace to group related data together (users namespace for user data)
    "user_123",  # Key within the namespace (user ID as key)
    {
        "name": "John Smith",
        "language": "English",
    }  # Data to store for the given user
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # Access the store - same as that provided to `create_agent`
    store = runtime.store 
    user_id = runtime.context.user_id
    # Retrieve data from store - returns StoreValue object with value and metadata
    user_info = store.get(("users",), user_id) 
    return str(user_info.value) if user_info else "Unknown user"

agent = create_agent(
    model="claude-sonnet-4-5-20250929",
    tools=[get_user_info],
    # Pass store to agent - enables agent to access store when running tools
    store=store, 
    context_schema=Context
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123") 
)

4、在工具中写入长期记忆

python 复制代码
from dataclasses import dataclass
from typing_extensions import TypedDict
from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime
from langgraph.store.memory import InMemoryStore

# InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
store = InMemoryStore() 

@dataclass
class Context:
    user_id: str

# TypedDict defines the structure of user information for the LLM
class UserInfo(TypedDict):
    name: str

# Tool that allows agent to update user information (useful for chat applications)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # Access the store - same as that provided to `create_agent`
    store = runtime.store 
    user_id = runtime.context.user_id 
    # Store data in the store (namespace, key, data)
    store.put(("users",), user_id, user_info) 
    return "Successfully saved user info."

agent = create_agent(
    model="claude-sonnet-4-5-20250929",
    tools=[save_user_info],
    store=store, 
    context_schema=Context
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # user_id passed in context to identify whose information is being updated
    context=Context(user_id="user_123") 
)

# You can access the store directly to get the value
store.get(("users",), "user_123").value
相关推荐
weixin_462446232 分钟前
使用 LangChain + Ollama + Neo4j 构建中文知识图谱完整教程(含 Docker 部署)
langchain·知识图谱·neo4j
qunaa01013 分钟前
基于YOLO11-CSP-EDLAN的软夹持器夹持状态检测方法研究
python
SunnyDays10114 分钟前
Python 文本转 PDF 完整指南:从字符串与 TXT 文件到专业 PDF 文档
python·txt转pdf·文本转pdf·文本文件转pdf
C系语言4 分钟前
安装Python版本opencv命令
开发语言·python·opencv
FJW0208146 分钟前
Python排序算法
python·算法·排序算法
pulinzt14 分钟前
【python】第六节anacoda+配置Jupyter notebook
人工智能·python·jupyter
逄逄不是胖胖22 分钟前
《动手学深度学习》-49Style_Transfer实现
pytorch·python·深度学习
充值修改昵称2 小时前
数据结构基础:B树磁盘IO优化的数据结构艺术
数据结构·b树·python·算法
C系语言2 小时前
python用pip生成requirements.txt
开发语言·python·pip
william_djj2 小时前
python3.8 提取xlsx表格内容填入单个文件
windows·python·xlsx