model = ChatOpenAI(model='gpt-3.5-turbo') store = {} def get_session_history(ses...

2025年09月26日 10:00 响应: 3.93秒 状态: success

🚨 错误信息

model = ChatOpenAI(model='gpt-3.5-turbo') store = {} def get_session_history(session_id:str) ->BaseChatMessageHistory: if session_id not in store: store[session_id] = InMemoryChatMessageHistory return store[session_id] with_message_history = RunnableWithMessageHistory(model,get_session_history) config = {"configurable":{"session_id":"abc12"}} response = with_message_history.invoke( [HumanMessage(content="Hi I'm Bob")], config=config ) print(response)

🤖 AI解决方案

TypeError: 'module' object is not callable

错误翻译

TypeError: 'module' 对象不可调用

原因分析

store[session_id] = InMemoryChatMessageHistory 这一行错误地将 InMemoryChatMessageHistory 模块本身赋值给了 store[session_id],而不是这个模块中的。当 get_session_history 函数后续尝试调用 store[session_id]() 时,Python 会尝试调用一个模块,这在编程中是不允许的,因此抛出 TypeError

解决方案

InMemoryChatMessageHistory 替换为其类 InMemoryChatMessageHistory()

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables import RunnableWithMessageHistory
from langchain_community.chat_message_histories import InMemoryChatMessageHistory

model = ChatOpenAI(model='gpt-3.5-turbo')

store = {}
def get_session_history(session_id:str) ->BaseChatMessageHistory:
    if session_id not in store:
        # 正确地实例化 InMemoryChatMessageHistory 类
        store[session_id] = InMemoryChatMessageHistory()
        return store[session_id]
    return store[session_id]

with_message_history = RunnableWithMessageHistory(
    model,
    get_session_history,
    input_messages_key="content", # 明确指定输入消息的键
    history_messages_key="history" # 明确指定历史消息的键
)
config = {"configurable": {"session_id": "abc12"}}
response = with_message_history.invoke(
    [HumanMessage(content="Hi I'm Bob")],
    config=config
)
print(response)

预防措施

  • 区分模块与类:在导入和使用类时,务必确保你使用的是类的实例化对象或类本身,而不是整个模块。
  • 代码审查:在团队协作中,进行代码审查可以帮助发现这类因为对模块和类混淆而导致的低级错误。