Skip to content

fix(vertexai): allow system messages at any position in ChatAnthropicVertex#1610

Merged
Leonid Kuligin (lkuligin) merged 1 commit intolangchain-ai:mainfrom
zamal-db:fix/vertexai-allow-system-message-any-position
Feb 24, 2026
Merged

fix(vertexai): allow system messages at any position in ChatAnthropicVertex#1610
Leonid Kuligin (lkuligin) merged 1 commit intolangchain-ai:mainfrom
zamal-db:fix/vertexai-allow-system-message-any-position

Conversation

@zamal-db
Copy link
Contributor

@zamal-db at384 (zamal-db) commented Feb 24, 2026

Problem

The _format_messages_anthropic() function required system messages to be at index 0, raising ValueError("System message must be at beginning of message list.") otherwise. This prevented valid patterns like [HumanMessage(...), SystemMessage(...), ...] that are supported by the Anthropic API and by langchain-anthropic.

Error from issue #1022:

ValueError: System message must be at beginning of message list.

Solution

  • Remove the positional index check (if i != 0) in _format_messages_anthropic()
  • Instead validate that non-consecutive system messages are not present (raises a clear ValueError)
  • Extend _merge_messages() to merge consecutive SystemMessages the same way it already merged consecutive HumanMessages
  • Use model_copy(update=...) instead of mutating message content in-place

Tests

  • 3 new unit tests covering: system message at non-zero position, consecutive system messages merged, multiple non-consecutive system messages raise ValueError
  • Full test suite passes: 56/56
  • Formatting logic verified with edge cases

Changes

File Lines
libs/vertexai/langchain_google_vertexai/_anthropic_utils.py +21/-8
libs/vertexai/tests/unit_tests/test_anthropic_utils.py +55

Fixes #1022

…Vertex

The _format_messages_anthropic() function required system messages to be at index 0, raising ValueError otherwise. This prevented valid patterns like [HumanMessage, SystemMessage, ...] that are supported by the Anthropic API and by langchain-anthropic.

This change removes the position check and instead validates that non-consecutive system messages are not present (raising a clear error). Consecutive system messages are merged. The _merge_messages() function is extended to merge consecutive SystemMessages the same way it already merged consecutive HumanMessages.

Fixes langchain-ai#1022
@lkuligin Leonid Kuligin (lkuligin) merged commit 7453adb into langchain-ai:main Feb 24, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Anthropic: remove limitation "System message must be at beginning of message list."

2 participants