Skip to content

Commit 03ebf83

Browse files
committed
fix: keep subclasses in the remaining content part from_dict methods
ToolCall, ToolCallResult, ReasoningContent, ToolCallDelta and ComponentInfo hardcoded their own class in from_dict, so a subclass lost its extra fields on a to_dict()/from_dict() round trip. #13180 and #13536 fixed the same bug for ByteStream and for TextContent/FileContent/ImageContent; this completes the set in haystack/dataclasses. Signed-off-by: Simin Yuan <281164480+simin-yuan@users.noreply.github.com>
1 parent 0ad7474 commit 03ebf83

5 files changed

Lines changed: 74 additions & 11 deletions

File tree

‎haystack/dataclasses/chat_message.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def to_dict(self) -> dict[str, Any]:
104104
return asdict(self)
105105

106106
@classmethod
107-
def from_dict(cls, data: dict[str, Any]) -> "ToolCall":
107+
def from_dict(cls, data: dict[str, Any]) -> Self:
108108
"""
109109
Creates a new ToolCall object from a dictionary.
110110
@@ -113,7 +113,7 @@ def from_dict(cls, data: dict[str, Any]) -> "ToolCall":
113113
:returns:
114114
The created object.
115115
"""
116-
return ToolCall(**data)
116+
return cls(**data)
117117

118118

119119
ToolCallResultContentT = str | Sequence[TextContent | ImageContent | FileContent]
@@ -165,7 +165,7 @@ def _to_dict(self, *, for_trace: bool = False) -> dict[str, Any]:
165165
return {"result": result, "origin": self.origin.to_dict(), "error": self.error}
166166

