1 validation error for RunnableWithMessageHistory get_session_history Input shou...

2025年09月26日 10:11 响应: 3.25秒 状态: success

🚨 错误信息

Traceback (most recent call last): File "D:\新建文件夹\langchain-base\Chatbot.py", line 23, in <module> with_message_history = RunnableWithMessageHistory(model,get_session_history("abc12")) File "D:\software\Python\Lib\site-packages\langchain_core\runnables\history.py", line 364, in __init__ super().__init__( ~~~~~~~~~~~~~~~~^ get_session_history=get_session_history, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<5 lines>... **kwargs, ^^^^^^^^^ ) ^ File "D:\software\Python\Lib\site-packages\langchain_core\runnables\base.py", line 5620, in __init__ super().__init__( ~~~~~~~~~~~~~~~~^ bound=bound, ^^^^^^^^^^^^ ...<5 lines>... **other_kwargs, ^^^^^^^^^^^^^^^ ) ^ File "D:\software\Python\Lib\site-packages\langchain_core\load\serializable.py", line 115, in __init__ super().__init__(*args, **kwargs) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ File "D:\software\Python\Lib\site-packages\pydantic\main.py", line 253, in __init__ validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) pydantic_core._pydantic_core.ValidationError: 1 validation error for RunnableWithMessageHistory get_session_history Input should be callable [type=callable_type, input_value=InMemoryChatMessageHistory(messages=[]), input_type=InMemoryChatMessageHistory] For further information visit https://errors.pydantic.dev/2.11/v/callable_type

🤖 AI解决方案

ValidationError: 1 validation error for RunnableWithMessageHistory
get_session_history
  Input should be callable [type=callable_type, input_value=InMemoryChatMessageHistory(messages=[]), input_type=InMemoryChatMessageHistory]

错误翻译:

ValidationError: RunnableWithMessageHistory 有 1 个验证错误
get_session_history
  输入应该是可调用的 [类型=callable_type, 输入值=InMemoryChatMessageHistory(messages=[]), 输入类型=InMemoryChatMessageHistory]

原因分析:

RunnableWithMessageHistoryget_session_history 参数需要一个函数(可调用对象),用于创建或获取会话历史记录。而你传入的是一个已经实例化好的对象 InMemoryChatMessageHistory(messages=[])

解决方案:

get_session_history 的值修改为一个函数,该函数返回 InMemoryChatMessageHistory 的实例。

from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import InMemoryChatMessageHistory

# 假设 model 是你的 ChatModel 实例

def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
    # 你可以根据 session_id 来管理不同的历史记录
    # 在这个例子中,我们直接返回一个新的 InMemoryChatMessageHistory
    return InMemoryChatMessageHistory(messages=[])

with_message_history = RunnableWithMessageHistory(
    model,
    get_session_history, # 传入的是函数而不是实例化对象
    input_messages_key="input", # 根据你的实际情况调整
    history_messages_key="chat_history", # 根据你的实际情况调整
)

预防措施:

  • 仔细阅读文档: 在使用新的类或函数时,仔细阅读其官方文档,特别是关于参数类型和期望值的说明。
  • 理解可调用对象: 区分函数(可调用对象)和对象实例,确保在需要函数的地方传入的是函数本身,而不是已经创建好的对象。