| 1 |
"""Unit tests for hass_nabucasa.llm.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
from collections.abc import AsyncIterator |
| 7 |
from types import SimpleNamespace |
| 8 |
from typing import TYPE_CHECKING, cast |
| 9 |
from unittest.mock import AsyncMock, MagicMock, patch |
| 10 |
|
| 11 |
import pytest |
| 12 |
|
| 13 |
from hass_nabucasa.exceptions import NabuCasaNotLoggedInError |
| 14 |
from hass_nabucasa.llm import ( |
| 15 |
LLMAuthenticationError, |
| 16 |
LLMImageAttachment, |
| 17 |
LLMRateLimitError, |
| 18 |
LLMRequestError, |
| 19 |
LLMResponseError, |
| 20 |
LLMServiceError, |
| 21 |
) |
| 22 |
from hass_nabucasa.llm.handler import ToolChoice, ToolParam, stream_llm_response_events |
| 23 |
from hass_nabucasa.llm.stream_events import ( |
| 24 |
LLMResponseOutputTextDeltaEvent, |
| 25 |
ResponsesApiStreamEvent, |
| 26 |
ResponsesApiStreamEventType, |
| 27 |
) |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from hass_nabucasa import Cloud |
| 31 |
|
| 32 |
from .utils.aiohttp import AiohttpClientMocker |
| 33 |
|
| 34 |
|
| 35 |
class _FakeStream: |
| 36 |
"""Simple async stream for simulating SSE responses.""" |
| 37 |
|
| 38 |
def __init__(self, lines: list[str]) -> None: |
| 39 |
self._lines = [line.encode("utf-8") for line in lines] |
| 40 |
|
| 41 |
async def readline(self) -> bytes: |
| 42 |
if not self._lines: |
| 43 |
await asyncio.sleep(0) |
| 44 |
return b"" |
| 45 |
return self._lines.pop(0) |
| 46 |
|
| 47 |
|
| 48 |
class _FakeResponse: |
| 49 |
"""Simplified ClientResponse for SSE tests.""" |
| 50 |
|
| 51 |
def __init__(self, lines: list[str]) -> None: |
| 52 |
self.status = 200 |
| 53 |
self.content = _FakeStream(lines) |
| 54 |
self._released = False |
| 55 |
|
| 56 |
def release(self) -> None: |
| 57 |
"""Mark the response as released.""" |
| 58 |
self._released = True |
| 59 |
|
| 60 |
@property |
| 61 |
def released(self) -> bool: |
| 62 |
"""Return True when release() was called.""" |
| 63 |
return self._released |
| 64 |
|
| 65 |
|
| 66 |
@pytest.fixture(autouse=True) |
| 67 |
def mock_llm_connection_details(aioclient_mock: AiohttpClientMocker) -> None: |
| 68 |
"""Mock the initial LLM connection details fetch.""" |
| 69 |
aioclient_mock.get( |
| 70 |
"https://api.example.com/llm/connection_details", |
| 71 |
json={ |
| 72 |
"token": "token", |
| 73 |
"valid_until": 9999999999, |
| 74 |
"base_url": "https://api.example", |
| 75 |
"generate_data_model": "responses-model", |
| 76 |
"generate_image_model": "image-model", |
| 77 |
"conversation_model": "conv-model", |
| 78 |
}, |
| 79 |
) |
| 80 |
|
| 81 |
|
| 82 |
async def test_async_ensure_token_skips_when_not_logged_in(cloud: Cloud) -> None: |
| 83 |
"""Ensure async_ensure_token exits early when the user is not logged in.""" |
| 84 |
cloud.id_token = None |
| 85 |
|
| 86 |
with pytest.raises(NabuCasaNotLoggedInError, match="User is not logged in"): |
| 87 |
await cloud.llm.async_ensure_token() |
| 88 |
|
| 89 |
|
| 90 |
async def test_async_generate_data_returns_response(cloud: Cloud) -> None: |
| 91 |
"""async_generate_data should call the Responses API with expected payload.""" |
| 92 |
await cloud.llm.async_ensure_token() |
| 93 |
messages = [{"role": "user", "content": "Hello"}] |
| 94 |
expected = {"output": [{"content": [{"type": "output_text", "text": "Hi"}]}]} |
| 95 |
fake_response = SimpleNamespace() |
| 96 |
mock_call = AsyncMock(return_value=fake_response) |
| 97 |
mock_get_response = AsyncMock(return_value=expected) |
| 98 |
|
| 99 |
with ( |
| 100 |
patch.object(cloud.llm, "_call_llm_api", mock_call), |
| 101 |
patch.object(cloud.llm, "_get_response", mock_get_response), |
| 102 |
): |
| 103 |
result = await cloud.llm.async_generate_data( |
| 104 |
messages=messages, |
| 105 |
conversation_id="conversation-id", |
| 106 |
response_format={"type": "json_object"}, |
| 107 |
) |
| 108 |
|
| 109 |
assert result == expected |
| 110 |
mock_get_response.assert_awaited_once_with(fake_response) |
| 111 |
assert mock_call.await_args is not None |
| 112 |
call_payload = mock_call.await_args.kwargs["payload"] |
| 113 |
assert call_payload["model"] == "responses-model" |
| 114 |
assert call_payload["input"] == messages |
| 115 |
assert call_payload["conversation"] == "conversation-id" |
| 116 |
assert call_payload["response_format"] == {"type": "json_object"} |
| 117 |
assert call_payload["stream"] is False |
| 118 |
|
| 119 |
|
| 120 |
async def test_async_generate_data_streams_when_requested(cloud: Cloud) -> None: |
| 121 |
"""async_generate_data should return a streaming iterator when stream=True.""" |
| 122 |
await cloud.llm.async_ensure_token() |
| 123 |
fake_response = _FakeResponse( |
| 124 |
lines=[ |
| 125 |
'data: {"type":"response.output_text.delta","delta":"hello"}\n', |
| 126 |
"\n", |
| 127 |
"data: [DONE]\n", |
| 128 |
"\n", |
| 129 |
] |
| 130 |
) |
| 131 |
mock_call = AsyncMock(return_value=fake_response) |
| 132 |
|
| 133 |
with patch.object(cloud.llm, "_call_llm_api", mock_call): |
| 134 |
iterator = await cloud.llm.async_generate_data( |
| 135 |
messages=[], |
| 136 |
conversation_id="conv-stream", |
| 137 |
stream=True, |
| 138 |
) |
| 139 |
|
| 140 |
events = [ |
| 141 |
event |
| 142 |
async for event in cast( |
| 143 |
"AsyncIterator[ResponsesApiStreamEvent]", |
| 144 |
iterator, |
| 145 |
) |
| 146 |
] |
| 147 |
|
| 148 |
assert len(events) == 1 |
| 149 |
assert isinstance(events[0], LLMResponseOutputTextDeltaEvent) |
| 150 |
assert events[0].type == ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA |
| 151 |
assert events[0].delta == "hello" |
| 152 |
assert fake_response.released |
| 153 |
assert mock_call.await_args is not None |
| 154 |
payload = mock_call.await_args.kwargs["payload"] |
| 155 |
assert payload["stream"] is True |
| 156 |
assert payload["model"] == "responses-model" |
| 157 |
|
| 158 |
|
| 159 |
@pytest.mark.parametrize( |
| 160 |
("status", "expected"), |
| 161 |
[ |
| 162 |
(401, LLMAuthenticationError), |
| 163 |
(429, LLMRateLimitError), |
| 164 |
(500, LLMServiceError), |
| 165 |
], |
| 166 |
) |
| 167 |
async def test_async_generate_data_maps_http_errors( |
| 168 |
status: int, |
| 169 |
expected: type[Exception], |
| 170 |
cloud: Cloud, |
| 171 |
aioclient_mock: AiohttpClientMocker, |
| 172 |
) -> None: |
| 173 |
"""async_generate_data should translate HTTP errors to LLM errors.""" |
| 174 |
await cloud.llm.async_ensure_token() |
| 175 |
aioclient_mock.post("https://api.example/responses", status=status, text="err") |
| 176 |
|
| 177 |
with pytest.raises(expected): |
| 178 |
await cloud.llm.async_generate_data(messages=[], conversation_id="conv") |
| 179 |
|
| 180 |
|
| 181 |
async def test_async_generate_image_posts_payload(cloud: Cloud) -> None: |
| 182 |
"""async_generate_image should call the image generation endpoint.""" |
| 183 |
await cloud.llm.async_ensure_token() |
| 184 |
fake_response = SimpleNamespace() |
| 185 |
mock_call = AsyncMock(return_value=fake_response) |
| 186 |
mock_get_response = AsyncMock(return_value={"data": []}) |
| 187 |
mock_extract = AsyncMock(return_value="normalized-image") |
| 188 |
|
| 189 |
with ( |
| 190 |
patch.object(cloud.llm, "_call_llm_api", mock_call), |
| 191 |
patch.object(cloud.llm, "_get_response", mock_get_response), |
| 192 |
patch.object(cloud.llm, "_extract_response_image_data", mock_extract), |
| 193 |
): |
| 194 |
result = await cloud.llm.async_generate_image(prompt="draw a cat") |
| 195 |
|
| 196 |
assert result == "normalized-image" |
| 197 |
payload = mock_call.await_args.kwargs["payload"] |
| 198 |
assert payload == {"prompt": "draw a cat", "model": "image-model"} |
| 199 |
mock_get_response.assert_awaited_once_with(fake_response) |
| 200 |
mock_extract.assert_awaited_once_with({"data": []}) |
| 201 |
|
| 202 |
|
| 203 |
@pytest.mark.parametrize( |
| 204 |
("status", "expected"), |
| 205 |
[ |
| 206 |
(401, LLMAuthenticationError), |
| 207 |
(429, LLMRateLimitError), |
| 208 |
(500, LLMServiceError), |
| 209 |
], |
| 210 |
) |
| 211 |
async def test_async_generate_image_maps_http_errors( |
| 212 |
status: int, |
| 213 |
expected: type[Exception], |
| 214 |
cloud: Cloud, |
| 215 |
aioclient_mock: AiohttpClientMocker, |
| 216 |
) -> None: |
| 217 |
"""async_generate_image should translate HTTP failures.""" |
| 218 |
await cloud.llm.async_ensure_token() |
| 219 |
aioclient_mock.post("https://api.example/images/generations", status=status) |
| 220 |
|
| 221 |
with pytest.raises(expected): |
| 222 |
await cloud.llm.async_generate_image(prompt="draw anything") |
| 223 |
|
| 224 |
|
| 225 |
async def test_async_edit_image_builds_file_payloads(cloud: Cloud) -> None: |
| 226 |
"""async_edit_image should convert attachments into multipart payloads.""" |
| 227 |
await cloud.llm.async_ensure_token() |
| 228 |
|
| 229 |
attachments: list[LLMImageAttachment] = [ |
| 230 |
{"filename": "base.png", "mime_type": "image/png", "data": b"base-bytes"}, |
| 231 |
] |
| 232 |
|
| 233 |
mock_response = SimpleNamespace() |
| 234 |
mock_call = AsyncMock(return_value=mock_response) |
| 235 |
mock_get_response = AsyncMock(return_value={"data": []}) |
| 236 |
mock_extract = AsyncMock(return_value="image-bytes") |
| 237 |
form_mock = MagicMock() |
| 238 |
|
| 239 |
with ( |
| 240 |
patch("hass_nabucasa.llm.handler.FormData", return_value=form_mock), |
| 241 |
patch.object(cloud.llm, "_call_llm_api", mock_call), |
| 242 |
patch.object(cloud.llm, "_get_response", mock_get_response), |
| 243 |
patch.object(cloud.llm, "_extract_response_image_data", mock_extract), |
| 244 |
): |
| 245 |
result = await cloud.llm.async_edit_image( |
| 246 |
prompt="enhance", |
| 247 |
attachments=attachments, |
| 248 |
) |
| 249 |
|
| 250 |
assert result == "image-bytes" |
| 251 |
mock_call.assert_awaited_once() |
| 252 |
assert mock_call.await_args.kwargs["data"] is form_mock |
| 253 |
prompt_calls = [ |
| 254 |
entry |
| 255 |
for entry in form_mock.add_field.mock_calls |
| 256 |
if entry.args[0] in {"prompt", "model"} |
| 257 |
] |
| 258 |
assert prompt_calls[0].args == ("prompt", "enhance") |
| 259 |
assert prompt_calls[1].args == ("model", "image-model") |
| 260 |
|
| 261 |
image_calls = [ |
| 262 |
entry for entry in form_mock.add_field.mock_calls if entry.args[0] == "image" |
| 263 |
] |
| 264 |
image = image_calls[0] |
| 265 |
assert image.kwargs["filename"] == "base.png" |
| 266 |
assert image.kwargs["content_type"] == "image/png" |
| 267 |
assert image.args[1].getvalue() == b"base-bytes" |
| 268 |
|
| 269 |
|
| 270 |
async def test_async_edit_image_requires_attachment(cloud: Cloud) -> None: |
| 271 |
"""async_edit_image should raise when no attachments are provided.""" |
| 272 |
await cloud.llm.async_ensure_token() |
| 273 |
|
| 274 |
with pytest.raises(LLMRequestError, match="No attachments provided"): |
| 275 |
await cloud.llm.async_edit_image(prompt="prompt", attachments=[]) |
| 276 |
|
| 277 |
|
| 278 |
async def test_async_process_conversation_returns_response(cloud: Cloud) -> None: |
| 279 |
"""async_process_conversation should call Responses API using conversation model.""" |
| 280 |
await cloud.llm.async_ensure_token() |
| 281 |
fake_response = SimpleNamespace() |
| 282 |
mock_call = AsyncMock(return_value=fake_response) |
| 283 |
mock_get_response = AsyncMock(return_value={"output": []}) |
| 284 |
|
| 285 |
tools: list[ToolParam] = [ |
| 286 |
{"type": "function", "function": {"name": "do_something"}}, |
| 287 |
] |
| 288 |
tool_choice: ToolChoice = { |
| 289 |
"type": "function", |
| 290 |
"function": {"name": "do_something"}, |
| 291 |
} |
| 292 |
|
| 293 |
payload = [{"role": "user", "content": "Hi"}] |
| 294 |
with ( |
| 295 |
patch.object(cloud.llm, "_call_llm_api", mock_call), |
| 296 |
patch.object(cloud.llm, "_get_response", mock_get_response), |
| 297 |
): |
| 298 |
result = await cloud.llm.async_process_conversation( |
| 299 |
messages=payload, |
| 300 |
conversation_id="abc", |
| 301 |
response_format={"type": "json_schema"}, |
| 302 |
tools=tools, |
| 303 |
tool_choice=tool_choice, |
| 304 |
) |
| 305 |
|
| 306 |
assert result == {"output": []} |
| 307 |
payload = mock_call.await_args.kwargs["payload"] |
| 308 |
assert payload["model"] == "conv-model" |
| 309 |
assert payload["tools"] == tools |
| 310 |
assert payload["tool_choice"] == tool_choice |
| 311 |
assert payload["response_format"] == {"type": "json_schema"} |
| 312 |
|
| 313 |
|
| 314 |
@pytest.mark.parametrize( |
| 315 |
("status", "expected"), |
| 316 |
[ |
| 317 |
(401, LLMAuthenticationError), |
| 318 |
(429, LLMRateLimitError), |
| 319 |
(500, LLMServiceError), |
| 320 |
], |
| 321 |
) |
| 322 |
async def test_async_process_conversation_maps_http_errors( |
| 323 |
status: int, |
| 324 |
expected: type[Exception], |
| 325 |
cloud: Cloud, |
| 326 |
aioclient_mock: AiohttpClientMocker, |
| 327 |
) -> None: |
| 328 |
"""async_process_conversation should translate HTTP errors.""" |
| 329 |
await cloud.llm.async_ensure_token() |
| 330 |
aioclient_mock.post("https://api.example/responses", status=status) |
| 331 |
|
| 332 |
with pytest.raises(expected): |
| 333 |
await cloud.llm.async_process_conversation(messages=[], conversation_id="conv") |
| 334 |
|
| 335 |
|
| 336 |
async def test_stream_llm_response_events_parses_lines() -> None: |
| 337 |
"""stream_llm_response_events should emit valid events.""" |
| 338 |
fake_response = _FakeResponse( |
| 339 |
[ |
| 340 |
'data: {"type":"response.output_text.delta","delta":"foo"}\n', |
| 341 |
"\n", |
| 342 |
'data: {"type":"response.output_text.delta","delta":"bar"}\n', |
| 343 |
"\n", |
| 344 |
"data: [DONE]\n", |
| 345 |
"\n", |
| 346 |
] |
| 347 |
) |
| 348 |
|
| 349 |
events = [ |
| 350 |
event |
| 351 |
async for event in cast( |
| 352 |
"AsyncIterator[ResponsesApiStreamEvent]", |
| 353 |
stream_llm_response_events(fake_response), |
| 354 |
) |
| 355 |
] |
| 356 |
|
| 357 |
assert len(events) == 2 |
| 358 |
assert isinstance(events[0], LLMResponseOutputTextDeltaEvent) |
| 359 |
assert events[0].type == ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA |
| 360 |
assert events[0].delta == "foo" |
| 361 |
assert isinstance(events[1], LLMResponseOutputTextDeltaEvent) |
| 362 |
assert events[1].type == ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA |
| 363 |
assert events[1].delta == "bar" |
| 364 |
assert fake_response.released |
| 365 |
|
| 366 |
|
| 367 |
async def test_stream_llm_response_events_ignores_empty_events() -> None: |
| 368 |
"""stream_llm_response_events should ignore empty (keepalive) SSE events.""" |
| 369 |
fake_response = _FakeResponse( |
| 370 |
[ |
| 371 |
"data:\n", |
| 372 |
"\n", |
| 373 |
'data: {"type":"response.output_text.delta","delta":"ok"}\n', |
| 374 |
"\n", |
| 375 |
"data: [DONE]\n", |
| 376 |
"\n", |
| 377 |
] |
| 378 |
) |
| 379 |
|
| 380 |
events = [ |
| 381 |
event |
| 382 |
async for event in cast( |
| 383 |
"AsyncIterator[ResponsesApiStreamEvent]", |
| 384 |
stream_llm_response_events(fake_response), |
| 385 |
) |
| 386 |
] |
| 387 |
|
| 388 |
assert len(events) == 1 |
| 389 |
assert isinstance(events[0], LLMResponseOutputTextDeltaEvent) |
| 390 |
assert events[0].type == ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA |
| 391 |
assert events[0].delta == "ok" |
| 392 |
assert fake_response.released |
| 393 |
|
| 394 |
|
| 395 |
async def test_stream_llm_response_events_raises_on_invalid_json() -> None: |
| 396 |
"""stream_llm_response_events should raise on invalid JSON. |
| 397 |
|
| 398 |
This avoids returning silently truncated output. |
| 399 |
""" |
| 400 |
fake_response = _FakeResponse( |
| 401 |
[ |
| 402 |
'data: {"type":"response.output_text.delta","delta":"hello"}\n', |
| 403 |
"\n", |
| 404 |
"data: not-json\n", |
| 405 |
"\n", |
| 406 |
] |
| 407 |
) |
| 408 |
|
| 409 |
iterator = cast( |
| 410 |
"AsyncIterator[ResponsesApiStreamEvent]", |
| 411 |
stream_llm_response_events(fake_response), |
| 412 |
) |
| 413 |
|
| 414 |
first_event = await anext(iterator) |
| 415 |
assert isinstance(first_event, LLMResponseOutputTextDeltaEvent) |
| 416 |
assert first_event.type == ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA |
| 417 |
assert first_event.delta == "hello" |
| 418 |
with pytest.raises( |
| 419 |
LLMResponseError, match="There was an error processing the Cloud LLM response" |
| 420 |
): |
| 421 |
await anext(iterator) |
| 422 |
assert fake_response.released |