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.
- haystack_integrations/iq_stream/__init__.py +18 -0
- haystack_integrations/iq_stream/callbacks.py +21 -0
- haystack_integrations/iq_stream/converters/__init__.py +10 -0
- haystack_integrations/iq_stream/converters/_messages.py +277 -0
- haystack_integrations/iq_stream/converters/agui.py +136 -0
- haystack_integrations/iq_stream/converters/ai_sdk.py +160 -0
- haystack_integrations/iq_stream/converters/base.py +247 -0
- haystack_integrations/iq_stream/converters/native.py +138 -0
- haystack_integrations/iq_stream/hayhooks.py +195 -0
- haystack_integrations/iq_stream/py.typed +0 -0
- haystack_integrations/iq_stream/stream.py +487 -0
- iq_stream_haystack-0.1.0.dist-info/METADATA +389 -0
- iq_stream_haystack-0.1.0.dist-info/RECORD +15 -0
- iq_stream_haystack-0.1.0.dist-info/WHEEL +4 -0
- iq_stream_haystack-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""What the converters share: the frame, the protocol a converter follows, the key of the caller, and the fitting
|
|
2
|
+
of text to the frame limit."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import threading
|
|
10
|
+
import uuid
|
|
11
|
+
from collections.abc import Callable, Hashable, Iterable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import TYPE_CHECKING, Protocol, TypedDict, cast
|
|
14
|
+
|
|
15
|
+
from haystack.dataclasses import StreamingChunk, TextContent, ToolCallResult
|
|
16
|
+
from iq_stream import DEFAULT_MAX_FRAME_BYTES, FrameTooLarge, frame_size
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from typing_extensions import Unpack
|
|
20
|
+
|
|
21
|
+
#: The text a browser gets in place of an error message, unless the stream exposes errors.
|
|
22
|
+
MASKED_ERROR = "An error occurred."
|
|
23
|
+
#: The content of a tool result that is not published (``include_tool_results=False``).
|
|
24
|
+
OMITTED_RESULT = "[tool result omitted]"
|
|
25
|
+
#: Why a tool call whose arguments are not JSON gets no result: Haystack drops such a call.
|
|
26
|
+
INVALID_ARGUMENTS = "The tool call's arguments are not valid JSON."
|
|
27
|
+
#: The finish reasons that end one model message; ``tool_call_results`` ends a batch of tool results instead.
|
|
28
|
+
MODEL_FINISH = frozenset({"stop", "length", "content_filter", "tool_calls"})
|
|
29
|
+
|
|
30
|
+
_ENCODER = json.JSONEncoder(ensure_ascii=False)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Frame:
|
|
35
|
+
"""One frame of a stream: ``data`` (usually JSON) and an optional SSE event name."""
|
|
36
|
+
|
|
37
|
+
data: str
|
|
38
|
+
event: str | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ChunkConverter(Protocol):
|
|
42
|
+
"""Turns a run's ``StreamingChunk`` objects into frames. ``IQStream`` calls it under a lock, one call at a time,
|
|
43
|
+
and sends every frame it returns, in order."""
|
|
44
|
+
|
|
45
|
+
def start(self) -> Iterable[Frame]:
|
|
46
|
+
"""The frames that open the stream."""
|
|
47
|
+
...
|
|
48
|
+
|
|
49
|
+
def convert(self, chunk: StreamingChunk, source: Hashable) -> Iterable[Frame]:
|
|
50
|
+
"""The frames of one chunk. ``source`` identifies the thread and task that called back: one model message
|
|
51
|
+
always arrives from a single source, while sub-agents and tool threads may interleave."""
|
|
52
|
+
...
|
|
53
|
+
|
|
54
|
+
def finish(self) -> Iterable[Frame]:
|
|
55
|
+
"""The frames of a run that completed."""
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
def error(self, exc: BaseException) -> Iterable[Frame]:
|
|
59
|
+
"""The frames of a run that raised ``exc``."""
|
|
60
|
+
...
|
|
61
|
+
|
|
62
|
+
def cancelled(self) -> Iterable[Frame]:
|
|
63
|
+
"""The frames of a run that was cancelled."""
|
|
64
|
+
...
|
|
65
|
+
|
|
66
|
+
def custom(self, name: str, value: object) -> Iterable[Frame]:
|
|
67
|
+
"""A named event of the application's own, such as a request for a confirmation."""
|
|
68
|
+
...
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def source_key() -> Hashable:
|
|
72
|
+
"""The caller: its thread and, in asyncio, its task."""
|
|
73
|
+
try:
|
|
74
|
+
task = asyncio.current_task()
|
|
75
|
+
except RuntimeError:
|
|
76
|
+
task = None
|
|
77
|
+
return threading.get_ident(), None if task is None else id(task)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def new_id(prefix: str) -> str:
|
|
81
|
+
return f"{prefix}_{uuid.uuid4().hex[:16]}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def dumps(value: object) -> str:
|
|
85
|
+
"""Compact JSON, non-ASCII text unescaped, as the browser's JSON.parse reads it. What JSON cannot hold is written
|
|
86
|
+
as its ``str()``, and a NaN or an infinity as ``null``, as JSON.stringify writes them: a bare ``NaN`` would make
|
|
87
|
+
the browser reject the frame."""
|
|
88
|
+
try:
|
|
89
|
+
return _dumps(value)
|
|
90
|
+
except ValueError: # a non-finite float, or a reference cycle, which _finite raises again
|
|
91
|
+
return _dumps(_finite(value, set()))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _dumps(value: object) -> str:
|
|
95
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str, allow_nan=False)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _finite(value: object, seen: set[int]) -> object:
|
|
99
|
+
"""``value`` with every non-finite float in its dicts, lists and tuples replaced by ``None``."""
|
|
100
|
+
if isinstance(value, float):
|
|
101
|
+
return value if math.isfinite(value) else None
|
|
102
|
+
if not isinstance(value, dict | list | tuple):
|
|
103
|
+
return value
|
|
104
|
+
marker = id(cast(object, value))
|
|
105
|
+
if marker in seen:
|
|
106
|
+
raise ValueError("Circular reference detected")
|
|
107
|
+
seen.add(marker)
|
|
108
|
+
if isinstance(value, dict):
|
|
109
|
+
copy: object = {key: _finite(item, seen) for key, item in cast(dict[object, object], value).items()}
|
|
110
|
+
else:
|
|
111
|
+
copy = [_finite(item, seen) for item in cast(list[object] | tuple[object, ...], value)]
|
|
112
|
+
seen.discard(marker)
|
|
113
|
+
return copy
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def result_text(result: ToolCallResult) -> str:
|
|
117
|
+
"""A tool result as the browser's text: the string, or the text parts with a placeholder for each image or file."""
|
|
118
|
+
value = result.result
|
|
119
|
+
if isinstance(value, str):
|
|
120
|
+
return value
|
|
121
|
+
return "\n".join(part.text if isinstance(part, TextContent) else f"[{type(part).__name__}]" for part in value)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def error_text(exc: BaseException) -> str:
|
|
125
|
+
message = str(exc)
|
|
126
|
+
return f"{type(exc).__name__}: {message}" if message else type(exc).__name__
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Fitter:
|
|
130
|
+
"""Makes frames fit the limit: a delta is split into several, a result is truncated with a marker.
|
|
131
|
+
|
|
132
|
+
Text inside a frame is encoded twice, as a JSON string in the protocol's event and again in the frame's
|
|
133
|
+
envelope, so a quote costs four bytes and a control character seven. Pieces are cut by an estimate of that cost
|
|
134
|
+
and each one is then measured for real.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __init__(self, max_frame_bytes: int, measure: Callable[[str], int]) -> None:
|
|
138
|
+
self.limit = max_frame_bytes
|
|
139
|
+
self.measure = measure
|
|
140
|
+
self._costs: dict[str, int] = {}
|
|
141
|
+
|
|
142
|
+
def fits(self, data: str) -> bool:
|
|
143
|
+
return self.measure(data) <= self.limit
|
|
144
|
+
|
|
145
|
+
def whole(self, data: str) -> str:
|
|
146
|
+
"""``data`` itself, which cannot be split: ``FrameTooLarge`` when it does not fit."""
|
|
147
|
+
size = self.measure(data)
|
|
148
|
+
if size > self.limit:
|
|
149
|
+
raise FrameTooLarge(size, self.limit)
|
|
150
|
+
return data
|
|
151
|
+
|
|
152
|
+
def split(self, text: str, build: Callable[[str], str]) -> list[str]:
|
|
153
|
+
"""Pieces of ``text``, in order, each of whose frames ``build(piece)`` fits; they concatenate to ``text``."""
|
|
154
|
+
if self.fits(build(text)):
|
|
155
|
+
return [text]
|
|
156
|
+
room = self.limit - self.measure(build(""))
|
|
157
|
+
if room <= 0:
|
|
158
|
+
raise FrameTooLarge(self.measure(build("")), self.limit)
|
|
159
|
+
pieces: list[str] = []
|
|
160
|
+
start = used = 0
|
|
161
|
+
for index, char in enumerate(text):
|
|
162
|
+
cost = self._cost(char)
|
|
163
|
+
if used + cost > room and index > start:
|
|
164
|
+
pieces.append(text[start:index])
|
|
165
|
+
start, used = index, 0
|
|
166
|
+
used += cost
|
|
167
|
+
pieces.append(text[start:])
|
|
168
|
+
return [part for piece in pieces for part in self._halves(piece, build)]
|
|
169
|
+
|
|
170
|
+
def truncate(self, text: str, build: Callable[[str], str], max_bytes: int | None = None) -> str:
|
|
171
|
+
"""The longest start of ``text`` that keeps ``build(...)`` within the limit (and ``text`` within ``max_bytes``
|
|
172
|
+
UTF-8 bytes), followed by a marker that gives the full length."""
|
|
173
|
+
marker = f"\n[truncated, {len(text)} characters in total]"
|
|
174
|
+
cut = text
|
|
175
|
+
if max_bytes is not None and len(text.encode("utf-8", "surrogatepass")) > max_bytes:
|
|
176
|
+
cut = text.encode("utf-8", "surrogatepass")[:max_bytes].decode("utf-8", "ignore")
|
|
177
|
+
if cut == text and self.fits(build(text)):
|
|
178
|
+
return text
|
|
179
|
+
if not self.fits(build(marker)):
|
|
180
|
+
raise FrameTooLarge(self.measure(build(marker)), self.limit)
|
|
181
|
+
low, high = 0, len(cut)
|
|
182
|
+
while low < high:
|
|
183
|
+
middle = (low + high + 1) // 2
|
|
184
|
+
if self.fits(build(cut[:middle] + marker)):
|
|
185
|
+
low = middle
|
|
186
|
+
else:
|
|
187
|
+
high = middle - 1
|
|
188
|
+
return cut[:low] + marker
|
|
189
|
+
|
|
190
|
+
def _halves(self, piece: str, build: Callable[[str], str]) -> list[str]:
|
|
191
|
+
if self.fits(build(piece)):
|
|
192
|
+
return [piece]
|
|
193
|
+
if len(piece) <= 1:
|
|
194
|
+
raise FrameTooLarge(self.measure(build(piece)), self.limit)
|
|
195
|
+
middle = len(piece) // 2
|
|
196
|
+
return self._halves(piece[:middle], build) + self._halves(piece[middle:], build)
|
|
197
|
+
|
|
198
|
+
def _cost(self, char: str) -> int:
|
|
199
|
+
cost = self._costs.get(char)
|
|
200
|
+
if cost is None:
|
|
201
|
+
inner = _ENCODER.encode(char)[1:-1]
|
|
202
|
+
cost = len(_ENCODER.encode(inner)[1:-1].encode("utf-8", "surrogatepass"))
|
|
203
|
+
self._costs[char] = cost
|
|
204
|
+
return cost
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class ConverterOptions(TypedDict, total=False):
|
|
208
|
+
"""The options every built-in converter takes."""
|
|
209
|
+
|
|
210
|
+
#: Publish tool results; ``False`` sends a placeholder in their place.
|
|
211
|
+
include_tool_results: bool
|
|
212
|
+
#: Tool results longer than this many UTF-8 bytes are truncated, with a marker that gives the full length.
|
|
213
|
+
max_tool_result_bytes: int
|
|
214
|
+
#: Publish error messages; by default a browser gets "An error occurred." in their place.
|
|
215
|
+
expose_errors: bool
|
|
216
|
+
#: The limit a frame must fit: the publisher's ``max_frame_bytes``.
|
|
217
|
+
max_frame_bytes: int
|
|
218
|
+
#: How a frame's data is measured: the publisher's ``frame_size``.
|
|
219
|
+
measure: Callable[[str], int]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class BaseConverter:
|
|
223
|
+
"""The options every built-in converter takes, and their frame fitting."""
|
|
224
|
+
|
|
225
|
+
def __init__(self, **options: Unpack[ConverterOptions]) -> None:
|
|
226
|
+
max_tool_result_bytes = options.get("max_tool_result_bytes", 32_768)
|
|
227
|
+
if max_tool_result_bytes < 1:
|
|
228
|
+
raise ValueError("max_tool_result_bytes must be at least 1.")
|
|
229
|
+
self.include_tool_results = options.get("include_tool_results", True)
|
|
230
|
+
self.max_tool_result_bytes = max_tool_result_bytes
|
|
231
|
+
self.expose_errors = options.get("expose_errors", False)
|
|
232
|
+
self.fit = Fitter(options.get("max_frame_bytes", DEFAULT_MAX_FRAME_BYTES), options.get("measure", frame_size))
|
|
233
|
+
|
|
234
|
+
def _error_message(self, exc: BaseException) -> str:
|
|
235
|
+
return error_text(exc) if self.expose_errors else MASKED_ERROR
|
|
236
|
+
|
|
237
|
+
def _result_content(self, result: ToolCallResult) -> str:
|
|
238
|
+
"""The text a browser gets for a tool result, before truncation."""
|
|
239
|
+
if result.error and not self.expose_errors:
|
|
240
|
+
return MASKED_ERROR
|
|
241
|
+
if not self.include_tool_results:
|
|
242
|
+
return OMITTED_RESULT
|
|
243
|
+
return result_text(result)
|
|
244
|
+
|
|
245
|
+
@staticmethod
|
|
246
|
+
def _frames(data: Iterable[str]) -> list[Frame]:
|
|
247
|
+
return [Frame(item) for item in data]
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""StreamingChunk -> its own JSON: one frame per chunk, for a page that reads Haystack's chunks as they are."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Hashable
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from haystack.dataclasses import StreamingChunk, ToolCallDelta
|
|
10
|
+
from iq_stream import FrameTooLarge
|
|
11
|
+
|
|
12
|
+
from .base import BaseConverter, Frame, dumps
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class NativeConverter(BaseConverter):
|
|
16
|
+
"""Each chunk as ``{"type": "chunk", ...}`` with the fields of ``StreamingChunk.to_dict()`` but ``meta`` (which
|
|
17
|
+
may hold objects that are not JSON) and the providers' ``extra``; a tool result is its text. The run opens with
|
|
18
|
+
``{"type": "start"}`` and ends with ``{"type": "finish"}``, ``{"type": "error", "message": ...}`` or
|
|
19
|
+
``{"type": "cancelled"}``.
|
|
20
|
+
|
|
21
|
+
A chunk too large for a frame is split into several chunks of the same kind (its ``start`` on the first, its
|
|
22
|
+
``finish_reason`` on the last); a tool result is truncated with a marker that gives its full length.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def start(self) -> list[Frame]:
|
|
26
|
+
return [Frame(dumps({"type": "start"}))]
|
|
27
|
+
|
|
28
|
+
def finish(self) -> list[Frame]:
|
|
29
|
+
return [Frame(dumps({"type": "finish"}))]
|
|
30
|
+
|
|
31
|
+
def cancelled(self) -> list[Frame]:
|
|
32
|
+
return [Frame(dumps({"type": "cancelled"}))]
|
|
33
|
+
|
|
34
|
+
def error(self, exc: BaseException) -> list[Frame]:
|
|
35
|
+
def build(text: str) -> str:
|
|
36
|
+
return dumps({"type": "error", "message": text})
|
|
37
|
+
|
|
38
|
+
return [Frame(build(self.fit.truncate(self._error_message(exc), build)))]
|
|
39
|
+
|
|
40
|
+
def custom(self, name: str, value: object) -> list[Frame]:
|
|
41
|
+
return [Frame(self.fit.whole(dumps({"type": "custom", "name": name, "value": value})))]
|
|
42
|
+
|
|
43
|
+
def convert(self, chunk: StreamingChunk, source: Hashable) -> list[Frame]:
|
|
44
|
+
data = self._encode(chunk)
|
|
45
|
+
if self.fit.fits(data):
|
|
46
|
+
return [Frame(data)]
|
|
47
|
+
if chunk.content:
|
|
48
|
+
pieces = self._split(chunk, lambda part: replace(chunk, content=part), chunk.content)
|
|
49
|
+
elif chunk.reasoning is not None and chunk.reasoning.reasoning_text:
|
|
50
|
+
reasoning = chunk.reasoning
|
|
51
|
+
pieces = self._split(
|
|
52
|
+
chunk,
|
|
53
|
+
lambda part: replace(chunk, reasoning=replace(reasoning, reasoning_text=part)),
|
|
54
|
+
reasoning.reasoning_text,
|
|
55
|
+
)
|
|
56
|
+
elif chunk.tool_calls:
|
|
57
|
+
pieces = [piece for delta in chunk.tool_calls for piece in self._split_call(chunk, delta)]
|
|
58
|
+
else: # a tool result is truncated to fit already
|
|
59
|
+
raise FrameTooLarge(self.fit.measure(data), self.fit.limit)
|
|
60
|
+
return self._frames(self._encode(piece) for piece in pieces)
|
|
61
|
+
|
|
62
|
+
def _encode(self, chunk: StreamingChunk, result_text: str | None = None, *, arguments: bool = True) -> str:
|
|
63
|
+
fields: dict[str, Any] = {
|
|
64
|
+
"type": "chunk",
|
|
65
|
+
"content": chunk.content,
|
|
66
|
+
"component_info": chunk.component_info.to_dict() if chunk.component_info else None,
|
|
67
|
+
"index": chunk.index,
|
|
68
|
+
"tool_calls": [
|
|
69
|
+
{"index": delta.index, "tool_name": delta.tool_name, "arguments": delta.arguments, "id": delta.id}
|
|
70
|
+
for delta in chunk.tool_calls
|
|
71
|
+
]
|
|
72
|
+
if chunk.tool_calls
|
|
73
|
+
else None,
|
|
74
|
+
"tool_call_result": None,
|
|
75
|
+
"start": chunk.start,
|
|
76
|
+
"finish_reason": chunk.finish_reason,
|
|
77
|
+
"reasoning": {"reasoning_text": chunk.reasoning.reasoning_text} if chunk.reasoning else None,
|
|
78
|
+
}
|
|
79
|
+
result = chunk.tool_call_result
|
|
80
|
+
if result is not None:
|
|
81
|
+
if result_text is None:
|
|
82
|
+
result_text, arguments = self._fit_result(chunk)
|
|
83
|
+
origin = result.origin
|
|
84
|
+
fields["tool_call_result"] = {
|
|
85
|
+
"result": result_text,
|
|
86
|
+
"origin": {
|
|
87
|
+
"tool_name": origin.tool_name,
|
|
88
|
+
# Left out (null) when they alone would not fit: the tool call's own chunks carried them.
|
|
89
|
+
"arguments": origin.arguments if arguments else None,
|
|
90
|
+
"id": origin.id,
|
|
91
|
+
},
|
|
92
|
+
"error": result.error,
|
|
93
|
+
}
|
|
94
|
+
return dumps(fields)
|
|
95
|
+
|
|
96
|
+
def _fit_result(self, chunk: StreamingChunk) -> tuple[str, bool]:
|
|
97
|
+
"""The result's text, truncated to fit, and whether the call's arguments fit beside it."""
|
|
98
|
+
assert chunk.tool_call_result is not None
|
|
99
|
+
content = self._result_content(chunk.tool_call_result)
|
|
100
|
+
limit = self.max_tool_result_bytes
|
|
101
|
+
try:
|
|
102
|
+
return self.fit.truncate(content, lambda text: self._encode(chunk, text), limit), True
|
|
103
|
+
except FrameTooLarge:
|
|
104
|
+
return self.fit.truncate(content, lambda text: self._encode(chunk, text, arguments=False), limit), False
|
|
105
|
+
|
|
106
|
+
def _split(
|
|
107
|
+
self, chunk: StreamingChunk, with_text: Callable[[str], StreamingChunk], text: str
|
|
108
|
+
) -> list[StreamingChunk]:
|
|
109
|
+
# Measured with start=False, the longer spelling, and with the finish_reason: the worst case of every piece.
|
|
110
|
+
parts = self.fit.split(text, lambda part: self._encode(replace(with_text(part), start=False)))
|
|
111
|
+
last = len(parts) - 1
|
|
112
|
+
return [
|
|
113
|
+
replace(
|
|
114
|
+
with_text(part),
|
|
115
|
+
start=chunk.start and number == 0,
|
|
116
|
+
finish_reason=chunk.finish_reason if number == last else None,
|
|
117
|
+
)
|
|
118
|
+
for number, part in enumerate(parts)
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
def _split_call(self, chunk: StreamingChunk, delta: ToolCallDelta) -> list[StreamingChunk]:
|
|
122
|
+
single = replace(chunk, tool_calls=[delta])
|
|
123
|
+
if not delta.arguments or self.fit.fits(self._encode(single)):
|
|
124
|
+
return [single]
|
|
125
|
+
pieces = self._split(
|
|
126
|
+
chunk, lambda part: replace(chunk, tool_calls=[replace(delta, arguments=part)]), delta.arguments
|
|
127
|
+
)
|
|
128
|
+
# Only the first fragment keeps the call's id and name, as providers send them.
|
|
129
|
+
return [
|
|
130
|
+
replace(piece, tool_calls=[replace(delta, id=None, tool_name=None, arguments=self._arguments(piece))])
|
|
131
|
+
if number
|
|
132
|
+
else piece
|
|
133
|
+
for number, piece in enumerate(pieces)
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def _arguments(chunk: StreamingChunk) -> str | None:
|
|
138
|
+
return chunk.tool_calls[0].arguments if chunk.tool_calls else None
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Start a run in the background and answer with its ticket at once: for a Hayhooks pipeline wrapper's
|
|
2
|
+
``run_api_async`` (``start_stream``) or ``run_api`` (``start_stream_sync``), or any other server route.
|
|
3
|
+
|
|
4
|
+
The run is published from the serving process, in a task or a thread of its own, inside an ``IQStream`` block;
|
|
5
|
+
``before_close`` is where the application saves the result, before the stream's close line. These helpers do not
|
|
6
|
+
import Hayhooks, so they serve FastAPI routes just as well.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import contextvars
|
|
13
|
+
import inspect
|
|
14
|
+
import logging
|
|
15
|
+
import threading
|
|
16
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
17
|
+
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
|
18
|
+
|
|
19
|
+
from haystack import Pipeline
|
|
20
|
+
from haystack.components.agents import Agent
|
|
21
|
+
from haystack.dataclasses import StreamingCallbackT
|
|
22
|
+
from iq_stream import IQClient, IQError, Outcome
|
|
23
|
+
|
|
24
|
+
from .converters import ChunkConverter
|
|
25
|
+
from .stream import IQStream, ProtocolName
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from typing_extensions import Unpack
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("haystack_integrations.iq_stream")
|
|
31
|
+
|
|
32
|
+
Target = Agent | Pipeline
|
|
33
|
+
BeforeClose = Callable[[str, dict[str, Any]], Awaitable[None] | None]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class StreamOptions(TypedDict, total=False):
|
|
37
|
+
"""The options of ``IQStream`` that the helpers pass on."""
|
|
38
|
+
|
|
39
|
+
stream_id: str | None
|
|
40
|
+
protocol: ProtocolName | ChunkConverter
|
|
41
|
+
thread_id: str | None
|
|
42
|
+
run_id: str | None
|
|
43
|
+
include_tool_results: bool
|
|
44
|
+
max_tool_result_bytes: int
|
|
45
|
+
expose_errors: bool
|
|
46
|
+
close_on_cancel: Outcome
|
|
47
|
+
close_timeout: float
|
|
48
|
+
on_dropped: Callable[[IQError], object] | None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# The event loop keeps only weak references to tasks: these keep the runs alive until they end.
|
|
52
|
+
_TASKS: set[asyncio.Task[None]] = set()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def start_stream(
|
|
56
|
+
client: IQClient,
|
|
57
|
+
target: Target,
|
|
58
|
+
run_args: Mapping[str, Any],
|
|
59
|
+
*,
|
|
60
|
+
before_close: BeforeClose | None = None,
|
|
61
|
+
ttl: float = 3600,
|
|
62
|
+
**stream_options: Unpack[StreamOptions],
|
|
63
|
+
) -> dict[str, str | int]:
|
|
64
|
+
"""Starts ``target`` in a task of the running loop and returns the ticket's ``to_dict()`` (``streamId``,
|
|
65
|
+
``token``, ``url``, ``expiresAt``) without waiting for it.
|
|
66
|
+
|
|
67
|
+
``run_args`` are the keyword arguments of ``Agent.run_async``, or the data of ``Pipeline.run_async`` in its
|
|
68
|
+
nested form (``{"component": {"input": ...}}``); the stream's callback is given to the agent, or to every
|
|
69
|
+
component of the pipeline that takes a ``streaming_callback``. ``before_close(stream_id, result)``, sync or
|
|
70
|
+
async, runs inside the stream's block, before its close line. ``stream_options`` go to ``IQStream``
|
|
71
|
+
(``stream_id``, ``protocol``, ``thread_id``, ``close_on_cancel``, ...). An exception in the run closes the stream
|
|
72
|
+
with ``fail`` and is logged; so is a publishing failure that leaves the block with a client opened with
|
|
73
|
+
``on_error="raise"``.
|
|
74
|
+
"""
|
|
75
|
+
stream = IQStream(client, **stream_options)
|
|
76
|
+
kwargs = _arguments(stream, target, run_args, sync=False)
|
|
77
|
+
ticket = client.ticket(stream.stream_id, ttl)
|
|
78
|
+
task = asyncio.create_task(_run_async(stream, target, kwargs, before_close))
|
|
79
|
+
_TASKS.add(task)
|
|
80
|
+
task.add_done_callback(_TASKS.discard)
|
|
81
|
+
return ticket.to_dict()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def start_stream_sync(
|
|
85
|
+
client: IQClient,
|
|
86
|
+
target: Target,
|
|
87
|
+
run_args: Mapping[str, Any],
|
|
88
|
+
*,
|
|
89
|
+
before_close: Callable[[str, dict[str, Any]], object] | None = None,
|
|
90
|
+
ttl: float = 3600,
|
|
91
|
+
**stream_options: Unpack[StreamOptions],
|
|
92
|
+
) -> dict[str, str | int]:
|
|
93
|
+
"""``start_stream`` for synchronous code: ``target.run()`` in a thread of its own, under a copy of the caller's
|
|
94
|
+
context, and ``before_close`` called in that thread."""
|
|
95
|
+
stream = IQStream(client, **stream_options)
|
|
96
|
+
kwargs = _arguments(stream, target, run_args, sync=True)
|
|
97
|
+
ticket = client.ticket(stream.stream_id, ttl)
|
|
98
|
+
context = contextvars.copy_context()
|
|
99
|
+
thread = threading.Thread(
|
|
100
|
+
target=context.run,
|
|
101
|
+
args=(_run_sync, stream, target, kwargs, before_close),
|
|
102
|
+
name=f"iq-stream-haystack {stream.stream_id}",
|
|
103
|
+
daemon=True,
|
|
104
|
+
)
|
|
105
|
+
thread.start()
|
|
106
|
+
return ticket.to_dict()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _arguments(stream: IQStream, target: Target, run_args: Mapping[str, Any], *, sync: bool) -> dict[str, Any]:
|
|
110
|
+
"""The keyword arguments of ``target.run`` or ``run_async``, with the stream's callback in place."""
|
|
111
|
+
if isinstance(target, Agent):
|
|
112
|
+
kwargs = dict(run_args)
|
|
113
|
+
kwargs["streaming_callback"] = _callback(stream, target, kwargs.get("streaming_callback"), sync=sync)
|
|
114
|
+
return kwargs
|
|
115
|
+
if isinstance(target, Pipeline): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
116
|
+
return {"data": _with_callbacks(stream, target, dict(run_args), sync=sync)}
|
|
117
|
+
raise TypeError("target must be a Haystack Agent or Pipeline.")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def _run_async(
|
|
121
|
+
stream: IQStream, target: Target, kwargs: dict[str, Any], before_close: BeforeClose | None
|
|
122
|
+
) -> None:
|
|
123
|
+
ran = False
|
|
124
|
+
try:
|
|
125
|
+
async with stream:
|
|
126
|
+
result = await target.run_async(**kwargs)
|
|
127
|
+
if before_close is not None:
|
|
128
|
+
saved = before_close(stream.stream_id, result)
|
|
129
|
+
if inspect.isawaitable(saved):
|
|
130
|
+
await saved
|
|
131
|
+
ran = True
|
|
132
|
+
except Exception as error:
|
|
133
|
+
_log_failure(stream, error, ran)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _run_sync(
|
|
137
|
+
stream: IQStream,
|
|
138
|
+
target: Target,
|
|
139
|
+
kwargs: dict[str, Any],
|
|
140
|
+
before_close: Callable[[str, dict[str, Any]], object] | None,
|
|
141
|
+
) -> None:
|
|
142
|
+
ran = False
|
|
143
|
+
try:
|
|
144
|
+
with stream:
|
|
145
|
+
result = target.run(**kwargs)
|
|
146
|
+
if before_close is not None:
|
|
147
|
+
before_close(stream.stream_id, result)
|
|
148
|
+
ran = True
|
|
149
|
+
except Exception as error:
|
|
150
|
+
_log_failure(stream, error, ran)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _log_failure(stream: IQStream, error: Exception, ran: bool) -> None:
|
|
154
|
+
if ran and error is stream.error: # leaving raised the publisher's IQError: its client has on_error="raise"
|
|
155
|
+
logger.warning("%s; the run itself completed, and before_close ran.", error)
|
|
156
|
+
else:
|
|
157
|
+
logger.exception("IQ stream %s: the run failed.", stream.stream_id)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _callback(stream: IQStream, component: object, theirs: Any = None, *, sync: bool = False) -> StreamingCallbackT:
|
|
161
|
+
"""The stream's callback for a component, teed with the component's own callback if the data gave one: async
|
|
162
|
+
only where every generator that gets it awaits it, since Haystack refuses a coroutine callback where it runs a
|
|
163
|
+
generator in a thread; the sync one works everywhere, at the cost of Haystack's warning."""
|
|
164
|
+
if theirs is not None:
|
|
165
|
+
return stream.tee(cast(StreamingCallbackT, theirs))
|
|
166
|
+
return stream.acallback if not sync and _awaits_callback(component) else stream.callback
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _awaits_callback(component: object) -> bool:
|
|
170
|
+
"""Whether every chat generator that would get the callback from ``component`` in ``run_async`` has ``run_async``
|
|
171
|
+
of its own. False when that is not known: an agent that passes its callback to tools hands it to sub-agents
|
|
172
|
+
and functions whose way of calling it cannot be seen, whether they were given at construction or at run time."""
|
|
173
|
+
if isinstance(component, Agent):
|
|
174
|
+
if component.tool_streaming_callback_passthrough:
|
|
175
|
+
return False
|
|
176
|
+
return _awaits_callback(component.chat_generator)
|
|
177
|
+
if not getattr(component, "__haystack_supports_async__", False):
|
|
178
|
+
return False
|
|
179
|
+
wrapped: object = getattr(component, "chat_generators", ()) # FallbackChatGenerator's, run each in its own way
|
|
180
|
+
return all(_awaits_callback(generator) for generator in cast(list[object], wrapped))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _with_callbacks(
|
|
184
|
+
stream: IQStream, pipeline: Pipeline, data: dict[str, Any], *, sync: bool = False
|
|
185
|
+
) -> dict[str, Any]:
|
|
186
|
+
sockets = pipeline.inputs(include_components_with_connected_inputs=True)
|
|
187
|
+
if not set(data) <= set(sockets):
|
|
188
|
+
raise ValueError("Pass the pipeline's data in its nested form: {component_name: {input_name: value}}.")
|
|
189
|
+
data = {name: dict(inputs) for name, inputs in data.items()}
|
|
190
|
+
for name, inputs_of in sockets.items():
|
|
191
|
+
if "streaming_callback" in inputs_of:
|
|
192
|
+
inputs = data.setdefault(name, {})
|
|
193
|
+
instance = pipeline.get_component(name)
|
|
194
|
+
inputs["streaming_callback"] = _callback(stream, instance, inputs.get("streaming_callback"), sync=sync)
|
|
195
|
+
return data
|
|
File without changes
|