Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions haystack/dataclasses/chat_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def to_dict(self) -> dict[str, Any]:
return asdict(self)

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ToolCall":
def from_dict(cls, data: dict[str, Any]) -> Self:
"""
Creates a new ToolCall object from a dictionary.

Expand All @@ -113,7 +113,7 @@ def from_dict(cls, data: dict[str, Any]) -> "ToolCall":
:returns:
The created object.
"""
return ToolCall(**data)
return cls(**data)


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

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ToolCallResult":
def from_dict(cls, data: dict[str, Any]) -> Self:
"""
Creates a ToolCallResult from a dictionary.

Expand All @@ -184,7 +184,7 @@ def from_dict(cls, data: dict[str, Any]) -> "ToolCallResult":
if isinstance(result, list):
result = [_deserialize_content_part(serialized_part) for serialized_part in result]

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


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

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ReasoningContent":
def from_dict(cls, data: dict[str, Any]) -> Self:
"""
Creates a new ReasoningContent object from a dictionary.

Expand All @@ -219,7 +219,7 @@ def from_dict(cls, data: dict[str, Any]) -> "ReasoningContent":
:returns:
The created object.
"""
return ReasoningContent(**data)
return cls(**data)


ChatMessageContentT = TextContent | ToolCall | ToolCallResult | ImageContent | ReasoningContent | FileContent
Expand Down
10 changes: 5 additions & 5 deletions haystack/dataclasses/streaming_chunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import inspect
from collections.abc import Awaitable, Callable
from dataclasses import asdict, dataclass, field
from typing import Any, Literal, overload
from typing import Any, Literal, Self, overload

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

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ToolCallDelta":
def from_dict(cls, data: dict[str, Any]) -> Self:
"""
Creates a ToolCallDelta from a serialized representation.

:param data: Dictionary containing ToolCallDelta's attributes.
:returns: A ToolCallDelta instance.
"""
return ToolCallDelta(**data)
return cls(**data)


@_warn_on_inplace_mutation
Expand Down Expand Up @@ -95,14 +95,14 @@ def to_dict(self) -> dict[str, Any]:
return asdict(self)

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ComponentInfo":
def from_dict(cls, data: dict[str, Any]) -> Self:
"""
Creates a ComponentInfo from a serialized representation.

:param data: Dictionary containing ComponentInfo's attributes.
:returns: A ComponentInfo instance.
"""
return ComponentInfo(**data)
return cls(**data)


@_warn_on_inplace_mutation
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
``ToolCall.from_dict``, ``ToolCallResult.from_dict`` and ``ReasoningContent.from_dict`` in ``haystack.dataclasses.chat_message``,
as well as ``ToolCallDelta.from_dict`` and ``ComponentInfo.from_dict`` in ``haystack.dataclasses.streaming_chunk``, now
instantiate ``cls`` instead of hardcoding their own class. Calling them on a subclass returns the subclass again, so
extra fields are no longer dropped on a ``to_dict()`` / ``from_dict()`` round trip, matching ``TextContent``, ``FileContent``,
``ImageContent`` and ``ByteStream``.
32 changes: 32 additions & 0 deletions test/dataclasses/test_chat_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,38 @@ class MyText(TextContent):
assert type(result) is MyText
assert result == MyText(text="hello")

def test_tool_call_subclass_from_dict(self):
@dataclass
class MyToolCall(ToolCall):
pass

original = MyToolCall(tool_name="get_weather", arguments={"city": "Paris"}, id="1")
result = MyToolCall.from_dict(original.to_dict())
assert type(result) is MyToolCall
assert result == original

def test_tool_call_result_subclass_from_dict(self):
@dataclass
class MyToolCallResult(ToolCallResult):
pass

original = MyToolCallResult(
result="sunny", origin=ToolCall(tool_name="get_weather", arguments={"city": "Paris"}, id="1"), error=False
)
result = MyToolCallResult.from_dict(original.to_dict())
assert type(result) is MyToolCallResult
assert result == original

def test_reasoning_content_subclass_from_dict(self):
@dataclass
class MyReasoning(ReasoningContent):
pass

original = MyReasoning(reasoning_text="thinking")
result = MyReasoning.from_dict(original.to_dict())
assert type(result) is MyReasoning
assert result == original

def test_text_content_no_warning_on_init(self):
with warnings.catch_warnings():
warnings.simplefilter("error", Warning)
Expand Down
23 changes: 23 additions & 0 deletions test/dataclasses/test_streaming_chunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import warnings
from dataclasses import dataclass

import pytest

Expand Down Expand Up @@ -440,3 +441,25 @@ async def callback(chunk):
chunk = StreamingChunk(content="world")
await _invoke_streaming_callback(callback, chunk)
assert captured == [chunk]


def test_tool_call_delta_subclass_from_dict():
@dataclass
class MyToolCallDelta(ToolCallDelta):
pass

original = MyToolCallDelta(index=0, tool_name="get_weather", arguments='{"city": "Paris"}', id="1")
result = MyToolCallDelta.from_dict(original.to_dict())
assert type(result) is MyToolCallDelta
assert result == original


def test_component_info_subclass_from_dict():
@dataclass
class MyComponentInfo(ComponentInfo):
pass

original = MyComponentInfo(type="haystack.components.generators.chat.openai.OpenAIChatGenerator", name="gen")
result = MyComponentInfo.from_dict(original.to_dict())
assert type(result) is MyComponentInfo
assert result == original
Loading