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-coreloadload
    Module●Since v0.1

    load

    Attributes

    Functions

    Classes

    View source on GitHub
    attribute
    OLD_CORE_NAMESPACES_MAPPING: dict[tuple[str, ...], tuple[str, ...]]
    attribute
    SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]]
    attribute
    CLASS_INIT_VALIDATORS: dict[tuple[str, ...], InitValidator]
    attribute
    DEFAULT_NAMESPACES: list
    attribute
    DISALLOW_LOAD_FROM_PATH: list
    attribute
    ALL_SERIALIZABLE_MAPPINGS: dict
    attribute
    AllowedObject: type[Serializable]

    Type alias for classes that can be included in the allowed_objects parameter.

    Must be a Serializable subclass (the class itself, not an instance).

    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.

    function
    beta

    Decorator to mark a function, a class, or a property as beta.

    When marking a classmethod, a staticmethod, or a property, the @beta decorator should go under @classmethod and @staticmethod (i.e., beta should directly decorate the underlying callable), but over @property.

    When marking a class C intended to be used as a base class in a multiple inheritance hierarchy, C must define an __init__ method (if C instead inherited its __init__ from its own base class, then @beta would mess up __init__ inheritance when installing its own (annotation-emitting) C.__init__).

    function
    warn_deprecated

    Display a standardized deprecation.

    function
    default_init_validator

    Default init validator that blocks jinja2 templates.

    This is the default validator used by load() and loads() when no custom validator is provided.

    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

    A serialized payload may carry constructor kwargs that affect runtime behavior (custom base_url, headers, model name, etc.), so it should be treated as executable configuration rather than plain text. If the source is untrusted, avoid calling loads() on it; if you must, pass allowed_objects='messages' or an explicit list of message classes. See the module-level threat model for details.

    function
    load

    Revive a LangChain class from a JSON object.

    Use this if you already have a parsed JSON object, eg. from json.load or orjson.loads.

    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

    A serialized payload may carry constructor kwargs that affect runtime behavior (custom base_url, headers, model name, etc.), so it should be treated as executable configuration rather than plain text. If the source is untrusted, avoid calling load() on it; if you must, pass allowed_objects='messages' or an explicit list of message classes. See the module-level threat model for details.

    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.

    class
    Reviver

    Reviver for JSON objects.

    Used as the object_hook for json.loads to reconstruct LangChain objects from their serialized JSON representation.

    Only classes in the allowlist can be instantiated.

    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.

    Threat model

    A serialized LangChain payload crosses a trust boundary because the manifest may contain serialized objects and configuration that affect runtime behavior. For example, a payload can configure a chat model with a custom base_url, custom headers, a different model name, or other constructor arguments. These are supported features, but they also mean the payload contents should be treated as executable configuration rather than plain text.

    Concretely, deserialization instantiates Python objects, so any constructor (__init__) or validator on an allowed class can run during load(). A crafted payload that is allowed to reach an unintended class — or an intended class with attacker-controlled kwargs — could cause network calls, file operations, or environment-variable access while the object is being built.

    Do not use with untrusted input

    If the source is untrusted, avoid calling load() / loads() on it. If you must, restrict allowed_objects to types that do not execute logic during init — allowed_objects='messages' (or an explicit list of message classes) is the safe choice. Keep secrets_from_env=False.

    The allowed_objects parameter controls which classes can be deserialized:

    • Explicit list of classes (recommended for untrusted input): only those specific classes are allowed.
    • 'messages': chat-message classes only (e.g. AIMessage, HumanMessage). Safe for untrusted input.
    • 'core' (current default) — unsafe with untrusted manifests. Classes defined in the serialization mappings under langchain_core (messages, documents, prompts, etc.).
    • 'all' — unsafe with untrusted manifests. Every class in the serialization mappings, including partner chat models and LLMs and their constructor kwargs (endpoint URLs, headers, model names, etc.).
    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 or constrain their constructor kwargs.

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

    Best practices

    • Use the most restrictive allowed_objects possible. For untrusted input, pass an explicit list of classes or 'messages'. 'core' and 'all' are unsafe with untrusted manifests — only use them when the source serves the entire payload, including its configuration.
    • 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,
        ],
    )