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 (Optional[Sequence[MessageLikeRepresentation]]) β Sequence Message-like objects to merge.
kwargs (Any)
- Returns:
List of BaseMessages with consecutive runs of message types merged into single messages. If two messages being merged both have string contents, the merged content is a concatenation of the two strings with a new-line 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\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" ), ]