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

Python继承问题:子类AnotherMem报错无user_id字段

问题原因与解决方法
  • 核心问题:LangChain的BaseMemory继承自Pydantic BaseModel,你的自定义类未遵循Pydantic的模型初始化规则,导致字段未被正确注册。

    • ChatMemory类的__init__方法没有调用父类BaseMemory的构造方法,跳过了Pydantic的字段初始化流程,user_id和type未被识别为模型字段。
    • 子类AnotherMem继承时,Pydantic无法检测到user_id字段,因此抛出ValueError。
  • 修复步骤:

    1. 补全UUID的导入语句:from uuid import UUID
    2. 按照Pydantic规范定义模型字段,并确保正确调用父类构造方法:

    方法一:使用Pydantic自动生成的构造方法(推荐)

    from langchain.schema import BaseMemory
    from uuid import UUID
    
    class ChatMemory(BaseMemory):
        # 直接声明Pydantic字段
        user_id: UUID
        type: str
    
        # 必须实现BaseMemory的抽象方法
        def load_memory_variables(self, inputs: dict) -> dict:
            return {"history": []}
        
        def save_context(self, inputs: dict, outputs: dict) -> None:
            pass
        
        def clear(self) -> None:
            pass
    
    class AnotherMem(ChatMemory):
        # 无需额外逻辑时,不用重写__init__
        pass
    

    方法二:自定义构造方法时必须调用父类__init__

    from langchain.schema import BaseMemory
    from uuid import UUID
    
    class ChatMemory(BaseMemory):
        user_id: UUID
        type: str
    
        def __init__(self, user_id: UUID, type: str, **kwargs):
            # 调用父类构造方法,传入必要参数和额外参数
            super().__init__(user_id=user_id, type=type, **kwargs)
            # 自定义初始化逻辑(如果需要)
    
        # 实现BaseMemory的抽象方法
        def load_memory_variables(self, inputs: dict) -> dict:
            return {"history": []}
        
        def save_context(self, inputs: dict, outputs: dict) -> None:
            pass
        
        def clear(self) -> None:
            pass
    
    class AnotherMem(ChatMemory):
        def __init__(self, user_id: UUID, type: str, **kwargs):
            super().__init__(user_id=user_id, type=type, **kwargs)
    
  • 补充说明:

    • 必须实现BaseMemory的所有抽象方法(load_memory_variables、save_context、clear),否则会抛出抽象方法未实现的错误。
    • Pydantic模型的字段需要显式声明在类层级,而非仅在__init__中赋值,才能被Pydantic的字段系统识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:03:27