fix(anthropic): handle empty message content gracefully - #35504
Jason Meng (JasonCZMeng) wants to merge 3 commits into
Conversation
Replace empty string content in human and system messages with a single space before sending to the Anthropic API. This prevents a 400 BadRequestError when HumanMessage or SystemMessage has content=''. Fixes langchain-ai#35081
Merging this PR will not alter performance
Comparing Footnotes
|
|
Friendly ping — CI is green and no performance impact per CodSpeed. This is a minimal fix (replaces empty content with |
| system.append(block) | ||
| else: | ||
| system.append( | ||
| {"type": "text", "text": " " if block == "" else block}, |
There was a problem hiding this comment.
i think this can be written for better readability this
block_text = " " if block=="" else block
obj = {"type":"text", "text:block_text}
system.append(obj)
though this codes looks like a lot, but's more readable in my 2 cents. I let u decide than compacting the code
|
Closing this to keep my PR queue focused — no reviewer activity in ~40 days. The change is still mergeable; happy to reopen if a maintainer wants to pick it up, or I'll revisit if the underlying issue resurfaces. Thanks! |
Summary
Replace empty string content in human and system messages with a single space (
) before sending to the Anthropic API. This prevents aBadRequestError(400) whenHumanMessageorSystemMessagehascontent="".Fixes #35081
Motivation
Anthropic's API rejects messages with empty content: "all messages must have non-empty content except for the optional final assistant message". This is a problem in multi-agent pipelines where one agent's empty output becomes the next agent's user input. The same approach was adopted by AutoGen.
Changes
libs/partners/anthropic/langchain_anthropic/chat_models.py_format_messages(), empty string content ("") in human and system messages is replaced with" "before calling the APIlibs/partners/anthropic/tests/unit_tests/test_chat_models.pytest__format_messages_with_empty_system_and_human_content()covering the fix