Skip to content

Commit f507007

Browse files
committed
feat(core): support custom message separator in get_buffer_string()
1 parent a7aad60 commit f507007

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

libs/core/langchain_core/messages/utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,18 @@ def _get_type(v: Any) -> str:
9999

100100

101101
def get_buffer_string(
102-
messages: Sequence[BaseMessage], human_prefix: str = "Human", ai_prefix: str = "AI"
102+
messages: Sequence[BaseMessage],
103+
human_prefix: str = "Human",
104+
ai_prefix: str = "AI",
105+
message_separator: str = "\n",
103106
) -> str:
104107
r"""Convert a sequence of messages to strings and concatenate them into one string.
105108
106109
Args:
107110
messages: Messages to be converted to strings.
108111
human_prefix: The prefix to prepend to contents of `HumanMessage`s.
109112
ai_prefix: The prefix to prepend to contents of `AIMessage`.
113+
message_separator: The separator to use between messages.
110114
111115
Returns:
112116
A single string concatenation of all input messages.
@@ -157,7 +161,7 @@ def get_buffer_string(
157161
message += f"{m.additional_kwargs['function_call']}"
158162
string_messages.append(message)
159163

160-
return "\n".join(string_messages)
164+
return message_separator.join(string_messages)
161165

162166

163167
def _message_from_dict(message: dict) -> BaseMessage:

libs/core/tests/unit_tests/test_messages.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,14 @@ def test_multiple_msg(self) -> None:
370370

371371
assert get_buffer_string(msgs) == expected_output
372372

373+
def test_custom_message_separator(self) -> None:
374+
msgs = [
375+
self._HUMAN_MSG,
376+
self._AI_MSG,
377+
]
378+
expected_output = "Human: human\n\nAI: ai"
379+
assert get_buffer_string(msgs, message_separator="\n\n") == expected_output
380+
373381

374382
def test_multiple_msg() -> None:
375383
human_msg = HumanMessage(content="human", additional_kwargs={"key": "value"})

0 commit comments

Comments
 (0)