litellm/tests/unit/llms/anthropic/test_message_sanitization.py
zoveki 65d625b86c
fix(bedrock): stop the prefill 400 when the last user message is empty (#50701)
* fix(bedrock): keep an empty user turn on Converse so Claude does not answer a prefill 400

* fix(responses): keep a user input item without content as an empty user turn

* fix(bedrock): only fill an empty last user turn after an assistant turn

A placeholder now goes in only when the request ends on a user turn with no content right after an assistant turn. Mid-conversation empty turns stay dropped, so tool calls stay next to their results and media-only turns are not called empty. The Responses adapter keeps a content-less final user item only on routes that fill it, and only when building the request to send.

* fix(bedrock): send the empty turn placeholder only to models that refuse a prefill

Check the explicit supports_assistant_prefill false entry in the cost map before filling an empty last user turn, so Nova and older Claude models keep their current behavior

Treat blank guarded_text and whitespace-only last turns as empty on those models, keep cache_control on the placeholder, and keep a lone null user item on a previous_response_id follow-up

* fix(responses): add the empty user turn after the stored history loads

A lone null user item on a previous_response_id follow-up was filled before
the stored history loaded, so an unknown id reached the model instead of
LiteLLM's own 400. The follow-up fill now runs after the history merge and
only when the merged messages end on an assistant turn

Stored turns replay with the same empty user turn when the route fills, so a
later follow-up resends the conversation the model saw and keeps its cache
prefix, and /v1/responses/input_tokens counts the same messages

* fix(responses): replay a stored empty user turn with the text the model saw

Converse drops an empty user message that sits between two assistant turns,
so the replayed empty turn vanished and the next turn sent a different
conversation than the follow-up did, which also missed its prompt cache. The
replay now sends the same placeholder text the follow-up sent, and that
placeholder constant is public so the Responses bridge can reuse it

* test(rust): point the placeholder comment at the public constant

The Python placeholder constant lost its leading underscore, so the Rust test comment now names it as it is

* fix(responses): replay each stored empty turn by its own model and budget its cache mark

A previous_response_id follow-up whose one null user item carried cache_control got its empty user turn after the replayed history had already used all 4 cache marks, so the provider saw 5 and refused the request. The turn is now built before the replay budget, counted as one of the request's own marks and checked the same way

A stored turn that got no answer no longer replays the placeholder, which used to merge into the next user turn

A stored turn now replays its empty user turn only when the model that answered it needed one, read from its own stored model, provider and priced model. A conversation that switched models mid-session used to replay every stored turn by the current model, so a turn the old model answered without the placeholder came back with it

The /v1/responses/input_tokens count for a deployment named by an inference profile ARN now reads the deployment's base_model the way inference does, so the counted request keeps the same empty user turn the real request sends

A request with no provider and a model name that does not resolve, such as a Bedrock batch record naming an alias, no longer raises when its input ends on an empty user item. It keeps the old behavior and drops the item

A new test covers litellm.modify_params on Bedrock Converse, which keeps sending its continue message for an empty last user turn

* fix(responses): count a blank turn the way inference sends it and keep a restored turn's mark under the cap

/v1/responses/input_tokens on Anthropic, Azure AI, Vertex and Bedrock now sends a blank user or assistant turn through the translation chat inference uses, so the count request carries the same placeholder text inference sends. A follow-up whose input ended on a null user item after an assistant turn used to count with an empty user message, and the count API answered that with a 400

Under drop_params, the empty user turn a previous_response_id follow-up restores now shares the request's 4 cache marks with the tools, the top-level cache_control and the input items, and the newest marks win as they do on a single-turn request. A marked null item used to add a 5th mark that the provider refused

* fix(responses): match inference for object inputs, alias counts, string follow-ups and model_info base_model

An object input on /v1/responses no longer reaches the empty-turn restore, so it is served instead of answering 500

input_tokens bridges the request with the routed deployment's model, so an alias counts the placeholder inference sends, and a string input on a previous_response_id follow-up replays the stored empty turn like a list input

A deployment that sets base_model only in model_info now gets the placeholder on /v1/responses and its count, as it already did on chat

The Anthropic, Azure AI and Bedrock counters keep a native Anthropic block as sent when a blank text turn sits next to it

* fix(responses): treat an empty base_model as unset when reading model_info

A deployment with base_model "" in litellm_params and a base_model in model_info now gets the placeholder on /v1/responses, as chat and input_tokens already read it

Tests now cover the previous_response_id follow-up read of model_info.base_model, a request base_model winning over it, and the empty-string fallback

* fix(responses): count what inference sends for client base_model and Converse blank assistant turns

The input_tokens route now leaves out the client pricing fields inference strips for a key without allow_client_pricing_override, and the Bedrock Converse Claude count drops empty assistant text and empty assistant turns the same way Converse inference does.

* fix(bedrock): count an empty Converse assistant turn as the continue message under modify_params

Converse inference replaces an all-empty assistant turn with the default continue message when modify_params is on, so the count now sends the same turn instead of dropping it.

* fix(bedrock): match the Converse continue-message check when counting empty assistant turns

The count now takes the continue-message path whenever litellm.modify_params is not False, as the inference helper does, counts the continue message when the helper leaves nothing Converse reads, and keeps the plain rule for a text block without text so it no longer answers 500.

* fix(bedrock): drop an empty Converse assistant turn the way inference does and add its continue turn between user turns

Under modify_params, an empty assistant turn with a non-content key is now dropped like Converse inference drops it, and the count adds Please continue. between adjacent user or tool turns only when modify_params is True, as the Converse loop does.

* fix(bedrock): count the continue turns and the neutralized tool history that Converse inference sends

* fix(bedrock): count Converse system messages and response_format tool history the way inference sends them

The Converse count now maps developer messages to system, keeps the leading system run for the system prompt, turns later system messages into the user turns inference sends, and keeps tool history as tool blocks when response_format adds a tool. Counting no longer logs inference's neutralization warning.

* fix(responses): replay a stored blank user turn with the placeholder its model saw

A previous_response_id follow-up replayed a stored user turn of only whitespace as sent, so Bedrock answered 400 on the next turn. The replay now swaps that turn for the placeholder when the stored model needed one, for list items and string input alike

* fix(responses): replay a blank user turn with the continue text Converse sent

With modify_params or a deployment user_continue_message, Bedrock Converse
sends the continue text for a blank user turn. A previous_response_id
follow-up replayed that stored turn with the empty-content placeholder
instead, so the history the model saw changed between turns. The replay now
keeps the turn blank in that case, so Converse fills it with the same continue
text it sent the first time

* fix(bedrock): count blank last user turns and system text the way Converse inference sends them

The Converse token count now sends the placeholder or continue text that
inference sends for an empty, null or blank last user turn, keeps only the
non-empty text parts of a leading system message, decides the response_format
tool by the deployment model, and leaves a message without a role for Bedrock
to reject with a 400. A previous_response_id follow-up count drops
additional_tools input items before restoring the empty user turn, as inference
does. When the deployment continues blank user turns, a stored follow-up with
several blank user items replays each of them instead of one placeholder turn.

* fix(bedrock): count list continue messages, keep string turns when lifting system, and leave other routes' stored blanks alone

The count now reads the deployment's continue message the way inference does, so list content no longer answers 500 and a continue turn around an assistant turn counts. A leading system message is lifted without translating the rest of the request, a malformed user block answers 400 again, a Responses count passes the deployment's continue message to the stored history, and a follow-up on a route that takes blank turns replays them as stored

* fix(responses): fill a stored blank turn only on routes that refuse blank text

* fix(bedrock): drop the empty turns from a Converse token count that inference drops

* fix(bedrock): count a spaces-only user turn as Converse sends it

* fix(responses): replay a stored empty string input turn on follow-ups

* fix(bedrock): count an empty last user turn the way Converse inference sends it

Drop an earlier empty user turn before the placeholder turn, and keep the
blank turn's cache mark on the placeholder, so the count matches inference.

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-18 03:44:11 +00:00

658 lines
25 KiB
Python

"""
Test message sanitization for Anthropic API when modify_params=True
Tests three cases:
A. Missing tool_result for tool_use (orphaned tool calls)
B. Orphaned tool_result without matching tool_use
C. Empty text content
"""
import copy
import json
import pytest
import sys
import os
# Add the parent directory to the path so we can import litellm
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../..")))
import litellm
from litellm.litellm_core_utils.prompt_templates.factory import (
EMPTY_TEXT_PLACEHOLDER as PLACEHOLDER,
_sanitize_empty_text_content,
sanitize_messages_for_tool_calling,
anthropic_messages_pt,
)
class TestMessageSanitization:
"""Test message sanitization for tool calling scenarios"""
@pytest.fixture(autouse=True)
def _modify_params_on(self, monkeypatch):
monkeypatch.setattr(litellm, "modify_params", True)
def test_case_a_orphaned_tool_call_single(self):
"""
Test Case A: Assistant message with tool_calls but no tool result
Should add a dummy tool result message
"""
messages = [
{"role": "user", "content": "What is the weather in Nashik?"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "toolu_01Kus2cC3ydjBW7UK4GJqBP4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"location": "Nashik, India"}',
},
}
],
},
]
sanitized = sanitize_messages_for_tool_calling(messages)
# Should have 3 messages: user, assistant, and dummy tool result
assert len(sanitized) == 3
assert sanitized[0]["role"] == "user"
assert sanitized[1]["role"] == "assistant"
assert sanitized[2]["role"] == "tool"
assert sanitized[2]["tool_call_id"] == "toolu_01Kus2cC3ydjBW7UK4GJqBP4"
assert "skipped" in sanitized[2]["content"].lower() or "interrupted" in sanitized[2]["content"].lower()
assert "get_weather" in sanitized[2]["content"]
def test_case_a_orphaned_tool_call_multiple(self):
"""
Test Case A: Assistant message with multiple tool_calls, some missing results
"""
messages = [
{"role": "user", "content": "Get weather for Nashik and Mumbai"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"location": "Nashik"}',
},
},
{
"id": "call_2",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"location": "Mumbai"}',
},
},
],
},
{
"role": "tool",
"tool_call_id": "call_1",
"content": "Weather in Nashik: 25°C",
},
]
sanitized = sanitize_messages_for_tool_calling(messages)
# Should have 4 messages: user, assistant, tool result for call_1, dummy for call_2
assert len(sanitized) == 4
assert sanitized[0]["role"] == "user"
assert sanitized[1]["role"] == "assistant"
assert sanitized[2]["tool_call_id"] == "call_1" # Original tool result (first in tool_calls)
assert sanitized[3]["tool_call_id"] == "call_2" # Dummy added for missing call_2
def test_case_b_orphaned_tool_result(self):
"""
Test Case B: Tool result without matching tool_call in previous assistant message
Should remove the orphaned tool result
"""
messages = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
{
"role": "tool",
"tool_call_id": "nonexistent_id",
"content": "Some result",
},
]
sanitized = sanitize_messages_for_tool_calling(messages)
# Should have only 2 messages, orphaned tool result removed
assert len(sanitized) == 2
assert sanitized[0]["role"] == "user"
assert sanitized[1]["role"] == "assistant"
def test_case_b_valid_tool_result_preserved(self):
"""
Test Case B: Valid tool result with matching tool_call should be preserved
"""
messages = [
{"role": "user", "content": "What's the weather?"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"location": "Boston"}',
},
}
],
},
{"role": "tool", "tool_call_id": "call_123", "content": "Weather: 20°C"},
]
sanitized = sanitize_messages_for_tool_calling(messages)
# All messages should be preserved
assert len(sanitized) == 3
assert sanitized[2]["role"] == "tool"
assert sanitized[2]["tool_call_id"] == "call_123"
def test_case_c_empty_text_content_user(self):
"""
Test Case C: Empty text content in user message
Should replace with placeholder
"""
messages = [
{"role": "user", "content": ""},
{"role": "assistant", "content": "Hello!"},
]
sanitized = sanitize_messages_for_tool_calling(messages)
assert len(sanitized) == 2
assert sanitized[0]["role"] == "user"
assert sanitized[0]["content"] == "[System: Empty message content sanitised to satisfy protocol]"
def test_case_c_whitespace_only_content(self):
"""
Test Case C: Whitespace-only content
Should replace with placeholder
"""
messages = [
{"role": "user", "content": " \n \t "},
{"role": "assistant", "content": " "},
]
sanitized = sanitize_messages_for_tool_calling(messages)
assert len(sanitized) == 2
assert sanitized[0]["content"] == "[System: Empty message content sanitised to satisfy protocol]"
assert sanitized[1]["content"] == "[System: Empty message content sanitised to satisfy protocol]"
def test_case_c_valid_content_preserved(self):
"""
Test Case C: Valid non-empty content should be preserved
"""
messages = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
]
sanitized = sanitize_messages_for_tool_calling(messages)
assert len(sanitized) == 2
assert sanitized[0]["content"] == "Hello"
assert sanitized[1]["content"] == "Hi there!"
def test_combined_cases(self):
"""
Test combination of multiple cases
"""
messages = [
{"role": "user", "content": "Get weather"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"location": "NYC"}',
},
}
],
},
# Missing tool result for call_1
{"role": "user", "content": ""}, # Empty content
{"role": "assistant", "content": "Response"},
{
"role": "tool",
"tool_call_id": "orphaned_id", # Orphaned tool result
"content": "Some data",
},
]
sanitized = sanitize_messages_for_tool_calling(messages)
# Should have: user, assistant, dummy tool result, user (sanitized), assistant
# Orphaned tool result should be removed
assert len(sanitized) == 5
assert sanitized[0]["role"] == "user"
assert sanitized[1]["role"] == "assistant"
assert sanitized[2]["role"] == "tool"
assert sanitized[2]["tool_call_id"] == "call_1" # Dummy added
assert sanitized[3]["role"] == "user"
assert sanitized[3]["content"] == "[System: Empty message content sanitised to satisfy protocol]"
assert sanitized[4]["role"] == "assistant"
def test_modify_params_false_no_sanitization(self, monkeypatch):
"""
Test that sanitization is skipped when modify_params=False
"""
monkeypatch.setattr(litellm, "modify_params", False)
messages = [
{"role": "user", "content": ""},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "get_weather", "arguments": "{}"},
}
],
},
]
sanitized = sanitize_messages_for_tool_calling(messages)
# Messages should be unchanged
assert len(sanitized) == 2
assert sanitized[0]["content"] == ""
assert len(sanitized[1].get("tool_calls", [])) == 1
def test_anthropic_messages_pt_integration(self):
"""
Test that sanitization is integrated into anthropic_messages_pt
"""
messages = [
{"role": "user", "content": "What is the weather in Nashik?"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "toolu_01Kus2cC3ydjBW7UK4GJqBP4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"location": "Nashik, India"}',
},
}
],
},
]
# This should not raise an error and should add dummy tool result
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-5", llm_provider="anthropic")
# Should have at least 2 messages (user and assistant)
# The tool result will be merged into user content
assert len(result) >= 2
assert result[0]["role"] == "user"
assert result[1]["role"] == "assistant"
def test_empty_string_content_sanitized_without_modify_params(self, monkeypatch):
"""
Regression: An empty user message ({"role": "user", "content": ""}) must
be rewritten to a non-empty placeholder *before* it reaches Anthropic,
even when litellm.modify_params is False. Otherwise Anthropic returns:
"messages: text content blocks must be non-empty"
Reproduces a real failure from the pr-review agent (pydantic-ai).
"""
monkeypatch.setattr(litellm, "modify_params", False)
messages = [
{"role": "user", "content": "First message"},
{"role": "user", "content": "please review this"},
{"role": "user", "content": ""},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-5", llm_provider="anthropic")
# All three user messages get merged into one user turn for Anthropic.
assert len(result) == 1
assert result[0]["role"] == "user"
text_blocks = [b for b in result[0]["content"] if isinstance(b, dict) and b.get("type") == "text"]
assert len(text_blocks) == 3
# No text block may be empty — that's the contract Anthropic enforces.
for block in text_blocks:
assert block["text"].strip() != ""
assert text_blocks[2]["text"] == ("[System: Empty message content sanitised to satisfy protocol]")
def test_empty_text_block_in_list_content_sanitized(self, monkeypatch):
"""
Same regression for the list-of-blocks form:
{"role": "user", "content": [{"type": "text", "text": ""}]}
Empty text *blocks* must be rewritten too, regardless of modify_params.
"""
monkeypatch.setattr(litellm, "modify_params", False)
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "real content"},
{"type": "text", "text": ""},
{"type": "text", "text": " \n "},
],
},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-5", llm_provider="anthropic")
assert len(result) == 1
text_blocks = [b for b in result[0]["content"] if isinstance(b, dict) and b.get("type") == "text"]
assert len(text_blocks) == 3
assert text_blocks[0]["text"] == "real content"
for block in text_blocks[1:]:
assert block["text"].strip() != ""
def test_non_empty_content_unchanged_without_modify_params(self, monkeypatch):
"""
Sanity check: when nothing is empty, the messages flow through unchanged
even with modify_params disabled.
"""
monkeypatch.setattr(litellm, "modify_params", False)
messages = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there"},
{"role": "user", "content": "How are you?"},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-5", llm_provider="anthropic")
# Two user turns + one assistant turn (alternation preserved).
assert len(result) == 3
assert result[0]["content"][0]["text"] == "Hello"
assert result[1]["content"][0]["text"] == "Hi there"
assert result[2]["content"][0]["text"] == "How are you?"
@pytest.mark.parametrize("modify_params", [True, False])
@pytest.mark.parametrize(
"empty_content",
[None, "", " \n \t ", [], [{"type": "text", "text": ""}]],
ids=["none", "empty_str", "whitespace_str", "empty_list", "empty_text_block"],
)
def test_tool_call_only_assistant_turn_never_gets_placeholder(self, monkeypatch, modify_params, empty_content):
"""
Regression for the placeholder leaking into tool-call-only assistant turns.
An OpenAI-format assistant turn that carries tool_calls but no text is the normal
shape emitted by coding agents. Anthropic accepts an assistant turn whose content
is just tool_use, so there is nothing to substitute; injecting the placeholder made
it look like the assistant had said it, and the model echoed it on later turns.
"""
monkeypatch.setattr(litellm, "modify_params", modify_params)
messages = [
{"role": "user", "content": "list the files"},
{
"role": "assistant",
"content": empty_content,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "run_bash", "arguments": '{"cmd": "ls"}'},
}
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "a.txt"},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
assistant_turns = [m for m in result if m["role"] == "assistant"]
assert len(assistant_turns) == 1
blocks = assistant_turns[0]["content"]
assert [b["type"] for b in blocks] == ["tool_use"]
assert blocks[0]["id"] == "call_1"
assert blocks[0]["name"] == "run_bash"
assert PLACEHOLDER not in json.dumps(result)
def test_empty_text_dropped_alongside_non_text_blocks(self):
"""
An assistant turn already carrying a non-text block has enough content for
Anthropic once the empty text block is dropped, so the placeholder must not be
substituted in its place.
"""
message = {
"role": "assistant",
"content": [
{"type": "text", "text": " "},
{"type": "thinking", "thinking": "weighing options", "signature": "sig"},
],
}
sanitized = _sanitize_empty_text_content(message)
assert [b["type"] for b in sanitized["content"]] == ["thinking"]
assert PLACEHOLDER not in json.dumps(sanitized)
@pytest.mark.parametrize(
"sibling_block",
[
{"type": "thinking", "thinking": "", "signature": "sig"},
{"type": "redacted_thinking", "data": "opaque"},
],
ids=["signed_empty_thinking", "redacted_thinking"],
)
def test_empty_text_dropped_alongside_kept_thinking_block(self, sibling_block):
"""
The converter keeps signed thinking blocks even with empty text, and keeps
redacted_thinking blocks, so the turn still reaches Anthropic without the
empty text and the placeholder must not be substituted.
"""
messages = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": [{"type": "text", "text": " "}, sibling_block]},
{"role": "user", "content": "and now?"},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
assert [m["role"] for m in result] == ["user", "assistant", "user"]
assert [b["type"] for b in result[1]["content"]] == [sibling_block["type"]]
assert PLACEHOLDER not in json.dumps(result)
def test_placeholder_kept_when_only_tool_call_is_dropped_tool_search(self, monkeypatch):
"""
A tool search call whose result is not replayed is dropped by the converter, so
it does not count as content: the empty text keeps its placeholder instead of
the assistant turn vanishing from the request. modify_params stays off so no
dummy tool result answers the call and keeps it.
"""
monkeypatch.setattr(litellm, "modify_params", False)
messages = [
{"role": "user", "content": "find a tool"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "srvtoolu_1",
"type": "function",
"function": {"name": "tool_search_tool_regex", "arguments": '{"query": "x"}'},
}
],
},
{"role": "user", "content": "go on"},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
assert [m["role"] for m in result] == ["user", "assistant", "user"]
assert result[1]["content"] == [{"type": "text", "text": PLACEHOLDER}]
@pytest.mark.parametrize(
"sibling_block",
[
{"type": "image_url", "image_url": {"url": "data:image/png;base64,aGk="}},
{"type": "thinking", "thinking": ""},
{"type": "redacted_thinking", "data": " "},
{"type": "unknown_future_block"},
{"no_type_key": "malformed"},
],
ids=["image_url", "unsignable_thinking", "blank_redacted_thinking", "unknown_type", "missing_type"],
)
def test_empty_text_kept_when_sibling_block_would_not_survive(self, sibling_block):
"""
Dropping empty text is only safe when something else in the turn actually reaches
Anthropic. Blocks the assistant conversion discards (assistant-side images,
signature-less thinking, unrecognised types) would leave an empty turn that gets
dropped from the request entirely, so the placeholder has to stay.
"""
messages = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": [{"type": "text", "text": " "}, sibling_block]},
{"role": "user", "content": "and now?"},
]
result = anthropic_messages_pt(messages=messages, model="claude-haiku-4-5", llm_provider="anthropic")
assert [m["role"] for m in result] == ["user", "assistant", "user"]
assert PLACEHOLDER in json.dumps(result)
def test_assistant_text_preserved_alongside_tool_calls(self):
"""
Dropping empty text must not drop real text: an assistant turn that says something
*and* calls a tool keeps both blocks.
"""
messages = [
{"role": "user", "content": "list the files"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "run_bash", "arguments": '{"cmd": "ls"}'},
}
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "a.txt"},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
assistant_turns = [m for m in result if m["role"] == "assistant"]
blocks = assistant_turns[0]["content"]
assert [b["type"] for b in blocks] == ["text", "tool_use"]
assert blocks[0]["text"] == "Let me check."
assert PLACEHOLDER not in json.dumps(result)
@pytest.mark.parametrize(
"messages",
[
[{"role": "user", "content": ""}],
[{"role": "user", "content": [{"type": "text", "text": " "}]}],
[{"role": "user", "content": "hi"}, {"role": "assistant", "content": ""}],
],
ids=["user_str", "user_block", "assistant_without_tool_calls"],
)
def test_placeholder_still_used_when_turn_would_be_empty(self, messages):
"""
The placeholder is still required where dropping the empty text would leave the
turn with no content at all, which Anthropic also rejects.
"""
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
assert PLACEHOLDER in json.dumps(result)
for message in result:
assert message["content"]
def test_no_empty_text_block_or_content_reaches_anthropic(self):
"""
The invariant Anthropic actually enforces, over a conversation mixing every shape:
no empty content list and no empty text block may survive the conversion.
"""
messages = [
{"role": "user", "content": ""},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "run_bash", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "out"},
{"role": "assistant", "content": [{"type": "text", "text": " "}]},
{"role": "user", "content": [{"type": "text", "text": "thanks"}]},
]
result = anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
for message in result:
content = message["content"]
assert content
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
assert block["text"].strip()
def test_sanitization_does_not_mutate_caller_messages(self):
"""
Callers reuse their message list across retries and fallbacks, so sanitization has
to stay copy-on-write.
"""
messages = [
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "run_bash", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "out"},
]
before = copy.deepcopy(messages)
anthropic_messages_pt(messages=messages, model="claude-sonnet-4-6", llm_provider="anthropic")
assert messages == before
if __name__ == "__main__":
pytest.main([__file__, "-v"])