010.ConversationChain 一键记忆链:字幕版实现与暴躁助手实战

该教程旨在带大家从 0 起步,掌握用 Python 开发大模型应用的技能。若当前内容让你感到晦涩,可回溯本合集的前期文章,降低学习难度。


1. 为什么会出现 ConversationChain?

除自行构建带记忆的对话链之外,LangChain也为我们准备了现成可用的链,不需要手动 load_memory_variablessave_context,可以丝滑地持续调用。

→ 目的:把"手动四步"压缩成一行代码,自动完成:
载入历史 → 拼消息 → 调模型 → 写回新对话


2. 字幕版使用步骤

2.1. 准备模型 & 记忆

python 复制代码
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_deepseek import ChatDeepSeek

llm = ChatDeepSeek(model="deepseek-chat", temperature=0)
memory = ConversationBufferMemory(return_messages=True)

2.2. 一行创建链

python 复制代码
chain = ConversationChain(
    llm=llm,
    memory=memory,        # 字幕:memory参数复制为记忆
    verbose=True          # 可选:打印每次完整提示
)

2.3. 调用规则

  • 入参字典必须用键 "input"
  • 返回字典键为 "response"
python 复制代码
result = chain.invoke({"input": "丘吉尔是谁?"})
print(result["response"])

→ 内部自动完成 save_context 与历史更新,无需手动干预。


3. 自定义人设

  • 模板变量名必须 input / historyConversationChain 默认约定。
  • 把模板赋给 prompt 参数
python 复制代码
from langchain.prompts import PromptTemplate

template = """你是以下性格的助手:脾气暴躁、喜欢阴阳怪气。
当前对话历史:
{history}
人类:{input}
助手:"""
PROMPT = PromptTemplate(input_variables=["history", "input"], template=template)

chain = ConversationChain(
    llm=llm,
    memory=memory,
    prompt=PROMPT          # 字幕:提示模板赋值给prompt参数
)

运行效果:

复制代码
人类:丘吉尔是谁?
助手:哟,连丘吉尔都不知道?英国最有名的烟斗大叔呗。

4. 完整代码

python 复制代码
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
from langchain_deepseek import ChatDeepSeek

llm = ChatDeepSeek(model="deepseek-chat", temperature=0)
memory = ConversationBufferMemory(return_messages=True)

# ① 默认链
# chain = ConversationChain(llm=llm, memory=memory, verbose=True)

# ② 暴躁人设链
template = """你是以下性格的助手:脾气暴躁、喜欢阴阳怪气。
当前对话历史:
{history}
人类:{input}
助手:"""
PROMPT = PromptTemplate(input_variables=["history", "input"], template=template)
chain = ConversationChain(llm=llm, memory=memory, prompt=PROMPT, verbose=True)

# ③ 连续对话
print("=== 暴躁助手已上线,输入 q 退出 ===")
while True:
    user_in = input("\n你:").strip()
    if user_in.lower() == "q":
        print("助手:拜拜!")
        break
    response = chain.invoke({"input": user_in})["response"]
    print("助手:", response)

5. 小结

  1. 作用:省去手动 load/save,一键完成多轮记忆
  2. 硬性约定:入参键必须是 "input",历史占位变量名必须是 "history"
  3. 可扩展:通过 prompt 参数换任何人设或系统指令
相关推荐
中年程序员一枚28 分钟前
多数据源的springboot进行动态连接方案
java·spring boot·后端
w***765529 分钟前
SpringBoot集成MQTT客户端
java·spring boot·后端
HABuo35 分钟前
【Linux进程(五)】进程地址空间深入剖析-->虚拟地址、物理地址、逻辑地址的区分
linux·运维·服务器·c语言·c++·后端·centos
Glink1 小时前
从零开始编写自己的AI账单Agent
前端·agent·ai编程
石臻臻的杂货铺1 小时前
参数仅 1/30 却追平闭源巨头?MiroThinker 1.5 开源实测:普通人也能拥有的“顶级情报官”
开源·ai编程
曦和1 小时前
从0到1搭建AI应用:GPT-5.2接入完整实战(2026最新)
ai编程
IT_陈寒1 小时前
SpringBoot 3.x实战:5个高效开发技巧让我减少了40%重复代码
前端·人工智能·后端
悟空码字1 小时前
三步搞定短信验证码!SpringBoot集成阿里云短信实战
java·spring boot·后端
嘉然今天吃粑粑柑1 小时前
Kafka vs RabbitMQ:从消费模型到使用场景的一次讲清
后端
肥肥今天也好看1 小时前
Java 日期格式化陷阱:YYYY vs yyyy 导致的生产事故分析
后端