langchain_core.messages.utils.merge_message_runs

langchain_core.messages.utils.merge_message_runs(messages: Optional[Sequence[MessageLikeRepresentation]] = None, **kwargs: Any) Union[List[BaseMessage], Runnable[Sequence[MessageLikeRepresentation], List[BaseMessage]]][source]

合并同一类型的连续消息。

注意:ToolMessages不会合并,因为每个都有一个独特的工具调用id,无法合并。

参数
  • messages (可选[Sequence[MessageLikeRepresentation]]) – 要合并的Message-like对象序列。

  • kwargs (任何) –

返回

将连续的消息类型合并的单个消息的BaseMessages列表。如果两个要合并的消息都具有字符串内容,则合并的内容是两个字符串的连接,并用新行分隔符连接。如果至少有一个消息具有内容块列表,则合并的内容是内容块列表。

返回类型

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

示例

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"
    ),
]