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
20 changes: 14 additions & 6 deletions nemoguardrails/colang/v2_x/runtime/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,21 @@ def encode_to_dict(obj: Any, refs: Dict[int, Any]):
"value": {k: encode_to_dict(v, refs) for k, v in obj.items()},
}
elif is_dataclass(obj):
value = {
"__type": type(obj).__name__,
"value": {
k: encode_to_dict(getattr(obj, k), refs)
for k in obj.__dataclass_fields__.keys()
},
# Encode dataclasses. If it's a known class (present in name_to_class),
# keep its type tag so we can fully round-trip via json_to_state.
# Otherwise, fall back to a plain dict to avoid "Unknown d_type" on decode.
cls = type(obj)
encoded_fields = {
k: encode_to_dict(getattr(obj, k), refs)
for k in obj.__dataclass_fields__.keys()
}

if cls.__name__ in name_to_class and name_to_class[cls.__name__] is cls:
value = {"__type": cls.__name__, "value": encoded_fields}
else:
# Unknown dataclass → JSON-friendly dict
value = {"__type": "dict", "value": encoded_fields}

elif isinstance(obj, RailsConfig):
value = {
"__type": "RailsConfig",
Expand Down
35 changes: 35 additions & 0 deletions tests/v2_x/test_serialization_dataclass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
from dataclasses import dataclass

from nemoguardrails.colang.v2_x.runtime.serialization import state_to_json


@dataclass
class Foo:
bar: str
baz: int


def test_state_to_json_unknown_dataclass_encodes_as_dict():
js = state_to_json({"out": Foo("ok", 1)})
d = json.loads(js)
# We expect unknown dataclasses to be encoded as plain dicts
assert d["__type"] == "dict"
out = d["value"]["out"]
assert out["__type"] == "dict"
assert out["value"] == {"bar": "ok", "baz": 1}