|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import re |
| 5 | +from typing import Any, AsyncIterator, Iterator, Optional, Tuple, Union |
| 6 | + |
| 7 | +import httpx |
| 8 | +from httpx._types import AsyncByteStream, SyncByteStream |
| 9 | + |
| 10 | +from mistralai.client._hooks.types import AfterSuccessContext, AfterSuccessHook |
| 11 | +from mistralai.extra.workflows.errors import ( |
| 12 | + StreamDisconnectReason, |
| 13 | + StreamDisconnectedError, |
| 14 | +) |
| 15 | + |
| 16 | +# Operation IDs of the two SSE-backed workflow stream endpoints. |
| 17 | +STREAM_OPERATIONS = { |
| 18 | + "get_stream_events_v1_workflows_events_stream_get", |
| 19 | + "stream_v1_workflows_executions__execution_id__stream_get", |
| 20 | +} |
| 21 | + |
| 22 | +_ERROR_EVENT = "error" |
| 23 | +_VALID_REASONS = ("read_error", "stream_error", "internal_error") |
| 24 | +_DEFAULT_REASON: StreamDisconnectReason = "stream_error" |
| 25 | + |
| 26 | +# SSE frame boundaries (blank line), longest first so the full separator is consumed. |
| 27 | +_BOUNDARIES = [ |
| 28 | + b"\r\n\r\n", |
| 29 | + b"\r\n\r", |
| 30 | + b"\r\n\n", |
| 31 | + b"\r\r\n", |
| 32 | + b"\n\r\n", |
| 33 | + b"\r\r", |
| 34 | + b"\n\r", |
| 35 | + b"\n\n", |
| 36 | +] |
| 37 | + |
| 38 | + |
| 39 | +def _strip_content_encoding_header(headers: httpx.Headers) -> httpx.Headers: |
| 40 | + return httpx.Headers( |
| 41 | + [(k, v) for k, v in headers.items() if k.lower() != "content-encoding"] |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +def _find_boundary(buffer: bytearray) -> Optional[Tuple[int, int]]: |
| 46 | + """Return (index, length) of the earliest frame boundary, or None if incomplete.""" |
| 47 | + best: Optional[Tuple[int, int]] = None |
| 48 | + for boundary in _BOUNDARIES: |
| 49 | + idx = buffer.find(boundary) |
| 50 | + if idx == -1: |
| 51 | + continue |
| 52 | + if ( |
| 53 | + best is None |
| 54 | + or idx < best[0] |
| 55 | + or (idx == best[0] and len(boundary) > best[1]) |
| 56 | + ): |
| 57 | + best = (idx, len(boundary)) |
| 58 | + return best |
| 59 | + |
| 60 | + |
| 61 | +def _parse_error_payload(data: str) -> Tuple[str, StreamDisconnectReason]: |
| 62 | + payload: dict[str, Any] = {} |
| 63 | + try: |
| 64 | + parsed = json.loads(data.strip()) |
| 65 | + if isinstance(parsed, dict): |
| 66 | + payload = parsed |
| 67 | + except json.JSONDecodeError: |
| 68 | + pass |
| 69 | + error = str(payload.get("error", data.strip())) |
| 70 | + reason = payload.get("reason", _DEFAULT_REASON) |
| 71 | + if reason not in _VALID_REASONS: |
| 72 | + reason = _DEFAULT_REASON |
| 73 | + return error, reason |
| 74 | + |
| 75 | + |
| 76 | +def _raise_if_error_frame(block: bytes) -> None: |
| 77 | + """Raise StreamDisconnectedError if the SSE frame is an ``event: error`` frame.""" |
| 78 | + event_name: Optional[str] = None |
| 79 | + data = "" |
| 80 | + for line in re.split(r"\r?\n|\r", block.decode("utf-8", errors="replace")): |
| 81 | + if not line or line.startswith(":"): |
| 82 | + continue |
| 83 | + field, _, value = line.partition(":") |
| 84 | + if value.startswith(" "): |
| 85 | + value = value[1:] |
| 86 | + if field == "event": |
| 87 | + event_name = value |
| 88 | + elif field == "data": |
| 89 | + data += value + "\n" |
| 90 | + |
| 91 | + if event_name != _ERROR_EVENT: |
| 92 | + return |
| 93 | + |
| 94 | + error, reason = _parse_error_payload(data) |
| 95 | + raise StreamDisconnectedError(reason=reason, error=error) |
| 96 | + |
| 97 | + |
| 98 | +class _FrameScanner: |
| 99 | + """Buffers raw SSE bytes, raising on error frames and passing others through.""" |
| 100 | + |
| 101 | + def __init__(self) -> None: |
| 102 | + self._buffer = bytearray() |
| 103 | + |
| 104 | + def feed(self, chunk: bytes) -> Iterator[bytes]: |
| 105 | + self._buffer += chunk |
| 106 | + while True: |
| 107 | + found = _find_boundary(self._buffer) |
| 108 | + if found is None: |
| 109 | + return |
| 110 | + idx, length = found |
| 111 | + block = bytes(self._buffer[:idx]) |
| 112 | + frame = bytes(self._buffer[: idx + length]) |
| 113 | + del self._buffer[: idx + length] |
| 114 | + _raise_if_error_frame(block) |
| 115 | + yield frame |
| 116 | + |
| 117 | + def flush(self) -> Iterator[bytes]: |
| 118 | + if not self._buffer: |
| 119 | + return |
| 120 | + block = bytes(self._buffer) |
| 121 | + self._buffer.clear() |
| 122 | + _raise_if_error_frame(block) |
| 123 | + yield block |
| 124 | + |
| 125 | + |
| 126 | +class _ErrorDetectingSyncByteStream(SyncByteStream): |
| 127 | + def __init__(self, original: SyncByteStream) -> None: |
| 128 | + self._original = original |
| 129 | + self._scanner = _FrameScanner() |
| 130 | + |
| 131 | + def __iter__(self) -> Iterator[bytes]: |
| 132 | + for chunk in self._original: |
| 133 | + yield from self._scanner.feed(chunk) |
| 134 | + yield from self._scanner.flush() |
| 135 | + |
| 136 | + def close(self) -> None: |
| 137 | + self._original.close() |
| 138 | + |
| 139 | + |
| 140 | +class _ErrorDetectingAsyncByteStream(AsyncByteStream): |
| 141 | + def __init__(self, original: AsyncByteStream) -> None: |
| 142 | + self._original = original |
| 143 | + self._scanner = _FrameScanner() |
| 144 | + |
| 145 | + async def __aiter__(self) -> AsyncIterator[bytes]: |
| 146 | + async for chunk in self._original: |
| 147 | + for frame in self._scanner.feed(chunk): |
| 148 | + yield frame |
| 149 | + for frame in self._scanner.flush(): |
| 150 | + yield frame |
| 151 | + |
| 152 | + async def aclose(self) -> None: |
| 153 | + await self._original.aclose() |
| 154 | + |
| 155 | + |
| 156 | +class WorkflowStreamErrorHook(AfterSuccessHook): |
| 157 | + """Raise StreamDisconnectedError when a workflow SSE stream sends an error frame. |
| 158 | +
|
| 159 | + Wraps the response byte stream for the two workflow SSE operations so that an |
| 160 | + ``event: error`` frame raises during iteration, terminating the consumer's |
| 161 | + ``for event in stream`` loop instead of yielding the error as a normal event. |
| 162 | + """ |
| 163 | + |
| 164 | + def after_success( |
| 165 | + self, |
| 166 | + hook_ctx: AfterSuccessContext, |
| 167 | + response: httpx.Response, |
| 168 | + ) -> Union[httpx.Response, Exception]: |
| 169 | + if hook_ctx.operation_id not in STREAM_OPERATIONS: |
| 170 | + return response |
| 171 | + if "text/event-stream" not in response.headers.get("content-type", ""): |
| 172 | + return response |
| 173 | + |
| 174 | + stream = response.stream |
| 175 | + wrapped: Union[SyncByteStream, AsyncByteStream] |
| 176 | + if isinstance(stream, AsyncByteStream): |
| 177 | + wrapped = _ErrorDetectingAsyncByteStream(stream) |
| 178 | + elif isinstance(stream, SyncByteStream): |
| 179 | + wrapped = _ErrorDetectingSyncByteStream(stream) |
| 180 | + else: |
| 181 | + return response |
| 182 | + |
| 183 | + return httpx.Response( |
| 184 | + status_code=response.status_code, |
| 185 | + headers=_strip_content_encoding_header(response.headers), |
| 186 | + stream=wrapped, |
| 187 | + request=response.request, |
| 188 | + extensions=response.extensions, |
| 189 | + ) |
0 commit comments