Search code examples
pythoninheritancelangchain

Python inheritance - Interfaces/classes


from langchain.schema import BaseMemory

class ChatMemory(BaseMemory):
   def __init__(self, user_id: UUID, type: str):
    self.user_id = user_id
    self.type = type

   # implemented abstract methods

class AnotherMem(ChatMemory):
    def __init__(self, user_id: UUID, type: str):
        super().__init__(user_id, type)

This seems simple enough - but I get an error: ValueError: "AnotherMem" object has no field "user_id". What am I doing wrong?

Note that BaseMemory is an interface.


Solution

  • It looks like BaseMemory from langchain is defined as a pydantic model, which has strict rules for defining instance attributes. Instead of using a constructor method, use the standard pydantic syntax of declaring expected instance attributes on the child class.

    import uuid
    from langchain.schema import BaseMemory
    
    
    class ChatMemory(BaseMemory):
        user_id: uuid.UUID
        type: str
    
        ...
    
    class AnotherMem(ChatMemory):
        pass
    
    
    print(AnotherMem(user_id=uuid.uuid4(), type="foo").user_id)
    
    d952d62e-79e0-4cf4-a786-d23d880f96a2