Documentation Index Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
记忆是一个记住以前交互信息的系统。对于 AI 智能体来说,记忆至关重要,因为它让智能体能够记住以前的交互、从反馈中学习并适应用户偏好。随着智能体处理越来越复杂的任务和大量用户交互,这种能力对于效率和用户满意度来说变得必不可少。
短期记忆让你的应用能够在单个线程或对话中记住以前的交互。
线程将会话中的多个交互组织在一起,类似于电子邮件将消息归组到单个对话中的方式。
对话历史是短期记忆最常见的形式。长对话对当今的 LLM 构成挑战;完整的历史可能无法放入 LLM 的上下文窗口,导致上下文丢失或错误。
即使你的模型支持完整的上下文长度,大多数 LLM 在处理长上下文时仍然表现不佳。它们会被过时或离题的内容”分散注意力”,同时还会遭受更慢的响应时间和更高的成本。
聊天模型使用消息 接受上下文,其中包括指令(系统消息)和输入(人工消息)。在聊天应用中,消息在人工输入和模型响应之间交替,形成一个随时间不断增长的消息列表。由于上下文窗口有限,许多应用可以从使用技术来移除或”遗忘”过时信息中受益。
需要跨 对话记住信息?使用长期记忆 来跨不同线程和会话存储和召回用户特定或应用级别的数据。
要为智能体添加短期记忆(线程级持久化),你需要在创建智能体时指定 checkpointer。
LangChain 的智能体将短期记忆作为智能体状态的一部分来管理。 通过将这些信息存储在图的状态中,智能体可以访问给定对话的完整上下文,同时维护不同线程之间的隔离。 状态使用检查点器持久化到数据库(或内存),以便线程可以在任何时候恢复。 短期记忆在智能体被调用或步骤(如工具调用)完成时更新,状态在每步开始时被读取。
import { createAgent } from "langchain" ;
import { MemorySaver } from "@langchain/langgraph" ;
const checkpointer = new MemorySaver () ;
const agent = createAgent ( {
model : "claude-sonnet-4-6" ,
tools : [] ,
checkpointer ,
} ) ;
await agent . invoke (
{ messages : [ { role : "user" , content : "hi! i am Bob" } ] },
{ configurable : { thread_id : "1" } }
) ;
在生产环境中
在生产环境中,使用由数据库支持的检查点器:
import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres" ;
const DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" ;
const checkpointer = PostgresSaver . fromConnString (DB_URI) ;
有关更多检查点器选项,包括 SQLite、Postgres 和 Azure Cosmos DB,请参阅持久化文档中的检查点器库列表 。
自定义智能体记忆
你可以通过创建带有状态 schema 的自定义中间件来扩展智能体状态。自定义状态 schema 可以使用中间件中的 stateSchema 参数传递。优先使用 StateSchema 类进行状态定义(也支持普通 Zod 对象)。
import { createAgent , createMiddleware } from "langchain" ;
import { StateSchema , MemorySaver } from "@langchain/langgraph" ;
import * as z from "zod" ;
const CustomState = new StateSchema ( {
userId : z . string () ,
preferences : z . record (z . string () , z . any ()) ,
} ) ;
const stateExtensionMiddleware = createMiddleware ( {
name : "StateExtension" ,
stateSchema : CustomState ,
} ) ;
const checkpointer = new MemorySaver () ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [stateExtensionMiddleware] ,
checkpointer ,
} ) ;
// 自定义状态可以在 invoke 中传递
const result = await agent . invoke ( {
messages : [ { role : "user" , content : "Hello" } ] ,
userId : "user_123" ,
preferences : { theme : "dark" },
} ) ;
常见模式
启用短期记忆 后,长对话可能会超出 LLM 的上下文窗口。常见的解决方案有:
裁剪消息 移除最前或最后的 N 条消息(在调用 LLM 之前)
删除消息 从 LangGraph 状态中永久删除消息
摘要消息 对历史中较早的消息进行总结并用摘要替换它们
这使智能体能够跟踪对话而不超出 LLM 的上下文窗口。
裁剪消息
大多数 LLM 都有最大支持的上下文窗口(以 Token 计)。
一种决定何时截断消息的方法是计算消息历史中的 Token 并在接近限制时截断。如果你使用 LangChain,可以使用裁剪消息工具并指定要从列表中保留的 Token 数量,以及用于处理边界的 strategy(例如保留最后 maxTokens)。
要在智能体中裁剪消息历史,使用带有 beforeModel 钩子的 createMiddleware :
import { RemoveMessage } from "@langchain/core/messages" ;
import { createAgent , createMiddleware } from "langchain" ;
import { MemorySaver , REMOVE_ALL_MESSAGES } from "@langchain/langgraph" ;
const trimMessages = createMiddleware ( {
name : "TrimMessages" ,
beforeModel : ( state ) => {
const messages = state . messages ;
if (messages . length <= 3 ) {
return ; // 无需更改
}
const firstMsg = messages[ 0 ] ;
const recentMessages =
messages . length % 2 === 0 ? messages . slice ( - 3 ) : messages . slice ( - 4 ) ;
const newMessages = [firstMsg , ... recentMessages] ;
return {
messages : [
new RemoveMessage ( { id : REMOVE_ALL_MESSAGES } ) ,
... newMessages ,
] ,
};
},
} ) ;
const checkpointer = new MemorySaver () ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [trimMessages] ,
checkpointer ,
} ) ;
删除消息
你可以从图状态中删除消息来管理消息历史。
当你想要删除特定消息或清除整个消息历史时,这很有用。
要从图状态中删除消息,可以使用 RemoveMessage。要使 RemoveMessage 工作,你需要使用带有 messagesStateReducer reducer 的状态键,如 MessagesValue。
要删除特定消息:
import { RemoveMessage } from "@langchain/core/messages" ;
const deleteMessages = ( state ) => {
const messages = state . messages ;
if (messages . length > 2 ) {
// 删除最早的两条消息
return {
messages : messages
. slice ( 0 , 2 )
. map ( ( m ) => new RemoveMessage ( { id : m . id } )) ,
};
}
};
删除消息时,确保 生成的消息历史是有效的。检查你使用的 LLM 提供商的限制。例如:
某些提供商要求消息历史以 user 消息开头
大多数提供商要求带有工具调用的 assistant 消息后面跟着相应的 tool 结果消息。
import { RemoveMessage } from "@langchain/core/messages" ;
import { createAgent , createMiddleware } from "langchain" ;
import { MemorySaver } from "@langchain/langgraph" ;
const deleteOldMessages = createMiddleware ( {
name : "DeleteOldMessages" ,
afterModel : ( state ) => {
const messages = state . messages ;
if (messages . length > 2 ) {
// 删除最早的两条消息
return {
messages : messages
. slice ( 0 , 2 )
. map ( ( m ) => new RemoveMessage ( { id : m . id ! } )) ,
};
}
return ;
},
} ) ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
systemPrompt : "Please be concise and to the point." ,
middleware : [deleteOldMessages] ,
checkpointer : new MemorySaver () ,
} ) ;
const config = { configurable : { thread_id : "1" } };
const streamA = await agent . stream (
{ messages : [ { role : "user" , content : "hi! I'm bob" } ] },
{ ... config , streamMode : "values" }
) ;
for await ( const event of streamA) {
const messageDetails = event . messages . map ( ( message ) => [
message . getType () ,
message . content ,
]) ;
console . log (messageDetails) ;
}
const streamB = await agent . stream (
{
messages : [ { role : "user" , content : "what's my name?" } ] ,
},
{ ... config , streamMode : "values" }
) ;
for await ( const event of streamB) {
const messageDetails = event . messages . map ( ( message ) => [
message . getType () ,
message . content ,
]) ;
console . log (messageDetails) ;
}
[[ "human", "hi! I'm bob" ]]
[[ "human", "hi! I'm bob" ], [ "ai", "Hello, Bob! How can I assist you today?" ]]
[[ "human", "hi! I'm bob" ], [ "ai", "Hello, Bob! How can I assist you today?" ]]
[[ "human", "hi! I'm bob" ], [ "ai", "Hello, Bob! How can I assist you today" ], ["human", "what's my name?" ]]
[[ "human", "hi! I'm bob" ], [ "ai", "Hello, Bob! How can I assist you today?" ], ["human", "what's my name?"], [ "ai", "Your name is Bob, as you mentioned. How can I help you further?" ]]
[[ "human", "what's my name?" ], [ "ai", "Your name is Bob, as you mentioned. How can I help you further?" ]]
摘要消息
如上所示,裁剪或删除消息的问题在于你可能会因为消息队列的裁减而丢失信息。
因此,某些应用可以从使用聊天模型对消息历史进行摘要这种更复杂的方法中受益。
要在智能体中对消息历史进行摘要,使用内置的 summarizationMiddleware :
import { createAgent , summarizationMiddleware } from "langchain" ;
import { MemorySaver } from "@langchain/langgraph" ;
const checkpointer = new MemorySaver () ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
summarizationMiddleware ( {
model : "gpt-5.4-mini" ,
trigger : { tokens : 4000 },
keep : { messages : 20 },
} ) ,
] ,
checkpointer ,
} ) ;
const config = { configurable : { thread_id : "1" } };
await agent . invoke ( { messages : "hi, my name is bob" }, config) ;
await agent . invoke ( { messages : "write a short poem about cats" }, config) ;
await agent . invoke ( { messages : "now do the same but for dogs" }, config) ;
const finalResponse = await agent . invoke ( { messages : "what's my name?" }, config) ;
console . log (finalResponse . messages . at ( - 1 ) ?. content) ;
// Your name is Bob!
有关更多配置选项,请参阅 summarizationMiddleware 。
访问记忆
你可以通过以下几种方式访问和修改智能体的短期记忆(状态):
在工具中读取短期记忆
使用 runtime 参数(类型为 ToolRuntime)在工具中访问短期记忆(状态)。
runtime 参数对工具签名是隐藏的(所以模型看不到它),但工具可以通过它访问状态。
import { createAgent , tool , type ToolRuntime } from "langchain" ;
import { StateSchema } from "@langchain/langgraph" ;
import * as z from "zod" ;
const CustomState = new StateSchema ( {
userId : z . string () ,
} ) ;
const getUserInfo = tool (
async ( _ , config : ToolRuntime < typeof CustomState . State > ) => {
const userId = config . state . userId ;
return userId === "user_123" ? "John Doe" : "Unknown User" ;
},
{
name : "get_user_info" ,
description : "Get user info" ,
schema : z . object ( {} ) ,
}
) ;
const agent = createAgent ( {
model : "gpt-5-nano" ,
tools : [getUserInfo] ,
stateSchema : CustomState ,
} ) ;
const result = await agent . invoke (
{
messages : [ { role : "user" , content : "what's my name?" } ] ,
userId : "user_123" ,
},
{
context : {},
}
) ;
console . log (result . messages . at ( - 1 ) ?. content) ;
// 输出:"Your name is John Doe."
从工具写入短期记忆
要在执行过程中修改智能体的短期记忆(状态),你可以直接从工具返回状态更新。
这对于持久化中间结果或使信息对后续工具或提示可访问非常有用。
import { tool , createAgent , ToolMessage , type ToolRuntime } from "langchain" ;
import { Command , StateSchema } from "@langchain/langgraph" ;
import * as z from "zod" ;
const CustomState = new StateSchema ( {
userId : z . string () . optional () ,
} ) ;
const updateUserInfo = tool (
async ( _ , config : ToolRuntime < typeof CustomState . State > ) => {
const userId = config . state . userId ;
const name = userId === "user_123" ? "John Smith" : "Unknown user" ;
return new Command ( {
update : {
userName : name ,
// 更新消息历史
messages : [
new ToolMessage ( {
content : "Successfully looked up user information" ,
tool_call_id : config . toolCall ?. id ?? "" ,
} ) ,
] ,
},
} ) ;
},
{
name : "update_user_info" ,
description : "Look up and update user info." ,
schema : z . object ( {} ) ,
}
) ;
const greet = tool (
async ( _ , config ) => {
const userName = config . context ?. userName ;
return `Hello ${ userName } !` ;
},
{
name : "greet" ,
description : "Use this to greet the user once you found their info." ,
schema : z . object ( {} ) ,
}
) ;
const agent = createAgent ( {
model : "openai:gpt-5-mini" ,
tools : [updateUserInfo , greet] ,
stateSchema : CustomState ,
} ) ;
const result = await agent . invoke ( {
messages : [ { role : "user" , content : "greet the user" } ] ,
userId : "user_123" ,
} ) ;
console . log (result . messages . at ( - 1 ) ?. content) ;
// 输出:"Hello! I'm here to help — what would you like to do today?"
在中间件中访问短期记忆(状态),基于对话历史或自定义状态字段创建动态提示。
import * as z from "zod" ;
import { createAgent , tool , dynamicSystemPromptMiddleware } from "langchain" ;
const contextSchema = z . object ( {
userName : z . string () ,
} ) ;
type ContextSchema = z . infer < typeof contextSchema > ;
const getWeather = tool (
async ({ city }) => {
return `The weather in ${ city } is always sunny!` ;
},
{
name : "get_weather" ,
description : "Get user info" ,
schema : z . object ( {
city : z . string () ,
} ) ,
}
) ;
const agent = createAgent ( {
model : "gpt-5-nano" ,
tools : [getWeather] ,
contextSchema ,
middleware : [
dynamicSystemPromptMiddleware < ContextSchema > ( ( _ , config ) => {
return `You are a helpful assistant. Address the user as ${ config . context ?. userName } .` ;
} ) ,
] ,
} ) ;
const result = await agent . invoke (
{
messages : [ { role : "user" , content : "What is the weather in SF?" } ] ,
},
{
context : {
userName : "John Smith" ,
},
}
) ;
for ( const message of result . messages) {
console . log (message) ;
}
/**
* HumanMessage {
* "content": "What is the weather in SF?",
* // ...
* }
* AIMessage {
* // ...
* "tool_calls": [
* {
* "name": "get_weather",
* "args": {
* "city": "San Francisco"
* },
* "type": "tool_call",
* "id": "call_tCidbv0apTpQpEWb3O2zQ4Yx"
* }
* ],
* // ...
* }
* ToolMessage {
* "content": "The weather in San Francisco is always sunny!",
* "tool_call_id": "call_tCidbv0apTpQpEWb3O2zQ4Yx"
* // ...
* }
* AIMessage {
* "content": "John Smith, here's the latest: The weather in San Francisco is always sunny!\n\nIf you'd like more details (temperature, wind, humidity) or a forecast for the next few days, I can pull that up. What would you like?",
* // ...
* }
*/
模型前
import { RemoveMessage } from "@langchain/core/messages" ;
import { createAgent , createMiddleware , trimMessages } from "langchain" ;
import { MemorySaver } from "@langchain/langgraph" ;
import { REMOVE_ALL_MESSAGES } from "@langchain/langgraph" ;
const trimMessageHistory = createMiddleware ( {
name : "TrimMessages" ,
beforeModel : async ( state ) => {
const trimmed = await trimMessages (state . messages , {
maxTokens : 384 ,
strategy : "last" ,
startOn : "human" ,
endOn : [ "human" , "tool" ] ,
tokenCounter : ( msgs ) => msgs . length ,
} ) ;
return {
messages : [ new RemoveMessage ( { id : REMOVE_ALL_MESSAGES } ) , ... trimmed] ,
};
},
} ) ;
const checkpointer = new MemorySaver () ;
const agent = createAgent ( {
model : "gpt-5-nano" ,
tools : [] ,
middleware : [trimMessageHistory] ,
checkpointer ,
} ) ;
模型后
import { RemoveMessage } from "@langchain/core/messages" ;
import { createAgent , createMiddleware } from "langchain" ;
import { REMOVE_ALL_MESSAGES } from "@langchain/langgraph" ;
const validateResponse = createMiddleware ( {
name : "ValidateResponse" ,
afterModel : ( state ) => {
const lastMessage = state . messages . at ( - 1 ) ?. content ;
if (
typeof lastMessage === "string" &&
lastMessage . toLowerCase () . includes ( "confidential" )
) {
return {
messages : [
new RemoveMessage ( { id : REMOVE_ALL_MESSAGES } ) ,
] ,
};
}
return ;
},
} ) ;
const agent = createAgent ( {
model : "gpt-5-nano" ,
tools : [] ,
middleware : [validateResponse] ,
} ) ;
将这些文档连接 到 Claude、VSCode 等,通过 MCP 获取实时答案。