sinapsis_deserialization 1.0.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.
- sinapsis_deserialization/__init__.py +4 -0
- sinapsis_deserialization/data_container_decoders.py +310 -0
- sinapsis_deserialization/schemas/__init__.py +15 -0
- sinapsis_deserialization/schemas/constant_variables.py +85 -0
- sinapsis_deserialization/schemas/messaging_base_models.py +81 -0
- sinapsis_deserialization/schemas/type_checkers.py +91 -0
- sinapsis_deserialization/sse_deserializers.py +115 -0
- sinapsis_deserialization-1.0.0.dist-info/METADATA +194 -0
- sinapsis_deserialization-1.0.0.dist-info/RECORD +12 -0
- sinapsis_deserialization-1.0.0.dist-info/WHEEL +4 -0
- sinapsis_deserialization-1.0.0.dist-info/licenses/LICENSE-APACHE +202 -0
- sinapsis_deserialization-1.0.0.dist-info/licenses/LICENSE-MIT +21 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import io
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from sinapsis.data_transport import (
|
|
5
|
+
AudioAnnotations,
|
|
6
|
+
AudioPacket,
|
|
7
|
+
BinaryPacket,
|
|
8
|
+
DataContainer,
|
|
9
|
+
DataFramePacket,
|
|
10
|
+
FilePacket,
|
|
11
|
+
ImageAnnotations,
|
|
12
|
+
ImageColor,
|
|
13
|
+
ImagePacket,
|
|
14
|
+
TextAnnotations,
|
|
15
|
+
TextPacket,
|
|
16
|
+
TimeSeriesPacket,
|
|
17
|
+
)
|
|
18
|
+
from sinapsis.logging import sinapsis_logger
|
|
19
|
+
|
|
20
|
+
from sinapsis_deserialization.schemas.constant_variables import (
|
|
21
|
+
BasePacketFieldNames,
|
|
22
|
+
ContainerFieldNames,
|
|
23
|
+
EncodedArrayFieldNames,
|
|
24
|
+
PacketFieldNames,
|
|
25
|
+
SupportedArrayTypeNames,
|
|
26
|
+
)
|
|
27
|
+
from sinapsis_deserialization.schemas.type_checkers import (
|
|
28
|
+
is_array_content,
|
|
29
|
+
is_encoded_array_type,
|
|
30
|
+
is_iterable,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class DataContainerDecoder:
|
|
35
|
+
"""Class to decode different types of data packets into corresponding objects."""
|
|
36
|
+
|
|
37
|
+
def __call__(self, container_dict: dict[str, Any]) -> DataContainer | dict[str, Any]:
|
|
38
|
+
return self.decode_container(container_dict)
|
|
39
|
+
|
|
40
|
+
def decode_container(self, container_dict: dict[str, Any]) -> DataContainer | dict[str, Any]:
|
|
41
|
+
"""Decode a container dictionary into a DataContainer object."""
|
|
42
|
+
if isinstance(container_dict, dict) and ContainerFieldNames.container_id in container_dict:
|
|
43
|
+
container_id = container_dict[ContainerFieldNames.container_id]
|
|
44
|
+
return DataContainer(
|
|
45
|
+
container_id=container_id,
|
|
46
|
+
images=[self.decode_image(packet) for packet in container_dict.get(ContainerFieldNames.images, [])],
|
|
47
|
+
audios=[self.decode_audio(packet) for packet in container_dict.get(ContainerFieldNames.audios, [])],
|
|
48
|
+
texts=[self.decode_text(packet) for packet in container_dict.get(ContainerFieldNames.texts, [])],
|
|
49
|
+
files=[self.decode_file(packet) for packet in container_dict.get(ContainerFieldNames.files, [])],
|
|
50
|
+
data_frames=[
|
|
51
|
+
self.decode_data_frame(packet) for packet in container_dict.get(ContainerFieldNames.data_frames, [])
|
|
52
|
+
],
|
|
53
|
+
time_series=[
|
|
54
|
+
self.decode_time_series(packet)
|
|
55
|
+
for packet in container_dict.get(ContainerFieldNames.time_series, [])
|
|
56
|
+
],
|
|
57
|
+
binary_data=[
|
|
58
|
+
self.decode_binary(packet) for packet in container_dict.get(ContainerFieldNames.binary_data, [])
|
|
59
|
+
],
|
|
60
|
+
generic_data=self.decode_generic_dict(container_dict.get(ContainerFieldNames.generic_data, {})),
|
|
61
|
+
)
|
|
62
|
+
return container_dict
|
|
63
|
+
|
|
64
|
+
def decode_arrays_in_dict(self, dataclass_dict: dict) -> dict:
|
|
65
|
+
"""Decode a Pydantic dataclass into a DataContainer object."""
|
|
66
|
+
for key, value in dataclass_dict.items():
|
|
67
|
+
if isinstance(value, dict):
|
|
68
|
+
if is_encoded_array_type(value):
|
|
69
|
+
dataclass_dict[key] = self.array_type_decoder(value)
|
|
70
|
+
else:
|
|
71
|
+
self.decode_arrays_in_dict(value)
|
|
72
|
+
return dataclass_dict
|
|
73
|
+
|
|
74
|
+
def decode_generic_dict(self, generic_dict: dict[str, Any]) -> dict:
|
|
75
|
+
"""Decode a dictionary into a DataContainer object. For each of the values in the dictionary,
|
|
76
|
+
recursively checkthe type of object to apply the proper decoding method
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
generic_dict: dictionary to be decoded
|
|
80
|
+
Returns:
|
|
81
|
+
decoded dictionary
|
|
82
|
+
"""
|
|
83
|
+
decoded = {}
|
|
84
|
+
for key, value in generic_dict.items():
|
|
85
|
+
if isinstance(value, dict):
|
|
86
|
+
if is_encoded_array_type(value):
|
|
87
|
+
decoded[key] = self.array_type_decoder(value)
|
|
88
|
+
else:
|
|
89
|
+
decoded[key] = self.decode_generic_dict(value)
|
|
90
|
+
|
|
91
|
+
elif is_iterable(value):
|
|
92
|
+
decoded[key] = self.decode_iterable(value)
|
|
93
|
+
|
|
94
|
+
else:
|
|
95
|
+
decoded[key] = value
|
|
96
|
+
|
|
97
|
+
return decoded
|
|
98
|
+
|
|
99
|
+
def decode_iterable(self, obj: Any) -> list:
|
|
100
|
+
"""Recursively traverses and decodes nested objects.
|
|
101
|
+
|
|
102
|
+
This method iterates through a collection (list, tuple, etc.) and evaluates
|
|
103
|
+
each element. It specifically handles nested dictionaries, iterables,
|
|
104
|
+
and encoded array types to ensure the entire tree is reconstructed into
|
|
105
|
+
its original Python or numerical types.
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
obj: The iterable collection containing potentially encoded elements.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
A new collection of the same type as the input (e.g., list or tuple)
|
|
113
|
+
containing the fully decoded items.
|
|
114
|
+
"""
|
|
115
|
+
decoded_items = []
|
|
116
|
+
for item in obj:
|
|
117
|
+
if isinstance(item, dict):
|
|
118
|
+
if is_encoded_array_type(item):
|
|
119
|
+
decoded_items.append(self.array_type_decoder(item))
|
|
120
|
+
else:
|
|
121
|
+
decoded_items.append(self.decode_generic_dict(item))
|
|
122
|
+
|
|
123
|
+
elif is_iterable(item) and not isinstance(item, (str, bytes)):
|
|
124
|
+
decoded_items.append(self.decode_iterable(item))
|
|
125
|
+
|
|
126
|
+
elif is_array_content(item):
|
|
127
|
+
decoded_items.append(self.array_type_decoder(item))
|
|
128
|
+
|
|
129
|
+
else:
|
|
130
|
+
decoded_items.append(item)
|
|
131
|
+
|
|
132
|
+
return type(obj)(decoded_items)
|
|
133
|
+
|
|
134
|
+
def base_packet_decoder(self, packet: dict[str, Any]) -> dict[str, Any]:
|
|
135
|
+
"""Decodes a DataPacket into a DataContainer object.
|
|
136
|
+
|
|
137
|
+
This helper extracts and decodes the shared metadata and content required
|
|
138
|
+
to instantiate specific packets. It specifically handles the
|
|
139
|
+
deserialization of the 'content', 'embedding', and 'generic_data' fields.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
packet: The raw dictionary containing base packet data.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
dict[str, Any]: A dictionary of decoded values suitable for
|
|
146
|
+
unpacking into a packet constructor.
|
|
147
|
+
"""
|
|
148
|
+
packet_content = packet[PacketFieldNames.content]
|
|
149
|
+
content = self.array_type_decoder(packet_content) if isinstance(packet_content, dict) else packet_content
|
|
150
|
+
base_dict = {
|
|
151
|
+
PacketFieldNames.content: content,
|
|
152
|
+
BasePacketFieldNames.id: packet[BasePacketFieldNames.id],
|
|
153
|
+
BasePacketFieldNames.source: packet[BasePacketFieldNames.source],
|
|
154
|
+
BasePacketFieldNames.embedding: [
|
|
155
|
+
self.array_type_decoder(emb) for emb in packet.get(BasePacketFieldNames.embedding, [])
|
|
156
|
+
],
|
|
157
|
+
BasePacketFieldNames.generic_data: self.decode_generic_dict(packet[BasePacketFieldNames.generic_data]),
|
|
158
|
+
}
|
|
159
|
+
return base_dict
|
|
160
|
+
|
|
161
|
+
def decode_image(self, packet: dict[str, Any]) -> ImagePacket:
|
|
162
|
+
"""Decodes a dictionary into an ImagePacket, including annotations and color space.
|
|
163
|
+
"""
|
|
164
|
+
base_dict = self.base_packet_decoder(packet)
|
|
165
|
+
return ImagePacket(
|
|
166
|
+
# content=content,
|
|
167
|
+
annotations=[
|
|
168
|
+
ImageAnnotations(**self.decode_arrays_in_dict(ann_dict))
|
|
169
|
+
for ann_dict in packet[PacketFieldNames.annotations]
|
|
170
|
+
],
|
|
171
|
+
color_space=ImageColor(packet[PacketFieldNames.color_space])
|
|
172
|
+
if packet[PacketFieldNames.color_space]
|
|
173
|
+
else None,
|
|
174
|
+
**base_dict,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def decode_audio(self, packet: dict[str, Any]) -> AudioPacket:
|
|
178
|
+
"""Decodes a dictionary into an AudioPacket with duration and sample rate metadata.
|
|
179
|
+
"""
|
|
180
|
+
return AudioPacket(
|
|
181
|
+
# content=cls.array_type_decoder(packet[PacketFieldNames.content]),
|
|
182
|
+
sample_rate=packet[PacketFieldNames.sample_rate],
|
|
183
|
+
audio_duration=packet[PacketFieldNames.audio_duration],
|
|
184
|
+
annotations=[
|
|
185
|
+
AudioAnnotations(**self.decode_arrays_in_dict(ann_dict))
|
|
186
|
+
for ann_dict in packet.get(PacketFieldNames.annotations, [])
|
|
187
|
+
],
|
|
188
|
+
# source=packet[PacketFieldNames.source],
|
|
189
|
+
# id=packet[BasePacketFieldNames.id]
|
|
190
|
+
**self.base_packet_decoder(packet),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def decode_text(self, packet: dict[str, Any]) -> TextPacket:
|
|
194
|
+
"""Decodes a dictionary into a TextPacket, maintaining text-specific annotations.
|
|
195
|
+
"""
|
|
196
|
+
anns = packet[PacketFieldNames.annotations]
|
|
197
|
+
if isinstance(anns, dict):
|
|
198
|
+
anns = anns.get(PacketFieldNames.annotations, [])
|
|
199
|
+
annotations = [TextAnnotations(ann) for ann in anns] if anns else []
|
|
200
|
+
return TextPacket(
|
|
201
|
+
# content=packet[PacketFieldNames.content],
|
|
202
|
+
annotations=annotations,
|
|
203
|
+
**self.base_packet_decoder(packet),
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
def decode_data_frame(self, packet: dict[str, Any]) -> DataFramePacket:
|
|
207
|
+
"""Decodes a dictionary into a DataFramePacket.
|
|
208
|
+
"""
|
|
209
|
+
return DataFramePacket(**self.base_packet_decoder(packet))
|
|
210
|
+
|
|
211
|
+
def decode_file(self, packet: dict[str, Any]) -> FilePacket:
|
|
212
|
+
"""Decodes a dictionary into a FilePacket.
|
|
213
|
+
"""
|
|
214
|
+
return FilePacket(**self.base_packet_decoder(packet))
|
|
215
|
+
|
|
216
|
+
def decode_time_series(self, packet: dict[str, Any]) -> TimeSeriesPacket:
|
|
217
|
+
"""Decodes a dictionary into a TimeSeriesPacket, including covariates and predictions.
|
|
218
|
+
"""
|
|
219
|
+
preds = packet[PacketFieldNames.predictions]
|
|
220
|
+
future_covs = packet[PacketFieldNames.future_covariates]
|
|
221
|
+
past_covs = packet[PacketFieldNames.past_covariates]
|
|
222
|
+
|
|
223
|
+
return TimeSeriesPacket(
|
|
224
|
+
# content= cls.array_type_decoder(packet[PacketFieldNames.content]),
|
|
225
|
+
predictions=self.array_type_decoder(preds) if preds else None,
|
|
226
|
+
past_covariates=self.array_type_decoder(past_covs) if past_covs else None,
|
|
227
|
+
future_covariates=self.array_type_decoder(future_covs) if future_covs else None,
|
|
228
|
+
**self.base_packet_decoder(packet),
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def decode_binary(self, packet: dict[str, Any]) -> BinaryPacket:
|
|
232
|
+
"""Decode a binary packet into a BinaryPacket object."""
|
|
233
|
+
return BinaryPacket(
|
|
234
|
+
# content=cls.array_type_decoder(packet[PacketFieldNames.content]),
|
|
235
|
+
**self.base_packet_decoder(packet)
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
@classmethod
|
|
239
|
+
def array_type_decoder(cls, packet_content: dict[str, Any]) -> Any:
|
|
240
|
+
"""The master decoder for converting serialized array data back into native objects.
|
|
241
|
+
|
|
242
|
+
Based on the 'array_type' flag, this method handles:
|
|
243
|
+
- NumPy arrays from buffer strings.
|
|
244
|
+
- PyTorch tensors (including device and dtype mapping).
|
|
245
|
+
- Pandas Series (via pickle) and DataFrames (via JSON split orient).
|
|
246
|
+
- Darts TimeSeries objects.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
packet_content: A dictionary representing an encoded array,
|
|
250
|
+
containing keys for content, shape, dtype, and type identifier.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
The reconstructed numerical or tabular object.
|
|
254
|
+
"""
|
|
255
|
+
content = packet_content[PacketFieldNames.content]
|
|
256
|
+
# we check for the special case where content is replaced by file names to be fetched
|
|
257
|
+
if isinstance(content, dict) and "sample" in content:
|
|
258
|
+
return packet_content
|
|
259
|
+
|
|
260
|
+
array_type = packet_content[EncodedArrayFieldNames.array_type]
|
|
261
|
+
# content = packet_content[PacketFieldNames.content]
|
|
262
|
+
|
|
263
|
+
if array_type == SupportedArrayTypeNames.bytes:
|
|
264
|
+
return content
|
|
265
|
+
|
|
266
|
+
dtype = packet_content.get(EncodedArrayFieldNames.dtype)
|
|
267
|
+
shape = tuple(packet_content.get(EncodedArrayFieldNames.shape, []))
|
|
268
|
+
|
|
269
|
+
if array_type == SupportedArrayTypeNames.numpy:
|
|
270
|
+
import numpy as np
|
|
271
|
+
|
|
272
|
+
return np.frombuffer(content, dtype=dtype).reshape(shape)
|
|
273
|
+
|
|
274
|
+
if array_type == SupportedArrayTypeNames.torch:
|
|
275
|
+
import torch
|
|
276
|
+
|
|
277
|
+
torch_dtype = eval(dtype) if isinstance(dtype, str) else dtype
|
|
278
|
+
return (
|
|
279
|
+
torch.frombuffer(bytearray(content), dtype=torch_dtype)
|
|
280
|
+
.reshape(shape)
|
|
281
|
+
.to(packet_content.get(EncodedArrayFieldNames.device, "cpu"))
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
if array_type == SupportedArrayTypeNames.pd_timeseries:
|
|
285
|
+
import pandas as pd
|
|
286
|
+
|
|
287
|
+
return pd.read_pickle(io.BytesIO(content))
|
|
288
|
+
|
|
289
|
+
if array_type == SupportedArrayTypeNames.pd_dataframe:
|
|
290
|
+
import pandas as pd
|
|
291
|
+
|
|
292
|
+
df = pd.read_json(io.StringIO(content), orient="split")
|
|
293
|
+
if isinstance(dtype, dict):
|
|
294
|
+
if set(dtype.keys()) == set(df.columns):
|
|
295
|
+
df = df.astype(dtype)
|
|
296
|
+
elif isinstance(dtype, str):
|
|
297
|
+
df = df.astype(dtype)
|
|
298
|
+
return df
|
|
299
|
+
|
|
300
|
+
if array_type == SupportedArrayTypeNames.darts_timeseries:
|
|
301
|
+
import darts
|
|
302
|
+
import numpy as np
|
|
303
|
+
|
|
304
|
+
ts = darts.TimeSeries.from_json(content)
|
|
305
|
+
if isinstance(dtype, str) and dtype in np.sctypeDict:
|
|
306
|
+
ts = ts.astype(np.dtype(dtype))
|
|
307
|
+
return ts
|
|
308
|
+
|
|
309
|
+
sinapsis_logger.warning(f"Unsupported array type '{array_type}', not decoding")
|
|
310
|
+
return packet_content
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .messaging_base_models import (
|
|
2
|
+
AgentResponse,
|
|
3
|
+
AgentResponseFieldNames,
|
|
4
|
+
SSEMessage,
|
|
5
|
+
TemplateResponseFieldNames,
|
|
6
|
+
TemplateStreamingResponse,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AgentResponse",
|
|
11
|
+
"AgentResponseFieldNames",
|
|
12
|
+
"SSEMessage",
|
|
13
|
+
"TemplateResponseFieldNames",
|
|
14
|
+
"TemplateStreamingResponse",
|
|
15
|
+
]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class BasePacketFieldNames:
|
|
6
|
+
"""Data class with base fields required when encoding/decoding data packets"""
|
|
7
|
+
|
|
8
|
+
id: str = "id"
|
|
9
|
+
source: str = "source"
|
|
10
|
+
embedding: str = "embedding"
|
|
11
|
+
generic_data: str = "generic_data"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ContainerFieldNames:
|
|
16
|
+
"""Data class with base fields required when encoding/decoding full data containers."""
|
|
17
|
+
|
|
18
|
+
container_id: str = "container_id"
|
|
19
|
+
images: str = "images"
|
|
20
|
+
audios: str = "audios"
|
|
21
|
+
texts: str = "texts"
|
|
22
|
+
data_frames: str = "data_frames"
|
|
23
|
+
time_series: str = "time_series"
|
|
24
|
+
binary_data: str = "binary_data"
|
|
25
|
+
generic_data: str = "generic_data"
|
|
26
|
+
files: str = "files"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class PacketFieldNames:
|
|
31
|
+
"""Data class the names of the fields for the Packet dataclass. It includes
|
|
32
|
+
some packet specific fields.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
content: str = "content"
|
|
36
|
+
source: str = "source"
|
|
37
|
+
shape: str = "shape"
|
|
38
|
+
embedding: str = "embedding"
|
|
39
|
+
annotations: str = "annotations"
|
|
40
|
+
color_space: str = "color_space"
|
|
41
|
+
sample_rate: str = "sample_rate"
|
|
42
|
+
predictions: str = "predictions"
|
|
43
|
+
audio_duration: str = "audio_duration"
|
|
44
|
+
segmentation: str = "segmentation"
|
|
45
|
+
mask: str = "mask"
|
|
46
|
+
past_covariates: str = "past_covariates"
|
|
47
|
+
future_covariates: str = "future_covariates"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class EncodedArrayFieldNames:
|
|
52
|
+
"""Dataclass for the fields that the content of the packet should be encoded into"""
|
|
53
|
+
|
|
54
|
+
type: str = "type"
|
|
55
|
+
content: str = "content"
|
|
56
|
+
shape: str = "shape"
|
|
57
|
+
device: str = "device"
|
|
58
|
+
dtype: str = "dtype"
|
|
59
|
+
array_type: str = "array_type"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class SupportedArrayTypeNames:
|
|
64
|
+
"""Dataclass for the types of content the encoder/decoder support"""
|
|
65
|
+
|
|
66
|
+
numpy: str = "numpy"
|
|
67
|
+
torch: str = "torch"
|
|
68
|
+
bytes: str = "bytes"
|
|
69
|
+
pd_dataframe: str = "pd_dataframe"
|
|
70
|
+
pd_timeseries: str = "pd_timeseries"
|
|
71
|
+
darts_timeseries: str = "darts_timeseries"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class SupportedContentArrays:
|
|
76
|
+
"""Dataclass for the types of content the encoder/decoder support"""
|
|
77
|
+
|
|
78
|
+
image = "image"
|
|
79
|
+
video = "video"
|
|
80
|
+
embedding = "embedding"
|
|
81
|
+
timeseries = "timeseries"
|
|
82
|
+
dataframe = "dataframe"
|
|
83
|
+
audio = "audio"
|
|
84
|
+
binary = "binary"
|
|
85
|
+
file = "file"
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict
|
|
5
|
+
from sinapsis.agent import SinapsisStatusCodes
|
|
6
|
+
from sinapsis.data_transport import DataContainer
|
|
7
|
+
from sinapsis.sentinels import SinapsisSentinel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class AgentResponseFieldNames:
|
|
12
|
+
"""Dataclass to handle Agent Response messages"""
|
|
13
|
+
|
|
14
|
+
agent_id: str = "agent_id"
|
|
15
|
+
agent_status: str = "agent_status"
|
|
16
|
+
template_data: str = "template_data"
|
|
17
|
+
timestamp: str = "timestamp"
|
|
18
|
+
agent_error: str = "agent_error"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class TemplateResponseFieldNames:
|
|
23
|
+
"""Dataclass to handle Template Response messages"""
|
|
24
|
+
|
|
25
|
+
template_name: str = "template_name"
|
|
26
|
+
error: str = "error"
|
|
27
|
+
output: str = "output"
|
|
28
|
+
status: str = "status"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TemplateStreamingResponse(BaseModel):
|
|
32
|
+
"""Basemodel where information regarding the template response is contained.
|
|
33
|
+
It includes the agent_id, the time of execution, template name, template status, the output container
|
|
34
|
+
from that template, if there has been any execution errors.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
parent_agent_id: str
|
|
38
|
+
timestamp: datetime
|
|
39
|
+
template_name: str
|
|
40
|
+
template_status: SinapsisStatusCodes
|
|
41
|
+
template_output_container: DataContainer | SinapsisSentinel
|
|
42
|
+
template_error: str | None = None
|
|
43
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AgentResponse(BaseModel):
|
|
47
|
+
"""Basemodel for the Agent response to be added in the SSE message.
|
|
48
|
+
It includes the agent_id, the time of execution, template name, template status,
|
|
49
|
+
the output container and execution errors.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
agent_id: str
|
|
53
|
+
timestamp: datetime
|
|
54
|
+
template_name: str
|
|
55
|
+
status: SinapsisStatusCodes
|
|
56
|
+
output: DataContainer | str
|
|
57
|
+
error: str | None = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class SSEMessage(BaseModel):
|
|
61
|
+
"""Schema for Server-Sent Events (SSE) emitted during agent execution.
|
|
62
|
+
|
|
63
|
+
This model defines the structured data packet used for real-time
|
|
64
|
+
communication between the execution engine and external consumers. It
|
|
65
|
+
tracks the agent's lifecycle state, payload delivery, and error reporting
|
|
66
|
+
within a streaming context.
|
|
67
|
+
|
|
68
|
+
Attributes:
|
|
69
|
+
agent_id: Unique identifier for the agent instance being executed.
|
|
70
|
+
agent_status: The current phase of execution (e.g., 'queued', 'processing', 'completed', 'failed').
|
|
71
|
+
template_data: A list of `AgentResponse` objects containing the
|
|
72
|
+
Agent response per template; defaults to None if the agent hasn't produced data yet.
|
|
73
|
+
agent_error: Descriptive error message if the execution fails.
|
|
74
|
+
timestamp: The UTC time when the message was generated.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
agent_id: str
|
|
78
|
+
agent_status: str
|
|
79
|
+
template_data: list[AgentResponse] | None = None
|
|
80
|
+
agent_error: str | None = None
|
|
81
|
+
timestamp: datetime = datetime.now()
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from typing import TYPE_CHECKING, Any, TypeGuard
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
import darts
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
ARRAY_CONTENT_TYPES = torch.Tensor | np.ndarray | pd.Series | pd.DataFrame | darts.TimeSeries
|
|
14
|
+
|
|
15
|
+
# Module-level cache to avoid import/lookup overhead on repeated function calls
|
|
16
|
+
_ARRAY_TYPES_CACHE: tuple[type, ...] | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _get_array_types() -> tuple[type, ...]:
|
|
20
|
+
"""Dynamically imports available packages once and caches their type classes."""
|
|
21
|
+
global _ARRAY_TYPES_CACHE
|
|
22
|
+
if _ARRAY_TYPES_CACHE is None:
|
|
23
|
+
target_specs = [
|
|
24
|
+
("torch", ["Tensor"]),
|
|
25
|
+
("numpy", ["ndarray"]),
|
|
26
|
+
("pandas", ["Series", "DataFrame"]),
|
|
27
|
+
("darts", ["TimeSeries"]),
|
|
28
|
+
]
|
|
29
|
+
resolved_types: list[type] = []
|
|
30
|
+
|
|
31
|
+
for module_name, class_names in target_specs:
|
|
32
|
+
try:
|
|
33
|
+
mod = importlib.import_module(module_name)
|
|
34
|
+
for class_name in class_names:
|
|
35
|
+
if hasattr(mod, class_name):
|
|
36
|
+
resolved_types.append(getattr(mod, class_name))
|
|
37
|
+
except (ImportError, AttributeError):
|
|
38
|
+
continue
|
|
39
|
+
|
|
40
|
+
_ARRAY_TYPES_CACHE = tuple(resolved_types)
|
|
41
|
+
|
|
42
|
+
return _ARRAY_TYPES_CACHE
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_array_content(obj: Any) -> TypeGuard[ARRAY_CONTENT_TYPES]:
|
|
46
|
+
"""Determines if an object belongs to a supported numerical or tabular data type.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
obj: The object to evaluate.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
True if the object is a Tensor, ndarray, Series, DataFrame, or TimeSeries.
|
|
53
|
+
"""
|
|
54
|
+
return isinstance(obj, _get_array_types())
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_builtin_type(obj: Any) -> bool:
|
|
58
|
+
"""Checks if an object is a standard Python primitive type.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
obj: The object to evaluate.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
True if the object is an int, float, bool, None, str, bytes, or bytearray.
|
|
65
|
+
"""
|
|
66
|
+
return isinstance(obj, (int, float, bool, type(None), str, bytes, bytearray))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_iterable(obj: Any) -> bool:
|
|
70
|
+
"""Checks if an object can be iterated over, excluding string-like types.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
obj: The object to evaluate.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
True if the object is an Iterable and not a string or byte sequence.
|
|
77
|
+
"""
|
|
78
|
+
return isinstance(obj, Iterable) and not isinstance(obj, (str, bytes))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def is_encoded_array_type(obj: Any) -> bool:
|
|
82
|
+
"""Identifies if a dictionary represents a previously encoded array structure.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
obj: The object to evaluate.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
True if the object is a dictionary containing both 'content' and
|
|
89
|
+
'array_type' keys.
|
|
90
|
+
"""
|
|
91
|
+
return isinstance(obj, dict) and "content" in obj and "array_type" in obj
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import msgpack
|
|
5
|
+
from sinapsis_contracts.common.sentinels import SINAPSIS_END_OF_STREAM
|
|
6
|
+
|
|
7
|
+
from sinapsis_deserialization.data_container_decoders import DataContainerDecoder
|
|
8
|
+
from sinapsis_deserialization.schemas.messaging_base_models import (
|
|
9
|
+
AgentResponse,
|
|
10
|
+
AgentResponseFieldNames,
|
|
11
|
+
SSEMessage,
|
|
12
|
+
TemplateResponseFieldNames,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
data_decoder = DataContainerDecoder()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def agent_response_decoder(data: dict[str, Any]) -> AgentResponse:
|
|
19
|
+
"""Decodes a dictionary format back into an AgentResponse instance.
|
|
20
|
+
|
|
21
|
+
Reconstructs datetime objects from ISO strings and resolves encoded
|
|
22
|
+
DataContainer payloads back into DataContainer instances.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
data: A dictionary containing the serialized agent response fields.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
An instantiated AgentResponse object.
|
|
29
|
+
"""
|
|
30
|
+
raw_output = data.get(TemplateResponseFieldNames.output)
|
|
31
|
+
|
|
32
|
+
# Resolve DataContainer if output was encoded as a container payload/URL
|
|
33
|
+
if isinstance(raw_output, dict) and getattr(data_decoder, "is_container", lambda x: True)(raw_output):
|
|
34
|
+
output = data_decoder.decode_container(raw_output)
|
|
35
|
+
else:
|
|
36
|
+
output = raw_output
|
|
37
|
+
|
|
38
|
+
raw_timestamp = data.get(AgentResponseFieldNames.timestamp)
|
|
39
|
+
timestamp = datetime.fromisoformat(raw_timestamp) if isinstance(raw_timestamp, str) else raw_timestamp
|
|
40
|
+
|
|
41
|
+
return AgentResponse(
|
|
42
|
+
agent_id=data.get(AgentResponseFieldNames.agent_id),
|
|
43
|
+
timestamp=timestamp,
|
|
44
|
+
template_name=data.get(TemplateResponseFieldNames.template_name),
|
|
45
|
+
status=data.get(TemplateResponseFieldNames.status),
|
|
46
|
+
output=output,
|
|
47
|
+
error=data.get(TemplateResponseFieldNames.error),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def sse_decoder(data: dict[str, Any]) -> SSEMessage:
|
|
52
|
+
"""Decodes a primitive dictionary structure back into an SSEMessage instance.
|
|
53
|
+
|
|
54
|
+
Deserializes nested `template_data` items into `AgentResponse` objects
|
|
55
|
+
and restores ISO timestamps to `datetime` objects.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
data: The dictionary representation of an SSE message.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
An SSEMessage instance with fully reconstructed child objects.
|
|
62
|
+
"""
|
|
63
|
+
raw_template_data = data.get(AgentResponseFieldNames.template_data, [])
|
|
64
|
+
|
|
65
|
+
template_data = [agent_response_decoder(item) if isinstance(item, dict) else item for item in raw_template_data]
|
|
66
|
+
|
|
67
|
+
raw_timestamp = data.get(AgentResponseFieldNames.timestamp)
|
|
68
|
+
timestamp = datetime.fromisoformat(raw_timestamp) if isinstance(raw_timestamp, str) else raw_timestamp
|
|
69
|
+
return SSEMessage(
|
|
70
|
+
agent_id=data.get(AgentResponseFieldNames.agent_id),
|
|
71
|
+
agent_status=data.get(AgentResponseFieldNames.agent_status),
|
|
72
|
+
template_data=template_data,
|
|
73
|
+
agent_error=data.get(AgentResponseFieldNames.agent_error),
|
|
74
|
+
timestamp=timestamp,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def deserialize_sse_message(payload: bytes | str) -> SSEMessage:
|
|
79
|
+
"""Deserializes a msgpack binary payload back into an SSEMessage instance.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
payload: The binary or byte-string msgpack payload to unpack.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
The fully restored SSEMessage instance.
|
|
86
|
+
|
|
87
|
+
Raises:
|
|
88
|
+
ValueError: If the payload is invalid or msgpack unpacking fails.
|
|
89
|
+
"""
|
|
90
|
+
if not payload:
|
|
91
|
+
return SINAPSIS_END_OF_STREAM
|
|
92
|
+
|
|
93
|
+
if isinstance(payload, str):
|
|
94
|
+
payload = payload.encode("utf-8")
|
|
95
|
+
|
|
96
|
+
# raw=False ensures msgpack returns str objects instead of bytes for keys/values
|
|
97
|
+
raw_dict: dict[str, Any] = msgpack.unpackb(payload, raw=False)
|
|
98
|
+
if AgentResponseFieldNames.template_data not in raw_dict:
|
|
99
|
+
return SINAPSIS_END_OF_STREAM
|
|
100
|
+
return sse_decoder(raw_dict)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class MsgpackStreamDecoder:
|
|
104
|
+
def __init__(self) -> None:
|
|
105
|
+
self._unpacker = msgpack.Unpacker(raw=False)
|
|
106
|
+
|
|
107
|
+
def sse_decode(self, chunk: bytes):
|
|
108
|
+
self._unpacker.feed(chunk)
|
|
109
|
+
|
|
110
|
+
for raw_dict in self._unpacker:
|
|
111
|
+
if AgentResponseFieldNames.template_data not in raw_dict:
|
|
112
|
+
yield SINAPSIS_END_OF_STREAM
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
yield sse_decoder(raw_dict)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sinapsis_deserialization
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Deserialization utilities for Sinapsis pipelines.
|
|
5
|
+
Project-URL: Homepage, https://sinapsis.tech
|
|
6
|
+
Project-URL: Documentation, https://docs.sinapsis.tech/docs/latest
|
|
7
|
+
Project-URL: Tutorials, https://docs.sinapsis.tech/docs/latest/tutorials
|
|
8
|
+
Project-URL: Repository, https://github.com/SinapsisHub/sinapsis-hub
|
|
9
|
+
Project-URL: Issues, https://github.com/SinapsisHub/sinapsis-hub/issues
|
|
10
|
+
Project-URL: Discord, https://discord.gg/uuBqQqu2vS
|
|
11
|
+
Author-email: Ariel Ruiz-Garcia <ariel@sinapsis.tech>, Nimesh Patel <nimesh@sinapsis.tech>
|
|
12
|
+
Maintainer-email: sinapsis <dev@sinapsis.tech>
|
|
13
|
+
License-Expression: MIT OR Apache-2.0
|
|
14
|
+
License-File: LICENSE-APACHE
|
|
15
|
+
License-File: LICENSE-MIT
|
|
16
|
+
Requires-Python: >=3.13
|
|
17
|
+
Requires-Dist: sinapsis<2,>=1
|
|
18
|
+
Provides-Extra: all
|
|
19
|
+
Requires-Dist: darts>=0.41.0; extra == 'all'
|
|
20
|
+
Requires-Dist: msgpack; extra == 'all'
|
|
21
|
+
Requires-Dist: numpy>=2.2.6; extra == 'all'
|
|
22
|
+
Requires-Dist: pandas>=2.3.3; extra == 'all'
|
|
23
|
+
Requires-Dist: sinapsis-generic-data-tools[all]>=1.0.0; extra == 'all'
|
|
24
|
+
Requires-Dist: soundfile>=0.13.1; extra == 'all'
|
|
25
|
+
Requires-Dist: torch>=2.8.0; extra == 'all'
|
|
26
|
+
Provides-Extra: darts
|
|
27
|
+
Requires-Dist: darts>=0.41.0; extra == 'darts'
|
|
28
|
+
Provides-Extra: msgpack
|
|
29
|
+
Requires-Dist: msgpack; extra == 'msgpack'
|
|
30
|
+
Provides-Extra: numpy
|
|
31
|
+
Requires-Dist: numpy>=2.2.6; extra == 'numpy'
|
|
32
|
+
Provides-Extra: pandas
|
|
33
|
+
Requires-Dist: pandas>=2.3.3; extra == 'pandas'
|
|
34
|
+
Provides-Extra: sinapsis-generic-data-tools
|
|
35
|
+
Requires-Dist: sinapsis-generic-data-tools[all]>=1.0.0; extra == 'sinapsis-generic-data-tools'
|
|
36
|
+
Provides-Extra: soundfile
|
|
37
|
+
Requires-Dist: soundfile>=0.13.1; extra == 'soundfile'
|
|
38
|
+
Provides-Extra: torch
|
|
39
|
+
Requires-Dist: torch>=2.8.0; extra == 'torch'
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
|
|
42
|
+
sinapsis-deserialization
|
|
43
|
+
<h1 align="center">
|
|
44
|
+
<br>
|
|
45
|
+
<a href="https://sinapsis.tech/">
|
|
46
|
+
<img
|
|
47
|
+
src="https://github.com/SinapsisHub/brand-resources/blob/main/public/logo/sinapsis-logo-horizontal-dark-brand.png?raw=true"
|
|
48
|
+
alt="Sinapsis"
|
|
49
|
+
width="300">
|
|
50
|
+
</a>
|
|
51
|
+
<br>
|
|
52
|
+
Sinapsis Deserialization
|
|
53
|
+
<br>
|
|
54
|
+
</h1>
|
|
55
|
+
|
|
56
|
+
<h3 align="center">Reconstruct typed Sinapsis data and execution messages.</h3>
|
|
57
|
+
|
|
58
|
+
`sinapsis-deserialization` decodes the structured dictionary representation of Sinapsis `DataContainer` objects and the MessagePack-backed execution messages used by the corresponding messaging integrations. It restores packet types and supported array payloads, and offers helpers for decoding streamed execution events.
|
|
59
|
+
|
|
60
|
+
`DataContainer` and the packet classes belong to Sinapsis Core; this package reconstructs them from encoded input. It is designed to work with the **dictionary/message format** used by `sinapsis-serializer-core` and related integrations—not as a replacement for `sinapsis-protocol`'s versioned binary decoder.
|
|
61
|
+
|
|
62
|
+
> [!WARNING]
|
|
63
|
+
> **Planned Deprecation**
|
|
64
|
+
>
|
|
65
|
+
> This package is currently used exclusively by the Sinapsis Cloud API and is maintained for compatibility with the existing serialization infrastructure.
|
|
66
|
+
>
|
|
67
|
+
> It is planned for deprecation in favour of [`sinapsis-protocol`](https://pypi.org/project/sinapsis-protocol/), which provides the unified, versioned serialization and communication protocol for the Sinapsis ecosystem.
|
|
68
|
+
>
|
|
69
|
+
> For new integrations, use `sinapsis-protocol` instead. Existing integrations will continue to be supported during the transition.
|
|
70
|
+
|
|
71
|
+
## Installation
|
|
72
|
+
|
|
73
|
+
Requires **Python 3.13+**.
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
uv pip install 'sinapsis-deserialization[msgpack]'
|
|
77
|
+
# or: pip install 'sinapsis-deserialization[msgpack]'
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The `msgpack` extra is needed for execution-message decoding. Depending on the payloads you expect, additional extras include `numpy`, `pandas`, `torch`, `darts`, `soundfile`, and `sinapsis-generic-data-tools`.
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
uv pip install 'sinapsis-deserialization[numpy,pandas]'
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## DataContainer decoding
|
|
87
|
+
|
|
88
|
+
`DataContainerDecoder` accepts a dictionary containing the `container_id` field and recognized packet collections. It reconstructs a `DataContainer` and its typed packets, decoding supported embedded array envelopes and nested generic data.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from sinapsis_deserialization import DataContainerDecoder
|
|
92
|
+
|
|
93
|
+
encoded = {
|
|
94
|
+
"container_id": "example-container",
|
|
95
|
+
"texts": [
|
|
96
|
+
{
|
|
97
|
+
"type": "text",
|
|
98
|
+
"content": "Hello Sinapsis",
|
|
99
|
+
"id": "text-1",
|
|
100
|
+
"source": None,
|
|
101
|
+
"embedding": [],
|
|
102
|
+
"generic_data": {},
|
|
103
|
+
"annotations": [],
|
|
104
|
+
}
|
|
105
|
+
],
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
result = DataContainerDecoder()(encoded)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
In a real integration, pass a dictionary produced by the corresponding Sinapsis encoder rather than constructing packet fields manually. If the input dictionary does **not** contain a recognized container identifier, the decoder returns it unchanged.
|
|
112
|
+
|
|
113
|
+
### Supported packet families
|
|
114
|
+
|
|
115
|
+
| Decoder method | Restored type |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| `decode_image` | `ImagePacket` |
|
|
118
|
+
| `decode_audio` | `AudioPacket` |
|
|
119
|
+
| `decode_text` | `TextPacket` |
|
|
120
|
+
| `decode_file` | `FilePacket` |
|
|
121
|
+
| `decode_data_frame` | `DataFramePacket` |
|
|
122
|
+
| `decode_time_series` | `TimeSeriesPacket` |
|
|
123
|
+
| `decode_binary` | `BinaryPacket` |
|
|
124
|
+
| `decode_generic_dict` | Nested generic metadata and supported values |
|
|
125
|
+
| `array_type_decoder` | Encoded array and data representations |
|
|
126
|
+
|
|
127
|
+
The decoder uses the embedded type and metadata fields to select a reconstruction path. Successful restoration of a specialized type depends on having the associated library available and on the payload using a compatible encoded representation. **Only decode payloads from trusted sources**: some legacy specialized decoding paths reconstruct Pandas objects through pickle and evaluate Torch dtype strings.
|
|
128
|
+
|
|
129
|
+
## Decoding execution messages
|
|
130
|
+
|
|
131
|
+
The package also supplies typed models for execution streams:
|
|
132
|
+
|
|
133
|
+
- `SSEMessage`: Agent-level status and a collection of per-Template responses.
|
|
134
|
+
- `AgentResponse`: A Template name, status, timestamp, output, and optional error.
|
|
135
|
+
- `TemplateStreamingResponse`: A typed representation of streaming Template output.
|
|
136
|
+
|
|
137
|
+
For a complete serialized message:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from sinapsis_deserialization import deserialize_sse_message
|
|
141
|
+
|
|
142
|
+
# payload is a MessagePack-encoded SSE message from the matching Sinapsis API.
|
|
143
|
+
message = deserialize_sse_message(payload)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
`deserialize_sse_message` decodes a message and reconstructs supported `DataContainer` output values and timestamps. An empty payload or a control frame without `template_data` is interpreted as an **end-of-stream marker**, not an ordinary `SSEMessage`.
|
|
147
|
+
|
|
148
|
+
### Incremental MessagePack stream decoding
|
|
149
|
+
|
|
150
|
+
`MsgpackStreamDecoder` keeps an incremental unpacker so that a message does not need to arrive in a single network chunk:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from sinapsis_deserialization import MsgpackStreamDecoder
|
|
154
|
+
|
|
155
|
+
decoder = MsgpackStreamDecoder()
|
|
156
|
+
|
|
157
|
+
for chunk in network_chunks: # successive bytes from your transport
|
|
158
|
+
for event in decoder.sse_decode(chunk):
|
|
159
|
+
handle_event(event)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The decoder yields restored messages and can yield the end-of-stream sentinel. Consumers should handle the sentinel separately from Template data. `network_chunks` and `handle_event` above are placeholders for your application's transport loop.
|
|
163
|
+
|
|
164
|
+
## Format boundaries
|
|
165
|
+
|
|
166
|
+
```text
|
|
167
|
+
Encoded DataContainer dictionary
|
|
168
|
+
|
|
|
169
|
+
v
|
|
170
|
+
DataContainerDecoder
|
|
171
|
+
|
|
|
172
|
+
v
|
|
173
|
+
DataContainer + typed packets
|
|
174
|
+
|
|
175
|
+
MessagePack execution event
|
|
176
|
+
|
|
|
177
|
+
v
|
|
178
|
+
deserialize_sse_message / MsgpackStreamDecoder
|
|
179
|
+
|
|
|
180
|
+
v
|
|
181
|
+
SSEMessage + AgentResponse (or control sentinel)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
This package **decodes** existing Sinapsis message formats. It does not construct or execute Agents, provide an HTTP client, or decode `sinapsis-protocol`'s versioned envelope format. Use the matching encoder/decoder pair for the transport you are integrating.
|
|
185
|
+
|
|
186
|
+
## Documentation
|
|
187
|
+
|
|
188
|
+
- [Sinapsis documentation](https://docs.sinapsis.tech/)
|
|
189
|
+
- [Tutorials and examples](https://docs.sinapsis.tech/docs/latest/tutorials)
|
|
190
|
+
- [Sinapsis website](https://sinapsis.tech/)
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
Sinapsis open-source components are available under your choice of the [MIT License](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), unless otherwise noted.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
sinapsis_deserialization/__init__.py,sha256=h9vls3TfWmmPzv1u3DwumqJFIzFegIr_IHNGjx2nSTE,222
|
|
2
|
+
sinapsis_deserialization/data_container_decoders.py,sha256=h8wHQ-DnOUmy0HmmmS9YF-Eh5X1vyyUsqOtX26k3hcM,12804
|
|
3
|
+
sinapsis_deserialization/sse_deserializers.py,sha256=_7T0UEsLPESTJSNuLFClUbNQM5FdGvb5QYRqcIodxu0,4021
|
|
4
|
+
sinapsis_deserialization/schemas/__init__.py,sha256=YKh-w6AiqIcFMVt4cKYWHM56_O6AtZFaOu_-gR1UoEc,318
|
|
5
|
+
sinapsis_deserialization/schemas/constant_variables.py,sha256=5TvR_IqtW2GehVYZY89wFZjqYz6dt8u3pAbwbE8J8kw,2243
|
|
6
|
+
sinapsis_deserialization/schemas/messaging_base_models.py,sha256=03v4N9AHP3NzM23nR5Zg0Ikfc8Fl_Y8e-GsC0_t6BG4,2786
|
|
7
|
+
sinapsis_deserialization/schemas/type_checkers.py,sha256=8-j_Ty1NE5jq8-9Oi5wZ_1FlZ7ulNpH8gTS6GqP0cQ0,2766
|
|
8
|
+
sinapsis_deserialization-1.0.0.dist-info/METADATA,sha256=3bh42unrxKOyrYuG4IYmh1ms8vRr1fWIgff9q85KDBY,8105
|
|
9
|
+
sinapsis_deserialization-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
sinapsis_deserialization-1.0.0.dist-info/licenses/LICENSE-APACHE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
sinapsis_deserialization-1.0.0.dist-info/licenses/LICENSE-MIT,sha256=iCOHXEYY1dWKRkzcJLxYZSxr3EbT8zDzS2OgrVytqD0,1079
|
|
12
|
+
sinapsis_deserialization-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sinapsis Group Limited
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|