Merge pull request #1344 from langchain-ai/nc/14aug/ignore-serialized-values-missing-constructor

checkpoint: Ignore serialized values when constructor no longer available
This commit is contained in:
Nuno Campos
2024-08-14 14:43:57 -07:00
committed by GitHub
2 changed files with 33 additions and 12 deletions
@@ -121,18 +121,21 @@ class JsonPlusSerializer(SerializerProtocol):
and value.get("type", None) == "constructor"
and value.get("id", None) is not None
):
# Get module and class name
[*module, name] = value["id"]
# Import module
mod = importlib.import_module(".".join(module))
# Import class
cls = getattr(mod, name)
# Instantiate class
if value["method"] is not None:
method = getattr(cls, value["method"])
return method(*value["args"], **value["kwargs"])
else:
return cls(*value["args"], **value["kwargs"])
try:
# Get module and class name
[*module, name] = value["id"]
# Import module
mod = importlib.import_module(".".join(module))
# Import class
cls = getattr(mod, name)
# Instantiate class
if value["method"] is not None:
method = getattr(cls, value["method"])
return method(*value["args"], **value["kwargs"])
else:
return cls(*value["args"], **value["kwargs"])
except (ImportError, AttributeError):
return None
return LC_REVIVER(value)
+18
View File
@@ -149,3 +149,21 @@ def test_serde_jsonplus_bytearray() -> None:
assert dumped == ("bytearray", some_bytearray)
assert serde.loads_typed(dumped) == some_bytearray
def test_loads_cannot_find() -> None:
serde = JsonPlusSerializer()
dumped = (
"json",
b'{"lc": 2, "type": "constructor", "id": ["tests", "test_jsonplus", "MyPydanticccc"], "method": null, "args": [], "kwargs": {"foo": "foo", "bar": 1}}',
)
assert serde.loads_typed(dumped) is None, "Should return None if cannot find class"
dumped = (
"json",
b'{"lc": 2, "type": "constructor", "id": ["tests", "test_jsonpluss", "MyPydantic"], "method": null, "args": [], "kwargs": {"foo": "foo", "bar": 1}}',
)
assert serde.loads_typed(dumped) is None, "Should return None if cannot find module"