Skip to content

fix: normalize system role messages for Anthropic partner endpoints - #31452

Closed
danielcherubini wants to merge 4 commits into
BerriAI:mainfrom
danielcherubini:fix/normalize-system-role-messages
Closed

danielcherubini wants to merge 4 commits into
BerriAI:mainfrom
danielcherubini:fix/normalize-system-role-messages

Conversation

@danielcherubini

Copy link
Copy Markdown
  • Anthropic's native Messages API now accepts role: "system" inside the messages array, but partner endpoints (Vertex AI, Bedrock, Azure AI Foundry) still reject it with 400 errors
  • Add should_normalize_system_role_messages() opt-in flag to the shared AnthropicMessagesConfig base class
  • When enabled, role: "system" entries are stripped from the messages array and merged into the top-level system field before the request is built
  • Enabled for Vertex AI and Azure AI Foundry (Bedrock can opt in via the same flag when the Bedrock-specific PR is merged)
  • Refs [Bug]: v1/messages now supports system prompt as well in the messages array. This breaks AWS Bedrock #29698

@CLAassistant

CLAassistant commented Jun 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes 400 errors from Anthropic partner endpoints (Vertex AI, Azure AI Foundry) that reject role: \"system\" entries inside the messages array by adding an opt-in normalization step that extracts those entries and merges their content into the top-level system field before the request is sent.

  • Adds should_normalize_system_role_messages() hook and _normalize_system_role_messages() to the shared AnthropicMessagesConfig base class; the flag defaults to False so the native Anthropic endpoint is unaffected.
  • Enables the flag for VertexAIPartnerModelsAnthropicMessagesConfig and AzureAnthropicMessagesConfig via a one-method override each; Bedrock is left as a follow-up.
  • The normalization correctly runs before billing-header stripping and before _remove_scope_from_cache_control, so both post-processing steps see the fully merged system field.

Confidence Score: 4/5

Safe to merge for the core fix; the base-class flag defaults to False so existing Anthropic pass-through behaviour is unchanged.

The Vertex AI and Azure AI overrides are two-line, low-risk changes. The base-class normalization logic handles the main content shapes (string, list-of-blocks, None) correctly and integrates cleanly with the existing billing-metadata strip. The only gaps are missing unit tests for the new normalization methods and a latent edge case when a system message's content is an arbitrary non-string/non-list value that falls through to a bare-wrap rather than a validation error.

litellm/llms/anthropic/experimental_pass_through/messages/transformation.py — new _normalize_system_role_messages and _as_system_content_blocks methods have no accompanying unit tests.

Important Files Changed

Filename Overview
litellm/llms/anthropic/experimental_pass_through/messages/transformation.py Adds should_normalize_system_role_messages() hook and _normalize_system_role_messages() implementation to the shared base config; normalization runs before billing-header stripping and is a no-op when the flag is False. No tests accompany the new methods.
litellm/llms/azure_ai/anthropic/messages_transformation.py Enables normalization for Azure AI Foundry by overriding should_normalize_system_role_messages() to return True; minimal, correct two-line change.
litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py Enables normalization for Vertex AI partner models by overriding should_normalize_system_role_messages() to return True; minimal, correct two-line change.

Reviews (1): Last reviewed commit: "fix: normalize system role messages for ..." | Re-trigger Greptile

Comment on lines +108 to +142

def _normalize_system_role_messages(
self,
messages: List[Dict],
anthropic_messages_optional_request_params: Dict,
) -> Tuple[List[Dict], Dict]:
"""Move ``role: "system"`` entries from the messages array into the
top-level ``system`` field.

Some Anthropic partner endpoints (Vertex AI, Bedrock) reject
``role: "system"`` inside messages — they only accept ``system`` as a
top-level parameter.
"""
system_role_messages = [
m for m in messages if isinstance(m, dict) and m.get("role") == "system"
]
if not system_role_messages:
return messages, anthropic_messages_optional_request_params

