Serialization
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/load/serializable.py
- libs/core/langchain_core/load/dump.py
- libs/core/langchain_core/load/load.py
- libs/core/tests/unit_tests/load/test_serializable.py
- libs/core/langchain_core/load/mapping.py
- libs/core/langchain_core/runnables/base.py
- libs/langchain/tests/unit_tests/test_schema.py
The LangChain serialization framework provides a standardized way to save and load LangChain objects, such as Runnables, prompts, and models. This capability is crucial for persisting complex chains, sharing them, and dynamically loading them in different environments. The core of this system is the Serializable base class, which defines the interface for objects that can be converted to and from a JSON-serializable format.
The framework is designed to be robust and maintain backward compatibility. It uses a mapping system to handle cases where classes are moved within the codebase, ensuring that objects serialized with older versions of LangChain can still be loaded correctly. It also includes a mechanism for securely handling sensitive information, like API keys, by masking them during the serialization process.
Core Components
The serialization system is built around a few key components: the Serializable base class, dump and load functions, and a mapping for backward compatibility.
Serializable Base Class
Any class that needs to be serialized must inherit from the Serializable class. This class, which is a Pydantic BaseModel, provides the necessary methods and properties to control the serialization process.
The following diagram illustrates the key components of the Serializable class.
Key methods and properties include:
is_lc_serializable() -> bool: A class method that must be overridden to returnTruefor a class to be considered serializable via the "constructor" method. If it returnsFalseor is not implemented, the object will be serialized as a "not_implemented" type, which stores its representation but cannot be fully deserialized.
Sources: libs/core/langchain_core/load/serializable.py:100-103lc_secrets: A property that returns a dictionary mapping attribute names to the secret's ID. This is used to mask sensitive data during serialization.
Sources: libs/core/langchain_core/load/serializable.py:65-70lc_id() -> list[str]: Returns a unique identifier for the class, typically its namespace path (e.g.,["langchain", "prompts", "PromptTemplate"]). This is used to locate the class during deserialization.
Sources: libs/core/langchain_core/load/serializable.py:105-115to_json() -> dict: Converts the object into a JSON-serializable dictionary. This method is called by thedumpdfunction.
Sources: libs/core/langchain_core/load/serializable.py:117-188
A RunnableSerializable class also exists, which inherits from both Serializable and Runnable, providing a base for all runnable components that need to be serialized.
Sources: libs/core/langchain_core/runnables/base.py:2020-2022
Serialized Object Schema
When a Serializable object is dumped, it is converted into a dictionary with a specific schema.
| Key | Type | Description |
|---|---|---|
lc | int | The serialization format version, currently 1. |
type | str | The type of serialization. Can be constructor, not_implemented, or secret. |
id | list[str] | The unique identifier path for the class or secret. Used for deserialization. |
kwargs | dict | A dictionary of constructor arguments for the object. Only present if type is constructor. |
repr | str | The string representation of the object. Only present if type is not_implemented. |
Sources: libs/core/langchain_core/load/serializable.py:117-188, libs/core/langchain_core/load/dump.py:17-49
Serialization Process
The serialization process is handled by the dumpd and dumps functions, which convert a Serializable object into a dictionary or a JSON string, respectively.
The following diagram shows the flow of the dumpd function.
dumpd(obj: Any) -> Any
This function takes any Python object and returns a JSON-serializable representation.
- It checks if the object is an instance of
Serializable. - If it is, it calls the object's
to_json()method. - The
to_json()method determines the serialization type:- If
is_lc_serializable()returnsTrue, the type isconstructor. The dictionary will contain the classidand constructorkwargs. - Otherwise, the type is
not_implemented, and the dictionary contains the object'srepr.
- If
- If the object is not
Serializable, it's treated as a primitive type (dict, list, etc.) and recursively processed. If it's another kind of object, it's serialized asnot_implemented.
Sources: libs/core/langchain_core/load/dump.py:17-49, libs/core/langchain_core/load/serializable.py:117-188
Handling Secrets
The framework provides a mechanism to avoid leaking sensitive information.
- A
Serializableclass can define thelc_secretsproperty, which is a dictionary mapping attribute names to secret IDs. - During serialization, if an attribute is found in
lc_secrets, its value is replaced by a special dictionary of typesecret. - This
secretdictionary contains the ID specified inlc_secrets, allowing it to be potentially loaded from a secure source later, but the actual value is not stored in the serialized output.
Here is an example from the test suite:
# libs/core/tests/unit_tests/load/test_serializable.py:46-61
class Foo(Serializable):
bar: int
baz: str
secret: SecretStr
secret_2: str
@classmethod
def is_lc_serializable(cls) -> bool:
return True
@property
def lc_secrets(self) -> dict[str, str]:
return {"secret": "MASKED_SECRET", "secret_2": "MASKED_SECRET_2"}
When an instance of this class is dumped, the secret and secret_2 fields are replaced with placeholders.
Sources: libs/core/tests/unit_tests/load/test_serializable.py:63-76
Deserialization Process
The load function is responsible for converting a serialized dictionary back into a Python object.
The following diagram illustrates the load function's logic.
load(serialized_obj: Any, *, valid_namespaces: Optional[list[str]] = None, **kwargs) -> Any
This function takes a serialized dictionary and reconstructs the original Python object.
- It checks if the input dictionary matches the LangChain serialization schema (i.e., contains
lcandtypekeys). - If
typeisconstructor, it uses theidfield to dynamically import the class.- It first checks the
SERIALIZABLE_MAPPINGto resolve the class path, ensuring backward compatibility. - It validates that the resolved namespace is within the
valid_namespacesif provided, as a security measure.
- It first checks the
- It recursively calls
loadon the values in thekwargsdictionary to deserialize any nested objects. - Finally, it instantiates the class with the deserialized
kwargs. - If
typeisnot_implemented, it will raise an error unlessignore_unserializable_fieldsis set toTrue, in which case it returnsNone. - If
typeissecret, it raises aNotImplementedError, as secrets are not meant to be deserialized directly from the dump.
Sources: libs/core/langchain_core/load/load.py:22-113
Backward Compatibility with SERIALIZABLE_MAPPING
To ensure that objects can be deserialized across different versions of LangChain, the SERIALIZABLE_MAPPING dictionary is used. This mapping contains entries that map old, legacy lc_namespace paths to their current locations.
For example, AIMessage was originally located at langchain.schema.AIMessage, but is now at langchain_core.messages.ai.AIMessage. The mapping ensures that older serialized objects can still find the correct class.
# libs/core/langchain_core/load/mapping.py:8-13
SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
("langchain", "schema", "messages", "AIMessage"): (
"langchain_core",
"messages",
"ai",
"AIMessage",
),
# ... more mappings
}
The load function consults this map before attempting to import a class, providing a layer of abstraction over the project's file structure.
Sources: libs/core/langchain_core/load/mapping.py:8-444, libs/core/langchain_core/load/load.py:73-74
Summary
The LangChain serialization framework is a powerful system for persisting and sharing LangChain components. By extending the Serializable class, developers can make their custom components compatible with this system. The use of dumpd/dumps for serialization and load for deserialization, combined with a robust backward-compatibility mapping and secure handling of secrets, makes the framework a cornerstone of the LangChain ecosystem, enabling modular and portable application development.