用 LangChain 克隆一个 ChatGPT:LLMChain + Memory 实战
0 前言ChatGPT 之所以好用核心在于个性化的系统提示词多轮对话记忆本文基于 LangChain用不到 30 行代码复刻这两个能力构建一个可自定义人格的对话 AI。1 技术栈组件说明LLMChainLangChain 的核心链将 LLM、Prompt、Memory 串联起来PromptTemplate结构化提示词模板支持变量注入ConversationBufferWindowMemory滑动窗口记忆保留最近 k 轮对话ChatOpenAI/Qwen底层大模型本文使用 Qwen2 核心思路自动保存对话历史用户输入PromptTemplate注入 history human_inputLLM输出ConversationBufferWindowMemory每次调用时Memory 自动将历史对话注入到{history}变量使 LLM 具备记忆能力。3 完整代码3.1 设计 Prompt 模板Prompt 是塑造 AI 个性的关键。注意两个必要的占位变量{history}由 Memory 自动填充无需手动传入{human_input}用户每次的输入templateAI助手是由OpenAI训练的大型语言模型。 AI助手旨在能够处理各种任务从回答简单问题到提供广泛话题的深入解释和讨论。 作为一个语言模型AI助手能够根据接收到的输入生成类似人类的文本使其能够进行 自然的对话并提供与当前话题相关且连贯的回答。 {history} Human: {human_input} AI助手:promptPromptTemplate(input_variables[history,human_input],templatetemplate)关键设计点系统描述放在最前面定义 AI 的能力边界和人格{history}和{human_input}之间保持清晰分隔末尾的AI助手:作为续写触发词引导模型以 AI 身份回复3.2 组装 LLMChainchatgpt_chainLLMChain(llmllm,promptprompt,memoryConversationBufferWindowMemory(k2),# 保留最近 2 轮对话)ConversationBufferWindowMemory(k2)只保留最近 2 轮对话避免 Token 超限适合生产环境。3.4 运行对话outputchatgpt_chain.predict(human_input你好介绍一下你自己)print(output)4 进阶玩法角色扮演 Linux 终端修改 Prompt让 AI 扮演一个 Linux 终端只返回命令执行结果outputchatgpt_chain.predict(human_input我要求你扮演Linux终端。我会输入命令你将回复终端应显示的内容。我希望你只在一个唯一的代码块内回复终端输出不添加其他内容。我的第一个命令是 pwd)print(output)之后可以像操作真实终端一样连续交互# 由于有 Memory模型知道当前目录的上下文outputchatgpt_chain.predict(human_inputls ~)outputchatgpt_chain.predict(human_inputcd ~)# 创建文件模拟outputchatgpt_chain.predict(human_input{创建一个名为crypto.txt的文件并在其中放入主流的加密货币代码})# 执行 Python 脚本模拟outputchatgpt_chain.predict(human_inputecho -e xlambda y:y*53;print(x(6)) run.py python3 run.py)这展示了 Memory 的核心价值多轮对话之间的状态共享。5 Memory 类型对比Memory 类型特点适用场景ConversationBufferMemory保存全部历史短对话、调试ConversationBufferWindowMemory保留最近 k 轮长对话、生产环境ConversationSummaryMemory用 LLM 压缩历史为摘要超长对话ConversationTokenBufferMemory按 Token 数量限制历史Token 精确控制6 总结步骤代码量核心组件定义模板~5 行PromptTemplate配置记忆~1 行ConversationBufferWindowMemory组装链~5 行LLMChain运行对话~1 行.predict()LLMChain LLM Prompt Memory 的优雅封装通过替换 Prompt 模板即可快速构建不同人格的 AI 助手这正是 LangChain 的设计哲学组合而非重写。