merge_message_runs#

langchain_core.messages.utils.merge_message_runs(
messages: Sequence[MessageLikeRepresentation] | None = None,
**kwargs: Any,
) β†’ list[BaseMessage] | Runnable[Sequence[MessageLikeRepresentation], list[BaseMessage]][source]#

Merge consecutive Messages of the same type.

NOTE: ToolMessages are not merged, as each has a distinct tool call id that can’t be merged.

Parameters:
  • messages (Union[Sequence[MessageLikeRepresentation], None]) – Sequence Message-like objects to merge.

  • chunk_separator – Specify the string to be inserted between message chunks.

  • "n". (Default is)

  • kwargs (Any)

Returns:

list of BaseMessages with consecutive runs of message types merged into single messages. By default, if two messages being merged both have string contents, the merged content is a concatenation of the two strings with a new-line separator. The separator inserted between message chunks can be controlled by specifying any string with chunk_separator. If at least one of the messages has a list of content blocks, the merged content is a list of content blocks.

Return type:

Union[list[BaseMessage], Runnable[Sequence[MessageLikeRepresentation], list[BaseMessage]]]

Example

from langchain_core.messages import (
    merge_message_runs,
    AIMessage,
    HumanMessage,
    SystemMessage,
    ToolCall,
)

messages = [
    SystemMessage("you're a good assistant."),
    HumanMessage(
        "what's your favorite color",
        id="foo",
    ),
    HumanMessage(
        "wait your favorite food",
        id="bar",
    ),
    AIMessage(
        "my favorite colo",
        tool_calls=[
            ToolCall(
                name="blah_tool", args={"x": 2}, id="123", type="tool_call"
            )
        ],
        id="baz",
    ),
    AIMessage(
        [{"type": "text", "text": "my favorite dish is lasagna"}],
        tool_calls=[
            ToolCall(
                name="blah_tool",
                args={"x": -10},
                id="456",
                type="tool_call",
            )
        ],
        id="blur",
    ),
]

merge_message_runs(messages)
[
    SystemMessage("you're a good assistant."),
    HumanMessage(
        "what's your favorite color\\n"
        "wait your favorite food", id="foo",
    ),
    AIMessage(
        [
            "my favorite colo",
            {"type": "text", "text": "my favorite dish is lasagna"}
        ],
        tool_calls=[
            ToolCall({
                "name": "blah_tool",
                "args": {"x": 2},
                "id": "123",
                "type": "tool_call"
            }),
            ToolCall({
                "name": "blah_tool",
                "args": {"x": -10},
                "id": "456",
                "type": "tool_call"
            })
        ]
        id="baz"
    ),
]

Examples using merge_message_runs