# Remove system-role entries from messages
filtered_messages = [
m
for m in messages
if not (isinstance(m, dict) and m.get("role") == "system")
]

# Merge into top-level system
existing_system = anthropic_messages_optional_request_params.get("system")
system_blocks: list = []

if existing_system is not None:
system_blocks.extend(
AnthropicMessagesConfig._as_system_content_blocks(existing_system)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 No unit tests for the new normalization logic

The new _normalize_system_role_messages and _as_system_content_blocks methods have no corresponding unit tests in any of the three touched provider test files (test_azure_anthropic_messages_transformation.py, test_vertex_ai_partner_models_anthropic_messages_config.py). Key paths that should be covered include: system message with a string content, with a list-of-blocks content, with a None content, merging with a pre-existing top-level system string, and the happy-path where there are no system-role messages (should be a no-op). Without these, a future refactor could silently regress the 400-error fix.

Rule Used: What: Ensure that any PR claiming to fix an issue ... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unit tests were added in the 2nd commit (725bc60, test_anthropic_messages_system_role_normalization.py) — 15 tests covering the string/list/None/dict content shapes, existing-system merge, multiple system messages, no-op path, and the should_normalize_system_role_messages() overrides for both Vertex AI and Azure AI. Codecov now reports all modified/coverable lines covered. This comment predates that commit landing.

Comment on lines +98 to +106
@staticmethod
def _as_system_content_blocks(value: Any) -> list:
"""Convert system content to a list of content blocks."""
if value is None:
return []
if isinstance(value, list):
return list(value)
if isinstance(value, str):
return [{"type": "text", "text": value}]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Arbitrary non-string/non-list content bypasses validation

_as_system_content_blocks falls through to return [value] for any value that isn't None, str, or list. If a caller passes a role: "system" message whose content is a raw dict (e.g. {"type": "text", "text": "…"}) — a common single-block shorthand — that dict is wrapped in a list as-is and forwarded to the upstream API. While Anthropic's API may accept this, if content is accidentally an integer or another scalar the resulting system list would contain an invalid value and produce a cryptic upstream 400 rather than a clear local error.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented this as intentional in fa4fa17: content is expected to already be validated against the Anthropic message schema before this normalization step runs, so a bare-wrap here is by design rather than a gap. Left as a docstring clarification rather than adding new validation, since raising here would be redundant with (and could drift from) whatever schema validation already exists upstream of this transform.

@codecov

codecov Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Anthropic's native Messages API now accepts role: "system" inside the
messages array, but partner endpoints (Vertex AI, Bedrock, Azure AI
Foundry) still reject it with:

  "Unexpected role \"system\". The Messages API accepts a top-level
   `system` parameter, not \"system\" as an input message role."

Add should_normalize_system_role_messages() opt-in flag to the shared
AnthropicMessagesConfig base class. When enabled, role: "system" entries
are stripped from the messages array and merged into the top-level
system field before the request is built.

Enabled for:
- Vertex AI (vertex_ai/claude-*)
- Azure AI Foundry (azure_ai/claude-*)

Refs BerriAI#29698
Covers _as_system_content_blocks(), _normalize_system_role_messages(),
and should_normalize_system_role_messages() for base class, Vertex AI,
and Azure AI overrides.

Refs BerriAI#29698
Addresses Greptile review comment on PR BerriAI#31452: document that non-str/
list/dict values falling through to a bare wrap is intentional, since
callers are expected to validate content against the Anthropic message
schema before this normalization step runs.
@danielcherubini
danielcherubini force-pushed the fix/normalize-system-role-messages branch from 6e57224 to fa4fa17 Compare July 6, 2026 11:28
@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:26
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:57
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 15:57
@mateo-berri

Copy link
Copy Markdown
Contributor

Main already moves system role messages into the top level system field for Azure and Vertex Claude /v1/messages since #33807. Reopen if something is missing

@mateo-berri mateo-berri closed this Nov 9, 2026
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.

4 participants