Skip to content

The agent engineering platform.

feat(core): support custom message separator in get_buffer_string() (#34569)

Chris Papademetrious0c7b7e045d9b
diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py
index 274be99b2e..2ac913a12e 100644
--- a/libs/core/langchain_core/messages/utils.py
+++ b/libs/core/langchain_core/messages/utils.py
@@ -99,7 +99,10 @@ AnyMessage = Annotated[
def get_buffer_string(
- messages: Sequence[BaseMessage], human_prefix: str = "Human", ai_prefix: str = "AI"
+ messages: Sequence[BaseMessage],
+ human_prefix: str = "Human",
+ ai_prefix: str = "AI",
+ message_separator: str = "\n",
) -> str:
r"""Convert a sequence of messages to strings and concatenate them into one string.
@@ -107,6 +110,7 @@ def get_buffer_string(
messages: Messages to be converted to strings.
human_prefix: The prefix to prepend to contents of `HumanMessage`s.
ai_prefix: The prefix to prepend to contents of `AIMessage`.
+ message_separator: The separator to use between messages.
Returns:
A single string concatenation of all input messages.
@@ -160,7 +164,7 @@ def get_buffer_string(
string_messages.append(message)
- return "\n".join(string_messages)
+ return message_separator.join(string_messages)
def _message_from_dict(message: dict) -> BaseMessage:
diff --git a/libs/core/tests/unit_tests/test_messages.py b/libs/core/tests/unit_tests/test_messages.py
index a2313b7122..c5a6b15728 100644
--- a/libs/core/tests/unit_tests/test_messages.py
+++ b/libs/core/tests/unit_tests/test_messages.py
@@ -370,6 +370,14 @@ class TestGetBufferString:
assert get_buffer_string(msgs) == expected_output
+ def test_custom_message_separator(self) -> None:
+ msgs = [
+ self._HUMAN_MSG,
+ self._AI_MSG,
+ ]
+ expected_output = "Human: human\n\nAI: ai"
+ assert get_buffer_string(msgs, message_separator="\n\n") == expected_output
+
def test_multiple_msg() -> None:
human_msg = HumanMessage(content="human", additional_kwargs={"key": "value"})