You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完整保存LangChain对话状态(含ChatPromptTemplate提示词)

LangChain保存完整对话状态(含所有提示词)解决方案

核心问题原因

LangChain的ConversationBufferMemory默认仅存储用户提问和AI回复的对话历史,而ChatPromptTemplate中的系统提示、示例对话等配置并不在chat_memory的消息列表里,需要单独提取模板的完整内容,再和对话历史组合保存。

具体实现步骤

1. 提取ChatPromptTemplate的完整配置

通过遍历ChatPromptTemplate.messages,可以获取所有类型的提示模块(系统提示、FewShot示例、用户输入模板等),提取每个模块的关键属性:

  • 系统提示:提取template属性
  • FewShot示例:提取examples(示例对话内容)、prefix/suffix(示例前后的引导语)、example_prompt(示例的消息模板)

2. 组合模板配置与对话历史

将提取到的模板完整信息,和chat_memory中的对话消息一起打包,通过messages_to_dict转成可序列化的字典后,写入JSON文件。

完整示例代码

from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
    ChatPromptTemplate, SystemMessagePromptTemplate,
    HumanMessagePromptTemplate, FewShotChatMessagePromptTemplate
)
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
from langchain.schema import messages_to_dict
import json

# 构建包含系统提示、示例对话的ChatPromptTemplate
examples = [
    {"input": "你好", "output": "你好!很高兴为你服务😊"},
    {"input": "今天天气怎么样", "output": "我没办法实时查天气,但可以教你如何查看哦~"}
]
example_prompt = ChatPromptTemplate.from_messages([
    HumanMessagePromptTemplate.from_template("{input}"),
    SystemMessagePromptTemplate.from_template("{output}")
])
few_shot_prompt = FewShotChatMessagePromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    prefix="以下是对话示例,请遵循相同风格回复:",
    suffix="现在开始正式对话:"
)
system_prompt = SystemMessagePromptTemplate.from_template("你是友好的AI助手,回复简洁亲切")
final_prompt = ChatPromptTemplate.from_messages([
    system_prompt, few_shot_prompt, HumanMessagePromptTemplate.from_template("{input}")
])

# 初始化对话链
memory = ConversationBufferMemory()
conversation = ConversationChain(
    llm=ChatOpenAI(temperature=0),
    memory=memory,
    prompt=final_prompt,
    verbose=True
)

# 模拟对话交互
conversation.predict(input="请问LangChain怎么保存完整对话状态?")
conversation.predict(input="那怎么提取示例提示词?")

# 提取完整对话状态
full_state = {
    "prompt_config": [
        {
            "type": msg.__class__.__name__,
            "template": msg.template if hasattr(msg, "template") else None,
            "prefix": msg.prefix if hasattr(msg, "prefix") else None,
            "suffix": msg.suffix if hasattr(msg, "suffix") else None,
            "examples": msg.examples if hasattr(msg, "examples") else None,
            "example_prompt": messages_to_dict(msg.example_prompt.messages) if hasattr(msg, "example_prompt") else None
        }
        for msg in final_prompt.messages
    ],
    "chat_history": messages_to_dict(memory.chat_memory.messages)
}

# 保存到本地JSON文件
with open("full_conversation_state.json", "w", encoding="utf-8") as f:
    json.dump(full_state, f, ensure_ascii=False, indent=2)

效果说明

运行代码后生成的full_conversation_state.json会包含:

  • 所有提示模板的类型、内容、配置参数
  • 用户和AI的完整对话历史
    完全满足保存整个对话状态的需求

内容的提问来源于stack exchange,提问作者ryan-serpico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:13:20