Skip to content

file ¤

This module contains the FileMessageHistory class, which is used to store chat message history in a local file.

Classes:

Name Description
FileMessageHistory

Chat message history that stores history in a local file.

FileMessageHistory ¤

FileMessageHistory(file_path: Optional[str] = None)

Bases: BaseChatMessageHistory

Chat message history that stores history in a local file.

Parameters:

Name Type Description Default
file_path Optional[str]

path of the local file to store the messages. if not passed the messages will be stored in a temporary file, and a warning will be logged.

None

Methods:

Name Description
add_message

Append the message to the record in the local file

clear

Clear session memory from the local file

Attributes:

Name Type Description
history List[Message]

Retrieve the messages from the local file

Source code in src/declarai/memory/file.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def __init__(self, file_path: Optional[str] = None):
    super().__init__()
    if not file_path:
        # Create a temporary file and immediately close it to get its name.
        temp = tempfile.NamedTemporaryFile(delete=False)
        self.file_path = Path(temp.name)
        self.file_path.write_text(json.dumps([]))
        logger.warning(
            "No file path provided to store the messages. "
            f"Messages will be stored in a temporary file path: {self.file_path}"
        )
    else:
        self.file_path = Path(file_path)

    if not self.file_path.exists():
        self.file_path.touch()
        self.file_path.write_text(json.dumps([]))

history property ¤

history: List[Message]

Retrieve the messages from the local file

add_message ¤

add_message(message: Message) -> None

Append the message to the record in the local file

Source code in src/declarai/memory/file.py
50
51
52
53
54
55
def add_message(self, message: Message) -> None:
    """Append the message to the record in the local file"""
    messages = self.history.copy()
    messages.append(message)
    messages_dict = [msg.dict() for msg in messages]
    self.file_path.write_text(json.dumps(messages_dict))

clear ¤

clear() -> None

Clear session memory from the local file

Source code in src/declarai/memory/file.py
57
58
59
def clear(self) -> None:
    """Clear session memory from the local file"""
    self.file_path.write_text(json.dumps([]))