mirror of
https://github.com/home-assistant/core.git
synced 2026-12-06 13:45:55 -04:00
Process one message per conversation at a time and keep failed messages (#188535)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
f97a49eb17
commit
8326b19029
@@ -594,7 +594,7 @@ class _DefaultPipelineProcessor:
|
||||
await conversation.async_prepare_intents(self.host.hass, language)
|
||||
await conversation.async_prepare_agent(self.host.hass, agent_id, language)
|
||||
|
||||
async def recognize_intent(
|
||||
async def recognize_intent( # noqa: C901
|
||||
self,
|
||||
intent_input: str,
|
||||
conversation_id: str,
|
||||
@@ -847,6 +847,11 @@ class _DefaultPipelineProcessor:
|
||||
)
|
||||
)
|
||||
|
||||
except conversation.ConversationBusyError as src_error:
|
||||
raise IntentRecognitionError(
|
||||
code="intent-busy",
|
||||
message=str(src_error),
|
||||
) from src_error
|
||||
except Unauthorized as src_error:
|
||||
raise IntentRecognitionError(
|
||||
code="intent-unauthorized",
|
||||
|
||||
@@ -22,6 +22,7 @@ from .chat_log import (
|
||||
Attachment,
|
||||
ChatLog,
|
||||
Content,
|
||||
ConversationBusyError,
|
||||
ConverseError,
|
||||
SystemContent,
|
||||
ToolResultContent,
|
||||
@@ -60,6 +61,7 @@ __all__ = [
|
||||
"Attachment",
|
||||
"ChatLog",
|
||||
"Content",
|
||||
"ConversationBusyError",
|
||||
"ConversationEntity",
|
||||
"ConversationEntityFeature",
|
||||
"ConversationInput",
|
||||
|
||||
@@ -17,6 +17,7 @@ from homeassistant.core import (
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import config_validation as cv, intent, singleton
|
||||
|
||||
from .chat_log import current_chat_log
|
||||
from .const import DATA_COMPONENT, HOME_ASSISTANT_AGENT, IntentSource
|
||||
from .entity import ConversationEntity
|
||||
from .models import (
|
||||
@@ -126,6 +127,11 @@ async def async_converse(
|
||||
try:
|
||||
result = await method(conversation_input)
|
||||
except HomeAssistantError as err:
|
||||
if (
|
||||
chat_log := current_chat_log.get()
|
||||
) and chat_log.conversation_id == conversation_id:
|
||||
# The open turn of the caller does not see the handled error.
|
||||
chat_log.async_add_error(agent_id, err)
|
||||
intent_response = intent.IntentResponse(language=language)
|
||||
intent_response.async_set_error(
|
||||
intent.IntentResponseErrorCode.UNKNOWN,
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
from collections.abc import AsyncGenerator, AsyncIterable, Callable, Generator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import asdict, dataclass, field, replace
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from pathlib import Path
|
||||
@@ -77,6 +77,8 @@ def async_get_chat_log(
|
||||
chat_log_delta_listener: Callable[[ChatLog, dict], None] | None = None,
|
||||
) -> Generator[ChatLog]:
|
||||
"""Return chat log for a specific chat session."""
|
||||
agent_id = (user_input.agent_id if user_input else None) or DOMAIN
|
||||
|
||||
# If a chat log is already active and it's the requested conversation ID,
|
||||
# return that. We won't update the last updated time in this case.
|
||||
if (
|
||||
@@ -92,7 +94,10 @@ def async_get_chat_log(
|
||||
):
|
||||
chat_log.async_add_user_content(UserContent(content=user_input.text))
|
||||
|
||||
yield chat_log
|
||||
try:
|
||||
yield chat_log
|
||||
finally:
|
||||
chat_log.async_trace_turn()
|
||||
return
|
||||
|
||||
all_chat_logs = hass.data.get(DATA_CHAT_LOGS)
|
||||
@@ -100,18 +105,14 @@ def async_get_chat_log(
|
||||
all_chat_logs = {}
|
||||
hass.data[DATA_CHAT_LOGS] = all_chat_logs
|
||||
|
||||
is_new_log = session.conversation_id not in all_chat_logs
|
||||
|
||||
if chat_log := all_chat_logs.get(session.conversation_id):
|
||||
chat_log = replace(chat_log, content=chat_log.content.copy())
|
||||
if chat_log.turn_active:
|
||||
raise ConversationBusyError(session.conversation_id)
|
||||
is_new_log = False
|
||||
else:
|
||||
chat_log = ChatLog(hass, session.conversation_id)
|
||||
|
||||
if chat_log_delta_listener:
|
||||
chat_log.delta_listener = chat_log_delta_listener
|
||||
|
||||
# Fire CREATED event for new chat logs before any content is added
|
||||
if is_new_log:
|
||||
is_new_log = True
|
||||
all_chat_logs[session.conversation_id] = chat_log
|
||||
_async_notify_subscribers(
|
||||
hass,
|
||||
session.conversation_id,
|
||||
@@ -119,35 +120,41 @@ def async_get_chat_log(
|
||||
{"chat_log": chat_log.as_dict()},
|
||||
)
|
||||
|
||||
chat_log.turn_start = len(chat_log.content)
|
||||
if user_input is not None:
|
||||
chat_log.async_add_user_content(UserContent(content=user_input.text))
|
||||
|
||||
if chat_log_delta_listener:
|
||||
chat_log.delta_listener = chat_log_delta_listener
|
||||
|
||||
last_message = chat_log.content[-1]
|
||||
|
||||
token = current_chat_log.set(chat_log)
|
||||
yield chat_log
|
||||
current_chat_log.reset(token)
|
||||
chat_log.turn_active = True
|
||||
try:
|
||||
yield chat_log
|
||||
except (Exception, asyncio.CancelledError) as err:
|
||||
chat_log.async_add_error(agent_id, err)
|
||||
raise
|
||||
finally:
|
||||
chat_log.turn_active = False
|
||||
current_chat_log.reset(token)
|
||||
chat_log.delta_listener = None
|
||||
|
||||
if chat_log.content[-1] is last_message:
|
||||
LOGGER.debug(
|
||||
"Chat Log opened but no assistant message was added, ignoring update"
|
||||
)
|
||||
# If this was a new log but nothing was added, fire DELETED to clean up
|
||||
if is_new_log:
|
||||
if chat_log.content[-1] is last_message and user_input is not None:
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent(agent_id=agent_id, content="(no response)")
|
||||
)
|
||||
chat_log.async_trace_turn()
|
||||
|
||||
if not is_new_log:
|
||||
_async_notify_subscribers(
|
||||
hass,
|
||||
session.conversation_id,
|
||||
ChatLogEventType.DELETED,
|
||||
{},
|
||||
ChatLogEventType.UPDATED,
|
||||
{"chat_log": chat_log.as_dict()},
|
||||
)
|
||||
return
|
||||
|
||||
# Parallel first turns share the session, so register the cleanup once.
|
||||
if session.conversation_id not in all_chat_logs:
|
||||
|
||||
@callback
|
||||
def do_cleanup() -> None:
|
||||
"""Handle cleanup."""
|
||||
elif chat_log.content[-1] is last_message:
|
||||
all_chat_logs.pop(session.conversation_id)
|
||||
_async_notify_subscribers(
|
||||
hass,
|
||||
@@ -155,23 +162,20 @@ def async_get_chat_log(
|
||||
ChatLogEventType.DELETED,
|
||||
{},
|
||||
)
|
||||
else:
|
||||
|
||||
session.async_on_cleanup(do_cleanup)
|
||||
@callback
|
||||
def do_cleanup() -> None:
|
||||
"""Handle cleanup."""
|
||||
all_chat_logs.pop(session.conversation_id)
|
||||
_async_notify_subscribers(
|
||||
hass,
|
||||
session.conversation_id,
|
||||
ChatLogEventType.DELETED,
|
||||
{},
|
||||
)
|
||||
|
||||
if chat_log_delta_listener:
|
||||
chat_log.delta_listener = None
|
||||
|
||||
all_chat_logs[session.conversation_id] = chat_log
|
||||
|
||||
# For new logs, CREATED was already fired before content was added
|
||||
# For existing logs, fire UPDATED
|
||||
if not is_new_log:
|
||||
_async_notify_subscribers(
|
||||
hass,
|
||||
session.conversation_id,
|
||||
ChatLogEventType.UPDATED,
|
||||
{"chat_log": chat_log.as_dict()},
|
||||
)
|
||||
session.async_on_cleanup(do_cleanup)
|
||||
|
||||
|
||||
class ConverseError(HomeAssistantError):
|
||||
@@ -196,6 +200,15 @@ class ConverseError(HomeAssistantError):
|
||||
)
|
||||
|
||||
|
||||
class ConversationBusyError(HomeAssistantError):
|
||||
"""Error when another turn of the conversation is in progress."""
|
||||
|
||||
def __init__(self, conversation_id: str) -> None:
|
||||
"""Initialize the error."""
|
||||
super().__init__("This conversation is busy with another message")
|
||||
self.conversation_id = conversation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SystemContent:
|
||||
"""Base class for chat messages."""
|
||||
@@ -365,6 +378,8 @@ class ChatLog:
|
||||
delta_listener: Callable[[ChatLog, dict], None] | None = None
|
||||
llm_input_provided_index = 0
|
||||
created: datetime = field(init=False, default_factory=utcnow)
|
||||
turn_active: bool = field(default=False, init=False, repr=False)
|
||||
turn_start: int = field(default=0, init=False, repr=False)
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
"""Return a dictionary representation of the chat log."""
|
||||
@@ -412,6 +427,43 @@ class ChatLog:
|
||||
{"content": content.as_dict()},
|
||||
)
|
||||
|
||||
@callback
|
||||
def async_add_error(self, agent_id: str, error: BaseException) -> None:
|
||||
"""Add the error that ended a turn as assistant content."""
|
||||
error_text = str(error) or type(error).__name__
|
||||
# LLM providers refuse a tool call without a result.
|
||||
answered: set[str] = set()
|
||||
index = len(self.content) - 1
|
||||
while isinstance(content := self.content[index], ToolResultContent):
|
||||
answered.add(content.tool_call_id)
|
||||
index -= 1
|
||||
if isinstance(content, AssistantContent) and content.tool_calls:
|
||||
for tool_call in content.tool_calls:
|
||||
if tool_call.id in answered or (
|
||||
# The provider handles its own tools, but sentence
|
||||
# triggers are sent to it as a regular tool call.
|
||||
tool_call.external and tool_call.tool_name != "trigger_sentence"
|
||||
):
|
||||
continue
|
||||
self.async_add_assistant_content_without_tools(
|
||||
ToolResultContent(
|
||||
agent_id=content.agent_id,
|
||||
tool_call_id=tool_call.id,
|
||||
tool_name=tool_call.tool_name,
|
||||
result=llm.ToolResult(
|
||||
data={
|
||||
"error": type(error).__name__,
|
||||
"error_text": error_text,
|
||||
},
|
||||
error=True,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
self.async_add_assistant_content_without_tools(
|
||||
AssistantContent(agent_id=agent_id, content=f"Error: {error_text}")
|
||||
)
|
||||
|
||||
@callback
|
||||
def async_add_assistant_content_without_tools(
|
||||
self, content: AssistantContent | ToolResultContent
|
||||
@@ -740,7 +792,9 @@ class ChatLog:
|
||||
# providers can cache them. Tool calls use the context of this turn.
|
||||
self.llm_api.llm_context = llm_context
|
||||
self.llm_input_provided_index = len(self.content)
|
||||
self.async_trace({"messages": self.content, "tools": self.llm_api.tools})
|
||||
self.async_trace(
|
||||
{"messages": list(self.content), "tools": self.llm_api.tools}
|
||||
)
|
||||
return
|
||||
|
||||
if not user_llm_hass_api:
|
||||
@@ -838,11 +892,18 @@ class ChatLog:
|
||||
|
||||
self.async_trace(
|
||||
{
|
||||
"messages": self.content,
|
||||
"messages": list(self.content),
|
||||
"tools": self.llm_api.tools if self.llm_api else None,
|
||||
}
|
||||
)
|
||||
|
||||
def async_trace_turn(self) -> None:
|
||||
"""Add the content of the current turn to the conversation trace."""
|
||||
trace.async_conversation_trace_append(
|
||||
trace.ConversationTraceEventType.TURN_CONTENT,
|
||||
{"content": self.content[self.turn_start :]},
|
||||
)
|
||||
|
||||
def async_trace(self, agent_details: dict[str, Any]) -> None:
|
||||
"""Append agent specific details to the conversation trace."""
|
||||
trace.async_conversation_trace_append(
|
||||
|
||||
@@ -19,7 +19,7 @@ from .agent_manager import (
|
||||
async_get_agent,
|
||||
get_agent_manager,
|
||||
)
|
||||
from .chat_log import DATA_CHAT_LOGS, async_get_chat_log, async_subscribe_chat_logs
|
||||
from .chat_log import DATA_CHAT_LOGS, async_subscribe_chat_logs
|
||||
from .const import DATA_COMPONENT, ChatLogEventType
|
||||
from .entity import ConversationEntity
|
||||
from .models import ConversationInput
|
||||
@@ -322,15 +322,13 @@ def websocket_subscribe_chat_log(
|
||||
connection.subscriptions[msg_id] = unsubscribe
|
||||
connection.send_result(msg_id)
|
||||
|
||||
with (
|
||||
async_get_chat_session(hass, subscribed_conversation, context=None) as session,
|
||||
async_get_chat_log(hass, session) as chat_log,
|
||||
):
|
||||
# Read the chat log directly, because opening it fails during a turn.
|
||||
with async_get_chat_session(hass, subscribed_conversation, context=None):
|
||||
connection.send_event(
|
||||
msg_id,
|
||||
{
|
||||
"event_type": ChatLogEventType.INITIAL_STATE,
|
||||
"data": chat_log.as_dict(),
|
||||
"data": chat_logs[subscribed_conversation].as_dict(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -25,6 +25,9 @@ class ConversationTraceEventType(enum.StrEnum):
|
||||
TOOL_CALL = "tool_call"
|
||||
"""A conversation agent Tool call or default agent intent call."""
|
||||
|
||||
TURN_CONTENT = "turn_content"
|
||||
"""The content added to the chat log during the turn."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConversationTraceEvent:
|
||||
|
||||
@@ -579,6 +579,39 @@ async def test_text_pipeline_timeout(
|
||||
assert msg["result"] == {"events": events}
|
||||
|
||||
|
||||
async def test_intent_busy(
|
||||
hass: HomeAssistant,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
init_components,
|
||||
) -> None:
|
||||
"""Test text-only pipeline run while another turn of the conversation runs."""
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
conversation.async_get_chat_log(hass, session),
|
||||
):
|
||||
await client.send_json_auto_id(
|
||||
{
|
||||
"type": "assist_pipeline/run",
|
||||
"start_stage": "intent",
|
||||
"end_stage": "intent",
|
||||
"input": {"text": "Are the lights on?"},
|
||||
"conversation_id": "koala",
|
||||
}
|
||||
)
|
||||
|
||||
msg = await client.receive_json()
|
||||
assert msg["success"]
|
||||
msg = await client.receive_json()
|
||||
assert msg["event"]["type"] == "run-start"
|
||||
msg = await client.receive_json()
|
||||
assert msg["event"]["type"] == "intent-start"
|
||||
msg = await client.receive_json()
|
||||
assert msg["event"]["type"] == "error"
|
||||
assert msg["event"]["data"]["code"] == "intent-busy"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_components")
|
||||
async def test_intent_unauthorized(
|
||||
hass: HomeAssistant,
|
||||
|
||||
@@ -2,8 +2,15 @@
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant.components.conversation import ConversationResult, async_converse
|
||||
from homeassistant.components.conversation import (
|
||||
ConversationInput,
|
||||
ConversationResult,
|
||||
async_converse,
|
||||
async_get_chat_log,
|
||||
)
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import chat_session
|
||||
from homeassistant.helpers.intent import IntentResponse
|
||||
|
||||
|
||||
@@ -34,3 +41,25 @@ async def test_async_converse(hass: HomeAssistant, init_components) -> None:
|
||||
assert conversation_input.agent_id == "conversation.home_assistant"
|
||||
assert conversation_input.device_id == "test device id"
|
||||
assert conversation_input.extra_system_prompt == "test extra prompt"
|
||||
|
||||
|
||||
async def test_async_converse_error_in_open_turn(
|
||||
hass: HomeAssistant,
|
||||
init_components: None,
|
||||
mock_conversation_input: ConversationInput,
|
||||
) -> None:
|
||||
"""Test an error of the agent is added to the open turn of the caller."""
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
patch(
|
||||
"homeassistant.components.conversation.default_agent.DefaultAgent._async_handle_message",
|
||||
side_effect=HomeAssistantError("Provider is down"),
|
||||
),
|
||||
):
|
||||
await async_converse(hass, "Hello", "koala", Context())
|
||||
|
||||
assert [(c.role, c.content) for c in chat_log.content[1:]] == [
|
||||
("user", "Hello"),
|
||||
("assistant", "Error: Provider is down"),
|
||||
]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import ExitStack
|
||||
import contextvars
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
@@ -17,6 +18,7 @@ from syrupy.assertion import SnapshotAssertion
|
||||
from homeassistant.components.conversation import (
|
||||
AssistantContent,
|
||||
AssistantContentDeltaDict,
|
||||
ConversationBusyError,
|
||||
ConversationInput,
|
||||
ConverseError,
|
||||
ToolResultContent,
|
||||
@@ -30,6 +32,10 @@ from homeassistant.components.conversation.chat_log import (
|
||||
ChatLogEventType,
|
||||
async_subscribe_chat_logs,
|
||||
)
|
||||
from homeassistant.components.conversation.trace import (
|
||||
ConversationTraceEventType,
|
||||
async_conversation_trace,
|
||||
)
|
||||
from homeassistant.components.llm import LLMTools
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError, Unauthorized
|
||||
@@ -279,37 +285,211 @@ async def test_unknown_llm_api(
|
||||
assert exc_info.value.as_conversation_result().as_dict() == snapshot
|
||||
|
||||
|
||||
async def test_new_chat_log_parallel_turns_cleanup(
|
||||
async def test_concurrent_turn_busy(
|
||||
hass: HomeAssistant, mock_conversation_input: ConversationInput
|
||||
) -> None:
|
||||
"""Test the cleanup after parallel first turns of a new conversation."""
|
||||
"""Test a second turn of a conversation raises while the first is open."""
|
||||
|
||||
async def run_turn() -> None:
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input),
|
||||
):
|
||||
pass
|
||||
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input),
|
||||
pytest.raises(ConversationBusyError),
|
||||
):
|
||||
# A new context runs the request like a separate task would.
|
||||
await asyncio.create_task(run_turn(), context=contextvars.Context())
|
||||
|
||||
with (
|
||||
pytest.raises(ValueError),
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input),
|
||||
):
|
||||
raise ValueError
|
||||
|
||||
# The failed turn has ended, so the next turn may start.
|
||||
await run_turn()
|
||||
|
||||
|
||||
async def test_turn_without_reply(
|
||||
hass: HomeAssistant, mock_conversation_input: ConversationInput
|
||||
) -> None:
|
||||
"""Test a user message without an assistant reply gets a placeholder reply."""
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
):
|
||||
pass
|
||||
|
||||
assert hass.data[DATA_CHAT_LOGS]["koala"] is chat_log
|
||||
assert [(item.role, item.content) for item in chat_log.content[1:]] == [
|
||||
("user", "Hello"),
|
||||
("assistant", "(no response)"),
|
||||
]
|
||||
assert chat_log.content[-1].agent_id == "mock-agent-id"
|
||||
|
||||
|
||||
async def test_trace_keeps_messages_of_its_turn(
|
||||
hass: HomeAssistant, mock_conversation_input: ConversationInput
|
||||
) -> None:
|
||||
"""Test a later turn does not change the messages in the trace of a turn."""
|
||||
with (
|
||||
async_conversation_trace() as conversation_trace,
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
):
|
||||
await chat_log.async_provide_llm_data(
|
||||
mock_conversation_input.as_llm_context("test"),
|
||||
user_llm_hass_api=None,
|
||||
user_llm_prompt=None,
|
||||
)
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent(agent_id="mock-agent-id", content="Hi")
|
||||
)
|
||||
|
||||
with async_get_chat_log(hass, session, mock_conversation_input) as chat_log:
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent(agent_id="mock-agent-id", content="Hi again")
|
||||
)
|
||||
|
||||
detail, turn = conversation_trace.as_dict()["events"]
|
||||
assert [message["role"] for message in detail["data"]["messages"]] == [
|
||||
"system",
|
||||
"user",
|
||||
]
|
||||
assert turn["event_type"] == ConversationTraceEventType.TURN_CONTENT
|
||||
assert [content["role"] for content in turn["data"]["content"]] == [
|
||||
"user",
|
||||
"assistant",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"layers",
|
||||
[
|
||||
pytest.param(["raises", "chat_log"], id="turn"),
|
||||
pytest.param(["raises", "chat_log", "chat_log"], id="nested_turn"),
|
||||
],
|
||||
)
|
||||
async def test_failed_turn_stored(
|
||||
hass: HomeAssistant, mock_conversation_input: ConversationInput, layers: list[str]
|
||||
) -> None:
|
||||
"""Test a failed turn stays in the history with its error once."""
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
ExitStack() as stack,
|
||||
):
|
||||
for layer in layers:
|
||||
stack.enter_context(
|
||||
pytest.raises(HomeAssistantError)
|
||||
if layer == "raises"
|
||||
else async_get_chat_log(hass, session, mock_conversation_input)
|
||||
)
|
||||
raise HomeAssistantError("Provider is down")
|
||||
|
||||
content = hass.data[DATA_CHAT_LOGS]["koala"].content
|
||||
assert [(item.role, item.content) for item in content] == [
|
||||
("system", ""),
|
||||
("user", "Hello"),
|
||||
("assistant", "Error: Provider is down"),
|
||||
]
|
||||
assert content[-1].agent_id == "mock-agent-id"
|
||||
|
||||
|
||||
@freeze_time("2025-10-31 12:00:00")
|
||||
async def test_failed_turn_tool_call_result(
|
||||
hass: HomeAssistant, mock_conversation_input: ConversationInput
|
||||
) -> None:
|
||||
"""Test a failed turn gets an error result for a tool call without one."""
|
||||
|
||||
async def failing_tool() -> llm.ToolResult:
|
||||
raise ValueError("Tool is broken")
|
||||
|
||||
async def run_turn() -> None:
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
):
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent(agent_id="mock-agent-id", content="Hi")
|
||||
await chat_log.async_provide_llm_data(
|
||||
mock_conversation_input.as_llm_context("test"),
|
||||
user_llm_hass_api="assist",
|
||||
)
|
||||
async for _ in chat_log.async_add_assistant_content(
|
||||
AssistantContent(
|
||||
agent_id="mock-agent-id",
|
||||
content=None,
|
||||
tool_calls=[
|
||||
llm.ToolInput(
|
||||
id="mock-tool-call-id", tool_name="test_tool", tool_args={}
|
||||
)
|
||||
],
|
||||
),
|
||||
tool_call_tasks={
|
||||
"mock-tool-call-id": hass.async_create_task(failing_tool())
|
||||
},
|
||||
):
|
||||
pass
|
||||
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
):
|
||||
# A new context runs the request like a separate task would.
|
||||
await asyncio.create_task(run_turn(), context=contextvars.Context())
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent(agent_id="mock-agent-id", content="Hello")
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
await run_turn()
|
||||
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + chat_session.CONVERSATION_TIMEOUT * 2,
|
||||
content = hass.data[DATA_CHAT_LOGS]["koala"].content
|
||||
assert content[-2] == ToolResultContent(
|
||||
agent_id="mock-agent-id",
|
||||
tool_call_id="mock-tool-call-id",
|
||||
tool_name="test_tool",
|
||||
result=llm.ToolResult(
|
||||
data={"error": "ValueError", "error_text": "Tool is broken"},
|
||||
error=True,
|
||||
),
|
||||
)
|
||||
assert content[-1].content == "Error: Tool is broken"
|
||||
|
||||
assert "koala" not in hass.data[DATA_CHAT_LOGS]
|
||||
assert "koala" not in hass.data[chat_session.DATA_CHAT_SESSION]
|
||||
|
||||
@freeze_time("2025-10-31 12:00:00")
|
||||
async def test_failed_turn_trigger_sentence_result(
|
||||
hass: HomeAssistant, mock_conversation_input: ConversationInput
|
||||
) -> None:
|
||||
"""Test a failed turn gets an error result for an open sentence trigger."""
|
||||
trigger_call = llm.ToolInput(
|
||||
tool_name="trigger_sentence", tool_args={}, external=True
|
||||
)
|
||||
provider_call = llm.ToolInput(tool_name="web_search", tool_args={}, external=True)
|
||||
|
||||
def run_turn() -> None:
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, "koala", context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
):
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent(
|
||||
agent_id="mock-agent-id",
|
||||
content=None,
|
||||
tool_calls=[trigger_call, provider_call],
|
||||
)
|
||||
)
|
||||
raise HomeAssistantError("Automation failed")
|
||||
|
||||
with pytest.raises(HomeAssistantError):
|
||||
run_turn()
|
||||
|
||||
content = hass.data[DATA_CHAT_LOGS]["koala"].content
|
||||
# The provider tool is left to the provider.
|
||||
assert content[-2] == ToolResultContent(
|
||||
agent_id="mock-agent-id",
|
||||
tool_call_id=trigger_call.id,
|
||||
tool_name="trigger_sentence",
|
||||
result=llm.ToolResult(
|
||||
data={"error": "HomeAssistantError", "error_text": "Automation failed"},
|
||||
error=True,
|
||||
),
|
||||
)
|
||||
assert content[-1].content == "Error: Automation failed"
|
||||
|
||||
|
||||
class AdminAPI(llm.API):
|
||||
|
||||
@@ -901,18 +901,6 @@ async def test_ws_chat_log_index_subscription(
|
||||
},
|
||||
}
|
||||
|
||||
# 2. The DELETED event (since no assistant message was added)
|
||||
msg = await client.receive_json()
|
||||
assert msg == {
|
||||
"type": "event",
|
||||
"id": event_id,
|
||||
"event": {
|
||||
"conversation_id": conversation_id,
|
||||
"event_type": "deleted",
|
||||
"data": {},
|
||||
},
|
||||
}
|
||||
|
||||
# Trigger session cleanup
|
||||
with patch(
|
||||
"homeassistant.helpers.chat_session.CONVERSATION_TIMEOUT",
|
||||
@@ -920,17 +908,13 @@ async def test_ws_chat_log_index_subscription(
|
||||
):
|
||||
async_fire_time_changed(hass, fire_all=True)
|
||||
|
||||
# 3. The DELETED event of before sub conversation
|
||||
msg = await client.receive_json()
|
||||
assert msg == {
|
||||
"type": "event",
|
||||
"id": event_id,
|
||||
"event": {
|
||||
"conversation_id": before_sub_conversation_id,
|
||||
"event_type": "deleted",
|
||||
"data": {},
|
||||
},
|
||||
}
|
||||
# 2. The DELETED events of both conversations
|
||||
deleted = set()
|
||||
for _ in range(2):
|
||||
msg = await client.receive_json()
|
||||
assert msg["event"]["event_type"] == "deleted"
|
||||
deleted.add(msg["event"]["conversation_id"])
|
||||
assert deleted == {before_sub_conversation_id, conversation_id}
|
||||
|
||||
|
||||
async def test_ws_chat_log_index_subscription_requires_admin(
|
||||
@@ -955,6 +939,50 @@ async def test_ws_chat_log_index_subscription_requires_admin(
|
||||
assert msg["error"]["code"] == "unauthorized"
|
||||
|
||||
|
||||
async def test_ws_chat_log_subscription_during_turn(
|
||||
hass: HomeAssistant,
|
||||
init_components,
|
||||
mock_conversation_input: ConversationInput,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
) -> None:
|
||||
"""Test subscribing to a chat log while a turn is in progress."""
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with (
|
||||
chat_session.async_get_chat_session(hass, context=None) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input) as chat_log,
|
||||
):
|
||||
conversation_id = session.conversation_id
|
||||
chat_log.async_add_assistant_content_without_tools(
|
||||
AssistantContent("test-agent-id", "I hear you")
|
||||
)
|
||||
|
||||
with (
|
||||
chat_session.async_get_chat_session(
|
||||
hass, conversation_id, context=None
|
||||
) as session,
|
||||
async_get_chat_log(hass, session, mock_conversation_input),
|
||||
):
|
||||
await client.send_json_auto_id(
|
||||
{
|
||||
"type": "conversation/chat_log/subscribe",
|
||||
"conversation_id": conversation_id,
|
||||
}
|
||||
)
|
||||
msg = await client.receive_json()
|
||||
assert msg["success"]
|
||||
|
||||
# The initial state includes the message of the open turn.
|
||||
msg = await client.receive_json()
|
||||
assert msg["event"]["event_type"] == "initial_state"
|
||||
assert [content["role"] for content in msg["event"]["data"]["content"]] == [
|
||||
"system",
|
||||
"user",
|
||||
"assistant",
|
||||
"user",
|
||||
]
|
||||
|
||||
|
||||
async def test_ws_chat_log_subscription(
|
||||
hass: HomeAssistant,
|
||||
init_components,
|
||||
|
||||
@@ -33,7 +33,7 @@ async def test_converation_trace(
|
||||
assert traces
|
||||
last_trace = traces[-1].as_dict()
|
||||
assert last_trace.get("events")
|
||||
assert len(last_trace.get("events")) == 2
|
||||
assert len(last_trace.get("events")) == 3
|
||||
trace_event = last_trace["events"][0]
|
||||
assert (
|
||||
trace_event.get("event_type") == trace.ConversationTraceEventType.ASYNC_PROCESS
|
||||
@@ -60,6 +60,17 @@ async def test_converation_trace(
|
||||
},
|
||||
}
|
||||
|
||||
trace_event = last_trace["events"][2]
|
||||
assert (
|
||||
trace_event.get("event_type") == trace.ConversationTraceEventType.TURN_CONTENT
|
||||
)
|
||||
assert [content["role"] for content in trace_event["data"]["content"]] == [
|
||||
"user",
|
||||
"assistant",
|
||||
"tool_result",
|
||||
"assistant",
|
||||
]
|
||||
|
||||
|
||||
async def test_converation_trace_uncaught_error(
|
||||
hass: HomeAssistant,
|
||||
|
||||
@@ -98,6 +98,7 @@ async def test_chat(
|
||||
assert [event["event_type"] for event in trace_events] == [
|
||||
trace.ConversationTraceEventType.ASYNC_PROCESS,
|
||||
trace.ConversationTraceEventType.AGENT_DETAIL,
|
||||
trace.ConversationTraceEventType.TURN_CONTENT,
|
||||
]
|
||||
# AGENT_DETAIL event contains the raw prompt passed to the model
|
||||
detail_event = trace_events[1]
|
||||
|
||||
Reference in New Issue
Block a user