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

如何在LangChain的RAG中使用ChatPromptTemplate.from_template添加对话历史

在LangChain的ChatPromptTemplate.from_template中添加对话历史

要在ChatPromptTemplate.from_template实现中加入对话历史,按以下步骤修改代码即可:

  1. 更新提示模板,新增对话历史占位符
    在模板中加入{chat_history}变量,将对话历史放在上下文与当前问题之前,让AI能参考过往交互内容:

    after_rag_template = """You are an respectful and honest assistant. You have to answer the user's questions using only the context provided to you. If you don't know the answer, just say you don't know. Don't try to make up an answer.
    
    Chat History:
    {chat_history}
    
    Context:
    {context}
    
    Question: {question}
    """
    after_rag_prompt = ChatPromptTemplate.from_template(after_rag_template)
    
  2. 调整Chain结构,传递对话历史输入
    将对话历史作为输入参数传入Chain,同时需将对话历史格式化为AI可识别的字符串形式:

    from langchain_core.runnables import RunnablePassthrough, RunnableMap
    
    # 格式化对话历史:将消息列表转为角色+内容的文本串
    def format_chat_history(chat_history):
        return "\n".join([f"{msg['role']}: {msg['content']}" for msg in chat_history])
    
    after_rag_chain = (
        RunnableMap({
            "context": retriever,
            "question": lambda x: x["question"],
            "chat_history": lambda x: format_chat_history(x["chat_history"])
        })
        | after_rag_prompt
        | model_local
        | StrOutputParser()
    )
    
    # 调用示例:传入当前问题与对话历史
    chat_history = [
        {"role": "user", "content": "What is LangChain?"},
        {"role": "assistant", "content": "LangChain is a framework for building LLM applications."}
    ]
    content = after_rag_chain.invoke({"question": prompt, "chat_history": chat_history})
    
  3. 额外说明

    • 如果使用LangChain内置的ChatMessage类,格式化函数可简化为lambda chat_history: "\n".join([str(msg) for msg in chat_history])
    • 对话历史的格式需与模板中的展示逻辑匹配,确保AI能正确解析过往交互信息

内容的提问来源于stack exchange,提问作者Elwebman Amsterdam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:36:07