167167
@classmethod
168-
def from_dict(cls, data: dict[str, Any]) -> "ToolCallResult":
168+
def from_dict(cls, data: dict[str, Any]) -> Self:
169169
"""
170170
Creates a ToolCallResult from a dictionary.
171171
@@ -184,7 +184,7 @@ def from_dict(cls, data: dict[str, Any]) -> "ToolCallResult":
184184
if isinstance(result, list):
185185
result = [_deserialize_content_part(serialized_part) for serialized_part in result]
186186

187-
return ToolCallResult(result=result, origin=ToolCall.from_dict(data["origin"]), error=data["error"])
187+
return cls(result=result, origin=ToolCall.from_dict(data["origin"]), error=data["error"])
188188

189189

190190
@_warn_on_inplace_mutation
@@ -210,7 +210,7 @@ def to_dict(self) -> dict[str, Any]:
210210
return asdict(self)
211211

212212
@classmethod
213-
def from_dict(cls, data: dict[str, Any]) -> "ReasoningContent":
213+
def from_dict(cls, data: dict[str, Any]) -> Self:
214214
"""
215215
Creates a new ReasoningContent object from a dictionary.
216216
@@ -219,7 +219,7 @@ def from_dict(cls, data: dict[str, Any]) -> "ReasoningContent":
219219
:returns:
220220
The created object.
221221
"""
222-
return ReasoningContent(**data)
222+
return cls(**data)
223223

224224

225225
ChatMessageContentT = TextContent | ToolCall | ToolCallResult | ImageContent | ReasoningContent | FileContent

‎haystack/dataclasses/streaming_chunk.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import inspect
66
from collections.abc import Awaitable, Callable
77
from dataclasses import asdict, dataclass, field
8-
from typing import Any, Literal, overload
8+
from typing import Any, Literal, Self, overload
99

1010
from haystack import logging
1111
from haystack.core.component import Component
@@ -48,14 +48,14 @@ def to_dict(self) -> dict[str, Any]:
4848
return asdict(self)
4949

5050
@classmethod
51-
def from_dict(cls, data: dict[str, Any]) -> "ToolCallDelta":
51+
def from_dict(cls, data: dict[str, Any]) -> Self:
5252
"""
5353
Creates a ToolCallDelta from a serialized representation.
5454
5555
:param data: Dictionary containing ToolCallDelta's attributes.
5656
:returns: A ToolCallDelta instance.
5757
"""
58-
return ToolCallDelta(**data)
58+
return cls(**data)
5959

6060

6161
@_warn_on_inplace_mutation
@@ -95,14 +95,14 @@ def to_dict(self) -> dict[str, Any]:
9595
return asdict(self)
9696

9797
@classmethod
98-
def from_dict(cls, data: dict[str, Any]) -> "ComponentInfo":
98+
def from_dict(cls, data: dict[str, Any]) -> Self:
9999
"""
100100
Creates a ComponentInfo from a serialized representation.
101101
102102
:param data: Dictionary containing ComponentInfo's attributes.
103103
:returns: A ComponentInfo instance.
104104
"""
105-
return ComponentInfo(**data)
105+
return cls(**data)
106106

107107

108108
@_warn_on_inplace_mutation
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
fixes:
3+
- |
4+
`ToolCall.from_dict`, `ToolCallResult.from_dict` and `ReasoningContent.from_dict` in `haystack.dataclasses.chat_message`,
5+
as well as `ToolCallDelta.from_dict` and `ComponentInfo.from_dict` in `haystack.dataclasses.streaming_chunk`, now
6+
instantiate `cls` instead of hardcoding their own class. Calling them on a subclass returns the subclass again, so
7+
extra fields are no longer dropped on a `to_dict()` / `from_dict()` round trip, matching `TextContent`, `FileContent`,
8+
`ImageContent` and `ByteStream`.

‎test/dataclasses/test_chat_message.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,38 @@ class MyText(TextContent):
5858
assert type(result) is MyText
5959
assert result == MyText(text="hello")
6060

61+
def test_tool_call_subclass_from_dict(self):
62+
@dataclass
63+
class MyToolCall(ToolCall):
64+
pass
65+
66+
original = MyToolCall(tool_name="get_weather", arguments={"city": "Paris"}, id="1")
67+
result = MyToolCall.from_dict(original.to_dict())
68+
assert type(result) is MyToolCall
69+
assert result == original
70+
71+
def test_tool_call_result_subclass_from_dict(self):
72+
@dataclass
73+
class MyToolCallResult(ToolCallResult):
74+
pass
75+
76+
original = MyToolCallResult(
77+
result="sunny", origin=ToolCall(tool_name="get_weather", arguments={"city": "Paris"}, id="1"), error=False
78+
)
79+
result = MyToolCallResult.from_dict(original.to_dict())
80+
assert type(result) is MyToolCallResult
81+
assert result == original
82+
83+
def test_reasoning_content_subclass_from_dict(self):
84+
@dataclass
85+
class MyReasoning(ReasoningContent):
86+
pass
87+
88+
original = MyReasoning(reasoning_text="thinking")
89+
result = MyReasoning.from_dict(original.to_dict())
90+
assert type(result) is MyReasoning
91+
assert result == original
92+
6193
def test_text_content_no_warning_on_init(self):
6294
with warnings.catch_warnings():
6395
warnings.simplefilter("error", Warning)

‎test/dataclasses/test_streaming_chunk.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import logging
66
import warnings
7+
from dataclasses import dataclass
78

89
import pytest
910

@@ -440,3 +441,25 @@ async def callback(chunk):
440441
chunk = StreamingChunk(content="world")
441442
await _invoke_streaming_callback(callback, chunk)
442443
assert captured == [chunk]
444+
445+
446+
def test_tool_call_delta_subclass_from_dict():
447+
@dataclass
448+
class MyToolCallDelta(ToolCallDelta):
449+
pass
450+
451+
original = MyToolCallDelta(index=0, tool_name="get_weather", arguments='{"city": "Paris"}', id="1")
452+
result = MyToolCallDelta.from_dict(original.to_dict())
453+
assert type(result) is MyToolCallDelta
454+
assert result == original
455+
456+
457+
def test_component_info_subclass_from_dict():
458+
@dataclass
459+
class MyComponentInfo(ComponentInfo):
460+
pass
461+
462+
original = MyComponentInfo(type="haystack.components.generators.chat.openai.OpenAIChatGenerator", name="gen")
463+
result = MyComponentInfo.from_dict(original.to_dict())
464+
assert type(result) is MyComponentInfo
465+
assert result == original

0 commit comments

Comments
 (0)