Use isinstance() for type checking instead of type()
if not warned and type(self) is obj and not is_caller_internal():
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 that *obj_type* defaults to144 'class' if decorating a class, 'attribute' if decorating a property, and 'function'145 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 """Context manager to suppress `LangChainDeprecationWarning`."""469 token = _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.set(True)470 try:471 with warnings.catch_warnings():472 warnings.simplefilter("ignore", LangChainDeprecationWarning)473 warnings.simplefilter("ignore", LangChainPendingDeprecationWarning)474 yield475 finally:476 _SUPPRESSING_LANGCHAIN_DEPRECATION_WARNING.reset(token)477478479def warn_deprecated(480 since: str,481 *,482 message: str = "",483 name: str = "",484 alternative: str = "",485 alternative_import: str = "",486 pending: bool = False,487 obj_type: str = "",488 addendum: str = "",489 removal: str = "",490 package: str = "",491) -> None:492 """Display a standardized deprecation.493494 Args:495 since: The release at which this API became deprecated.496 message: Override the default deprecation message.497498 The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,499 `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the500 values of the respective arguments passed to this function.501 name: The name of the deprecated object.502 alternative: An alternative API that the user may use in place of the503 deprecated API.504505 The deprecation warning will tell the user about this alternative if506 provided.507 alternative_import: An alternative import that the user may use instead.508 pending: If `True`, uses a `PendingDeprecationWarning` instead of a509 `DeprecationWarning`.510511 Cannot be used together with removal.512 obj_type: The object type being deprecated.513 addendum: Additional text appended directly to the final message.514 removal: The expected removal version.515516 With the default (an empty string), no removal version is shown in the517 warning message.518519 Cannot be used together with pending.520 package: The package of the deprecated object.521 """522 if not pending and removal:523 removal = f"in {removal}"524525 if not message:526 message = ""527 package_ = (528 package or name.split(".", maxsplit=1)[0].replace("_", "-")529 if "." in name530 else "LangChain"531 )532533 if obj_type:534 message += f"The {obj_type} `{name}`"535 else:536 message += f"`{name}`"537538 if pending:539 message += " will be deprecated in a future version"540 else:541 message += f" was deprecated in {package_} {since}"542543 if removal:544 message += f" and will be removed {removal}"545546 if alternative_import:547 alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")548 if alt_package == package_:549 message += f". Use {alternative_import} instead."550 else:551 alt_module, alt_name = alternative_import.rsplit(".", 1)552 message += (553 f". An updated version of the {obj_type} exists in the "554 f"{alt_package} package and should be used instead. To use it run "555 f"`pip install -U {alt_package}` and import as "556 f"`from {alt_module} import {alt_name}`."557 )558 elif alternative:559 message += f". Use {alternative} instead."560561 if addendum:562 message += f" {addendum}"563564 warning_cls = (565 LangChainPendingDeprecationWarning if pending else LangChainDeprecationWarning566 )567 warning = warning_cls(message)568 warnings.warn(warning, category=LangChainDeprecationWarning, stacklevel=4)569570571def surface_langchain_deprecation_warnings() -> None:572 """Unmute LangChain deprecation warnings."""573 warnings.filterwarnings(574 "default",575 category=LangChainPendingDeprecationWarning,576 )577578 warnings.filterwarnings(579 "default",580 category=LangChainDeprecationWarning,581 )582583584_P = ParamSpec("_P")585_R = TypeVar("_R")586587588def rename_parameter(589 *,590 since: str,591 removal: str,592 old: str,593 new: str,594) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:595 """Decorator indicating that parameter *old* of *func* is renamed to *new*.596597 The actual implementation of *func* should use *new*, not *old*. If *old* is passed598 to *func*, a `DeprecationWarning` is emitted, and its value is used, even if *new*599 is also passed by keyword.600601 Args:602 since: The version in which the parameter was renamed.603 removal: The version in which the old parameter will be removed.604 old: The old parameter name.605 new: The new parameter name.606607 Returns:608 A decorator indicating that a parameter was renamed.609610 Example:611 ```python612 @_api.rename_parameter("3.1", "bad_name", "good_name")613 def func(good_name): ...614 ```615 """616617 def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:618 @functools.wraps(f)619 def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:620 if new in kwargs and old in kwargs:621 msg = f"{f.__name__}() got multiple values for argument {new!r}"622 raise TypeError(msg)623 if old in kwargs:624 warn_deprecated(625 since,626 removal=removal,627 message=f"The parameter `{old}` of `{f.__name__}` was "628 f"deprecated in {since} and will be removed "629 f"in {removal} Use `{new}` instead.",630 )631 kwargs[new] = kwargs.pop(old)632 return f(*args, **kwargs)633634 return wrapper635636 return decorator
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