libs/core/langchain_core/_api/deprecation.py PYTHON 655 lines View on github.com → Search inside
1"""Helper functions for deprecating parts of the LangChain API.23This module was adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)4module.56!!! warning78    This module is for internal use only. Do not use it in your own code. We may change9    the API at any time with no warning.10"""1112import contextlib13import functools14import inspect15import sys16import warnings17from collections.abc import Callable, Generator18from contextvars import ContextVar19from typing import (20    TYPE_CHECKING,21    Any,22    ParamSpec,23    TypeGuard,24    TypeVar,25    cast,26)2728from pydantic.fields import FieldInfo2930from langchain_core._api.internal import is_caller_internal3132if TYPE_CHECKING:33    from pydantic.v1.fields import FieldInfo as FieldInfoV1343536def _is_pydantic_v1_field_info(obj: Any) -> TypeGuard["FieldInfoV1"]:37    """Check if `obj` is a `pydantic.v1.fields.FieldInfo` without forcing import.3839    Avoids importing `pydantic.v1`, which emits a `UserWarning` on Python 3.14+40    with Pydantic 2.12. A v1 `FieldInfo` can only exist once a caller has imported41    `pydantic.v1.fields`, so this check consults it only if it is already loaded.42    """43    mod = sys.modules.get("pydantic.v1.fields")44    if mod is None:45        return False46    return isinstance(obj, mod.FieldInfo)474849def _build_deprecation_message(50    *,51    alternative: str = "",52    alternative_import: str = "",53) -> str:54    """Build a simple deprecation message for `__deprecated__` attribute.5556    Args:57        alternative: An alternative API name.58        alternative_import: A fully qualified import path for the alternative.5960    Returns:61        A deprecation message string for IDE/type checker display.62    """63    if alternative_import:64        return f"Use {alternative_import} instead."65    if alternative:66        return f"Use {alternative} instead."67    return "Deprecated."686970class LangChainDeprecationWarning(DeprecationWarning):71    """A class for issuing deprecation warnings for LangChain users."""727374class LangChainPendingDeprecationWarning(PendingDeprecationWarning):75    """A class for issuing deprecation warnings for LangChain users."""767778# Tracks when callers intentionally silence LangChain deprecation warnings.79# Suppressed warnings should not consume a deprecated callable's one-time80# warning state; otherwise an internal compatibility path can prevent the first81# user-visible call from warning.82_SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING = ContextVar(83    "_SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING", default=False84)858687# PUBLIC API888990# Bound is `Any` (not `FieldInfoV1`) because importing `pydantic.v1` at module91# scope emits a `UserWarning` on Python 3.14+; v1 `FieldInfo` support is handled92# at runtime via `_is_pydantic_v1_field_info`.93T = TypeVar("T", bound=type | Callable[..., Any] | Any)949596def _validate_deprecation_params(97    removal: str,98    alternative: str,99    alternative_import: str,100    *,101    pending: bool,102) -> None:103    """Validate the deprecation parameters."""104    if pending and removal:105        msg = "A pending deprecation cannot have a scheduled removal"106        raise ValueError(msg)107    if alternative and alternative_import:108        msg = "Cannot specify both alternative and alternative_import"109        raise ValueError(msg)110111    if alternative_import and "." not in alternative_import:112        msg = (113            "alternative_import must be a fully qualified module path. Got "114            f" {alternative_import}"115        )116        raise ValueError(msg)117118119def deprecated(120    since: str,121    *,122    message: str = "",123    name: str = "",124    alternative: str = "",125    alternative_import: str = "",126    pending: bool = False,127    obj_type: str = "",128    addendum: str = "",129    removal: str = "",130    package: str = "",131) -> Callable[[T], T]:132    """Decorator to mark a function, a class, or a property as deprecated.133134    When deprecating a classmethod, a staticmethod, or a property, the `@deprecated`135    decorator should go *under* `@classmethod` and `@staticmethod` (i.e., `deprecated`136    should directly decorate the underlying callable), but *over* `@property`.137138    When deprecating a class `C` intended to be used as a base class in a multiple139    inheritance hierarchy, `C` *must* define an `__init__` method (if `C` instead140    inherited its `__init__` from its own base class, then `@deprecated` would mess up141    `__init__` inheritance when installing its own (deprecation-emitting) `C.__init__`).142143    Parameters are the same as for `warn_deprecated`, except for `stacklevel`;144    *obj_type* defaults to 'class' if decorating a class, 'attribute' if decorating a145    property, and 'function' otherwise.146147    Args:148        since: The release at which this API became deprecated.149        message: Override the default deprecation message.150151            The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,152            `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the153            values of the respective arguments passed to this function.154        name: The name of the deprecated object.155        alternative: An alternative API that the user may use in place of the deprecated156            API.157158            The deprecation warning will tell the user about this alternative if159            provided.160        alternative_import: An alternative import that the user may use instead.161        pending: If `True`, uses a `PendingDeprecationWarning` instead of a162            `DeprecationWarning`.163164            Cannot be used together with removal.165        obj_type: The object type being deprecated.166        addendum: Additional text appended directly to the final message.167        removal: The expected removal version.168169            With the default (an empty string), no removal version is shown in the170            warning message.171172            Cannot be used together with pending.173        package: The package of the deprecated object.174175    Returns:176        A decorator to mark a function or class as deprecated.177178    Example:179        ```python180        @deprecated("1.4.0")181        def the_function_to_deprecate():182            pass183        ```184    """185    _validate_deprecation_params(186        removal, alternative, alternative_import, pending=pending187    )188189    def deprecate(190        obj: T,191        *,192        _obj_type: str = obj_type,193        _name: str = name,194        _message: str = message,195        _alternative: str = alternative,196        _alternative_import: str = alternative_import,197        _pending: bool = pending,198        _addendum: str = addendum,199        _package: str = package,200    ) -> T:201        """Implementation of the decorator returned by `deprecated`."""202203        def emit_warning() -> None:204            """Emit the warning."""205            warn_deprecated(206                since,207                message=_message,208                name=_name,209                alternative=_alternative,210                alternative_import=_alternative_import,211                pending=_pending,212                obj_type=_obj_type,213                addendum=_addendum,214                removal=removal,215                package=_package,216            )217218        warned = False219220        def warning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:221            """Wrapper for the original wrapped callable that emits a warning.222223            Args:224                *args: The positional arguments to the function.225                **kwargs: The keyword arguments to the function.226227            Returns:228                The return value of the function being wrapped.229            """230            nonlocal warned231            if not warned and not is_caller_internal():232                emit_warning()233                # Only mark the warning as emitted if it was not intentionally234                # suppressed by `suppress_langchain_deprecation_warning()`.235                warned = not _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.get()236            return wrapped(*args, **kwargs)237238        async def awarning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:239            """Same as warning_emitting_wrapper, but for async functions."""240            nonlocal warned241            if not warned and not is_caller_internal():242                emit_warning()243                # Only mark the warning as emitted if it was not intentionally244                # suppressed by `suppress_langchain_deprecation_warning()`.245                warned = not _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.get()246            return await wrapped(*args, **kwargs)247248        _package = _package or obj.__module__.split(".")[0].replace("_", "-")249250        if isinstance(obj, type):251            if not _obj_type:252                _obj_type = "class"253            wrapped = obj.__init__  # type: ignore[misc]254            _name = _name or obj.__qualname__255            old_doc = obj.__doc__256257            def finalize(_: Callable[..., Any], new_doc: str, /) -> T:258                """Finalize the deprecation of a class."""259                # Can't set new_doc on some extension objects.260                with contextlib.suppress(AttributeError):261                    obj.__doc__ = new_doc262263                def warn_if_direct_instance(264                    self: Any, *args: Any, **kwargs: Any265                ) -> Any:266                    """Warn that the class is in beta."""267                    nonlocal warned268                    if not warned and type(self) is obj and not is_caller_internal():269                        emit_warning()270                        # Only mark the warning as emitted if it was not intentionally271                        # suppressed by `suppress_langchain_deprecation_warning()`.272                        warned = not _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.get()273                    return wrapped(self, *args, **kwargs)274275                obj.__init__ = functools.wraps(obj.__init__)(  # type: ignore[misc]276                    warn_if_direct_instance277                )278                # Set __deprecated__ for PEP 702 (IDE/type checker support)279                obj.__deprecated__ = _build_deprecation_message(  # type: ignore[attr-defined]280                    alternative=alternative,281                    alternative_import=alternative_import,282                )283                return obj284285        elif _is_pydantic_v1_field_info(obj):286            wrapped = None287            if not _obj_type:288                _obj_type = "attribute"289            if not _name:290                msg = f"Field {obj} must have a name to be deprecated."291                raise ValueError(msg)292            old_doc = obj.description293294            def finalize(_: Callable[..., Any], new_doc: str, /) -> T:295                from pydantic.v1.fields import FieldInfo as FieldInfoV1  # noqa: PLC0415296297                return cast(298                    "T",299                    FieldInfoV1(300                        default=obj.default,301                        default_factory=obj.default_factory,302                        description=new_doc,303                        alias=obj.alias,304                        exclude=obj.exclude,305                    ),306                )307308        elif isinstance(obj, FieldInfo):309            wrapped = None310            if not _obj_type:311                _obj_type = "attribute"312            if not _name:313                msg = f"Field {obj} must have a name to be deprecated."314                raise ValueError(msg)315            old_doc = obj.description316317            def finalize(_: Callable[..., Any], new_doc: str, /) -> T:318                return cast(319                    "T",320                    FieldInfo(321                        default=obj.default,322                        default_factory=obj.default_factory,323                        description=new_doc,324                        alias=obj.alias,325                        exclude=obj.exclude,326                    ),327                )328329        elif isinstance(obj, property):330            if not _obj_type:331                _obj_type = "attribute"332            wrapped = None333            _name = _name or cast("type", obj.fget).__qualname__334            old_doc = obj.__doc__335336            class _DeprecatedProperty(property):337                """A deprecated property."""338339                def __init__(340                    self,341                    fget: Callable[[Any], Any] | None = None,342                    fset: Callable[[Any, Any], None] | None = None,343                    fdel: Callable[[Any], None] | None = None,344                    doc: str | None = None,345                ) -> None:346                    super().__init__(fget, fset, fdel, doc)347                    self.__orig_fget = fget348                    self.__orig_fset = fset349                    self.__orig_fdel = fdel350351                def __get__(self, instance: Any, owner: type | None = None) -> Any:352                    if instance is not None or owner is not None:353                        emit_warning()354                    if self.fget is None:355                        return None356                    return self.fget(instance)357358                def __set__(self, instance: Any, value: Any) -> None:359                    if instance is not None:360                        emit_warning()361                    if self.fset is not None:362                        self.fset(instance, value)363364                def __delete__(self, instance: Any) -> None:365                    if instance is not None:366                        emit_warning()367                    if self.fdel is not None:368                        self.fdel(instance)369370                def __set_name__(self, owner: type | None, set_name: str) -> None:371                    nonlocal _name372                    if _name == "<lambda>":373                        _name = set_name374375            def finalize(_: Callable[..., Any], new_doc: str, /) -> T:376                """Finalize the property."""377                prop = _DeprecatedProperty(378                    fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc379                )380                # Set __deprecated__ for PEP 702 (IDE/type checker support)381                prop.__deprecated__ = _build_deprecation_message(  # type: ignore[attr-defined]382                    alternative=alternative,383                    alternative_import=alternative_import,384                )385                return cast("T", prop)386387        else:388            _name = _name or cast("type", obj).__qualname__389            if not _obj_type:390                # edge case: when a function is within another function391                # within a test, this will call it a "method" not a "function"392                _obj_type = "function" if "." not in _name else "method"393            wrapped = obj394            old_doc = wrapped.__doc__395396            def finalize(wrapper: Callable[..., Any], new_doc: str, /) -> T:397                """Wrap the wrapped function using the wrapper and update the docstring.398399                Args:400                    wrapper: The wrapper function.401                    new_doc: The new docstring.402403                Returns:404                    The wrapped function.405                """406                wrapper = functools.wraps(wrapped)(wrapper)407                wrapper.__doc__ = new_doc408                # Set __deprecated__ for PEP 702 (IDE/type checker support)409                wrapper.__deprecated__ = _build_deprecation_message(  # type: ignore[attr-defined]410                    alternative=alternative,411                    alternative_import=alternative_import,412                )413                return cast("T", wrapper)414415        old_doc = inspect.cleandoc(old_doc or "").strip("\n")416417        # old_doc can be None418        if not old_doc:419            old_doc = ""420421        # Modify the docstring to include a deprecation notice.422        if (423            _alternative424            and _alternative.rsplit(".", maxsplit=1)[-1].lower()425            == _alternative.rsplit(".", maxsplit=1)[-1]426        ) or _alternative:427            _alternative = f"`{_alternative}`"428429        if (430            _alternative_import431            and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()432            == _alternative_import.rsplit(".", maxsplit=1)[-1]433        ) or _alternative_import:434            _alternative_import = f"`{_alternative_import}`"435436        components = [437            _message,438            f"Use {_alternative} instead." if _alternative else "",439            f"Use {_alternative_import} instead." if _alternative_import else "",440            _addendum,441        ]442        details = " ".join([component.strip() for component in components if component])443        package = _package or (444            _name.split(".")[0].replace("_", "-") if "." in _name else None445        )446        if removal:447            if removal.startswith("1.") and package and package.startswith("langchain"):448                removal_str = f"It will not be removed until {package}=={removal}."449            else:450                removal_str = f"It will be removed in {package}=={removal}."451        else:452            removal_str = ""453        new_doc = f"""\454!!! deprecated "{since} {details} {removal_str}"455456{old_doc}\457"""458459        if inspect.iscoroutinefunction(obj):460            return finalize(awarning_emitting_wrapper, new_doc)461        return finalize(warning_emitting_wrapper, new_doc)462463    return deprecate464465466@contextlib.contextmanager467def suppress_langchain_deprecation_warning() -> Generator[None, None, None]:468    """Suppress LangChain deprecation warnings within the current context.469470    Silences warnings emitted through `warn_deprecated` and `@deprecated`. It does not471    modify the global `warnings` filters, so calling `warnings.warn` directly with472    `LangChainDeprecationWarning` is not suppressed; use `warnings.filterwarnings` for473    that.474475    Suppression is stored in a context variable, not a process-wide filter. It476    applies to the current thread or asyncio task, and to tasks or copied contexts477    created inside the block (e.g. `asyncio.create_task`, `asyncio.to_thread`),478    which keep it even after the block exits. Other threads are unaffected.479    """480    token = _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.set(True)481    try:482        yield483    finally:484        # Exiting from a different context (e.g. an async generator suspended485        # inside the block and closed by another task) makes `reset` raise. That486        # context never saw this block's `set`, so there is nothing to undo.487        with contextlib.suppress(ValueError):488            _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.reset(token)489490491def warn_deprecated(492    since: str,493    *,494    message: str = "",495    name: str = "",496    alternative: str = "",497    alternative_import: str = "",498    pending: bool = False,499    obj_type: str = "",500    addendum: str = "",501    removal: str = "",502    package: str = "",503    stacklevel: int = 4,504) -> None:505    """Display a standardized deprecation.506507    Args:508        since: The release at which this API became deprecated.509        message: Override the default deprecation message.510511            The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,512            `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the513            values of the respective arguments passed to this function.514        name: The name of the deprecated object.515        alternative: An alternative API that the user may use in place of the516            deprecated API.517518            The deprecation warning will tell the user about this alternative if519            provided.520        alternative_import: An alternative import that the user may use instead.521        pending: If `True`, uses a `PendingDeprecationWarning` instead of a522            `DeprecationWarning`.523524            Cannot be used together with removal.525        obj_type: The object type being deprecated.526        addendum: Additional text appended directly to the final message.527        removal: The expected removal version.528529            With the default (an empty string), no removal version is shown in the530            warning message.531532            Cannot be used together with pending.533        package: The package of the deprecated object.534        stacklevel: Warning attribution depth passed to `warnings.warn`; `1` points535            inside this helper and `2` points to its caller.536    """537    if _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.get():538        return539540    if not pending and removal:541        removal = f"in {removal}"542543    if not message:544        message = ""545        package_ = (546            package or name.split(".", maxsplit=1)[0].replace("_", "-")547            if "." in name548            else "LangChain"549        )550551        if obj_type:552            message += f"The {obj_type} `{name}`"553        else:554            message += f"`{name}`"555556        if pending:557            message += " will be deprecated in a future version"558        else:559            message += f" was deprecated in {package_} {since}"560561            if removal:562                message += f" and will be removed {removal}"563564        if alternative_import:565            alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")566            if alt_package == package_:567                message += f". Use {alternative_import} instead."568            else:569                alt_module, alt_name = alternative_import.rsplit(".", 1)570                message += (571                    f". An updated version of the {obj_type} exists in the "572                    f"{alt_package} package and should be used instead. To use it run "573                    f"`pip install -U {alt_package}` and import as "574                    f"`from {alt_module} import {alt_name}`."575                )576        elif alternative:577            message += f". Use {alternative} instead."578579        if addendum:580            message += f" {addendum}"581582    warning_cls = (583        LangChainPendingDeprecationWarning if pending else LangChainDeprecationWarning584    )585    warning = warning_cls(message)586    warnings.warn(warning, category=LangChainDeprecationWarning, stacklevel=stacklevel)587588589def surface_langchain_deprecation_warnings() -> None:590    """Unmute LangChain deprecation warnings."""591    warnings.filterwarnings(592        "default",593        category=LangChainPendingDeprecationWarning,594    )595596    warnings.filterwarnings(597        "default",598        category=LangChainDeprecationWarning,599    )600601602_P = ParamSpec("_P")603_R = TypeVar("_R")604605606def rename_parameter(607    *,608    since: str,609    removal: str,610    old: str,611    new: str,612) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:613    """Decorator indicating that parameter *old* of *func* is renamed to *new*.614615    The actual implementation of *func* should use *new*, not *old*. If *old* is passed616    to *func*, a `DeprecationWarning` is emitted, and its value is used, even if *new*617    is also passed by keyword.618619    Args:620        since: The version in which the parameter was renamed.621        removal: The version in which the old parameter will be removed.622        old: The old parameter name.623        new: The new parameter name.624625    Returns:626        A decorator indicating that a parameter was renamed.627628    Example:629        ```python630        @_api.rename_parameter("3.1", "bad_name", "good_name")631        def func(good_name): ...632        ```633    """634635    def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:636        @functools.wraps(f)637        def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:638            if new in kwargs and old in kwargs:639                msg = f"{f.__name__}() got multiple values for argument {new!r}"640                raise TypeError(msg)641            if old in kwargs:642                warn_deprecated(643                    since,644                    removal=removal,645                    message=f"The parameter `{old}` of `{f.__name__}` was "646                    f"deprecated in {since} and will be removed "647                    f"in {removal} Use `{new}` instead.",648                )649                kwargs[new] = kwargs.pop(old)650            return f(*args, **kwargs)651652        return wrapper653654    return decorator

Code quality findings 5

Use isinstance() for type checking instead of type()
info correctness type-check
if not warned and type(self) is obj and not is_caller_internal():
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings