Python继承问题:子类AnotherMem报错无user_id字段
问题原因与解决方法
核心问题:LangChain的
BaseMemory继承自PydanticBaseModel,你的自定义类未遵循Pydantic的模型初始化规则,导致字段未被正确注册。ChatMemory类的__init__方法没有调用父类BaseMemory的构造方法,跳过了Pydantic的字段初始化流程,user_id和type未被识别为模型字段。- 子类
AnotherMem继承时,Pydantic无法检测到user_id字段,因此抛出ValueError。
修复步骤:
- 补全
UUID的导入语句:from uuid import UUID - 按照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
相关产品推荐
相关产品推荐

