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

LangChain调用报错求助:Python ChatGPT聊天机器人内存存储问题修复

问题修复方案

错误原因分析

  1. LangChainDeprecationWarning:BaseChatModel.__call__方法已被弃用,LangChain 0.1.7+版本要求使用invoke方法替代直接调用模型实例。
  2. AttributeError: 'SystemMessage' object has no attribute 'name':新版本LangChain的消息转换逻辑会读取name属性,但旧版本的SystemMessage或pickle序列化的旧消息对象缺少该属性,导致转换失败。

修复后的完整代码

import pickle, os
from langchain_openai.chat_models import ChatOpenAI
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)

def execute_prompt(text, history, jarvis_setup):
    print(f"You said: {text}")
    history.append(HumanMessage(content=text))
    # 替换弃用的__call__方法为invoke
    response = jarvis_setup.invoke(history)
    history.append(AIMessage(content=response.content))
    with open('JarvisMemory.txt', 'wb') as file:
        pickle.dump(history, file)
        
    print(response.content)

def main():
    jarvis_setup = ChatOpenAI(openai_api_key="API_KEY", model="gpt-3.5-turbo", temperature=0.7, max_tokens=400)
    
    if os.path.exists("JarvisMemory.txt"):
        try:
            with open("JarvisMemory.txt", "rb") as file:
                history = pickle.load(file)
            # 为旧消息对象补充缺失的name属性
            for msg in history:
                if not hasattr(msg, 'name'):
                    setattr(msg, 'name', None)
        except AttributeError:
            # 旧文件完全不兼容时,删除后重新初始化
            os.remove("JarvisMemory.txt")
            history = [SystemMessage(
                content="You are a human-like virtual assistant named Jarvis. Answer all questions as shortly as possible, unless a longer, more detailed response is requested.",
                name=None
            )]
            with open("JarvisMemory.txt", "wb") as file:
                pickle.dump(history, file)
    else:
        history = [SystemMessage(
            content="You are a human-like virtual assistant named Jarvis. Answer all questions as shortly as possible, unless a longer, more detailed response is requested.",
            name=None
        )]
        with open("JarvisMemory.txt", "wb") as file:
            pickle.dump(history, file)
    
    while True:
        print("\n")
        print("Enter prompt.")
        text = input().lower()
        print("Prompt sent.")
    
        if text:
            execute_prompt(text, history, jarvis_setup)
        else:
            print("No prompt given.")
            continue
                    
if __name__ == "__main__":
    main()

关键修复点说明

  • 替换弃用方法:将response = jarvis_setup(history)改为response = jarvis_setup.invoke(history),符合LangChain新版本API规范,消除弃用警告。
  • 兼容name属性:
    1. 创建新SystemMessage时明确指定name=None参数,确保消息对象具备新版本所需属性。
    2. 对已存在的pickle历史文件,尝试加载后检查并补充缺失的name属性;若加载失败则删除旧文件,重新初始化聊天历史。
  • 可选优化:如果想更稳定管理聊天历史,建议使用LangChain内置的ChatMessageHistory类替代手动pickle,它会自动处理消息对象的版本兼容问题。

内容的提问来源于stack exchange,提问作者symmetrical pattern with teal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:19:59