LangChain 中的记忆与对话上下文
学习 LangChain 记忆如何跟踪对话历史,让链和聊天机器人能够进行连贯的多轮对话。
LangChain 中的记忆与对话上下文 是 CoddyKit 上的免费 LangChain / RAG / Vector DBs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 LangChain / RAG / Vector DBs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 LangChain / RAG / Vector DBs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
LLMs Are Stateless
A language model has no memory between calls. Each request is independent — it only knows what you put in the current prompt. To build a chatbot that remembers, you must feed prior turns back in yourself.
What LangChain Memory Does
LangChain memory automates this: it stores the conversation and injects relevant history into the prompt on each new turn. Your chain stays simple while the model appears to remember.
Conversation Buffer Memory
The simplest memory keeps the full transcript and prepends it to every prompt. Great for short chats, but it grows with every turn.
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory.save_context({'input': 'Hi, I am Sam'}, {'output': 'Hello Sam!'})
print(memory.load_memory_variables({}))The Context Window Limit
Every model has a finite context window (a token budget). A growing buffer eventually overflows it, causing errors or truncation. Managing history size is the central challenge of memory.
turns = 50
tokens_per_turn = 200
total = turns * tokens_per_turn
print('history tokens:', total)Window Memory
ConversationBufferWindowMemory keeps only the last k turns. It bounds token usage at the cost of forgetting older context — a simple, effective trade-off for many chatbots.
from langchain.memory import ConversationBufferWindowMemory
memory = ConversationBufferWindowMemory(k=3)
# only the most recent 3 exchanges are keptSummary Memory
ConversationSummaryMemory uses the LLM to compress old turns into a running summary. You keep the gist of a long conversation in far fewer tokens, sacrificing exact wording for breadth.
Summary Buffer: Best of Both
ConversationSummaryBufferMemory keeps recent turns verbatim and summarizes everything older. Recent context stays precise while distant context is condensed — a popular default for production chatbots.
Wiring Memory into a Chain
You attach memory to a conversational chain. On each call, the chain loads history, builds the prompt, calls the model, and saves the new turn back to memory automatically.
from langchain.chains import ConversationChain
chain = ConversationChain(llm=llm, memory=memory)
chain.predict(input='What is my name?')Memory Variables and Prompts
Memory exposes its content as a variable (often history or chat_history) that your prompt template references. The placeholder is where the stored conversation gets injected.
template = 'Conversation so far:\n{history}\nHuman: {input}\nAI:'Persisting Memory
In-process memory vanishes when the app restarts. For real users, back memory with a store — Redis, a database, or a chat-message-history backend keyed by session id — so conversations survive across requests and servers.
Choosing a Memory Type
Match memory to need: buffer for short chats, window when you only care about recent turns, summary for long sessions on a budget, and summary-buffer for the common case. Always persist memory for multi-user apps.
Quick Check
Test your understanding of LangChain memory.
Recap
You learned how LangChain gives chatbots memory:
- LLMs are stateless; memory re-injects history each turn
- Buffer, window, summary, and summary-buffer trade detail against tokens
- Memory exposes a history variable that the prompt template uses
- Persist memory per session for multi-user, multi-server apps
常见问题解答
「LangChain 中的记忆与对话上下文」课时是免费的吗?
是的 — 「LangChain 中的记忆与对话上下文」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 LangChain / RAG / Vector DBs 课程的其余内容,请升级到 CoddyKit PRO。 LangChain / RAG / Vector DBs 课程共包含 4 节课。
「LangChain 中的记忆与对话上下文」这节课中我会学到什么?
学习 LangChain 记忆如何跟踪对话历史,让链和聊天机器人能够进行连贯的多轮对话。 你通过在浏览器中直接运行的动手代码来练习 LangChain / RAG / Vector DBs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 LangChain / RAG / Vector DBs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 LangChain / RAG / Vector DBs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「LangChain 中的记忆与对话上下文」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 LangChain / RAG / Vector DBs 课中编写并运行代码吗?
能。每节 LangChain / RAG / Vector DBs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 设置您的 LangChain 环境
- 提示、LLM 与基础链
- 输出解析器与回调
- LangChain 中的记忆与对话上下文