| 1 |
"""Runtime stream event models for Cloud LLM Responses API. |
| 2 |
|
| 3 |
These classes model only a subset of stream events and not the full Responses API |
| 4 |
stream events. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
from dataclasses import dataclass, field |
| 10 |
from enum import StrEnum |
| 11 |
from typing import Any |
| 12 |
|
| 13 |
from .errors import LLMStreamEventParseError |
| 14 |
|
| 15 |
|
| 16 |
class ResponsesApiStreamEventType(StrEnum): |
| 17 |
"""Responses API stream event types used by Home Assistant.""" |
| 18 |
|
| 19 |
ERROR = "error" |
| 20 |
FUNCTION_CALL_ARGUMENTS_DELTA = "response.function_call_arguments.delta" |
| 21 |
FUNCTION_CALL_ARGUMENTS_DONE = "response.function_call_arguments.done" |
| 22 |
OUTPUT_ITEM_ADDED = "response.output_item.added" |
| 23 |
OUTPUT_ITEM_DONE = "response.output_item.done" |
| 24 |
OUTPUT_TEXT_DELTA = "response.output_text.delta" |
| 25 |
REASONING_SUMMARY_TEXT_DELTA = "response.reasoning_summary_text.delta" |
| 26 |
RESPONSE_COMPLETED = "response.completed" |
| 27 |
RESPONSE_FAILED = "response.failed" |
| 28 |
RESPONSE_INCOMPLETE = "response.incomplete" |
| 29 |
WEB_SEARCH_CALL_SEARCHING = "response.web_search_call.searching" |
| 30 |
|
| 31 |
|
| 32 |
class ResponseOutputItemType(StrEnum): |
| 33 |
"""Response output item types used by Home Assistant.""" |
| 34 |
|
| 35 |
FUNCTION_CALL = "function_call" |
| 36 |
IMAGE = "image" |
| 37 |
MESSAGE = "message" |
| 38 |
REASONING = "reasoning" |
| 39 |
WEB_SEARCH_CALL = "web_search_call" |
| 40 |
|
| 41 |
|
| 42 |
@dataclass(slots=True, frozen=True) |
| 43 |
class LLMResponseUnknownOutputItem: |
| 44 |
"""Fallback for output items Home Assistant does not model.""" |
| 45 |
|
| 46 |
type: str |
| 47 |
id: str |
| 48 |
raw: dict[str, Any] |
| 49 |
|
| 50 |
|
| 51 |
# The Responses API sends function calls in different events (DELTA and DONE). Not |
| 52 |
# freezing this class allows the caller to aggregate the delta and done events into a |
| 53 |
# single dataclass. |
| 54 |
@dataclass(slots=True) |
| 55 |
class LLMResponseFunctionCallOutputItem: |
| 56 |
"""Function call output item.""" |
| 57 |
|
| 58 |
type: ResponseOutputItemType |
| 59 |
id: str |
| 60 |
call_id: str |
| 61 |
name: str |
| 62 |
arguments: str = "" |
| 63 |
status: str | None = None |
| 64 |
|
| 65 |
|
| 66 |
@dataclass(slots=True, frozen=True) |
| 67 |
class LLMResponseMessageOutputItem: |
| 68 |
"""Message output item.""" |
| 69 |
|
| 70 |
type: ResponseOutputItemType |
| 71 |
id: str |
| 72 |
|
| 73 |
|
| 74 |
@dataclass(slots=True, frozen=True) |
| 75 |
class LLMResponseReasoningOutputItem: |
| 76 |
"""Reasoning output item.""" |
| 77 |
|
| 78 |
type: ResponseOutputItemType |
| 79 |
id: str |
| 80 |
encrypted_content: str | None = None |
| 81 |
summary: list[Any] = field(default_factory=list) |
| 82 |
|
| 83 |
|
| 84 |
@dataclass(slots=True, frozen=True) |
| 85 |
class LLMResponseWebSearchCallOutputItem: |
| 86 |
"""Web search call output item.""" |
| 87 |
|
| 88 |
type: ResponseOutputItemType |
| 89 |
id: str |
| 90 |
action: dict[str, Any] |
| 91 |
status: str | None = None |
| 92 |
|
| 93 |
|
| 94 |
@dataclass(slots=True, frozen=True) |
| 95 |
class LLMResponseImageOutputItem: |
| 96 |
"""Image output item.""" |
| 97 |
|
| 98 |
type: ResponseOutputItemType |
| 99 |
id: str |
| 100 |
raw: dict[str, Any] |
| 101 |
|
| 102 |
|
| 103 |
type ResponseOutputItem = ( |
| 104 |
LLMResponseFunctionCallOutputItem |
| 105 |
| LLMResponseMessageOutputItem |
| 106 |
| LLMResponseReasoningOutputItem |
| 107 |
| LLMResponseWebSearchCallOutputItem |
| 108 |
| LLMResponseImageOutputItem |
| 109 |
| LLMResponseUnknownOutputItem |
| 110 |
) |
| 111 |
|
| 112 |
|
| 113 |
@dataclass(slots=True, frozen=True) |
| 114 |
class LLMResponseOutputItemAddedEvent: |
| 115 |
"""Event emitted when an output item is added to the response.""" |
| 116 |
|
| 117 |
type: ResponsesApiStreamEventType |
| 118 |
item: ResponseOutputItem |
| 119 |
|
| 120 |
|
| 121 |
@dataclass(slots=True, frozen=True) |
| 122 |
class LLMResponseOutputItemDoneEvent: |
| 123 |
"""Event emitted when an output item is marked done.""" |
| 124 |
|
| 125 |
type: ResponsesApiStreamEventType |
| 126 |
item: ResponseOutputItem |
| 127 |
|
| 128 |
|
| 129 |
@dataclass(slots=True, frozen=True) |
| 130 |
class LLMResponseOutputTextDeltaEvent: |
| 131 |
"""Event carrying a delta chunk of assistant output text.""" |
| 132 |
|
| 133 |
type: ResponsesApiStreamEventType |
| 134 |
delta: str |
| 135 |
|
| 136 |
|
| 137 |
@dataclass(slots=True, frozen=True) |
| 138 |
class LLMResponseReasoningSummaryTextDeltaEvent: |
| 139 |
"""Event carrying a delta chunk of reasoning summary text.""" |
| 140 |
|
| 141 |
type: ResponsesApiStreamEventType |
| 142 |
delta: str |
| 143 |
summary_index: int |
| 144 |
|
| 145 |
|
| 146 |
@dataclass(slots=True, frozen=True) |
| 147 |
class LLMResponseFunctionCallArgumentsDeltaEvent: |
| 148 |
"""Event carrying a delta chunk of function call arguments.""" |
| 149 |
|
| 150 |
type: ResponsesApiStreamEventType |
| 151 |
delta: str |
| 152 |
|
| 153 |
|
| 154 |
@dataclass(slots=True, frozen=True) |
| 155 |
class LLMResponseFunctionCallArgumentsDoneEvent: |
| 156 |
"""Event emitted when function call arguments are complete.""" |
| 157 |
|
| 158 |
type: ResponsesApiStreamEventType |
| 159 |
arguments: str |
| 160 |
name: str | None |
| 161 |
item_id: str |
| 162 |
|
| 163 |
|
| 164 |
@dataclass(slots=True, frozen=True) |
| 165 |
class LLMResponseWebSearchCallSearchingEvent: |
| 166 |
"""Event emitted when a web search call starts searching.""" |
| 167 |
|
| 168 |
type: ResponsesApiStreamEventType |
| 169 |
item_id: str |
| 170 |
|
| 171 |
|
| 172 |
@dataclass(slots=True, frozen=True) |
| 173 |
class LLMResponseCompletedEvent: |
| 174 |
"""Event emitted when the overall response is completed.""" |
| 175 |
|
| 176 |
type: ResponsesApiStreamEventType |
| 177 |
response: dict[str, Any] |
| 178 |
|
| 179 |
|
| 180 |
@dataclass(slots=True, frozen=True) |
| 181 |
class LLMResponseIncompleteEvent: |
| 182 |
"""Event emitted when the response is incomplete.""" |
| 183 |
|
| 184 |
type: ResponsesApiStreamEventType |
| 185 |
response: dict[str, Any] |
| 186 |
|
| 187 |
|
| 188 |
@dataclass(slots=True, frozen=True) |
| 189 |
class LLMResponseFailedEvent: |
| 190 |
"""Event emitted when the response has failed.""" |
| 191 |
|
| 192 |
type: ResponsesApiStreamEventType |
| 193 |
response: dict[str, Any] |
| 194 |
|
| 195 |
|
| 196 |
@dataclass(slots=True, frozen=True) |
| 197 |
class LLMResponseErrorEvent: |
| 198 |
"""Error event emitted by the streaming API.""" |
| 199 |
|
| 200 |
type: ResponsesApiStreamEventType |
| 201 |
message: str |
| 202 |
|
| 203 |
|
| 204 |
@dataclass(slots=True, frozen=True) |
| 205 |
class LLMResponseUnhandledEvent: |
| 206 |
"""Fallback for stream events Home Assistant does not model.""" |
| 207 |
|
| 208 |
type: str |
| 209 |
raw: dict[str, Any] |
| 210 |
|
| 211 |
|
| 212 |
type ResponsesApiStreamEvent = ( |
| 213 |
LLMResponseOutputItemAddedEvent |
| 214 |
| LLMResponseOutputItemDoneEvent |
| 215 |
| LLMResponseOutputTextDeltaEvent |
| 216 |
| LLMResponseReasoningSummaryTextDeltaEvent |
| 217 |
| LLMResponseFunctionCallArgumentsDeltaEvent |
| 218 |
| LLMResponseFunctionCallArgumentsDoneEvent |
| 219 |
| LLMResponseWebSearchCallSearchingEvent |
| 220 |
| LLMResponseCompletedEvent |
| 221 |
| LLMResponseIncompleteEvent |
| 222 |
| LLMResponseFailedEvent |
| 223 |
| LLMResponseErrorEvent |
| 224 |
| LLMResponseUnhandledEvent |
| 225 |
) |
| 226 |
|
| 227 |
|
| 228 |
def _parse_output_item(item: dict[str, Any]) -> ResponseOutputItem: |
| 229 |
"""Parse a response output item dict into a typed output item.""" |
| 230 |
item_type = item.get("type") |
| 231 |
if not isinstance(item_type, str): |
| 232 |
raise LLMStreamEventParseError("Missing or invalid output item 'type'") |
| 233 |
item_id = item.get("id") |
| 234 |
if not isinstance(item_id, str): |
| 235 |
return LLMResponseUnknownOutputItem(type=item_type, id="", raw=item) |
| 236 |
|
| 237 |
match item_type: |
| 238 |
case ResponseOutputItemType.FUNCTION_CALL: |
| 239 |
call_id = item.get("call_id") |
| 240 |
if not isinstance(call_id, str): |
| 241 |
raise LLMStreamEventParseError( |
| 242 |
"Missing or invalid function call 'call_id'" |
| 243 |
) |
| 244 |
name = item.get("name") |
| 245 |
if not isinstance(name, str): |
| 246 |
raise LLMStreamEventParseError( |
| 247 |
"Missing or invalid function call 'name'" |
| 248 |
) |
| 249 |
arguments = item.get("arguments", "") |
| 250 |
if not isinstance(arguments, str): |
| 251 |
raise LLMStreamEventParseError("Invalid function call 'arguments'") |
| 252 |
status = item.get("status") |
| 253 |
if status is not None and not isinstance(status, str): |
| 254 |
raise LLMStreamEventParseError("Invalid function call 'status'") |
| 255 |
return LLMResponseFunctionCallOutputItem( |
| 256 |
type=ResponseOutputItemType.FUNCTION_CALL, |
| 257 |
id=item_id, |
| 258 |
call_id=call_id, |
| 259 |
name=name, |
| 260 |
arguments=arguments, |
| 261 |
status=status, |
| 262 |
) |
| 263 |
case ResponseOutputItemType.MESSAGE: |
| 264 |
return LLMResponseMessageOutputItem( |
| 265 |
type=ResponseOutputItemType.MESSAGE, |
| 266 |
id=item_id, |
| 267 |
) |
| 268 |
case ResponseOutputItemType.REASONING: |
| 269 |
encrypted_content = item.get("encrypted_content") |
| 270 |
if encrypted_content is not None and not isinstance(encrypted_content, str): |
| 271 |
raise LLMStreamEventParseError("Invalid reasoning 'encrypted_content'") |
| 272 |
summary = item.get("summary", []) |
| 273 |
if not isinstance(summary, list): |
| 274 |
raise LLMStreamEventParseError("Invalid reasoning 'summary'") |
| 275 |
return LLMResponseReasoningOutputItem( |
| 276 |
type=ResponseOutputItemType.REASONING, |
| 277 |
id=item_id, |
| 278 |
encrypted_content=encrypted_content, |
| 279 |
summary=summary, |
| 280 |
) |
| 281 |
case ResponseOutputItemType.WEB_SEARCH_CALL: |
| 282 |
action = item.get("action", {}) |
| 283 |
if not isinstance(action, dict): |
| 284 |
raise LLMStreamEventParseError("Invalid web search call 'action'") |
| 285 |
if (status := item.get("status")) is not None and not isinstance( |
| 286 |
status, str |
| 287 |
): |
| 288 |
raise LLMStreamEventParseError("Invalid web search call 'status'") |
| 289 |
return LLMResponseWebSearchCallOutputItem( |
| 290 |
type=ResponseOutputItemType.WEB_SEARCH_CALL, |
| 291 |
id=item_id, |
| 292 |
action=action, |
| 293 |
status=status, |
| 294 |
) |
| 295 |
case ResponseOutputItemType.IMAGE: |
| 296 |
return LLMResponseImageOutputItem( |
| 297 |
type=ResponseOutputItemType.IMAGE, |
| 298 |
id=item_id, |
| 299 |
raw=item, |
| 300 |
) |
| 301 |
case _: |
| 302 |
# Preserve unknown item types so consumers can ignore them. |
| 303 |
return LLMResponseUnknownOutputItem(type=item_type, id=item_id, raw=item) |
| 304 |
|
| 305 |
|
| 306 |
def _parse_item_event( |
| 307 |
payload: dict[str, Any], |
| 308 |
*, |
| 309 |
event_type: ResponsesApiStreamEventType, |
| 310 |
) -> LLMResponseOutputItemAddedEvent | LLMResponseOutputItemDoneEvent: |
| 311 |
item = payload.get("item") |
| 312 |
if not isinstance(item, dict): |
| 313 |
raise LLMStreamEventParseError("Missing or invalid 'item'") |
| 314 |
parsed_item = _parse_output_item(item) |
| 315 |
|
| 316 |
if event_type is ResponsesApiStreamEventType.OUTPUT_ITEM_ADDED: |
| 317 |
return LLMResponseOutputItemAddedEvent(type=event_type, item=parsed_item) |
| 318 |
return LLMResponseOutputItemDoneEvent(type=event_type, item=parsed_item) |
| 319 |
|
| 320 |
|
| 321 |
def _parse_delta_event( |
| 322 |
payload: dict[str, Any], |
| 323 |
*, |
| 324 |
event_type: ResponsesApiStreamEventType, |
| 325 |
) -> ( |
| 326 |
LLMResponseOutputTextDeltaEvent |
| 327 |
| LLMResponseReasoningSummaryTextDeltaEvent |
| 328 |
| LLMResponseFunctionCallArgumentsDeltaEvent |
| 329 |
): |
| 330 |
delta = payload.get("delta") |
| 331 |
if not isinstance(delta, str): |
| 332 |
raise LLMStreamEventParseError("Missing or invalid 'delta'") |
| 333 |
|
| 334 |
if event_type is ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA: |
| 335 |
return LLMResponseOutputTextDeltaEvent(type=event_type, delta=delta) |
| 336 |
|
| 337 |
if event_type is ResponsesApiStreamEventType.FUNCTION_CALL_ARGUMENTS_DELTA: |
| 338 |
return LLMResponseFunctionCallArgumentsDeltaEvent(type=event_type, delta=delta) |
| 339 |
|
| 340 |
summary_index = payload.get("summary_index") |
| 341 |
if not isinstance(summary_index, int): |
| 342 |
raise LLMStreamEventParseError("Missing or invalid 'summary_index'") |
| 343 |
return LLMResponseReasoningSummaryTextDeltaEvent( |
| 344 |
type=event_type, |
| 345 |
delta=delta, |
| 346 |
summary_index=summary_index, |
| 347 |
) |
| 348 |
|
| 349 |
|
| 350 |
def _parse_function_call_arguments_done_event( |
| 351 |
payload: dict[str, Any], |
| 352 |
) -> LLMResponseFunctionCallArgumentsDoneEvent: |
| 353 |
arguments = payload.get("arguments") |
| 354 |
name = payload.get("name") |
| 355 |
item_id = payload.get("item_id") |
| 356 |
if not isinstance(arguments, str): |
| 357 |
raise LLMStreamEventParseError("Missing or invalid 'arguments'") |
| 358 |
if name is not None and not isinstance(name, str): |
| 359 |
raise LLMStreamEventParseError("Invalid 'name'") |
| 360 |
if not isinstance(item_id, str): |
| 361 |
raise LLMStreamEventParseError("Missing or invalid 'item_id'") |
| 362 |
return LLMResponseFunctionCallArgumentsDoneEvent( |
| 363 |
type=ResponsesApiStreamEventType.FUNCTION_CALL_ARGUMENTS_DONE, |
| 364 |
arguments=arguments, |
| 365 |
name=name if isinstance(name, str) else None, |
| 366 |
item_id=item_id, |
| 367 |
) |
| 368 |
|
| 369 |
|
| 370 |
def _parse_web_search_call_searching_event( |
| 371 |
payload: dict[str, Any], |
| 372 |
) -> LLMResponseWebSearchCallSearchingEvent: |
| 373 |
item_id = payload.get("item_id") |
| 374 |
if not isinstance(item_id, str): |
| 375 |
raise LLMStreamEventParseError("Missing or invalid 'item_id'") |
| 376 |
return LLMResponseWebSearchCallSearchingEvent( |
| 377 |
type=ResponsesApiStreamEventType.WEB_SEARCH_CALL_SEARCHING, |
| 378 |
item_id=item_id, |
| 379 |
) |
| 380 |
|
| 381 |
|
| 382 |
def _parse_completion_event( |
| 383 |
payload: dict[str, Any], |
| 384 |
*, |
| 385 |
event_type: ResponsesApiStreamEventType, |
| 386 |
) -> LLMResponseCompletedEvent | LLMResponseIncompleteEvent | LLMResponseFailedEvent: |
| 387 |
response = payload.get("response") |
| 388 |
if not isinstance(response, dict): |
| 389 |
raise LLMStreamEventParseError("Missing or invalid 'response'") |
| 390 |
|
| 391 |
if event_type is ResponsesApiStreamEventType.RESPONSE_COMPLETED: |
| 392 |
return LLMResponseCompletedEvent(type=event_type, response=response) |
| 393 |
if event_type is ResponsesApiStreamEventType.RESPONSE_INCOMPLETE: |
| 394 |
return LLMResponseIncompleteEvent(type=event_type, response=response) |
| 395 |
return LLMResponseFailedEvent(type=event_type, response=response) |
| 396 |
|
| 397 |
|
| 398 |
def _parse_error_event(payload: dict[str, Any]) -> LLMResponseErrorEvent: |
| 399 |
message = payload.get("message") |
| 400 |
if not isinstance(message, str): |
| 401 |
raise LLMStreamEventParseError("Missing or invalid 'message'") |
| 402 |
return LLMResponseErrorEvent( |
| 403 |
type=ResponsesApiStreamEventType.ERROR, |
| 404 |
message=message, |
| 405 |
) |
| 406 |
|
| 407 |
|
| 408 |
def parse_response_stream_event(payload: dict[str, Any]) -> ResponsesApiStreamEvent: |
| 409 |
"""Parse a SSE JSON payload into a typed stream event. |
| 410 |
|
| 411 |
Raises LLMStreamEventParseError if the payload does not match a supported |
| 412 |
event type/shape. |
| 413 |
""" |
| 414 |
event_type = payload.get("type") |
| 415 |
if not isinstance(event_type, str): |
| 416 |
raise LLMStreamEventParseError("Missing or invalid 'type'") |
| 417 |
|
| 418 |
if event_type == ResponsesApiStreamEventType.OUTPUT_ITEM_ADDED.value: |
| 419 |
result: ResponsesApiStreamEvent = _parse_item_event( |
| 420 |
payload, |
| 421 |
event_type=ResponsesApiStreamEventType.OUTPUT_ITEM_ADDED, |
| 422 |
) |
| 423 |
elif event_type == ResponsesApiStreamEventType.OUTPUT_ITEM_DONE.value: |
| 424 |
result = _parse_item_event( |
| 425 |
payload, |
| 426 |
event_type=ResponsesApiStreamEventType.OUTPUT_ITEM_DONE, |
| 427 |
) |
| 428 |
elif event_type in { |
| 429 |
ResponsesApiStreamEventType.OUTPUT_TEXT_DELTA.value, |
| 430 |
ResponsesApiStreamEventType.REASONING_SUMMARY_TEXT_DELTA.value, |
| 431 |
ResponsesApiStreamEventType.FUNCTION_CALL_ARGUMENTS_DELTA.value, |
| 432 |
}: |
| 433 |
try: |
| 434 |
event_enum = ResponsesApiStreamEventType(event_type) |
| 435 |
except ValueError as err: |
| 436 |
raise LLMStreamEventParseError("Unsupported event 'type'") from err |
| 437 |
result = _parse_delta_event(payload, event_type=event_enum) |
| 438 |
elif event_type == ResponsesApiStreamEventType.FUNCTION_CALL_ARGUMENTS_DONE.value: |
| 439 |
result = _parse_function_call_arguments_done_event(payload) |
| 440 |
elif event_type == ResponsesApiStreamEventType.WEB_SEARCH_CALL_SEARCHING.value: |
| 441 |
result = _parse_web_search_call_searching_event(payload) |
| 442 |
elif event_type in { |
| 443 |
ResponsesApiStreamEventType.RESPONSE_COMPLETED.value, |
| 444 |
ResponsesApiStreamEventType.RESPONSE_INCOMPLETE.value, |
| 445 |
ResponsesApiStreamEventType.RESPONSE_FAILED.value, |
| 446 |
}: |
| 447 |
try: |
| 448 |
event_enum = ResponsesApiStreamEventType(event_type) |
| 449 |
except ValueError as err: |
| 450 |
raise LLMStreamEventParseError("Unsupported event 'type'") from err |
| 451 |
result = _parse_completion_event(payload, event_type=event_enum) |
| 452 |
elif event_type == ResponsesApiStreamEventType.ERROR.value: |
| 453 |
result = _parse_error_event(payload) |
| 454 |
else: |
| 455 |
result = LLMResponseUnhandledEvent(type=event_type, raw=payload) |
| 456 |
|
| 457 |
return result |