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.
- Args:
messages: Sequence Message-like objects to merge. chunk_separator: Specify the string to be inserted between message chunks. Default is β
β.
- 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.- 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\nwait 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" ), ]
- Parameters:
messages (Optional[Sequence[MessageLikeRepresentation]]) β
kwargs (Any) β
- Return type:
Union[List[BaseMessage], Runnable[Sequence[MessageLikeRepresentation], List[BaseMessage]]]
Examples using merge_message_runs