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

LangChain中向Runnable传递ChatMessageHistory列表报错求助

修复LangChain RAG链中ChatMessageHistory传入错误

错误原因

你遇到的TypeError是因为在RAG链的字典配置中,直接将chat_history(列表类型)作为值传入,而LangChain的RunnableMap(链中的字典结构)要求每个键对应的值必须是Runnable、可调用对象或字典,不能直接传入原始列表。

修复方案

1. 正确传递聊天历史参数

将链中chat_history的值改为RunnablePassthrough(),让链从invoke方法的输入参数中获取该值,而非直接引用外部变量。

2. 格式化ChatMessageHistory为字符串

ChatMessageHistory是消息对象的列表,需先转换为Prompt能识别的字符串格式(区分人类与AI消息),否则模板无法正确解析内容。

修改后的完整代码

def format_chat_history(chat_history):
    # 将ChatMessageHistory列表格式化为可读性字符串
    formatted_history = []
    for message in chat_history:
        if message.type == "human":
            formatted_history.append(f"Human: {message.content}")
        elif message.type == "ai":
            formatted_history.append(f"AI: {message.content}")
    return "\n".join(formatted_history)

def process_chat(question, retriever, chat_history):
    template = """
        Use the concrete examples of thought and action as a guide for the creation of the ontology.
        Examples: 

        {context}

        END OF EXAMPLES

        The history of discussion is the following: 
        
        {chat_history}

        END OF CHAT HISTORY

        Question: {question}
    """

    custom_rag_prompt = PromptTemplate.from_template(template)

    rag_chain = (
        {
            "context": retriever | format_docs,
            "question": RunnablePassthrough(),
            # 先获取输入的聊天历史,再通过格式化函数转换为字符串
            "chat_history": RunnablePassthrough() | format_chat_history
        }
        | custom_rag_prompt
        | model
        | StrOutputParser()
    )
    response = rag_chain.invoke({"question": question, "chat_history": chat_history})
    return response

关键修改点说明

  • 新增format_chat_history函数:把ChatMessageHistory的消息列表转换为清晰的字符串格式,确保Prompt能正确渲染聊天历史内容。
  • 链中chat_history配置:使用RunnablePassthrough() | format_chat_history组合,先获取输入的聊天历史列表,再通过格式化函数转换为字符串,完全符合LangChain Runnable的类型要求。
  • 补充函数参数:将chat_history作为参数传入process_chat,保证链能获取到正确的输入数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:35:08