LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
    • Overview
    • Caches
    • Callbacks
    • Documents
    • Document loaders
    • Embeddings
    • Exceptions
    • Language models
    • Serialization
    • Output parsers
    • Prompts
    • Rate limiters
    • Retrievers
    • Runnables
    • Utilities
    • Vector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    โŒ˜I

    LangChain Assistant

    Ask a question to get started

    Enter to sendโ€ขShift+Enter new line

    Menu

    OverviewCachesCallbacksDocumentsDocument loadersEmbeddingsExceptionsLanguage modelsSerializationOutput parsersPromptsRate limitersRetrieversRunnablesUtilitiesVector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    Language
    Theme
    Pythonlangchain-coreload
    Moduleโ—Since v0.1

    load

    Load module helps with serialization and deserialization.

    Attributes

    attribute
    InitValidator: Callable[[tuple[str, ...], dict[str, Any]], None]

    Type alias for a callable that validates kwargs during deserialization.

    The callable receives:

    • class_path: A tuple of strings identifying the class being instantiated (e.g., ('langchain', 'schema', 'messages', 'AIMessage')).
    • kwargs: The kwargs dict that will be passed to the constructor.

    The validator should raise an exception if the object should not be deserialized.

    Functions

    function
    import_attr

    Import an attribute from a module located in a package.

    This utility function is used in custom __getattr__ methods within __init__.py files to dynamically import attributes.

    function
    dumpd

    Return a dict representation of an object.

    function
    dumps

    Return a JSON string representation of an object.

    function
    loads

    Revive a LangChain class from a JSON string.

    Equivalent to load(json.loads(text)).

    Only classes in the allowlist can be instantiated. The default allowlist includes core LangChain types (messages, prompts, documents, etc.). See langchain_core.load.mapping for the full list.

    Do not use with untrusted input

    This function instantiates Python objects and can trigger side effects during deserialization. Never call loads() on data from an untrusted or unauthenticated source. See the module-level security model documentation for details and best practices.

    Classes

    class
    Serializable

    Serializable base class.

    This class is used to serialize objects to JSON.

    It relies on the following methods and properties:

    • is_lc_serializable: Is this class serializable?

      By design, even if a class inherits from Serializable, it is not serializable by default. This is to prevent accidental serialization of objects that should not be serialized.

    • get_lc_namespace: Get the namespace of the LangChain object.

      During deserialization, this namespace is used to identify the correct class to instantiate.

      Please see the Reviver class in langchain_core.load.load for more details.

      During deserialization an additional mapping is handle classes that have moved or been renamed across package versions.

    • lc_secrets: A map of constructor argument names to secret ids.

    • lc_attributes: List of additional attribute names that should be included as part of the serialized representation.

    Modules

    module
    load

    Load LangChain objects from JSON strings or objects.

    How it works

    Each Serializable LangChain object has a unique identifier (its "class path"), which is a list of strings representing the module path and class name. For example:

    • AIMessage -> ["langchain_core", "messages", "ai", "AIMessage"]
    • ChatPromptTemplate -> ["langchain_core", "prompts", "chat", "ChatPromptTemplate"]

    When deserializing, the class path from the JSON 'id' field is checked against an allowlist. If the class is not in the allowlist, deserialization raises a ValueError.

    Security model

    Exercise caution with untrusted input

    These functions deserialize by instantiating Python objects, which means constructors (__init__) and validators may run and can trigger side effects. With the default settings, deserialization is restricted to a core allowlist of langchain_core types (for example: messages, documents, and prompts) defined in langchain_core.load.mapping.

    If you broaden allowed_objects (for example, by using 'all' or adding additional classes), treat the serialized payload as a manifest and only deserialize data that comes from a trusted source. A crafted payload that is allowed to instantiate unintended classes could cause network calls, file operations, or environment variable access during __init__.

    The allowed_objects parameter controls which classes can be deserialized:

    • 'core' (default): Allow classes defined in the serialization mappings for langchain_core.
    • 'all': Allow classes defined in the serialization mappings. This includes core LangChain types (messages, prompts, documents, etc.) and trusted partner integrations. See langchain_core.load.mapping for the full list.
    • Explicit list of classes: Only those specific classes are allowed.

    For simple data types like messages and documents, the default allowlist is safe to use. These classes do not perform side effects during initialization.

    Side effects in allowed classes

    Deserialization calls __init__ on allowed classes. If those classes perform side effects during initialization (network calls, file operations, etc.), those side effects will occur. The allowlist prevents instantiation of classes outside the allowlist, but does not sandbox the allowed classes themselves.

    Import paths are also validated against trusted namespaces before any module is imported.

    Best practices

    • Use the most restrictive allowed_objects possible. Prefer an explicit list of classes over 'core' or 'all'.
    • Keep secrets_from_env set to False (the default). If you must use it, ensure the serialized data comes from a fully trusted source, as a crafted payload can read arbitrary environment variables.
    • When using secrets_map, include only the specific secrets that the serialized object requires.

    Injection protection (escape-based)

    During serialization, plain dicts that contain an 'lc' key are escaped by wrapping them: {"__lc_escaped__": {...}}. During deserialization, escaped dicts are unwrapped and returned as plain dicts, NOT instantiated as LC objects.

    This is an allowlist approach: only dicts explicitly produced by Serializable.to_json() (which are NOT escaped) are treated as LC objects; everything else is user data.

    Even if an attacker's payload includes __lc_escaped__ wrappers, it will be unwrapped to plain dicts and NOT instantiated as malicious objects.

    Examples

    from langchain_core.load import load
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.messages import AIMessage, HumanMessage
    
    # Use default allowlist (classes from mappings) - recommended
    obj = load(data)
    
    # Allow only specific classes (most restrictive)
    obj = load(
        data,
        allowed_objects=[
            ChatPromptTemplate,
            AIMessage,
            HumanMessage,
        ],
    )
    module
    mapping

    Serialization mapping.

    This file contains a mapping between the lc_namespace path for a given subclass that implements from Serializable to the namespace where that class is actually located.

    This mapping helps maintain the ability to serialize and deserialize well-known LangChain objects even if they are moved around in the codebase across different LangChain versions.

    For example, the code for the AIMessage class is located in langchain_core.messages.ai.AIMessage. This message is associated with the lc_namespace of ["langchain", "schema", "messages", "AIMessage"], because this code was originally in langchain.schema.messages.AIMessage.

    The mapping allows us to deserialize an AIMessage created with an older version of LangChain where the code was in a different location.

    module
    dump

    Serialize LangChain objects to JSON.

    Provides dumps (to JSON string) and dumpd (to dict) for serializing Serializable objects.

    Escaping

    During serialization, plain dicts (user data) that contain an 'lc' key are escaped by wrapping them: {"__lc_escaped__": {...original...}}. This prevents injection attacks where malicious data could trick the deserializer into instantiating arbitrary classes. The escape marker is removed during deserialization.

    This is an allowlist approach: only dicts explicitly produced by Serializable.to_json() are treated as LC objects; everything else is escaped if it could be confused with the LC format.

    module
    serializable

    Serializable base class.

    View source on GitHub