Repository navigation
fix: normalize system role messages for Anthropic partner endpoints - #31452
danielcherubini wants to merge 4 commits into
Conversation
Greptile SummaryThis PR fixes 400 errors from Anthropic partner endpoints (Vertex AI, Azure AI Foundry) that reject
Confidence Score: 4/5Safe 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
|
| 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
|
|
||
| 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) | ||
| ) | ||
|
|
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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.
| @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}] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 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.
6e57224 to
fa4fa17
Compare
|
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 |
role: "system"inside the messages array, but partner endpoints (Vertex AI, Bedrock, Azure AI Foundry) still reject it with 400 errorsshould_normalize_system_role_messages()opt-in flag to the sharedAnthropicMessagesConfigbase classrole: "system"entries are stripped from the messages array and merged into the top-levelsystemfield before the request is built