| 1 |
"""LLM handler.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import base64 |
| 7 |
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable |
| 8 |
from contextlib import suppress |
| 9 |
from dataclasses import dataclass |
| 10 |
from datetime import datetime, timedelta |
| 11 |
from functools import wraps |
| 12 |
import io |
| 13 |
import json |
| 14 |
import logging |
| 15 |
from typing import ( |
| 16 |
TYPE_CHECKING, |
| 17 |
Any, |
| 18 |
Literal, |
| 19 |
ParamSpec, |
| 20 |
TypedDict, |
| 21 |
TypeVar, |
| 22 |
cast, |
| 23 |
) |
| 24 |
|
| 25 |
from aiohttp import ( |
| 26 |
ClientResponse, |
| 27 |
ClientResponseError, |
| 28 |
ClientTimeout, |
| 29 |
ContentTypeError, |
| 30 |
FormData, |
| 31 |
) |
| 32 |
|
| 33 |
from ..api import ApiBase, CloudApiError, api_exception_handler |
| 34 |
from ..exceptions import NabuCasaNotLoggedInError |
| 35 |
from ..utils import utc_from_timestamp, utcnow |
| 36 |
from .errors import ( |
| 37 |
LLMAuthenticationError, |
| 38 |
LLMError, |
| 39 |
LLMRateLimitError, |
| 40 |
LLMRequestError, |
| 41 |
LLMResponseError, |
| 42 |
LLMServiceError, |
| 43 |
) |
| 44 |
from .stream_events import ( |
| 45 |
LLMStreamEventParseError, |
| 46 |
ResponsesApiStreamEvent, |
| 47 |
parse_response_stream_event, |
| 48 |
) |
| 49 |
|
| 50 |
if TYPE_CHECKING: |
| 51 |
from .. import Cloud, _ClientT |
| 52 |
|
| 53 |
|
| 54 |
_LOGGER = logging.getLogger(__name__) |
| 55 |
|
| 56 |
ResponsesAPIResponse = dict[str, Any] |
| 57 |
ResponseInputParam = dict[str, Any] | list[Any] |
| 58 |
ToolParam = dict[str, Any] |
| 59 |
ToolChoice = Literal["auto", "none"] | dict[str, Any] |
| 60 |
|
| 61 |
|
| 62 |
class LLMConnectionDetails(TypedDict): |
| 63 |
"""LLM connection details from LLM API.""" |
| 64 |
|
| 65 |
token: str |
| 66 |
valid_until: int |
| 67 |
base_url: str |
| 68 |
generate_data_model: str |
| 69 |
generate_image_model: str |
| 70 |
conversation_model: str |
| 71 |
|
| 72 |
|
| 73 |
class LLMGeneratedData(TypedDict): |
| 74 |
"""LLM data generation response.""" |
| 75 |
|
| 76 |
content: str |
| 77 |
role: Literal["assistant", "user"] | None |
| 78 |
|
| 79 |
|
| 80 |
class LLMGeneratedImage(TypedDict): |
| 81 |
"""Normalized LLM image generation response.""" |
| 82 |
|
| 83 |
mime_type: str |
| 84 |
image_data: bytes |
| 85 |
model: str | None |
| 86 |
width: int | None |
| 87 |
height: int | None |
| 88 |
revised_prompt: str | None |
| 89 |
|
| 90 |
|
| 91 |
class LLMImageAttachment(TypedDict): |
| 92 |
"""Image attachment for editing requests.""" |
| 93 |
|
| 94 |
filename: str | None |
| 95 |
mime_type: str | None |
| 96 |
data: bytes |
| 97 |
|
| 98 |
|
| 99 |
IMAGE_MIME_TYPE = "image/png" |
| 100 |
TOKEN_EXP_BUFFER_MINUTES = timedelta(minutes=5) |
| 101 |
RESPONSES_API_TIMEOUT = 30.0 |
| 102 |
IMAGE_API_TIMEOUT = 120.0 |
| 103 |
|
| 104 |
|
| 105 |
@dataclass |
| 106 |
class _ServerSentEvent: |
| 107 |
"""Minimal Server-Sent Event container.""" |
| 108 |
|
| 109 |
event: str | None = None |
| 110 |
data: str = "" |
| 111 |
id: str | None = None |
| 112 |
retry: int | None = None |
| 113 |
|
| 114 |
|
| 115 |
type JSONPrimitive = str | int | float | bool | None |
| 116 |
|
| 117 |
|
| 118 |
P = ParamSpec("P") |
| 119 |
R = TypeVar("R") |
| 120 |
|
| 121 |
|
| 122 |
class _SSEDecoder: |
| 123 |
"""Decode Server-Sent Events (SSE) lines into events. |
| 124 |
|
| 125 |
Based on the WHATWG SSE spec. |
| 126 |
""" |
| 127 |
|
| 128 |
def __init__(self) -> None: |
| 129 |
self._event: str | None = None |
| 130 |
self._data: list[str] = [] |
| 131 |
self._last_event_id: str | None = None |
| 132 |
self._retry: int | None = None |
| 133 |
|
| 134 |
def decode(self, line: str) -> _ServerSentEvent | None: |
| 135 |
"""Feed a single decoded line (without trailing newline). |
| 136 |
|
| 137 |
Returns an event when a blank line indicates the end of an SSE event. |
| 138 |
See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation |
| 139 |
""" |
| 140 |
# Blank line terminates the current event |
| 141 |
if not line: |
| 142 |
if ( |
| 143 |
not self._event |
| 144 |
and not self._data |
| 145 |
and not self._last_event_id |
| 146 |
and self._retry is None |
| 147 |
): |
| 148 |
return None |
| 149 |
|
| 150 |
sse = _ServerSentEvent( |
| 151 |
event=self._event, |
| 152 |
data="\n".join(self._data), |
| 153 |
id=self._last_event_id, |
| 154 |
retry=self._retry, |
| 155 |
) |
| 156 |
|
| 157 |
# NOTE: as per the SSE spec, do not reset last_event_id. |
| 158 |
self._event = None |
| 159 |
self._data = [] |
| 160 |
self._retry = None |
| 161 |
return sse |
| 162 |
|
| 163 |
# Comment line |
| 164 |
if line.startswith(":"): |
| 165 |
return None |
| 166 |
|
| 167 |
fieldname, _, value = line.partition(":") |
| 168 |
value = value.removeprefix(" ") |
| 169 |
|
| 170 |
if fieldname == "event": |
| 171 |
self._event = value |
| 172 |
elif fieldname == "data": |
| 173 |
self._data.append(value) |
| 174 |
elif fieldname == "id": |
| 175 |
if "\0" not in value: |
| 176 |
self._last_event_id = value |
| 177 |
elif fieldname == "retry": |
| 178 |
with suppress(TypeError, ValueError): |
| 179 |
self._retry = int(value) |
| 180 |
|
| 181 |
return None |
| 182 |
|
| 183 |
|
| 184 |
def llm_http_exception_handler( |
| 185 |
func: Callable[P, Awaitable[R]], |
| 186 |
) -> Callable[P, Awaitable[R]]: |
| 187 |
"""Convert HTTP/client errors into LLM-specific exceptions.""" |
| 188 |
|
| 189 |
@wraps(func) |
| 190 |
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: |
| 191 |
try: |
| 192 |
return await func(*args, **kwargs) |
| 193 |
except LLMRequestError: |
| 194 |
raise |
| 195 |
except ClientResponseError as err: |
| 196 |
if err.status == 401: |
| 197 |
raise LLMAuthenticationError("Cloud LLM authentication failed") from err |
| 198 |
if err.status == 429: |
| 199 |
raise LLMRateLimitError("Cloud LLM is rate limited") from err |
| 200 |
raise LLMServiceError("Couldn't process Cloud LLM response") from err |
| 201 |
except CloudApiError as err: |
| 202 |
raise LLMServiceError("Error talking to Cloud LLM") from err |
| 203 |
except Exception as err: |
| 204 |
raise LLMServiceError("Unknown error talking to Cloud LLM") from err |
| 205 |
|
| 206 |
return wrapper |
| 207 |
|
| 208 |
|
| 209 |
async def stream_llm_response_events( |
| 210 |
response: ClientResponse, |
| 211 |
) -> AsyncIterator[ResponsesApiStreamEvent]: |
| 212 |
"""Yield response events from the Cloud LLM stream.""" |
| 213 |
try: |
| 214 |
decoder = _SSEDecoder() |
| 215 |
while True: |
| 216 |
line_bytes = await response.content.readline() |
| 217 |
if not line_bytes: |
| 218 |
break |
| 219 |
line = line_bytes.decode("utf-8").rstrip("\r\n") |
| 220 |
if (sse := decoder.decode(line)) is None: |
| 221 |
continue |
| 222 |
|
| 223 |
if not (data := sse.data): |
| 224 |
# Allow keepalive/empty events |
| 225 |
continue |
| 226 |
|
| 227 |
if data.startswith("[DONE]"): |
| 228 |
break |
| 229 |
|
| 230 |
try: |
| 231 |
payload = json.loads(data) |
| 232 |
except json.JSONDecodeError as err: |
| 233 |
raise LLMResponseError( |
| 234 |
"There was an error processing the Cloud LLM response" |
| 235 |
) from err |
| 236 |
if not isinstance(payload, dict): |
| 237 |
raise LLMResponseError("Unexpected event from Cloud LLM stream") |
| 238 |
try: |
| 239 |
yield parse_response_stream_event(payload) |
| 240 |
except LLMStreamEventParseError as err: |
| 241 |
raise LLMResponseError( |
| 242 |
"Unexpected event from Cloud LLM stream" |
| 243 |
) from err |
| 244 |
finally: |
| 245 |
response.release() |
| 246 |
|
| 247 |
|
| 248 |
class LLMHandler(ApiBase): |
| 249 |
"""Class to handle LLM services.""" |
| 250 |
|
| 251 |
def __init__(self, cloud: Cloud[_ClientT]) -> None: |
| 252 |
"""Initialize LLM services.""" |
| 253 |
super().__init__(cloud) |
| 254 |
self._token: str | None = None |
| 255 |
self._base_url: str | None = None |
| 256 |
self._models: dict[str, str | None] = {} |
| 257 |
self._valid_until: datetime | None = None |
| 258 |
self._lock = asyncio.Lock() |
| 259 |
|
| 260 |
def _validate_token(self) -> bool: |
| 261 |
"""Validate token outside of coroutine.""" |
| 262 |
# Check subscription and token expiry with buffer |
| 263 |
return self._cloud.valid_subscription and bool( |
| 264 |
self._valid_until |
| 265 |
and utcnow() + TOKEN_EXP_BUFFER_MINUTES < self._valid_until |
| 266 |
) |
| 267 |
|
| 268 |
@api_exception_handler(LLMAuthenticationError) |
| 269 |
async def _get_connection_details(self) -> LLMConnectionDetails: |
| 270 |
details: LLMConnectionDetails = await self._call_cloud_api( |
| 271 |
action="llm_connection_details", |
| 272 |
) |
| 273 |
return details |
| 274 |
|
| 275 |
@api_exception_handler(LLMServiceError) |
| 276 |
async def _async_fetch_image_from_url(self, url: str) -> bytes: |
| 277 |
"""Fetch image data from a URL asynchronously.""" |
| 278 |
async with self._cloud.websession.get(url) as response: |
| 279 |
response.raise_for_status() |
| 280 |
return await response.read() |
| 281 |
|
| 282 |
async def _update_connection_details(self) -> None: |
| 283 |
"""Update connection details.""" |
| 284 |
if not self._cloud.valid_subscription: |
| 285 |
raise LLMAuthenticationError("Invalid subscription") |
| 286 |
|
| 287 |
details: LLMConnectionDetails = await self._get_connection_details() |
| 288 |
|
| 289 |
self._token = details["token"] |
| 290 |
self._valid_until = utc_from_timestamp(float(details["valid_until"])) |
| 291 |
self._base_url = details["base_url"] |
| 292 |
self._models = { |
| 293 |
"generate_data": details["generate_data_model"], |
| 294 |
"generate_image": details["generate_image_model"], |
| 295 |
"conversation": details["conversation_model"], |
| 296 |
} |
| 297 |
|
| 298 |
async def async_ensure_token(self) -> None: |
| 299 |
"""Ensure the LLM token is valid and available.""" |
| 300 |
async with self._lock: |
| 301 |
if not self._cloud.is_logged_in: |
| 302 |
raise NabuCasaNotLoggedInError("User is not logged in") |
| 303 |
|
| 304 |
if not self._validate_token(): |
| 305 |
await self._update_connection_details() |
| 306 |
|
| 307 |
if not self._token or not self._base_url: |
| 308 |
raise LLMError("Cloud LLM connection details are unavailable") |
| 309 |
|
| 310 |
@llm_http_exception_handler |
| 311 |
async def _call_llm_api( |
| 312 |
self, |
| 313 |
endpoint: str, |
| 314 |
*, |
| 315 |
method: str = "POST", |
| 316 |
accept: str = "application/json", |
| 317 |
content_type: str | None = None, |
| 318 |
payload: dict[str, Any] | None = None, |
| 319 |
data: Any | None = None, |
| 320 |
include_path_in_log: bool = False, |
| 321 |
api_timeout: float = RESPONSES_API_TIMEOUT, |
| 322 |
) -> ClientResponse: |
| 323 |
"""Call the Cloud LLM API and ensure errors are handled uniformly.""" |
| 324 |
if TYPE_CHECKING: |
| 325 |
assert self._base_url is not None |
| 326 |
|
| 327 |
await self.async_ensure_token() |
| 328 |
|
| 329 |
url = f"{self._base_url.rstrip('/')}/{endpoint.lstrip('/')}" |
| 330 |
headers: dict[str, str] = { |
| 331 |
"Authorization": f"Bearer {self._token}", |
| 332 |
"Accept": accept, |
| 333 |
**({"Content-Type": content_type} if content_type is not None else {}), |
| 334 |
} |
| 335 |
|
| 336 |
response = await self._call_raw_api( |
| 337 |
method=method, |
| 338 |
url=url, |
| 339 |
headers=headers, |
| 340 |
jsondata=payload, |
| 341 |
data=data, |
| 342 |
client_timeout=ClientTimeout(total=api_timeout), |
| 343 |
include_path_in_log=include_path_in_log, |
| 344 |
) |
| 345 |
|
| 346 |
if response.status >= 400: |
| 347 |
response.raise_for_status() |
| 348 |
|
| 349 |
return response |
| 350 |
|
| 351 |
async def _get_response( |
| 352 |
self, |
| 353 |
response: ClientResponse, |
| 354 |
) -> dict[str, Any]: |
| 355 |
"""Parse a JSON response from the Cloud LLM API.""" |
| 356 |
try: |
| 357 |
data = cast("dict[str, Any]", await response.json()) |
| 358 |
except (ContentTypeError, json.JSONDecodeError) as err: |
| 359 |
raise LLMResponseError("Invalid JSON response from Cloud LLM") from err |
| 360 |
|
| 361 |
return data |
| 362 |
|
| 363 |
def _build_responses_payload( |
| 364 |
self, |
| 365 |
*, |
| 366 |
model: str, |
| 367 |
messages: str | ResponseInputParam, |
| 368 |
conversation_id: str, |
| 369 |
response_format: dict[str, Any] | None, |
| 370 |
stream: bool, |
| 371 |
tools: Iterable[ToolParam] | None, |
| 372 |
tool_choice: ToolChoice | None, |
| 373 |
) -> dict[str, Any]: |
| 374 |
"""Build the payload for the Responses API.""" |
| 375 |
payload: dict[str, Any] = { |
| 376 |
"model": model, |
| 377 |
"input": messages, |
| 378 |
"stream": stream, |
| 379 |
"conversation": conversation_id, |
| 380 |
} |
| 381 |
if response_format is not None: |
| 382 |
payload["response_format"] = response_format |
| 383 |
if tools is not None: |
| 384 |
payload["tools"] = list(tools) |
| 385 |
if tool_choice is not None: |
| 386 |
payload["tool_choice"] = tool_choice |
| 387 |
return payload |
| 388 |
|
| 389 |
@llm_http_exception_handler |
| 390 |
async def _responses_api_call( |
| 391 |
self, |
| 392 |
payload: dict[str, Any], |
| 393 |
*, |
| 394 |
stream: bool, |
| 395 |
) -> ResponsesAPIResponse | AsyncIterator[ResponsesApiStreamEvent]: |
| 396 |
"""Call the Responses API via HTTP.""" |
| 397 |
accept = "text/event-stream" if stream else "application/json" |
| 398 |
response = await self._call_llm_api( |
| 399 |
"responses", |
| 400 |
accept=accept, |
| 401 |
content_type="application/json", |
| 402 |
payload=payload, |
| 403 |
api_timeout=RESPONSES_API_TIMEOUT, |
| 404 |
) |
| 405 |
|
| 406 |
if not stream: |
| 407 |
return await self._get_response(response) |
| 408 |
|
| 409 |
return cast( |
| 410 |
"ResponsesAPIResponse | AsyncIterator[ResponsesApiStreamEvent]", |
| 411 |
stream_llm_response_events(response), |
| 412 |
) |
| 413 |
|
| 414 |
async def _extract_response_image_data( |
| 415 |
self, |
| 416 |
response: dict[str, Any], |
| 417 |
) -> LLMGeneratedImage: |
| 418 |
data = response.get("data") |
| 419 |
if not (data and isinstance(data, list) and len(data) > 0): |
| 420 |
raise LLMResponseError("Unexpected response from Cloud LLM") |
| 421 |
|
| 422 |
item = data[0] |
| 423 |
|
| 424 |
if not (b64 := item.get("b64_json")) and (url := item.get("url")) is not None: |
| 425 |
image_bytes = await self._async_fetch_image_from_url(url) |
| 426 |
b64 = base64.b64encode(image_bytes).decode("utf-8") |
| 427 |
|
| 428 |
if not b64: |
| 429 |
raise LLMResponseError( |
| 430 |
"Image generation response contains neither url nor b64_json" |
| 431 |
) |
| 432 |
|
| 433 |
return LLMGeneratedImage( |
| 434 |
mime_type=IMAGE_MIME_TYPE, |
| 435 |
model=response.get("model"), |
| 436 |
image_data=base64.b64decode(b64), |
| 437 |
width=item.get("width"), |
| 438 |
height=item.get("height"), |
| 439 |
revised_prompt=item.get("revised_prompt"), |
| 440 |
) |
| 441 |
|
| 442 |
async def async_generate_data( |
| 443 |
self, |
| 444 |
*, |
| 445 |
messages: str | ResponseInputParam, |
| 446 |
conversation_id: str, |
| 447 |
response_format: dict[str, Any] | None = None, |
| 448 |
stream: bool = False, |
| 449 |
tools: Iterable[ToolParam] | None = None, |
| 450 |
tool_choice: ToolChoice | None = None, |
| 451 |
) -> ResponsesAPIResponse | AsyncIterator[ResponsesApiStreamEvent]: |
| 452 |
"""Generate structured or free-form LLM data.""" |
| 453 |
if TYPE_CHECKING: |
| 454 |
assert self._models["generate_data"] is not None |
| 455 |
|
| 456 |
payload = self._build_responses_payload( |
| 457 |
model=self._models["generate_data"], |
| 458 |
messages=messages, |
| 459 |
conversation_id=conversation_id, |
| 460 |
response_format=response_format, |
| 461 |
stream=stream, |
| 462 |
tools=tools, |
| 463 |
tool_choice=tool_choice, |
| 464 |
) |
| 465 |
|
| 466 |
return await self._responses_api_call( |
| 467 |
payload, |
| 468 |
stream=stream, |
| 469 |
) |
| 470 |
|
| 471 |
async def async_generate_image( |
| 472 |
self, |
| 473 |
*, |
| 474 |
prompt: str, |
| 475 |
) -> LLMGeneratedImage: |
| 476 |
"""Generate an image via Cloud LLM.""" |
| 477 |
if TYPE_CHECKING: |
| 478 |
assert self._models["generate_image"] is not None |
| 479 |
|
| 480 |
payload = { |
| 481 |
"prompt": prompt, |
| 482 |
"model": self._models["generate_image"], |
| 483 |
} |
| 484 |
|
| 485 |
response = await self._call_llm_api( |
| 486 |
"images/generations", |
| 487 |
payload=payload, |
| 488 |
content_type="application/json", |
| 489 |
api_timeout=IMAGE_API_TIMEOUT, |
| 490 |
) |
| 491 |
data = await self._get_response(response) |
| 492 |
|
| 493 |
return await self._extract_response_image_data(data) |
| 494 |
|
| 495 |
async def async_edit_image( |
| 496 |
self, |
| 497 |
*, |
| 498 |
prompt: str, |
| 499 |
attachments: list[LLMImageAttachment], |
| 500 |
) -> LLMGeneratedImage: |
| 501 |
"""Edit an image via Cloud LLM.""" |
| 502 |
if TYPE_CHECKING: |
| 503 |
assert self._models["generate_image"] is not None |
| 504 |
|
| 505 |
file_buffers: list[tuple[io.BytesIO, str | None]] = [] |
| 506 |
for idx, attachment in enumerate(attachments): |
| 507 |
buffer = io.BytesIO(attachment["data"]) |
| 508 |
buffer.name = attachment["filename"] or f"attachment_{idx}" |
| 509 |
file_buffers.append((buffer, attachment["mime_type"])) |
| 510 |
|
| 511 |
if not file_buffers: |
| 512 |
raise LLMRequestError("No attachments provided for LLM image editing") |
| 513 |
|
| 514 |
image_buffers = ( |
| 515 |
file_buffers |
| 516 |
if len(file_buffers) == 1 |
| 517 |
# HA doesn't support masks, so we can ignore it here at file_buffers[1] |
| 518 |
else [file_buffers[0], *file_buffers[2:]] |
| 519 |
) |
| 520 |
|
| 521 |
form = FormData() |
| 522 |
for key, value in { |
| 523 |
"prompt": prompt, |
| 524 |
"model": self._models["generate_image"], |
| 525 |
}.items(): |
| 526 |
form.add_field(key, str(value)) |
| 527 |
|
| 528 |
for image_buffer, mime_type in image_buffers: |
| 529 |
image_buffer.seek(0) |
| 530 |
form.add_field( |
| 531 |
"image", |
| 532 |
image_buffer, |
| 533 |
filename=getattr(image_buffer, "name", "image.png"), |
| 534 |
content_type=mime_type or IMAGE_MIME_TYPE, |
| 535 |
) |
| 536 |
|
| 537 |
response = await self._call_llm_api( |
| 538 |
"images/edits", |
| 539 |
data=form, |
| 540 |
api_timeout=IMAGE_API_TIMEOUT, |
| 541 |
) |
| 542 |
result = await self._get_response(response) |
| 543 |
|
| 544 |
return await self._extract_response_image_data(result) |
| 545 |
|
| 546 |
async def async_process_conversation( |
| 547 |
self, |
| 548 |
*, |
| 549 |
messages: str | ResponseInputParam, |
| 550 |
conversation_id: str, |
| 551 |
response_format: dict[str, Any] | None = None, |
| 552 |
stream: bool = False, |
| 553 |
tools: Iterable[ToolParam] | None = None, |
| 554 |
tool_choice: ToolChoice | None = None, |
| 555 |
) -> ResponsesAPIResponse | AsyncIterator[ResponsesApiStreamEvent]: |
| 556 |
"""Generate a response for a conversation.""" |
| 557 |
if TYPE_CHECKING: |
| 558 |
assert self._models["conversation"] is not None |
| 559 |
payload = self._build_responses_payload( |
| 560 |
model=self._models["conversation"], |
| 561 |
messages=messages, |
| 562 |
conversation_id=conversation_id, |
| 563 |
response_format=response_format, |
| 564 |
stream=stream, |
| 565 |
tools=tools, |
| 566 |
tool_choice=tool_choice, |
| 567 |
) |
| 568 |
|
| 569 |
return await self._responses_api_call( |
| 570 |
payload, |
| 571 |
stream=stream, |
| 572 |
) |