feat: enhance serialization for v1 message classes in dump and load modules

This commit is contained in:
Mason Daugherty 2025-07-31 17:08:39 -04:00
parent e1b8ae2e6c
commit 02d02ccf1b
No known key found for this signature in database
2 changed files with 27 additions and 2 deletions

View File

@ -19,6 +19,29 @@ def default(obj: Any) -> Any:
"""
if isinstance(obj, Serializable):
return obj.to_json()
# Handle v1 message classes
from langchain_core.messages.v1 import MessageV1Types
if type(obj) in MessageV1Types:
import dataclasses
import inspect
# Get the constructor signature to only include valid parameters
init_sig = inspect.signature(type(obj).__init__)
valid_params = set(init_sig.parameters.keys()) - {"self"}
# Filter the dataclass fields to only include constructor parameters
all_fields = dataclasses.asdict(obj)
kwargs = {k: v for k, v in all_fields.items() if k in valid_params}
return {
"lc": 1,
"type": "constructor",
"id": ["langchain_core", "messages", "v1", type(obj).__name__],
"kwargs": kwargs,
}
return to_json_not_implemented(obj)

View File

@ -156,8 +156,10 @@ class Reviver:
cls = getattr(mod, name)
# The class must be a subclass of Serializable.
if not issubclass(cls, Serializable):
# The class must be a subclass of Serializable or a v1 message class.
from langchain_core.messages.v1 import MessageV1Types
if not (issubclass(cls, Serializable) or cls in MessageV1Types):
msg = f"Invalid namespace: {value}"
raise ValueError(msg)