iq-stream-haystack 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,487 @@
1
+ """``IQStream``: a context manager around one Haystack run that publishes its ``StreamingChunk`` objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import contextvars
8
+ import inspect
9
+ import logging
10
+ import math
11
+ import re
12
+ import threading
13
+ from collections.abc import Awaitable, Callable, Iterable, Mapping
14
+ from types import TracebackType
15
+ from typing import TYPE_CHECKING, Literal, overload
16
+
17
+ from ag_ui.core import BaseEvent
18
+ from haystack.dataclasses import StreamingChunk
19
+ from iq_stream import FrameTooLarge, IQClient, IQError, Outcome, PublisherLike, PublishResult, Ticket
20
+
21
+ from .converters import AGUIConverter, AISDKConverter, ChunkConverter, ConverterOptions, Frame, NativeConverter
22
+ from .converters.agui import encode_event
23
+ from .converters.base import dumps, source_key
24
+
25
+ if TYPE_CHECKING:
26
+ from typing_extensions import Self
27
+
28
+ logger = logging.getLogger("haystack_integrations.iq_stream")
29
+
30
+ ProtocolName = Literal["ag-ui", "ai-sdk", "haystack"]
31
+
32
+ _STREAM_ID = re.compile(r"[A-Za-z0-9_-]{16,128}")
33
+ _ACTIVE: contextvars.ContextVar[IQStream | None] = contextvars.ContextVar("iq_stream_haystack", default=None)
34
+
35
+
36
+ def current_stream() -> IQStream | None:
37
+ """The ``IQStream`` whose block is active in this context (thread, task, or a tool thread Haystack started from
38
+ it), or ``None``."""
39
+ return _ACTIVE.get()
40
+
41
+
42
+ class IQStream:
43
+ """Publishes one Haystack run to an IQ-Stream server.
44
+
45
+ Create it where the run happens and enter it around the run; hand Haystack ``callback`` (for ``run()``) or
46
+ ``acallback`` (for ``run_async()``) as the ``streaming_callback``, and save the run's result inside the block::
47
+
48
+ with IQStream(iq, stream_id) as stream:
49
+ result = agent.run(messages, streaming_callback=stream.callback)
50
+ save(result["messages"]) # before the close line
51
+
52
+ Entering opens the publisher and sends the protocol's start event. Leaving sends the protocol's final event and
53
+ closes the stream with ``end``, or with ``fail`` when the block raised; a cancelled run closes with
54
+ ``close_on_cancel``. The run's exception goes on unchanged.
55
+
56
+ Publishing never breaks the run. A chunk that cannot be converted, or a frame of the application's own that
57
+ cannot be encoded or is too large, is skipped and reported to ``on_dropped`` (else logged once per kind), and the
58
+ stream goes on. When the publisher gives up (the core's ``IQError``) or fails, publishing stops, ``on_dropped``
59
+ hears of it once, the stream closes with ``fail``, and the run is read to its end. With a client opened with
60
+ ``on_error="raise"``, leaving the block then raises the publisher's ``IQError``, unless the block raised already.
61
+
62
+ ``client`` is an ``IQClient``, whose publisher the block opens, or a synchronous publisher that is already open
63
+ (``iq_stream.PublisherLike``, such as the testing kit's ``RecordingPublisher``). Creating the object opens
64
+ nothing, so the process that hands out the ticket may create one to learn the stream id, and the worker that
65
+ runs the agent another with the same id.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ client: IQClient | PublisherLike,
71
+ stream_id: str | None = None,
72
+ *,
73
+ protocol: ProtocolName | ChunkConverter = "ag-ui",
74
+ thread_id: str | None = None,
75
+ run_id: str | None = None,
76
+ include_tool_results: bool = True,
77
+ max_tool_result_bytes: int = 32_768,
78
+ expose_errors: bool = False,
79
+ close_on_cancel: Outcome = "fail",
80
+ close_timeout: float = 10.0,
81
+ on_dropped: Callable[[IQError], object] | None = None,
82
+ ) -> None:
83
+ if isinstance(client, IQClient):
84
+ self._client: IQClient | None = client
85
+ self._given: PublisherLike | None = None
86
+ stream_id = client.new_stream_id() if stream_id is None else stream_id
87
+ else:
88
+ if inspect.iscoroutinefunction(getattr(client, "close", None)):
89
+ # Haystack calls back from worker threads, where an asyncio publisher cannot be used.
90
+ raise TypeError(
91
+ "IQStream takes a synchronous publisher: client.publisher(), or RecordingPublisher in tests."
92
+ )
93
+ self._client = None
94
+ self._given = client
95
+ if stream_id is not None and stream_id != client.stream_id:
96
+ raise ValueError("stream_id differs from the publisher's.")
97
+ stream_id = client.stream_id
98
+ if not isinstance(stream_id, str) or not _STREAM_ID.fullmatch(stream_id): # pyright: ignore[reportUnnecessaryIsInstance]
99
+ raise ValueError("stream_id must be 16 to 128 characters of A-Z a-z 0-9 _ -")
100
+ if isinstance(protocol, str) and protocol not in ("ag-ui", "ai-sdk", "haystack"):
101
+ raise ValueError("protocol must be 'ag-ui', 'ai-sdk', 'haystack' or a ChunkConverter.")
102
+ if close_on_cancel not in ("end", "fail"):
103
+ raise ValueError("close_on_cancel must be 'end' or 'fail'.")
104
+ if max_tool_result_bytes < 1:
105
+ raise ValueError("max_tool_result_bytes must be at least 1.")
106
+ if (
107
+ isinstance(close_timeout, bool)
108
+ or not isinstance(close_timeout, int | float) # pyright: ignore[reportUnnecessaryIsInstance]
109
+ or not math.isfinite(close_timeout)
110
+ or close_timeout <= 0
111
+ ):
112
+ # 0 would not wait for the server's answer at all: every stream would end failed with close_timeout.
113
+ raise ValueError("close_timeout must be a finite number of seconds above 0.")
114
+ self._stream_id = stream_id
115
+ self._protocol = protocol
116
+ self._thread_id = thread_id or stream_id
117
+ self._run_id = run_id or stream_id
118
+ self._include_tool_results = include_tool_results
119
+ self._max_tool_result_bytes = max_tool_result_bytes
120
+ self._expose_errors = expose_errors
121
+ self._close_on_cancel: Outcome = close_on_cancel
122
+ self._close_timeout = close_timeout
123
+ self._on_dropped = on_dropped
124
+
125
+ # Haystack calls back from tool threads and from asyncio.to_thread workers: one lock orders every frame.
126
+ self._lock = threading.Lock()
127
+ self._state: Literal["new", "open", "closing", "closed"] = "new"
128
+ self._publisher: PublisherLike | None = None
129
+ self._converter: ChunkConverter | None = None
130
+ self._stopped: IQError | None = None # why publishing stopped on this side
131
+ self._heard = False # on_dropped was told that the publisher gave up
132
+ self._logged: set[str] = set()
133
+ self._token: contextvars.Token[IQStream | None] | None = None
134
+ self._result: PublishResult | None = None
135
+
136
+ # -- what the application reads --------------------------------------------------------------------------------
137
+
138
+ @property
139
+ def stream_id(self) -> str:
140
+ return self._stream_id
141
+
142
+ @property
143
+ def publisher(self) -> PublisherLike | None:
144
+ """The publisher, once the block was entered."""
145
+ return self._publisher
146
+
147
+ @property
148
+ def error(self) -> IQError | None:
149
+ """Why publishing stopped: the publisher's ``IQError`` when it gave up, else this adapter's when the publisher
150
+ failed (code ``publish_failed``). The run itself goes on."""
151
+ if self._publisher is not None and self._publisher.error is not None:
152
+ return self._publisher.error
153
+ return self._stopped
154
+
155
+ @property
156
+ def failed(self) -> bool:
157
+ """Whether publishing stopped before the run ended."""
158
+ return self.error is not None
159
+
160
+ @property
161
+ def result(self) -> PublishResult | None:
162
+ """The server's answer to the close line, once the block was left."""
163
+ return self._result
164
+
165
+ def ticket(self, ttl: float = 3600) -> Ticket:
166
+ """What the browser needs to subscribe: ``stream_id``, the ``sub`` token, the URL and its expiry."""
167
+ if self._client is None:
168
+ raise RuntimeError("ticket() needs the IQClient: this stream was given a publisher.")
169
+ return self._client.ticket(self._stream_id, ttl)
170
+
171
+ # -- the callbacks handed to Haystack ----------------------------------------------------------------------------
172
+
173
+ def callback(self, chunk: StreamingChunk) -> None:
174
+ """The streaming callback for ``run()``, and for ``run_async()`` whenever a generator that gets it has no
175
+ ``run_async``. Thread-safe; never raises, never blocks on the network."""
176
+ if self._state == "open":
177
+ self._publish(lambda converter: converter.convert(chunk, source_key()), "a chunk")
178
+
179
+ async def acallback(self, chunk: StreamingChunk) -> None:
180
+ """The streaming callback for ``run_async()`` when every generator that gets it has ``run_async``: Haystack
181
+ refuses a coroutine callback where it runs a generator in a thread. It awaits nothing: frames are queued."""
182
+ self.callback(chunk)
183
+
184
+ @overload
185
+ def tee(
186
+ self, other: Callable[[StreamingChunk], Awaitable[None]]
187
+ ) -> Callable[[StreamingChunk], Awaitable[None]]: ...
188
+
189
+ @overload
190
+ def tee(self, other: Callable[[StreamingChunk], None]) -> Callable[[StreamingChunk], None]: ...
191
+
192
+ def tee(
193
+ self, other: Callable[[StreamingChunk], Awaitable[None]] | Callable[[StreamingChunk], None]
194
+ ) -> Callable[[StreamingChunk], Awaitable[None]] | Callable[[StreamingChunk], None]:
195
+ """A callback that publishes each chunk and then calls ``other``, the application's own callback: a callback
196
+ given at run time replaces the one a component was built with. Async when ``other`` is."""
197
+ if inspect.iscoroutinefunction(other):
198
+ second = other
199
+
200
+ async def both_async(chunk: StreamingChunk) -> None:
201
+ self.callback(chunk)
202
+ await second(chunk)
203
+
204
+ return both_async
205
+
206
+ def both(chunk: StreamingChunk) -> None:
207
+ self.callback(chunk)
208
+ other(chunk)
209
+
210
+ return both
211
+
212
+ # -- frames of the application's own -----------------------------------------------------------------------------
213
+
214
+ def emit(self, payload: BaseEvent | Mapping[str, object] | str, event: str | None = None) -> bool:
215
+ """Publishes one frame as given, in order with the run's: an AG-UI event, a mapping (as JSON) or a string.
216
+ Returns whether it was queued. It never raises: a frame that cannot be encoded or is over the limit is dropped
217
+ and reported to ``on_dropped`` (else logged), and the stream goes on."""
218
+
219
+ def frames(converter: ChunkConverter) -> list[Frame]:
220
+ if isinstance(payload, BaseEvent):
221
+ data = encode_event(payload)
222
+ elif isinstance(payload, str):
223
+ data = payload
224
+ else:
225
+ data = dumps(dict(payload))
226
+ return [Frame(data, event)]
227
+
228
+ return self._publish(frames, "a frame of the application's", whole=True)
229
+
230
+ def custom(self, name: str, value: object) -> bool:
231
+ """Publishes a named event of the application's own in the stream's protocol: an AG-UI ``CUSTOM`` event, an
232
+ AI SDK ``data-<name>`` chunk, or ``{"type": "custom"}``; what JSON cannot hold is written as its ``str()``, a
233
+ NaN or an infinity as ``null``. A human-in-the-loop strategy uses it to publish its request before it blocks.
234
+ Returns whether it was queued, and never raises, as ``emit``."""
235
+ return self._publish(lambda converter: converter.custom(name, value), "a custom event", whole=True)
236
+
237
+ # -- lifecycle --------------------------------------------------------------------------------------------------
238
+
239
+ def __enter__(self) -> Self:
240
+ with self._lock:
241
+ if self._state != "new":
242
+ raise RuntimeError("An IQStream serves one run: create a new one for the next run.")
243
+ self._state = "open"
244
+ self._token = _ACTIVE.set(self)
245
+ try:
246
+ publisher = self._given if self._given is not None else self._open()
247
+ self._publisher = publisher
248
+ self._converter = self._make_converter(publisher)
249
+ except Exception as error:
250
+ self._stop(error)
251
+ else:
252
+ self._publish(lambda converter: converter.start(), "the start of the run")
253
+ return self
254
+
255
+ def __exit__(
256
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
257
+ ) -> bool:
258
+ self._leave()
259
+ self._finish(exc)
260
+ return False
261
+
262
+ async def __aenter__(self) -> Self:
263
+ return self.__enter__()
264
+
265
+ async def __aexit__(
266
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
267
+ ) -> bool:
268
+ self._leave()
269
+ # close() waits for the server: off the event loop, and carried through even when this task is cancelled.
270
+ await asyncio.shield(asyncio.to_thread(self._finish, exc))
271
+ return False
272
+
273
+ def __deepcopy__(self, memo: dict[int, object]) -> Self:
274
+ # Pipeline.run deep-copies its inputs, and with them the object a bound-method callback belongs to.
275
+ return self
276
+
277
+ def __copy__(self) -> Self:
278
+ return self
279
+
280
+ def __repr__(self) -> str:
281
+ return f"IQStream(stream_id={self._stream_id!r}, state={self._state!r})"
282
+
283
+ # -- internals ---------------------------------------------------------------------------------------------------
284
+
285
+ def _open(self) -> PublisherLike:
286
+ assert self._client is not None
287
+ return self._client.publisher(self._stream_id)
288
+
289
+ def _make_converter(self, publisher: PublisherLike) -> ChunkConverter:
290
+ if not isinstance(self._protocol, str):
291
+ return self._protocol
292
+ options = ConverterOptions(
293
+ include_tool_results=self._include_tool_results,
294
+ max_tool_result_bytes=self._max_tool_result_bytes,
295
+ expose_errors=self._expose_errors,
296
+ max_frame_bytes=publisher.max_frame_bytes,
297
+ measure=publisher.frame_size,
298
+ )
299
+ if self._protocol == "ag-ui":
300
+ return AGUIConverter(thread_id=self._thread_id, run_id=self._run_id, **options)
301
+ if self._protocol == "ai-sdk":
302
+ return AISDKConverter(message_id=self._run_id, **options)
303
+ return NativeConverter(**options)
304
+
305
+ def _publish(
306
+ self,
307
+ build: Callable[[ChunkConverter], Iterable[Frame]],
308
+ what: str,
309
+ *,
310
+ whole: bool = False,
311
+ closing: bool = False,
312
+ ) -> bool:
313
+ """Builds frames with the converter and queues them, under the lock, and returns whether they were queued.
314
+ Never raises. What cannot be built, or a frame that does not fit, is skipped and reported, and publishing
315
+ goes on; ``whole`` frames are measured first, so that none is sent unless all fit. A publisher that fails
316
+ stops publishing."""
317
+ skipped: IQError | None = None
318
+ failure: Exception | None = None
319
+ sent = False
320
+ with self._lock:
321
+ if self._publishing(closing):
322
+ assert self._converter is not None
323
+ try:
324
+ frames = list(build(self._converter))
325
+ if whole:
326
+ self._check_fit(frames)
327
+ sent = self._send(frames)
328
+ except FrameTooLarge as error:
329
+ skipped = error
330
+ except _PublisherFailed as error:
331
+ failure = error.cause
332
+ except Exception as cause:
333
+ skipped = IQError(
334
+ f"IQ stream {self._stream_id}: {what} could not be encoded ({type(cause).__name__}); "
335
+ "it was skipped.",
336
+ stream_id=self._stream_id,
337
+ code="encode_failed",
338
+ )
339
+ skipped.__cause__ = cause
340
+ if skipped is not None:
341
+ self._report(skipped)
342
+ elif failure is not None:
343
+ self._stop(failure)
344
+ elif not sent:
345
+ self._note_gave_up()
346
+ return sent
347
+
348
+ def _publishing(self, closing: bool = False) -> bool:
349
+ return (
350
+ self._state == ("closing" if closing else "open")
351
+ and self._stopped is None
352
+ and self._publisher is not None
353
+ and self._publisher.alive
354
+ and self._converter is not None
355
+ )
356
+
357
+ def _check_fit(self, frames: list[Frame]) -> None:
358
+ assert self._publisher is not None
359
+ for frame in frames:
360
+ size = self._publisher.frame_size(frame.data, frame.event)
361
+ if size > self._publisher.max_frame_bytes:
362
+ raise FrameTooLarge(size, self._publisher.max_frame_bytes)
363
+
364
+ def _send(self, frames: Iterable[Frame]) -> bool:
365
+ """Queues frames; the caller holds the lock. Returns False once the publisher has given up. A frame the
366
+ publisher refuses (too large, invalid) raises as it is; a publisher that fails raises ``_PublisherFailed``."""
367
+ publisher = self._publisher
368
+ assert publisher is not None
369
+ for frame in frames:
370
+ try:
371
+ alive = publisher.send(frame.data, frame.event)
372
+ except (FrameTooLarge, ValueError):
373
+ raise
374
+ except Exception as error:
375
+ if error is publisher.error: # with on_error="raise": the error the publisher gave up on
376
+ return False
377
+ raise _PublisherFailed(error) from error
378
+ if not alive:
379
+ return False
380
+ return True
381
+
382
+ def _stop(self, cause: Exception) -> None:
383
+ """Publishing stops: the publisher failed, or could not be opened. Reported once."""
384
+ error = IQError(
385
+ f"IQ stream {self._stream_id}: publishing stopped after {type(cause).__name__}; the run goes on.",
386
+ stream_id=self._stream_id,
387
+ code="publish_failed",
388
+ )
389
+ error.__cause__ = cause
390
+ with self._lock:
391
+ if self._stopped is not None:
392
+ return
393
+ self._stopped = error
394
+ self._report(error)
395
+
396
+ def _note_gave_up(self) -> None:
397
+ """Tells ``on_dropped``, once, that the core's publisher gave up (unreachable, stream too large, ...). The core
398
+ logged it already, unless its client raises it: then leaving the block raises it, or logs it (``_finish``)."""
399
+ publisher = self._publisher
400
+ if publisher is None or publisher.alive or publisher.error is None:
401
+ return
402
+ with self._lock:
403
+ if self._heard:
404
+ return
405
+ self._heard = True
406
+ if self._on_dropped is not None:
407
+ self._call_on_dropped(publisher.error)
408
+
409
+ def _report(self, error: IQError) -> None:
410
+ """Hands ``error`` to ``on_dropped``, else logs it once per kind, without frame data."""
411
+ if self._on_dropped is not None:
412
+ self._call_on_dropped(error)
413
+ return
414
+ kind = error.code or type(error).__name__
415
+ with self._lock:
416
+ if kind in self._logged:
417
+ return
418
+ self._logged.add(kind)
419
+ if isinstance(error, FrameTooLarge):
420
+ logger.warning(
421
+ "IQ stream %s: a frame of %d bytes was not published; the limit is %d.",
422
+ self._stream_id,
423
+ error.size,
424
+ error.limit,
425
+ )
426
+ else:
427
+ logger.warning("%s", error)
428
+
429
+ def _call_on_dropped(self, error: IQError) -> None:
430
+ assert self._on_dropped is not None
431
+ try:
432
+ self._on_dropped(error)
433
+ except Exception:
434
+ logger.exception("IQ stream %s: on_dropped raised.", self._stream_id)
435
+
436
+ def _leave(self) -> None:
437
+ if self._token is None:
438
+ return
439
+ token, self._token = self._token, None
440
+ try:
441
+ _ACTIVE.reset(token)
442
+ except ValueError: # left in another context than the one it was entered in
443
+ _ACTIVE.set(None)
444
+
445
+ def _finish(self, exc: BaseException | None) -> None:
446
+ cancelled = isinstance(exc, asyncio.CancelledError)
447
+ with self._lock:
448
+ if self._state != "open":
449
+ return
450
+ self._state = "closing"
451
+ publisher = self._publisher
452
+ if publisher is None:
453
+ self._state = "closed"
454
+ return
455
+ if exc is None:
456
+ self._publish(lambda converter: converter.finish(), "the end of the run", closing=True)
457
+ elif cancelled:
458
+ self._publish(lambda converter: converter.cancelled(), "the end of the run", closing=True)
459
+ else:
460
+ self._publish(lambda converter: converter.error(exc), "the run's error", closing=True)
461
+ if self._stopped is not None or publisher.error is not None or (exc is not None and not cancelled):
462
+ outcome: Outcome = "fail"
463
+ else:
464
+ outcome = self._close_on_cancel if cancelled else "end"
465
+ try:
466
+ self._result = publisher.close(outcome, self._close_timeout)
467
+ except Exception as error:
468
+ if error is not publisher.error: # with on_error="raise", close() raises the error it gave up on: below
469
+ self._stop(error)
470
+ if publisher.alive: # a failed stream is closed, never left open
471
+ with contextlib.suppress(Exception):
472
+ self._result = publisher.close("fail")
473
+ finally:
474
+ self._state = "closed"
475
+ self._note_gave_up()
476
+ gave_up = publisher.error
477
+ if gave_up is not None and publisher.on_error == "raise":
478
+ if exc is None:
479
+ raise gave_up
480
+ if self._on_dropped is None: # the core logs only in report mode, and the block's exception goes on
481
+ logger.warning("%s; the block's own exception goes on.", gave_up)
482
+
483
+
484
+ class _PublisherFailed(Exception):
485
+ def __init__(self, cause: Exception) -> None:
486
+ super().__init__(type(cause).__name__)
487
+ self.cause = cause