From cdb9742511d57b8eb3d37f93d115ae9b4d60dba4 Mon Sep 17 00:00:00 2001 From: ccurme Date: Tue, 24 Feb 2026 08:45:54 -0500 Subject: [PATCH] fix(anthropic): filter out common OpenAI Responses block types (#35417) --- .../langchain_anthropic/chat_models.py | 6 ++++++ .../tests/unit_tests/test_chat_models.py | 20 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py index c22b76df86b..ee9f480427a 100644 --- a/libs/partners/anthropic/langchain_anthropic/chat_models.py +++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py @@ -471,6 +471,12 @@ def _format_messages( if "type" not in block: msg = "Dict content block must have a type key" raise ValueError(msg) + if block["type"] in ("reasoning", "function_call") and ( + not isinstance(message, AIMessage) + or message.response_metadata.get("model_provider") + != "anthropic" + ): + continue if block["type"] == "image_url": # convert format source = _format_image(block["image_url"]["url"]) 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 d4f894e4e7c..2f6ffbffe36 100644 --- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py +++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py @@ -2395,6 +2395,26 @@ def test_extras_with_multiple_fields() -> None: assert "input_examples" in tool_def +@pytest.mark.parametrize("block_type", ["reasoning", "function_call"]) +def test__format_messages_filters_non_anthropic_blocks(block_type: str) -> None: + """Test that reasoning/function_call blocks are filtered for non-anthropic.""" + block = {"type": block_type, "other": "foo"} + human = HumanMessage("hi") # type: ignore[misc] + ai = AIMessage( # type: ignore[misc] + content=[block, {"type": "text", "text": "hello"}], + response_metadata={"model_provider": "openai"}, + ) + _, msgs = _format_messages([human, ai]) + assert msgs[1]["content"] == [{"type": "text", "text": "hello"}] + + ai_anthropic = AIMessage( # type: ignore[misc] + content=[block, {"type": "text", "text": "hello"}], + response_metadata={"model_provider": "anthropic"}, + ) + _, msgs = _format_messages([human, ai_anthropic]) + assert any(b["type"] == block_type for b in msgs[1]["content"]) + + def test__format_messages_trailing_whitespace() -> None: """Test that trailing whitespace is trimmed from the final assistant message.""" human = HumanMessage("foo") # type: ignore[misc]