Skip to content

Commit da002db

Browse files
authored
[None][fix] Anthropic Messages: no whitespace-only text blocks (#20874)
Signed-off-by: JunyiXu-nv <219237550+JunyiXu-nv@users.noreply.github.com>
1 parent 0a97382 commit da002db

2 files changed

Lines changed: 119 additions & 3 deletions

File tree

‎tensorrt_llm/serve/anthropic_adapter.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,7 @@ def convert_chat_response(chat_response: ChatCompletionResponse) -> AnthropicMes
624624
reasoning = message.reasoning_content or message.reasoning
625625
if reasoning:
626626
content.append(AnthropicThinkingBlock(thinking=reasoning))
627-
if message.content:
627+
if message.content and message.content.strip():
628628
content.append(AnthropicTextBlock(text=message.content))
629629
for tool_call in message.tool_calls:
630630
try:
@@ -733,6 +733,14 @@ def __init__(self, model: str):
733733
# Whether this stream emitted any tool_use block, which decides the
734734
# terminating stop_reason; see finish().
735735
self.emitted_tool_use = False
736+
# Whitespace-only text waiting for text that is more than whitespace.
737+
# Anthropic clients drop whitespace-only text blocks when they send a
738+
# turn back (the API rejects them), so such a block would make the
739+
# replayed turn differ from the one served. The model's layout between
740+
# blocks (the newlines before a tool call, say) is held here instead:
741+
# it opens a text block only together with the text that follows it,
742+
# and is dropped when another kind of block opens or the stream ends.
743+
self.pending_whitespace = ""
736744
self.stop_reason: AnthropicStopReason = "end_turn"
737745
self.stop_sequence: Optional[str] = None
738746
self.final_usage: Optional[AnthropicUsage] = None
@@ -748,6 +756,8 @@ def _close_block(self) -> List[str]:
748756
return [anthropic_sse(event)]
749757

750758
def _open_block(self, block: Any, block_type: str) -> List[str]:
759+
if block_type != "text":
760+
self.pending_whitespace = ""
751761
frames = self._close_block()
752762
self.block_index += 1
753763
self.open_block_type = block_type
@@ -937,12 +947,18 @@ def process_chunk(self, chunk: ChatCompletionStreamResponse) -> List[str]:
937947
)
938948
)
939949
)
940-
if delta.content:
950+
text = delta.content
951+
if text and self.open_block_type != "text":
952+
text = self.pending_whitespace + text
953+
self.pending_whitespace = "" if text.strip() else text
954+
if self.pending_whitespace:
955+
text = ""
956+
if text:
941957
frames.extend(self._ensure_block("text"))
942958
frames.append(
943959
anthropic_sse(
944960
AnthropicContentBlockDeltaEvent(
945-
index=self.block_index, delta=AnthropicTextDelta(text=delta.content)
961+
index=self.block_index, delta=AnthropicTextDelta(text=text)
946962
)
947963
)
948964
)

‎tests/unittest/llmapi/apps/test_anthropic_adapter.py‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,106 @@ def test_stream_tool_call_arguments_concatenate():
937937
assert message_delta["delta"]["stop_reason"] == "tool_use"
938938

939939

940+
def _tool_call_chunk(index, call_id, name, arguments):
941+
return chunk(
942+
{
943+
"tool_calls": [
944+
{"index": index, "id": call_id, "function": {"name": name, "arguments": arguments}}
945+
]
946+
}
947+
)
948+
949+
950+
def test_stream_whitespace_between_blocks_opens_no_text_block():
951+
"""Whitespace-only text between blocks opens no text block of its own."""
952+
events = run_reframer(
953+
[
954+
chunk({"reasoning_content": "check the weather"}),
955+
chunk({"content": "\n\n"}),
956+
_tool_call_chunk(0, "call_1", "get_weather", '{"city": "sf"}'),
957+
chunk({"content": "\n"}),
958+
_tool_call_chunk(1, "call_2", "get_weather", '{"city": "nyc"}'),
959+
chunk({"content": "\n"}),
960+
chunk({}, finish_reason="tool_calls"),
961+
]
962+
)
963+
assert_event_invariants(events)
964+
starts = [p["content_block"]["type"] for n, p in events if n == "content_block_start"]
965+
assert starts == ["thinking", "tool_use", "tool_use"]
966+
967+
968+
def test_stream_whitespace_before_text_stays_with_the_text():
969+
"""Whitespace that precedes text is that text's, delivered unchanged."""
970+
events = run_reframer(
971+
[
972+
chunk({"reasoning_content": "plan"}),
973+
chunk({"content": "\n\n"}),
974+
chunk({"content": "Answer.\n"}),
975+
chunk({}, finish_reason="stop"),
976+
]
977+
)
978+
assert_event_invariants(events)
979+
texts = [
980+
p["delta"]["text"]
981+
for n, p in events
982+
if n == "content_block_delta" and p["delta"]["type"] == "text_delta"
983+
]
984+
assert "".join(texts) == "\n\nAnswer.\n"
985+
starts = [p["content_block"]["type"] for n, p in events if n == "content_block_start"]
986+
assert starts == ["thinking", "text"]
987+
988+
989+
def test_stream_whitespace_inside_an_open_text_block_stays_with_the_text():
990+
"""Whitespace inside a text block that holds text is delivered unchanged."""
991+
events = run_reframer(
992+
[
993+
chunk({"content": "hello"}),
994+
chunk({"content": " "}),
995+
chunk({"content": "world"}),
996+
chunk({}, finish_reason="stop"),
997+
]
998+
)
999+
assert_event_invariants(events)
1000+
texts = [
1001+
p["delta"]["text"]
1002+
for n, p in events
1003+
if n == "content_block_delta" and p["delta"]["type"] == "text_delta"
1004+
]
1005+
assert "".join(texts) == "hello world"
1006+
starts = [p["content_block"]["type"] for n, p in events if n == "content_block_start"]
1007+
assert starts == ["text"]
1008+
1009+
1010+
def test_stream_trailing_whitespace_opens_no_text_block():
1011+
"""Whitespace-only text at the end of the stream opens no text block."""
1012+
events = run_reframer(
1013+
[
1014+
chunk({"reasoning_content": "plan"}),
1015+
chunk({"content": "\n\n"}, finish_reason="stop"),
1016+
]
1017+
)
1018+
assert_event_invariants(events)
1019+
starts = [p["content_block"]["type"] for n, p in events if n == "content_block_start"]
1020+
assert starts == ["thinking"]
1021+
assert not [
1022+
p for n, p in events if n == "content_block_delta" and p["delta"]["type"] == "text_delta"
1023+
]
1024+
1025+
1026+
def test_whitespace_only_content_is_not_a_text_block():
1027+
message = ChatMessage(
1028+
role="assistant",
1029+
content="\n\n",
1030+
tool_calls=[
1031+
ToolCall(
1032+
id="call_1", function=FunctionCall(name="get_weather", arguments='{"city": "sf"}')
1033+
)
1034+
],
1035+
)
1036+
resp = convert_chat_response(make_chat_response(message, finish_reason="tool_calls"))
1037+
assert [block.type for block in resp.content] == ["tool_use"]
1038+
1039+
9401040
def test_stream_parallel_tool_calls_get_separate_blocks():
9411041
events = run_reframer(
9421042
[

0 commit comments

Comments
 (0)