Preserve explicit empty assistant messages (#182754)

This commit is contained in:
Denis Shulyaka
2026-10-06 20:06:50 +02:00
committed by GitHub
parent 275f402cf6
commit 5cddb5e2ec
8 changed files with 526 additions and 12 deletions
@@ -551,6 +551,7 @@ class AnthropicDeltaStream:
self._content_details.add_citation_detail()
self._input_usage: Usage | None = None
self._first_block: bool = True
self._has_content = False
def __aiter__(
self,
@@ -603,11 +604,14 @@ class AnthropicDeltaStream:
"""Handle RawMessageStartEvent."""
self._input_usage = message.usage
self._first_block = True
self._has_content = False
def on_content_block_start_event(
self, content_block: ContentBlock, index: int
) -> None:
"""Handle RawContentBlockStartEvent."""
if not isinstance(content_block, TextBlock) or content_block.text:
self._has_content = True
if isinstance(content_block, ToolUseBlock):
self.on_tool_use_block(
content_block.id,
@@ -781,6 +785,7 @@ class AnthropicDeltaStream:
}
)
self._first_block = True
self._has_content = False
def on_content_block_delta_event(self, delta: RawContentBlockDelta) -> None:
"""Handle RawContentBlockDeltaEvent."""
@@ -808,6 +813,7 @@ class AnthropicDeltaStream:
def on_text_delta(self, text: str) -> None:
"""Handle TextDelta."""
if text:
self._has_content = True
self._content_details.citation_details[-1].length += len(text)
self._buffer.append({"content": text})
@@ -865,6 +871,8 @@ class AnthropicDeltaStream:
def on_message_stop_event(self) -> None:
"""Handle RawMessageStopEvent."""
if self.stop_reason == "end_turn" and not self._has_content:
self._buffer.append({"role": "assistant", "content": ""})
if self._content_details:
self._content_details.delete_empty()
self._buffer.append({"native": self._content_details})
@@ -276,7 +276,7 @@ class AssistantContent:
"agent_id": self.agent_id,
"created": self.created,
}
if self.content:
if self.content is not None:
result["content"] = self.content
if self.thinking_content:
result["thinking_content"] = self.thinking_content
@@ -522,8 +522,10 @@ class ChatLog:
The keys content and tool_calls will be concatenated
if they appear multiple times.
An explicit empty content string is preserved as a silent response.
"""
current_content = ""
current_content: str | None = None
current_thinking_content = ""
current_native: Any = None
current_tool_calls: list[llm.ToolInput] = []
@@ -536,8 +538,8 @@ class ChatLog:
if "role" not in delta:
# ToolResultContentDeltaDict will always have a role
assistant_delta = cast(AssistantContentDeltaDict, delta)
if delta_content := assistant_delta.get("content"):
current_content += delta_content
if (delta_content := assistant_delta.get("content")) is not None:
current_content = (current_content or "") + delta_content
if delta_thinking_content := assistant_delta.get("thinking_content"):
current_thinking_content += delta_thinking_content
if delta_native := assistant_delta.get("native"):
@@ -571,14 +573,14 @@ class ChatLog:
# Starting a new message
# Yield the previous message if it has content
if (
current_content
current_content is not None
or current_thinking_content
or current_tool_calls
or current_native
):
content: AssistantContent | ToolResultContent = AssistantContent(
agent_id=agent_id,
content=current_content or None,
content=current_content,
thinking_content=current_thinking_content or None,
tool_calls=current_tool_calls or None,
native=current_native,
@@ -590,13 +592,13 @@ class ChatLog:
yield tool_result
if self.delta_listener:
self.delta_listener(self, tool_result.as_dict())
current_content = ""
current_content = None
current_thinking_content = ""
current_native = None
current_tool_calls = []
if delta["role"] == "assistant":
current_content = delta.get("content") or ""
current_content = delta.get("content")
current_thinking_content = delta.get("thinking_content") or ""
current_tool_calls = delta.get("tool_calls") or []
current_native = delta.get("native")
@@ -635,14 +637,14 @@ class ChatLog:
)
if (
current_content
current_content is not None
or current_thinking_content
or current_tool_calls
or current_native
):
content = AssistantContent(
agent_id=agent_id,
content=current_content or None,
content=current_content,
thinking_content=current_thinking_content or None,
tool_calls=current_tool_calls or None,
native=current_native,
@@ -438,6 +438,19 @@ async def _transform_stream( # noqa: C901 - This is complex, but better to have
]
}
elif isinstance(event, ResponseCompletedEvent):
if (
event.response.output
and isinstance(
message := event.response.output[-1], ResponseOutputMessage
)
and message.status == "completed"
and message.content
and all(
part.type == "output_text" and part.text == ""
for part in message.content
)
):
yield {"content": ""}
if event.response.usage is not None:
chat_log.async_trace(
{
+21 -1
View File
@@ -79,9 +79,29 @@ async def test_empty_data(
hass: HomeAssistant,
mock_create_stream: AsyncMock,
) -> None:
"""Test AI Task data generation but the data returned is empty."""
"""Test a completed empty response returns empty data."""
mock_create_stream.return_value = [create_content_block(0, [""])]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
)
assert result.data == ""
@pytest.mark.usefixtures("mock_init_component")
async def test_missing_response(
hass: HomeAssistant,
mock_create_stream: AsyncMock,
) -> None:
"""Test a stream without a response still raises an error."""
mock_create_stream.side_effect = None
mock_create_stream.return_value = AsyncMock()
mock_create_stream.return_value.__aiter__.return_value = []
with pytest.raises(
HomeAssistantError, match="Last content in chat log is not an AssistantContent"
):
+209 -1
View File
@@ -1,6 +1,6 @@
"""Tests for the Anthropic integration."""
from collections.abc import AsyncIterator, Generator
from collections.abc import AsyncGenerator, AsyncIterator, Generator
from copy import deepcopy
import datetime
from pathlib import Path
@@ -71,6 +71,7 @@ from homeassistant.components.anthropic.const import (
)
from homeassistant.components.anthropic.entity import (
MAX_TOOL_ITERATIONS,
AnthropicDeltaStream,
CitationDetails,
ContentDetails,
_convert_content,
@@ -472,6 +473,140 @@ async def test_prompt_caching_automatic(
assert isinstance(system, str)
@pytest.mark.parametrize(
("body_events", "expected_roles"),
[
pytest.param(create_content_block(0, []), [], id="empty-response"),
pytest.param(
[
*create_server_tool_use_block(
0, "srvtoolu_test", "web_search", ['{"query":"Home Assistant"}']
),
*create_web_search_result_block(1, "srvtoolu_test", []),
*create_content_block(2, []),
],
["assistant", "tool_result"],
id="server-tool-result",
),
],
)
@pytest.mark.parametrize(
"end_events",
[
pytest.param(
[
RawMessageDeltaEvent(
type="message_delta",
delta=Delta(stop_reason="max_tokens"),
usage=MessageDeltaUsage(output_tokens=0),
),
RawMessageStopEvent(type="message_stop"),
],
id="token-limit",
),
pytest.param(
[
RawMessageDeltaEvent(
type="message_delta",
delta=Delta(stop_reason="pause_turn"),
usage=MessageDeltaUsage(output_tokens=0),
),
RawMessageStopEvent(type="message_stop"),
],
id="paused-turn",
),
pytest.param(
[
RawMessageDeltaEvent(
type="message_delta",
delta=Delta(stop_reason="tool_use"),
usage=MessageDeltaUsage(output_tokens=0),
),
RawMessageStopEvent(type="message_stop"),
],
id="tool-use",
),
pytest.param(
[RawMessageStopEvent(type="message_stop")], id="missing-stop-reason"
),
pytest.param(
[
RawMessageDeltaEvent(
type="message_delta",
delta=Delta(stop_reason="end_turn"),
usage=MessageDeltaUsage(output_tokens=0),
),
],
id="missing-message-stop",
),
],
)
async def test_empty_response_without_completed_turn(
hass: HomeAssistant,
body_events: list[RawMessageStreamEvent],
expected_roles: list[str],
end_events: list[RawMessageStreamEvent],
) -> None:
"""Test incomplete empty responses do not produce a silent acknowledgement."""
chat_log = conversation.ChatLog(hass, "test-conversation")
async def stream() -> AsyncGenerator[RawMessageStreamEvent]:
for event in (*body_events, *end_events):
yield event
results = [
content
async for content in chat_log.async_add_delta_content_stream(
"conversation.claude_conversation", AnthropicDeltaStream(chat_log, stream())
)
]
assert [content.role for content in results] == expected_roles
@pytest.mark.usefixtures("mock_config_entry_with_assist", "mock_init_component")
@pytest.mark.parametrize(
"events",
[
pytest.param([], id="no-content-blocks"),
pytest.param(create_content_block(0, []), id="empty-text-block"),
pytest.param(create_content_block(0, [""]), id="empty-text-delta"),
],
)
@patch("homeassistant.components.llm.async_get_tools", new_callable=AsyncMock)
async def test_function_call_with_silent_response(
mock_get_tools: AsyncMock,
hass: HomeAssistant,
mock_create_stream: AsyncMock,
events: list[RawMessageStreamEvent],
) -> None:
"""Test an empty completed turn acknowledges tool results without retries."""
mock_tool = AsyncMock()
mock_tool.name = "test_tool"
mock_tool.description = "Test function"
mock_tool.parameters = probatio.Schema({})
mock_tool.async_call.return_value = llm.ToolResult(data="Test response")
mock_get_tools.return_value = LLMTools(tools=[mock_tool])
mock_create_stream.return_value = [
create_tool_use_block(0, "toolu_test", "test_tool", ["{}"]),
events,
]
result = await conversation.async_converse(
hass,
"Please call the test function silently",
None,
Context(),
agent_id="conversation.claude_conversation",
)
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
assert result.response.speech["plain"]["speech"] == ""
assert not result.continue_conversation
assert mock_create_stream.await_count == 2
mock_tool.async_call.assert_awaited_once()
@patch("homeassistant.components.llm.async_get_tools", new_callable=AsyncMock)
@pytest.mark.parametrize(
("tool_call_json_parts", "expected_call_tool_args"),
@@ -1367,6 +1502,79 @@ async def test_web_search(
assert mock_create_stream.call_args.kwargs["messages"] == snapshot
@pytest.mark.usefixtures("mock_init_component")
@pytest.mark.parametrize(
"preamble",
[
pytest.param([], id="no-preamble"),
pytest.param(create_content_block(0, ["Searching"]), id="with-preamble"),
],
)
@pytest.mark.parametrize(
("final_events", "expected_speech"),
[
pytest.param([], "", id="no-final-text"),
pytest.param(create_content_block(3, [""]), "", id="empty-final-text"),
pytest.param(
create_content_block(3, ["Found it"]), "Found it", id="nonempty-final-text"
),
],
)
async def test_web_search_final_response(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
preamble: list[RawMessageStreamEvent],
final_events: list[RawMessageStreamEvent],
expected_speech: str,
) -> None:
"""Test completed server tool results can be followed by a silent response."""
hass.config_entries.async_update_subentry(
mock_config_entry,
next(iter(mock_config_entry.subentries.values())),
data={CONF_WEB_SEARCH: True},
)
await hass.async_block_till_done()
mock_create_stream.return_value = [
(
*preamble,
*create_server_tool_use_block(
1, "srvtoolu_test", "web_search", ['{"query":"Home Assistant"}']
),
*create_web_search_result_block(
2,
"srvtoolu_test",
[
WebSearchResultBlock(
type="web_search_result",
title="Home Assistant",
url="https://www.home-assistant.io/",
encrypted_content="test",
)
],
),
*final_events,
)
]
result = await conversation.async_converse(
hass,
"Search for Home Assistant",
None,
Context(),
agent_id="conversation.claude_conversation",
)
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
assert result.response.speech["plain"]["speech"] == expected_speech
assert not result.continue_conversation
mock_create_stream.assert_awaited_once()
chat_log = hass.data[conversation.chat_log.DATA_CHAT_LOGS][result.conversation_id]
assert not chat_log.unresponded_tool_results
assert isinstance(chat_log.content[-1], conversation.AssistantContent)
assert chat_log.content[-1].content == expected_speech
@freeze_time("2025-10-31 12:00:00")
@pytest.mark.usefixtures("mock_init_component")
async def test_web_search_error(
@@ -1,5 +1,6 @@
"""Test the conversation session."""
from collections.abc import AsyncGenerator
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -12,6 +13,7 @@ from syrupy.assertion import SnapshotAssertion
from homeassistant.components.conversation import (
AssistantContent,
AssistantContentDeltaDict,
ConversationInput,
ConverseError,
ToolResultContent,
@@ -21,6 +23,7 @@ from homeassistant.components.conversation import (
from homeassistant.components.conversation.chat_log import (
DATA_CHAT_LOGS,
Attachment,
ChatLog,
ChatLogEventType,
async_subscribe_chat_logs,
)
@@ -759,6 +762,57 @@ async def test_add_delta_content_stream(
assert chat_log.content[2:] == results
@freeze_time("2025-10-31 12:00:00")
@pytest.mark.parametrize(
("deltas", "expected_content"),
[
pytest.param([{"role": "assistant"}], [], id="role-only"),
pytest.param([{"role": "assistant", "content": ""}], [""], id="empty-message"),
pytest.param([{"role": "assistant"}, {"content": ""}], [""], id="empty-delta"),
pytest.param(
[
{"role": "assistant", "content": ""},
{"role": "assistant", "content": "Next"},
],
["", "Next"],
id="empty-before-next-message",
),
pytest.param(
[{"role": "assistant", "content": ""}, {"content": "Hello"}],
["Hello"],
id="text-after-empty-delta",
),
],
)
async def test_add_delta_content_stream_empty_content(
hass: HomeAssistant,
mock_conversation_input: ConversationInput,
deltas: list[AssistantContentDeltaDict],
expected_content: list[str],
) -> None:
"""Test explicit empty content is preserved but role-only messages are not."""
async def stream() -> AsyncGenerator[AssistantContentDeltaDict]:
for delta in deltas:
yield delta
with (
chat_session.async_get_chat_session(hass) as session,
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
):
results = [
content
async for content in chat_log.async_add_delta_content_stream(
"mock-agent-id", stream()
)
]
assert results == [
AssistantContent(agent_id="mock-agent-id", content=content)
for content in expected_content
]
async def test_add_delta_content_stream_errors(
hass: HomeAssistant,
mock_conversation_input: ConversationInput,
@@ -871,6 +925,43 @@ async def test_chat_log_continue_conversation(
assert chat_log.continue_conversation is True
@pytest.mark.parametrize(
("content", "expected_content"),
[
pytest.param(None, {}, id="absent-content"),
pytest.param("", {"content": ""}, id="empty-content"),
pytest.param("Hello", {"content": "Hello"}, id="nonempty-content"),
],
)
async def test_assistant_content_serialization(
hass: HomeAssistant,
content: str | None,
expected_content: dict[str, str],
) -> None:
"""Test chat logs and events distinguish empty text from absent text."""
chat_log = ChatLog(hass, "test-conversation")
message = AssistantContent(agent_id="test-agent", content=content)
expected_message = {
"role": "assistant",
"agent_id": "test-agent",
"created": message.created,
**expected_content,
}
event_callback = Mock()
unsubscribe = async_subscribe_chat_logs(hass, event_callback)
chat_log.async_add_assistant_content_without_tools(message)
assert message.as_dict() == expected_message
assert chat_log.as_dict()["content"][-1] == expected_message
event_callback.assert_called_once_with(
"test-conversation",
ChatLogEventType.CONTENT_ADDED,
{"content": expected_message},
)
unsubscribe()
@freeze_time("2025-10-31 12:00:00")
async def test_chat_log_subscription(
hass: HomeAssistant,
@@ -355,6 +355,102 @@
}),
])
# ---
# name: test_function_call_with_silent_response[empty-delta]
list([
dict({
'attachments': None,
'content': 'Please call the test function silently',
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'role': 'user',
}),
dict({
'agent_id': 'conversation.openai_conversation',
'content': None,
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'native': None,
'role': 'assistant',
'thinking_content': None,
'tool_calls': list([
dict({
'external': False,
'id': 'call_call_1',
'tool_args': dict({
'param1': 'call1',
}),
'tool_name': 'test_tool',
}),
]),
}),
dict({
'agent_id': 'conversation.openai_conversation',
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'result': dict({
'data': 'value1',
'error': False,
}),
'role': 'tool_result',
'tool_call_id': 'call_call_1',
'tool_name': 'test_tool',
}),
dict({
'agent_id': 'conversation.openai_conversation',
'content': '',
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'native': None,
'role': 'assistant',
'thinking_content': None,
'tool_calls': None,
}),
])
# ---
# name: test_function_call_with_silent_response[no-text-deltas]
list([
dict({
'attachments': None,
'content': 'Please call the test function silently',
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'role': 'user',
}),
dict({
'agent_id': 'conversation.openai_conversation',
'content': None,
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'native': None,
'role': 'assistant',
'thinking_content': None,
'tool_calls': list([
dict({
'external': False,
'id': 'call_call_1',
'tool_args': dict({
'param1': 'call1',
}),
'tool_name': 'test_tool',
}),
]),
}),
dict({
'agent_id': 'conversation.openai_conversation',
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'result': dict({
'data': 'value1',
'error': False,
}),
'role': 'tool_result',
'tool_call_id': 'call_call_1',
'tool_name': 'test_tool',
}),
dict({
'agent_id': 'conversation.openai_conversation',
'content': '',
'created': HAFakeDatetime(2025, 10, 31, 18, 0, tzinfo=datetime.timezone.utc),
'native': None,
'role': 'assistant',
'thinking_content': None,
'tool_calls': None,
}),
])
# ---
# name: test_function_call_without_reasoning
list([
dict({
@@ -395,6 +395,82 @@ async def test_function_call_without_reasoning(
assert mock_chat_log.content[1:] == snapshot
@freeze_time("2025-10-31 18:00:00")
@pytest.mark.usefixtures("mock_config_entry_with_assist", "mock_init_component")
@pytest.mark.parametrize(
"text",
[pytest.param("", id="empty-delta"), pytest.param([], id="no-text-deltas")],
)
async def test_function_call_with_silent_response(
hass: HomeAssistant,
mock_create_stream: AsyncMock,
mock_chat_log: MockChatLog, # noqa: F811
snapshot: SnapshotAssertion,
text: str | list[str],
) -> None:
"""Test a completed empty response acknowledges tool results without retries."""
mock_create_stream.return_value = [
create_function_tool_call_item(
id="fc_1",
arguments=['{"param1":"call1"}'],
call_id="call_call_1",
name="test_tool",
output_index=0,
),
create_message_item(id="msg_A", text=text, output_index=0),
]
mock_chat_log.mock_tool_results({"call_call_1": "value1"})
result = await conversation.async_converse(
hass,
"Please call the test function silently",
mock_chat_log.conversation_id,
Context(),
agent_id="conversation.openai_conversation",
)
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
assert result.response.speech["plain"]["speech"] == ""
assert not result.continue_conversation
assert mock_create_stream.await_count == 2
assert not mock_chat_log.unresponded_tool_results
assert mock_chat_log.content[1:] == snapshot
@pytest.mark.usefixtures("mock_init_component")
@pytest.mark.parametrize(
("events", "speech"),
[
pytest.param([], "Unable to get response", id="missing-message"),
pytest.param(
[
*create_message_item(id="msg_A", text=[], output_index=0),
IncompleteDetails(reason="max_output_tokens"),
],
"OpenAI response incomplete: max output tokens reached",
id="incomplete-empty-response",
),
],
)
async def test_missing_or_incomplete_empty_response(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
events: list[ResponseStreamEvent | IncompleteDetails],
speech: str,
) -> None:
"""Test absent and incomplete responses are not treated as silent success."""
mock_create_stream.return_value = [events]
result = await conversation.async_converse(
hass, "hello", None, Context(), agent_id=mock_config_entry.entry_id
)
assert result.response.response_type is intent.IntentResponseType.ERROR
assert result.response.speech["plain"]["speech"] == speech
assert mock_create_stream.await_count == 1
@freeze_time("2025-10-31 18:00:00")
async def test_reasoning_summary_off_omits_summary_key(
hass: HomeAssistant,