Skip to content

Comments

fix: sanitize Anthropic messages for empty content and trailing whitespace#4542

Open
hztBUAA wants to merge 1 commit intocrewAIInc:mainfrom
hztBUAA:fix/anthropic-message-sanitization
Open

fix: sanitize Anthropic messages for empty content and trailing whitespace#4542
hztBUAA wants to merge 1 commit intocrewAIInc:mainfrom
hztBUAA:fix/anthropic-message-sanitization

Conversation

@hztBUAA
Copy link

@hztBUAA hztBUAA commented Feb 20, 2026

Summary

Fixes two confirmed Anthropic API BadRequestError issues in AnthropicCompletion._format_messages_for_anthropic():

Both sanitization steps are implemented in a single _sanitize_messages_for_anthropic() static method, called at the end of _format_messages_for_anthropic() before returning.

Fixes #4413
Fixes #4427

Changes

  • lib/crewai/src/crewai/llms/providers/anthropic/completion.py: Added _sanitize_messages_for_anthropic() static method and call site
  • lib/crewai/tests/llms/anthropic/test_anthropic_message_sanitization.py: 15 unit tests covering empty content replacement, trailing whitespace stripping, structured content blocks, and combined scenarios

Test plan

  • 15 new unit tests pass (pytest lib/crewai/tests/llms/anthropic/test_anthropic_message_sanitization.py)
  • All 23 existing non-API anthropic tests still pass (API tests fail due to network restrictions in CI, unrelated to this change)
  • Manual verification: create an Anthropic LLM, send messages with empty content and trailing whitespace, confirm no BadRequestError

…space

Add message sanitization in _format_messages_for_anthropic to prevent
two classes of Anthropic API BadRequestErrors:

1. Empty message content: Anthropic rejects all messages with empty
   content (except an optional final assistant message). Empty strings
   are now replaced with a placeholder before sending.

2. Trailing whitespace in final assistant message: Anthropic rejects
   requests where the final assistant message ends with whitespace.
   Trailing whitespace is now stripped from the final assistant message,
   including structured content blocks (e.g. thinking + text).

Fixes crewAIInc#4413, Fixes crewAIInc#4427
@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant