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,18 @@
|
|
|
1
|
+
"""Publish Haystack agent and pipeline runs to browsers through an IQ-Stream server."""
|
|
2
|
+
|
|
3
|
+
from .callbacks import iq_streaming_callback, iq_streaming_callback_async
|
|
4
|
+
from .converters import AGUIConverter, AISDKConverter, ChunkConverter, Frame, NativeConverter
|
|
5
|
+
from .stream import IQStream, ProtocolName, current_stream
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AGUIConverter",
|
|
9
|
+
"AISDKConverter",
|
|
10
|
+
"ChunkConverter",
|
|
11
|
+
"Frame",
|
|
12
|
+
"IQStream",
|
|
13
|
+
"NativeConverter",
|
|
14
|
+
"ProtocolName",
|
|
15
|
+
"current_stream",
|
|
16
|
+
"iq_streaming_callback",
|
|
17
|
+
"iq_streaming_callback_async",
|
|
18
|
+
]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Module-level streaming callbacks. A component built with one of them serializes (``to_dict()``, YAML) and loads
|
|
2
|
+
without configuration, since Haystack allows the ``haystack_integrations`` namespace by default; at run time the
|
|
3
|
+
callback publishes to the ``IQStream`` whose block is active in the calling context, and does nothing outside one."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from haystack.dataclasses import StreamingChunk
|
|
8
|
+
|
|
9
|
+
from .stream import current_stream
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def iq_streaming_callback(chunk: StreamingChunk) -> None:
|
|
13
|
+
"""Publishes ``chunk`` to the active ``IQStream``, if there is one. For ``run()``."""
|
|
14
|
+
stream = current_stream()
|
|
15
|
+
if stream is not None:
|
|
16
|
+
stream.callback(chunk)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def iq_streaming_callback_async(chunk: StreamingChunk) -> None:
|
|
20
|
+
"""Publishes ``chunk`` to the active ``IQStream``, if there is one. For ``run_async()``."""
|
|
21
|
+
iq_streaming_callback(chunk)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Converters from Haystack's ``StreamingChunk`` to the frames a browser reads: AG-UI events, AI SDK UI message
|
|
2
|
+
chunks, or the chunks' own JSON. ``IQStream`` builds the one its ``protocol`` names; any object that follows
|
|
3
|
+
``ChunkConverter`` can take its place."""
|
|
4
|
+
|
|
5
|
+
from .agui import AGUIConverter
|
|
6
|
+
from .ai_sdk import AISDKConverter
|
|
7
|
+
from .base import ChunkConverter, ConverterOptions, Frame
|
|
8
|
+
from .native import NativeConverter
|
|
9
|
+
|
|
10
|
+
__all__ = ["AGUIConverter", "AISDKConverter", "ChunkConverter", "ConverterOptions", "Frame", "NativeConverter"]
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""The bookkeeping that the AG-UI and the AI SDK converters share: which model messages are open, from which
|
|
2
|
+
source, with which text, reasoning and tool calls, and which tool call a result answers."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Hashable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import TYPE_CHECKING, Literal
|
|
10
|
+
|
|
11
|
+
from haystack.dataclasses import StreamingChunk, ToolCall, ToolCallResult
|
|
12
|
+
|
|
13
|
+
from .base import MODEL_FINISH, BaseConverter, ConverterOptions, Frame, dumps, new_id
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from typing_extensions import Unpack
|
|
17
|
+
|
|
18
|
+
Block = Literal["reasoning", "text", "call"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Call:
|
|
23
|
+
id: str
|
|
24
|
+
name: str
|
|
25
|
+
#: The id was made here, since the provider gave none.
|
|
26
|
+
generated: bool
|
|
27
|
+
arguments: list[str] = field(default_factory=lambda: [])
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def text(self) -> str:
|
|
31
|
+
return "".join(self.arguments)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Message:
|
|
36
|
+
"""The open parts of one model message from one source."""
|
|
37
|
+
|
|
38
|
+
id: str
|
|
39
|
+
#: The message a tool call belongs to: the last text block, or the message itself.
|
|
40
|
+
parent_id: str
|
|
41
|
+
text_id: str | None = None
|
|
42
|
+
reasoning_id: str | None = None
|
|
43
|
+
texts: int = 0
|
|
44
|
+
calls: dict[int, Call] = field(default_factory=lambda: {})
|
|
45
|
+
#: The chunk indexes that carried something, by kind, and the highest: a provider numbers a message's blocks
|
|
46
|
+
#: upwards, so a block that starts again, or below the highest, belongs to another model call. Tool calls are
|
|
47
|
+
#: also told apart by ``ToolCallDelta.index``, in ``calls``, which is another numbering.
|
|
48
|
+
blocks: dict[Block, set[int]] = field(default_factory=lambda: {"reasoning": set(), "text": set(), "call": set()})
|
|
49
|
+
top: int = -1
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class MessageConverter(BaseConverter):
|
|
53
|
+
"""Tracks model messages by source and tool calls by ``ToolCallDelta.index`` and id; the subclasses say how
|
|
54
|
+
each step is written in their protocol."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, **options: Unpack[ConverterOptions]) -> None:
|
|
57
|
+
super().__init__(**options)
|
|
58
|
+
self._messages: dict[Hashable, Message] = {}
|
|
59
|
+
#: Open tool calls by id, and the source whose message holds them.
|
|
60
|
+
self._open_calls: dict[str, Hashable] = {}
|
|
61
|
+
#: Every tool call id the browser has seen started.
|
|
62
|
+
self._started: set[str] = set()
|
|
63
|
+
#: Tool calls whose ids were made here, waiting for their results, oldest first.
|
|
64
|
+
self._unanswered: list[Call] = []
|
|
65
|
+
|
|
66
|
+
def convert(self, chunk: StreamingChunk, source: Hashable) -> list[Frame]:
|
|
67
|
+
out: list[str] = []
|
|
68
|
+
open_message = self._messages.get(source)
|
|
69
|
+
if open_message is not None and _starts_another(open_message, chunk):
|
|
70
|
+
# The model call that streamed the open message failed without a finish_reason, and the same caller
|
|
71
|
+
# streams another one: FallbackChatGenerator retrying with the next generator. The two stay apart.
|
|
72
|
+
del self._messages[source]
|
|
73
|
+
out += self._close(open_message)
|
|
74
|
+
reasoning = chunk.reasoning.reasoning_text if chunk.reasoning is not None else ""
|
|
75
|
+
if reasoning:
|
|
76
|
+
message = self._message(source, out)
|
|
77
|
+
out += self._close_text(message)
|
|
78
|
+
if message.reasoning_id is None:
|
|
79
|
+
message.reasoning_id = new_id("rsn")
|
|
80
|
+
out += self._start_reasoning(message.reasoning_id)
|
|
81
|
+
out += self._reasoning_delta(message.reasoning_id, reasoning)
|
|
82
|
+
if chunk.content:
|
|
83
|
+
message = self._message(source, out)
|
|
84
|
+
out += self._close_reasoning(message)
|
|
85
|
+
if message.text_id is None:
|
|
86
|
+
message.text_id = message.id if message.texts == 0 else new_id("msg")
|
|
87
|
+
message.parent_id = message.text_id
|
|
88
|
+
message.texts += 1
|
|
89
|
+
out += self._start_text(message.text_id)
|
|
90
|
+
out += self._text_delta(message.text_id, chunk.content)
|
|
91
|
+
for delta in chunk.tool_calls or []:
|
|
92
|
+
message = self._message(source, out)
|
|
93
|
+
out += self._close_reasoning(message)
|
|
94
|
+
out += self._close_text(message)
|
|
95
|
+
call = message.calls.get(delta.index)
|
|
96
|
+
if call is None:
|
|
97
|
+
call = Call(delta.id or new_id("call"), delta.tool_name or "", generated=not delta.id)
|
|
98
|
+
message.calls[delta.index] = call
|
|
99
|
+
self._open_calls[call.id] = source
|
|
100
|
+
self._started.add(call.id)
|
|
101
|
+
out += self._start_call(call, message.parent_id)
|
|
102
|
+
if delta.arguments:
|
|
103
|
+
call.arguments.append(delta.arguments)
|
|
104
|
+
out += self._call_delta(call, delta.arguments)
|
|
105
|
+
if chunk.tool_call_result is not None or chunk.finish_reason == "tool_call_results":
|
|
106
|
+
# The agent streams tool results from the thread or task that called the model, once the model call has
|
|
107
|
+
# returned: a message still open there was cut off. Its generator failed, and FallbackChatGenerator
|
|
108
|
+
# retried with one that runs elsewhere (a generator without run_async runs in a worker thread).
|
|
109
|
+
stale = self._messages.pop(source, None)
|
|
110
|
+
if stale is not None:
|
|
111
|
+
out += self._close(stale)
|
|
112
|
+
if chunk.tool_call_result is not None:
|
|
113
|
+
out += self._result(chunk.tool_call_result)
|
|
114
|
+
message = self._messages.get(source)
|
|
115
|
+
if message is not None and chunk.index is not None and (reasoning or chunk.content or chunk.tool_calls):
|
|
116
|
+
message.blocks[_block(chunk)].add(chunk.index)
|
|
117
|
+
message.top = max(message.top, chunk.index)
|
|
118
|
+
if chunk.finish_reason in MODEL_FINISH:
|
|
119
|
+
message = self._messages.pop(source, None)
|
|
120
|
+
if message is not None:
|
|
121
|
+
out += self._close(message)
|
|
122
|
+
out += self._message_finished(chunk.finish_reason)
|
|
123
|
+
elif chunk.finish_reason == "tool_call_results":
|
|
124
|
+
out += self._results_finished()
|
|
125
|
+
return self._frames(out)
|
|
126
|
+
|
|
127
|
+
# -- what the subclasses write ---------------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
def _message_opened(self) -> list[str]:
|
|
130
|
+
return []
|
|
131
|
+
|
|
132
|
+
def _start_reasoning(self, reasoning_id: str) -> list[str]:
|
|
133
|
+
raise NotImplementedError
|
|
134
|
+
|
|
135
|
+
def _reasoning_delta(self, reasoning_id: str, delta: str) -> list[str]:
|
|
136
|
+
raise NotImplementedError
|
|
137
|
+
|
|
138
|
+
def _end_reasoning(self, reasoning_id: str) -> list[str]:
|
|
139
|
+
raise NotImplementedError
|
|
140
|
+
|
|
141
|
+
def _start_text(self, text_id: str) -> list[str]:
|
|
142
|
+
raise NotImplementedError
|
|
143
|
+
|
|
144
|
+
def _text_delta(self, text_id: str, delta: str) -> list[str]:
|
|
145
|
+
raise NotImplementedError
|
|
146
|
+
|
|
147
|
+
def _end_text(self, text_id: str) -> list[str]:
|
|
148
|
+
raise NotImplementedError
|
|
149
|
+
|
|
150
|
+
def _start_call(self, call: Call, parent_id: str) -> list[str]:
|
|
151
|
+
raise NotImplementedError
|
|
152
|
+
|
|
153
|
+
def _call_delta(self, call: Call, delta: str) -> list[str]:
|
|
154
|
+
raise NotImplementedError
|
|
155
|
+
|
|
156
|
+
def _end_calls(self, calls: list[Call]) -> list[str]:
|
|
157
|
+
raise NotImplementedError
|
|
158
|
+
|
|
159
|
+
def _replay_call(self, call: Call) -> list[str]:
|
|
160
|
+
"""A tool call the browser never saw started, written in full before its result."""
|
|
161
|
+
raise NotImplementedError
|
|
162
|
+
|
|
163
|
+
def _result_frames(self, call_id: str, result: ToolCallResult) -> list[str]:
|
|
164
|
+
raise NotImplementedError
|
|
165
|
+
|
|
166
|
+
def _message_finished(self, reason: str | None) -> list[str]:
|
|
167
|
+
return []
|
|
168
|
+
|
|
169
|
+
def _results_finished(self) -> list[str]:
|
|
170
|
+
return []
|
|
171
|
+
|
|
172
|
+
# -- bookkeeping -------------------------------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
def _message(self, source: Hashable, out: list[str]) -> Message:
|
|
175
|
+
message = self._messages.get(source)
|
|
176
|
+
if message is None:
|
|
177
|
+
message_id = new_id("msg")
|
|
178
|
+
message = self._messages[source] = Message(message_id, message_id)
|
|
179
|
+
out += self._message_opened()
|
|
180
|
+
return message
|
|
181
|
+
|
|
182
|
+
def _close_reasoning(self, message: Message) -> list[str]:
|
|
183
|
+
if message.reasoning_id is None:
|
|
184
|
+
return []
|
|
185
|
+
reasoning_id, message.reasoning_id = message.reasoning_id, None
|
|
186
|
+
return self._end_reasoning(reasoning_id)
|
|
187
|
+
|
|
188
|
+
def _close_text(self, message: Message) -> list[str]:
|
|
189
|
+
if message.text_id is None:
|
|
190
|
+
return []
|
|
191
|
+
text_id, message.text_id = message.text_id, None
|
|
192
|
+
return self._end_text(text_id)
|
|
193
|
+
|
|
194
|
+
def _close(self, message: Message) -> list[str]:
|
|
195
|
+
out = self._close_reasoning(message) + self._close_text(message)
|
|
196
|
+
calls = list(message.calls.values())
|
|
197
|
+
message.calls = {}
|
|
198
|
+
for call in calls:
|
|
199
|
+
self._open_calls.pop(call.id, None)
|
|
200
|
+
if call.generated:
|
|
201
|
+
self._unanswered.append(call)
|
|
202
|
+
return out + (self._end_calls(calls) if calls else [])
|
|
203
|
+
|
|
204
|
+
def _close_all(self) -> list[str]:
|
|
205
|
+
out: list[str] = []
|
|
206
|
+
while self._messages:
|
|
207
|
+
out += self._close(self._messages.pop(next(iter(self._messages))))
|
|
208
|
+
return out
|
|
209
|
+
|
|
210
|
+
def _result(self, result: ToolCallResult) -> list[str]:
|
|
211
|
+
origin = result.origin
|
|
212
|
+
out: list[str] = []
|
|
213
|
+
call_id = origin.id
|
|
214
|
+
source = self._open_calls.get(call_id) if call_id else None
|
|
215
|
+
if source is not None: # the generator never said its message was finished
|
|
216
|
+
message = self._messages.pop(source, None)
|
|
217
|
+
if message is not None:
|
|
218
|
+
out += self._close(message)
|
|
219
|
+
if not call_id:
|
|
220
|
+
call_id = self._answered(origin)
|
|
221
|
+
if call_id is None or call_id not in self._started:
|
|
222
|
+
call = Call(call_id or new_id("call"), origin.tool_name, generated=call_id is None)
|
|
223
|
+
call.arguments.append(dumps(origin.arguments))
|
|
224
|
+
self._started.add(call.id)
|
|
225
|
+
out += self._replay_call(call)
|
|
226
|
+
call_id = call.id
|
|
227
|
+
return out + self._result_frames(call_id, result)
|
|
228
|
+
|
|
229
|
+
def _answered(self, origin: ToolCall) -> str | None:
|
|
230
|
+
"""The id of the waiting id-less call that ``origin`` answers: same tool and arguments, else same tool."""
|
|
231
|
+
same_tool = [call for call in self._unanswered if call.name == origin.tool_name]
|
|
232
|
+
for call in same_tool:
|
|
233
|
+
try:
|
|
234
|
+
if json.loads(call.text or "{}") == origin.arguments:
|
|
235
|
+
self._unanswered.remove(call)
|
|
236
|
+
return call.id
|
|
237
|
+
except ValueError:
|
|
238
|
+
continue
|
|
239
|
+
if same_tool:
|
|
240
|
+
self._unanswered.remove(same_tool[0])
|
|
241
|
+
return same_tool[0].id
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _block(chunk: StreamingChunk) -> Block:
|
|
246
|
+
if chunk.tool_calls:
|
|
247
|
+
return "call"
|
|
248
|
+
return "reasoning" if chunk.reasoning is not None and not chunk.content else "text"
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _starts_another(message: Message, chunk: StreamingChunk) -> bool:
|
|
252
|
+
"""Whether ``chunk``, from the caller whose ``message`` is open, begins another model message.
|
|
253
|
+
|
|
254
|
+
A tool call delta at a ``ToolCallDelta.index`` the message used does when its chunk starts a block, when it
|
|
255
|
+
carries another provider id, or when, without ids, it names the call again after its arguments (some providers
|
|
256
|
+
repeat a call's id and name on every fragment, so those alone mean nothing). A block that starts below the highest
|
|
257
|
+
chunk index does.
|
|
258
|
+
A text or reasoning block that starts at a chunk index the message used for that kind, or for a tool call, does.
|
|
259
|
+
A tool call does not count the text's chunk index, since OpenAI's chat completions number text and tool calls
|
|
260
|
+
apart, both from 0; and chunk and delta indexes are never compared, since Ollama numbers its chunks by position
|
|
261
|
+
and its tool calls from 1."""
|
|
262
|
+
for delta in chunk.tool_calls or []:
|
|
263
|
+
call = message.calls.get(delta.index)
|
|
264
|
+
if call is None:
|
|
265
|
+
continue
|
|
266
|
+
if chunk.start:
|
|
267
|
+
return True
|
|
268
|
+
if delta.id and not call.generated and delta.id != call.id:
|
|
269
|
+
return True
|
|
270
|
+
if not delta.id and call.generated and delta.tool_name and call.arguments:
|
|
271
|
+
return True
|
|
272
|
+
if not chunk.start or chunk.index is None or chunk.tool_call_result is not None:
|
|
273
|
+
return False
|
|
274
|
+
if chunk.index < message.top:
|
|
275
|
+
return True
|
|
276
|
+
kind = _block(chunk)
|
|
277
|
+
return kind != "call" and chunk.index in message.blocks[kind] | message.blocks["call"]
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""StreamingChunk -> AG-UI events, built with the ``ag_ui.core`` models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from ag_ui.core import (
|
|
9
|
+
BaseEvent,
|
|
10
|
+
CustomEvent,
|
|
11
|
+
ReasoningEndEvent,
|
|
12
|
+
ReasoningMessageContentEvent,
|
|
13
|
+
ReasoningMessageEndEvent,
|
|
14
|
+
ReasoningMessageStartEvent,
|
|
15
|
+
ReasoningStartEvent,
|
|
16
|
+
RunErrorEvent,
|
|
17
|
+
RunFinishedCancelledOutcome,
|
|
18
|
+
RunFinishedEvent,
|
|
19
|
+
RunStartedEvent,
|
|
20
|
+
TextMessageContentEvent,
|
|
21
|
+
TextMessageEndEvent,
|
|
22
|
+
TextMessageStartEvent,
|
|
23
|
+
ToolCallArgsEvent,
|
|
24
|
+
ToolCallEndEvent,
|
|
25
|
+
ToolCallResultEvent,
|
|
26
|
+
ToolCallStartEvent,
|
|
27
|
+
)
|
|
28
|
+
from haystack.dataclasses import ToolCallResult
|
|
29
|
+
|
|
30
|
+
from ._messages import Call, MessageConverter
|
|
31
|
+
from .base import ConverterOptions, Frame, dumps, new_id
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from typing_extensions import Unpack
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def encode_event(event: BaseEvent) -> str:
|
|
38
|
+
"""An event's JSON as the TypeScript client reads it: camelCase, unset fields left out. A value JSON cannot hold
|
|
39
|
+
is written as its ``str()``, and a NaN or an infinity as ``null``, as ``dumps`` writes them."""
|
|
40
|
+
return event.model_dump_json(by_alias=True, exclude_none=True, fallback=str)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AGUIConverter(MessageConverter):
|
|
44
|
+
"""One AG-UI event per frame, unnamed: ``RUN_STARTED``, text, reasoning and tool call events, then
|
|
45
|
+
``RUN_FINISHED`` (with the ``cancelled`` outcome for a cancelled run) or ``RUN_ERROR``.
|
|
46
|
+
|
|
47
|
+
Text, reasoning and argument deltas too large for a frame are split into several events; a tool result is
|
|
48
|
+
truncated with a marker that gives its full length.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, *, thread_id: str, run_id: str, **options: Unpack[ConverterOptions]) -> None:
|
|
52
|
+
super().__init__(**options)
|
|
53
|
+
self.thread_id = thread_id
|
|
54
|
+
self.run_id = run_id
|
|
55
|
+
|
|
56
|
+
def start(self) -> list[Frame]:
|
|
57
|
+
return [Frame(self.fit.whole(encode_event(RunStartedEvent(thread_id=self.thread_id, run_id=self.run_id))))]
|
|
58
|
+
|
|
59
|
+
def finish(self) -> list[Frame]:
|
|
60
|
+
event = RunFinishedEvent(thread_id=self.thread_id, run_id=self.run_id)
|
|
61
|
+
return self._frames([*self._close_all(), self.fit.whole(encode_event(event))])
|
|
62
|
+
|
|
63
|
+
def cancelled(self) -> list[Frame]:
|
|
64
|
+
event = RunFinishedEvent(thread_id=self.thread_id, run_id=self.run_id, outcome=RunFinishedCancelledOutcome())
|
|
65
|
+
return self._frames([*self._close_all(), self.fit.whole(encode_event(event))])
|
|
66
|
+
|
|
67
|
+
def error(self, exc: BaseException) -> list[Frame]:
|
|
68
|
+
message = self.fit.truncate(
|
|
69
|
+
self._error_message(exc), lambda text: encode_event(RunErrorEvent(message=text, code="error"))
|
|
70
|
+
)
|
|
71
|
+
return self._frames([*self._close_all(), encode_event(RunErrorEvent(message=message, code="error"))])
|
|
72
|
+
|
|
73
|
+
def custom(self, name: str, value: object) -> list[Frame]:
|
|
74
|
+
# Through the JSON the other protocols write, so that the three write every value alike.
|
|
75
|
+
event = CustomEvent(name=name, value=json.loads(dumps(value)))
|
|
76
|
+
return [Frame(self.fit.whole(encode_event(event)))]
|
|
77
|
+
|
|
78
|
+
def _start_reasoning(self, reasoning_id: str) -> list[str]:
|
|
79
|
+
return [
|
|
80
|
+
encode_event(ReasoningStartEvent(message_id=reasoning_id)),
|
|
81
|
+
encode_event(ReasoningMessageStartEvent(message_id=reasoning_id, role="reasoning")),
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
def _reasoning_delta(self, reasoning_id: str, delta: str) -> list[str]:
|
|
85
|
+
def build(text: str) -> str:
|
|
86
|
+
return encode_event(ReasoningMessageContentEvent(message_id=reasoning_id, delta=text))
|
|
87
|
+
|
|
88
|
+
return [build(piece) for piece in self.fit.split(delta, build)]
|
|
89
|
+
|
|
90
|
+
def _end_reasoning(self, reasoning_id: str) -> list[str]:
|
|
91
|
+
return [
|
|
92
|
+
encode_event(ReasoningMessageEndEvent(message_id=reasoning_id)),
|
|
93
|
+
encode_event(ReasoningEndEvent(message_id=reasoning_id)),
|
|
94
|
+
]
|
|
95
|
+
|
|
96
|
+
def _start_text(self, text_id: str) -> list[str]:
|
|
97
|
+
return [encode_event(TextMessageStartEvent(message_id=text_id, role="assistant"))]
|
|
98
|
+
|
|
99
|
+
def _text_delta(self, text_id: str, delta: str) -> list[str]:
|
|
100
|
+
def build(text: str) -> str:
|
|
101
|
+
return encode_event(TextMessageContentEvent(message_id=text_id, delta=text))
|
|
102
|
+
|
|
103
|
+
return [build(piece) for piece in self.fit.split(delta, build)]
|
|
104
|
+
|
|
105
|
+
def _end_text(self, text_id: str) -> list[str]:
|
|
106
|
+
return [encode_event(TextMessageEndEvent(message_id=text_id))]
|
|
107
|
+
|
|
108
|
+
def _start_call(self, call: Call, parent_id: str) -> list[str]:
|
|
109
|
+
event = ToolCallStartEvent(tool_call_id=call.id, tool_call_name=call.name, parent_message_id=parent_id)
|
|
110
|
+
return [self.fit.whole(encode_event(event))]
|
|
111
|
+
|
|
112
|
+
def _call_delta(self, call: Call, delta: str) -> list[str]:
|
|
113
|
+
def build(text: str) -> str:
|
|
114
|
+
return encode_event(ToolCallArgsEvent(tool_call_id=call.id, delta=text))
|
|
115
|
+
|
|
116
|
+
return [build(piece) for piece in self.fit.split(delta, build)]
|
|
117
|
+
|
|
118
|
+
def _end_calls(self, calls: list[Call]) -> list[str]:
|
|
119
|
+
return [encode_event(ToolCallEndEvent(tool_call_id=call.id)) for call in calls]
|
|
120
|
+
|
|
121
|
+
def _replay_call(self, call: Call) -> list[str]:
|
|
122
|
+
return [
|
|
123
|
+
*self._start_call(call, new_id("msg")),
|
|
124
|
+
*self._call_delta(call, call.text),
|
|
125
|
+
*self._end_calls([call]),
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
def _result_frames(self, call_id: str, result: ToolCallResult) -> list[str]:
|
|
129
|
+
message_id = new_id("tool")
|
|
130
|
+
|
|
131
|
+
def build(text: str) -> str:
|
|
132
|
+
return encode_event(
|
|
133
|
+
ToolCallResultEvent(message_id=message_id, tool_call_id=call_id, content=text, role="tool")
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
return [build(self.fit.truncate(self._result_content(result), build, self.max_tool_result_bytes))]
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""StreamingChunk -> AI SDK UI message chunks, the stream that ``useChat`` reads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from haystack.dataclasses import ToolCallResult
|
|
9
|
+
|
|
10
|
+
from ._messages import Call, MessageConverter
|
|
11
|
+
from .base import INVALID_ARGUMENTS, ConverterOptions, Frame, dumps
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from typing_extensions import Unpack
|
|
15
|
+
|
|
16
|
+
# Haystack's finish reasons, in the AI SDK's spelling.
|
|
17
|
+
_FINISH_REASONS = {"stop": "stop", "length": "length", "content_filter": "content-filter", "tool_calls": "tool-calls"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AISDKConverter(MessageConverter):
|
|
21
|
+
"""One UI message chunk per frame, unnamed: ``start``, then a step per model call and its tool results
|
|
22
|
+
(``start-step`` ... ``finish-step``), then ``finish``, ``error`` or, for a cancelled run, ``abort``.
|
|
23
|
+
|
|
24
|
+
The whole run is one assistant message, whose id is ``message_id``. Deltas too large for a frame are split; a
|
|
25
|
+
tool's output is truncated with a marker; a ``tool-input-available`` too large for a frame is left out, since
|
|
26
|
+
the input deltas carried the arguments already. A call whose arguments are not JSON, cut off by a broken
|
|
27
|
+
stream or by the length limit, ends with ``tool-input-error``: Haystack runs no such call.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, *, message_id: str, **options: Unpack[ConverterOptions]) -> None:
|
|
31
|
+
super().__init__(**options)
|
|
32
|
+
self.message_id = message_id
|
|
33
|
+
self._step_open = False
|
|
34
|
+
self._waiting: set[str] = set() # tool calls of the open step that have no result yet
|
|
35
|
+
self._last_reason: str | None = None
|
|
36
|
+
|
|
37
|
+
def start(self) -> list[Frame]:
|
|
38
|
+
return [Frame(self.fit.whole(dumps({"type": "start", "messageId": self.message_id})))]
|
|
39
|
+
|
|
40
|
+
def finish(self) -> list[Frame]:
|
|
41
|
+
chunk: dict[str, str] = {"type": "finish"}
|
|
42
|
+
if self._last_reason in _FINISH_REASONS:
|
|
43
|
+
chunk["finishReason"] = _FINISH_REASONS[self._last_reason]
|
|
44
|
+
return self._frames([*self._close_all(), *self._finish_step(), dumps(chunk)])
|
|
45
|
+
|
|
46
|
+
def cancelled(self) -> list[Frame]:
|
|
47
|
+
return self._frames([*self._close_all(), *self._finish_step(), dumps({"type": "abort", "reason": "cancelled"})])
|
|
48
|
+
|
|
49
|
+
def error(self, exc: BaseException) -> list[Frame]:
|
|
50
|
+
def build(text: str) -> str:
|
|
51
|
+
return dumps({"type": "error", "errorText": text})
|
|
52
|
+
|
|
53
|
+
text = self.fit.truncate(self._error_message(exc), build)
|
|
54
|
+
return self._frames([*self._close_all(), *self._finish_step(), build(text)])
|
|
55
|
+
|
|
56
|
+
def custom(self, name: str, value: object) -> list[Frame]:
|
|
57
|
+
return [Frame(self.fit.whole(dumps({"type": f"data-{name}", "data": value})))]
|
|
58
|
+
|
|
59
|
+
def _message_opened(self) -> list[str]:
|
|
60
|
+
if self._step_open:
|
|
61
|
+
return []
|
|
62
|
+
self._step_open = True
|
|
63
|
+
return [dumps({"type": "start-step"})]
|
|
64
|
+
|
|
65
|
+
def _message_finished(self, reason: str | None) -> list[str]:
|
|
66
|
+
self._last_reason = reason
|
|
67
|
+
return [] if self._waiting else self._finish_step()
|
|
68
|
+
|
|
69
|
+
def _results_finished(self) -> list[str]:
|
|
70
|
+
self._waiting.clear()
|
|
71
|
+
return self._finish_step()
|
|
72
|
+
|
|
73
|
+
def _finish_step(self) -> list[str]:
|
|
74
|
+
# finish-step forgets the open text and reasoning parts: it waits until no source has a message open.
|
|
75
|
+
if not self._step_open or self._messages:
|
|
76
|
+
return []
|
|
77
|
+
self._step_open = False
|
|
78
|
+
return [dumps({"type": "finish-step"})]
|
|
79
|
+
|
|
80
|
+
def _start_reasoning(self, reasoning_id: str) -> list[str]:
|
|
81
|
+
return [dumps({"type": "reasoning-start", "id": reasoning_id})]
|
|
82
|
+
|
|
83
|
+
def _reasoning_delta(self, reasoning_id: str, delta: str) -> list[str]:
|
|
84
|
+
def build(text: str) -> str:
|
|
85
|
+
return dumps({"type": "reasoning-delta", "id": reasoning_id, "delta": text})
|
|
86
|
+
|
|
87
|
+
return [build(piece) for piece in self.fit.split(delta, build)]
|
|
88
|
+
|
|
89
|
+
def _end_reasoning(self, reasoning_id: str) -> list[str]:
|
|
90
|
+
return [dumps({"type": "reasoning-end", "id": reasoning_id})]
|
|
91
|
+
|
|
92
|
+
def _start_text(self, text_id: str) -> list[str]:
|
|
93
|
+
return [dumps({"type": "text-start", "id": text_id})]
|
|
94
|
+
|
|
95
|
+
def _text_delta(self, text_id: str, delta: str) -> list[str]:
|
|
96
|
+
def build(text: str) -> str:
|
|
97
|
+
return dumps({"type": "text-delta", "id": text_id, "delta": text})
|
|
98
|
+
|
|
99
|
+
return [build(piece) for piece in self.fit.split(delta, build)]
|
|
100
|
+
|
|
101
|
+
def _end_text(self, text_id: str) -> list[str]:
|
|
102
|
+
return [dumps({"type": "text-end", "id": text_id})]
|
|
103
|
+
|
|
104
|
+
def _start_call(self, call: Call, parent_id: str) -> list[str]:
|
|
105
|
+
return [self.fit.whole(dumps({"type": "tool-input-start", "toolCallId": call.id, "toolName": call.name}))]
|
|
106
|
+
|
|
107
|
+
def _call_delta(self, call: Call, delta: str) -> list[str]:
|
|
108
|
+
def build(text: str) -> str:
|
|
109
|
+
return dumps({"type": "tool-input-delta", "toolCallId": call.id, "inputTextDelta": text})
|
|
110
|
+
|
|
111
|
+
return [build(piece) for piece in self.fit.split(delta, build)]
|
|
112
|
+
|
|
113
|
+
def _end_calls(self, calls: list[Call]) -> list[str]:
|
|
114
|
+
out: list[str] = []
|
|
115
|
+
for call in calls:
|
|
116
|
+
try:
|
|
117
|
+
arguments: object = json.loads(call.text or "{}")
|
|
118
|
+
except ValueError:
|
|
119
|
+
out.append(self._input_error(call))
|
|
120
|
+
continue
|
|
121
|
+
self._waiting.add(call.id)
|
|
122
|
+
chunk = dumps(
|
|
123
|
+
{"type": "tool-input-available", "toolCallId": call.id, "toolName": call.name, "input": arguments}
|
|
124
|
+
)
|
|
125
|
+
if self.fit.fits(chunk):
|
|
126
|
+
out.append(chunk)
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
def _input_error(self, call: Call) -> str:
|
|
130
|
+
def build(text: str) -> str:
|
|
131
|
+
return dumps(
|
|
132
|
+
{
|
|
133
|
+
"type": "tool-input-error",
|
|
134
|
+
"toolCallId": call.id,
|
|
135
|
+
"toolName": call.name,
|
|
136
|
+
"input": text,
|
|
137
|
+
"errorText": INVALID_ARGUMENTS,
|
|
138
|
+
}
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
chunk = build(call.text)
|
|
142
|
+
return chunk if self.fit.fits(chunk) else self.fit.whole(build("")) # the input deltas carried it
|
|
143
|
+
|
|
144
|
+
def _replay_call(self, call: Call) -> list[str]:
|
|
145
|
+
return [*self._start_call(call, ""), *self._end_calls([call])]
|
|
146
|
+
|
|
147
|
+
def _result_frames(self, call_id: str, result: ToolCallResult) -> list[str]:
|
|
148
|
+
self._waiting.discard(call_id)
|
|
149
|
+
content = self._result_content(result)
|
|
150
|
+
if result.error:
|
|
151
|
+
|
|
152
|
+
def build(text: str) -> str:
|
|
153
|
+
return dumps({"type": "tool-output-error", "toolCallId": call_id, "errorText": text})
|
|
154
|
+
|
|
155
|
+
else:
|
|
156
|
+
|
|
157
|
+
def build(text: str) -> str:
|
|
158
|
+
return dumps({"type": "tool-output-available", "toolCallId": call_id, "output": text})
|
|
159
|
+
|
|
160
|
+
return [build(self.fit.truncate(content, build, self.max_tool_result_bytes))]
|