diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py index 380f06714228b..a3d57e42e2d56 100644 --- a/libs/partners/anthropic/langchain_anthropic/chat_models.py +++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py @@ -584,6 +584,14 @@ def _format_messages( if k in ("type", "cache_control", "data") }, ) + elif block["type"] == "compaction": + content.append( + { + k: v + for k, v in block.items() + if k in ("type", "content", "cache_control") + }, + ) elif ( block["type"] == "tool_result" and isinstance(block.get("content"), list) diff --git a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py index 1a8db3713801d..ad9596382c627 100644 --- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py +++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py @@ -808,6 +808,32 @@ def test__format_tool_use_block() -> None: assert result == (None, [expected]) +def test__format_compaction_block() -> None: + message = AIMessage( + [ + { + "type": "compaction", + "content": "summary text", + "cache_control": {"type": "ephemeral"}, + "index": 0, + "signature": "stream-only-metadata", + } + ] + ) + result = _format_messages([message]) + expected = { + "role": "assistant", + "content": [ + { + "type": "compaction", + "content": "summary text", + "cache_control": {"type": "ephemeral"}, + } + ], + } + assert result == (None, [expected]) + + def test__format_messages_with_str_content_and_tool_calls() -> None: system = SystemMessage("fuzz") # type: ignore[misc] human = HumanMessage("foo") # type: ignore[misc]