Adding BaseChatMessageHistory.__str__ (#14311)

Adding __str__ to base chat message history to make it easier to debug
This commit is contained in:
James Braza 2023-12-05 16:22:31 -05:00 committed by GitHub
parent 8b0060184d
commit 3b75d37cee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 2 deletions

View File

@ -3,7 +3,12 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
from langchain_core.messages import (
AIMessage,
BaseMessage,
HumanMessage,
get_buffer_string,
)
class BaseChatMessageHistory(ABC):
@ -65,3 +70,6 @@ class BaseChatMessageHistory(ABC):
@abstractmethod
def clear(self) -> None:
"""Remove all messages from the store"""
def __str__(self) -> str:
return get_buffer_string(self.messages)

View File

@ -1,6 +1,6 @@
from typing import Any, Callable, Sequence, Union
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables.base import RunnableLambda
from langchain_core.runnables.config import RunnableConfig
@ -8,6 +8,15 @@ from langchain_core.runnables.history import RunnableWithMessageHistory
from tests.unit_tests.fake.memory import ChatMessageHistory
def test_interfaces() -> None:
history = ChatMessageHistory()
history.add_message(SystemMessage(content="system"))
history.add_user_message("human 1")
history.add_ai_message("ai")
history.add_message(HumanMessage(content="human 2"))
assert str(history) == "System: system\nHuman: human 1\nAI: ai\nHuman: human 2"
def _get_get_session_history() -> Callable[..., ChatMessageHistory]:
chat_history_store = {}