Skip to content

Commit cdb9742

Browse files
authored
fix(anthropic): filter out common OpenAI Responses block types (#35417)
1 parent 0b975d4 commit cdb9742

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

libs/partners/anthropic/langchain_anthropic/chat_models.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,12 @@ def _format_messages(
471471
if "type" not in block:
472472
msg = "Dict content block must have a type key"
473473
raise ValueError(msg)
474+
if block["type"] in ("reasoning", "function_call") and (
475+
not isinstance(message, AIMessage)
476+
or message.response_metadata.get("model_provider")
477+
!= "anthropic"
478+
):
479+
continue
474480
if block["type"] == "image_url":
475481
# convert format
476482
source = _format_image(block["image_url"]["url"])

libs/partners/anthropic/tests/unit_tests/test_chat_models.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2395,6 +2395,26 @@ def search_code(query: str) -> str:
23952395
assert "input_examples" in tool_def
23962396

23972397

2398+
@pytest.mark.parametrize("block_type", ["reasoning", "function_call"])
2399+
def test__format_messages_filters_non_anthropic_blocks(block_type: str) -> None:
2400+
"""Test that reasoning/function_call blocks are filtered for non-anthropic."""
2401+
block = {"type": block_type, "other": "foo"}
2402+
human = HumanMessage("hi") # type: ignore[misc]
2403+
ai = AIMessage( # type: ignore[misc]
2404+
content=[block, {"type": "text", "text": "hello"}],
2405+
response_metadata={"model_provider": "openai"},
2406+
)
2407+
_, msgs = _format_messages([human, ai])
2408+
assert msgs[1]["content"] == [{"type": "text", "text": "hello"}]
2409+
2410+
ai_anthropic = AIMessage( # type: ignore[misc]
2411+
content=[block, {"type": "text", "text": "hello"}],
2412+
response_metadata={"model_provider": "anthropic"},
2413+
)
2414+
_, msgs = _format_messages([human, ai_anthropic])
2415+
assert any(b["type"] == block_type for b in msgs[1]["content"])
2416+
2417+
23982418
def test__format_messages_trailing_whitespace() -> None:
23992419
"""Test that trailing whitespace is trimmed from the final assistant message."""
24002420
human = HumanMessage("foo") # type: ignore[misc]

0 commit comments

Comments
 (0)