Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: Add ruff rules D (docstring) #29406

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions libs/core/langchain_core/_api/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ def deprecated(
An alternative API that the user may use in place of the
deprecated API. The deprecation warning will tell the user
about this alternative if provided.
alternative_import: str, optional
An alternative import that the user may use instead.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with removal.
Expand All @@ -121,6 +123,8 @@ def deprecated(
string), a removal version is automatically computed from
since. Set to other Falsy values to not schedule a removal
date. Cannot be used together with pending.
package: str, optional
The package of the deprecated object.

Examples:

Expand Down Expand Up @@ -422,6 +426,8 @@ def warn_deprecated(
An alternative API that the user may use in place of the
deprecated API. The deprecation warning will tell the user
about this alternative if provided.
alternative_import: str, optional
An alternative import that the user may use instead.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with removal.
Expand All @@ -434,6 +440,8 @@ def warn_deprecated(
string), a removal version is automatically computed from
since. Set to other Falsy values to not schedule a removal
date. Cannot be used together with pending.
package: str, optional
The package of the deprecated object.
"""
if not pending:
if not removal:
Expand Down
19 changes: 16 additions & 3 deletions libs/core/langchain_core/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,28 @@ class AgentAction(Serializable):
def __init__(
self, tool: str, tool_input: Union[str, dict], log: str, **kwargs: Any
):
"""Create an AgentAction.

Args:
tool: The name of the tool to execute.
tool_input: The input to pass in to the Tool.
log: Additional information to log about the action.
"""
super().__init__(tool=tool, tool_input=tool_input, log=log, **kwargs)

@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether or not the class is serializable.
Default is True.
"""AgentAction is serializable.

Returns:
True
"""
return True

@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.

Default is ["langchain", "schema", "agent"].
"""
return ["langchain", "schema", "agent"]
Expand Down Expand Up @@ -148,7 +158,10 @@ def is_lc_serializable(cls) -> bool:

@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object."""
"""Get the namespace of the langchain object.

Default namespace is ["langchain", "schema", "agent"].
"""
return ["langchain", "schema", "agent"]

@property
Expand Down
1 change: 1 addition & 0 deletions libs/core/langchain_core/beta/runnables/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Runnables."""
50 changes: 50 additions & 0 deletions libs/core/langchain_core/beta/runnables/context.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Context management for runnables."""

import asyncio
import threading
from collections import defaultdict
Expand All @@ -13,6 +15,7 @@
)

from pydantic import ConfigDict
from typing_extensions import override

from langchain_core._api.beta_decorator import beta
from langchain_core.runnables.base import (
Expand Down Expand Up @@ -161,11 +164,13 @@ class ContextGet(RunnableSerializable):

key: Union[str, list[str]]

@override
def __str__(self) -> str:
return f"ContextGet({_print_keys(self.key)})"

@property
def ids(self) -> list[str]:
"""The context getter ids."""
prefix = self.prefix + "/" if self.prefix else ""
keys = self.key if isinstance(self.key, list) else [self.key]
return [
Expand All @@ -174,6 +179,7 @@ def ids(self) -> list[str]:
]

@property
@override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return super().config_specs + [
ConfigurableFieldSpec(
Expand All @@ -183,6 +189,7 @@ def config_specs(self) -> list[ConfigurableFieldSpec]:
for id_ in self.ids
]

@override
def invoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
Expand All @@ -193,6 +200,7 @@ def invoke(
else:
return configurable[self.ids[0]]()

@override
async def ainvoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
Expand Down Expand Up @@ -238,6 +246,14 @@ def __init__(
prefix: str = "",
**kwargs: SetValue,
):
"""Create a context setter.

Args:
key: The context setter key.
value: The context setter value.
prefix: The context setter prefix.
**kwargs: Additional context setter key-value pairs.
"""
if key is not None:
kwargs[key] = value
super().__init__( # type: ignore[call-arg]
Expand All @@ -248,18 +264,21 @@ def __init__(
prefix=prefix,
)

@override
def __str__(self) -> str:
return f"ContextSet({_print_keys(list(self.keys.keys()))})"

@property
def ids(self) -> list[str]:
"""The context setter ids."""
prefix = self.prefix + "/" if self.prefix else ""
return [
f"{CONTEXT_CONFIG_PREFIX}{prefix}{key}{CONTEXT_CONFIG_SUFFIX_SET}"
for key in self.keys
]

@property
@override
def config_specs(self) -> list[ConfigurableFieldSpec]:
mapper_config_specs = [
s
Expand All @@ -281,6 +300,7 @@ def config_specs(self) -> list[ConfigurableFieldSpec]:
for id_ in self.ids
]

@override
def invoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
Expand All @@ -293,6 +313,7 @@ def invoke(
configurable[id_](input)
return input

@override
async def ainvoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
Expand Down Expand Up @@ -361,6 +382,11 @@ def create_scope(scope: str, /) -> "PrefixContext":

@staticmethod
def getter(key: Union[str, list[str]], /) -> ContextGet:
"""Return a context getter.

Args:
key: The context getter key.
"""
return ContextGet(key=key)

@staticmethod
Expand All @@ -370,6 +396,13 @@ def setter(
/,
**kwargs: SetValue,
) -> ContextSet:
"""Return a context setter.

Args:
_key: The context setter key.
_value: The context setter value.
**kwargs: Additional context setter key-value pairs.
"""
return ContextSet(_key, _value, prefix="", **kwargs)


Expand All @@ -379,9 +412,19 @@ class PrefixContext:
prefix: str = ""

def __init__(self, prefix: str = ""):
"""Create a prefix context.

Args:
prefix: The prefix.
"""
self.prefix = prefix

def getter(self, key: Union[str, list[str]], /) -> ContextGet:
"""Return a prefixed context getter.

Args:
key: The context getter key.
"""
return ContextGet(key=key, prefix=self.prefix)

def setter(
Expand All @@ -391,6 +434,13 @@ def setter(
/,
**kwargs: SetValue,
) -> ContextSet:
"""Return a prefixed context setter.

Args:
_key: The context setter key.
_value: The context setter value.
**kwargs: Additional context setter key-value pairs.
"""
return ContextSet(_key, _value, prefix=self.prefix, **kwargs)


Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/caches.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""
"""Cache classes.

.. warning::
Beta Feature!

Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/callbacks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,8 @@ def __init__(
inheritable_tags (Optional[List[str]]): The inheritable tags.
Default is None.
metadata (Optional[Dict[str, Any]]): The metadata. Default is None.
inheritable_metadata (Optional[Dict[str, Any]]): The inheritable metadata.
Default is None.
"""
self.handlers: list[BaseCallbackHandler] = handlers
self.inheritable_handlers: list[BaseCallbackHandler] = (
Expand Down
4 changes: 4 additions & 0 deletions libs/core/langchain_core/callbacks/manager.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Run managers."""

from __future__ import annotations

import asyncio
Expand Down Expand Up @@ -66,6 +68,7 @@ def trace_as_chain_group(
metadata: Optional[dict[str, Any]] = None,
) -> Generator[CallbackManagerForChainGroup, None, None]:
"""Get a callback manager for a chain group in a context manager.

Useful for grouping different calls together as a single run even if
they aren't composed in a single chain.

Expand Down Expand Up @@ -146,6 +149,7 @@ async def atrace_as_chain_group(
metadata: Optional[dict[str, Any]] = None,
) -> AsyncGenerator[AsyncCallbackManagerForChainGroup, None]:
"""Get an async callback manager for a chain group in a context manager.

Useful for grouping different async calls together as a single run even if
they aren't composed in a single chain.

Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/chat_loaders.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Chat loaders."""

from abc import ABC, abstractmethod
from collections.abc import Iterator

Expand Down
5 changes: 3 additions & 2 deletions libs/core/langchain_core/chat_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@


class ChatSession(TypedDict, total=False):
"""Chat Session represents a single
conversation, channel, or other group of messages.
"""Chat Session.

Chat Session represents a single conversation, channel, or other group of messages.
"""

messages: Sequence[BaseMessage]
Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/document_loaders/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Document loaders."""

from langchain_core.document_loaders.base import BaseBlobParser, BaseLoader
from langchain_core.document_loaders.blob_loaders import Blob, BlobLoader, PathLike
from langchain_core.document_loaders.langsmith import LangSmithLoader
Expand Down
8 changes: 7 additions & 1 deletion libs/core/langchain_core/document_loaders/langsmith.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""LangSmith document loader."""

import datetime
import json
import uuid
from collections.abc import Iterator, Sequence
from typing import Any, Callable, Optional, Union

from langsmith import Client as LangSmithClient
from typing_extensions import override

from langchain_core.document_loaders.base import BaseLoader
from langchain_core.documents import Document
Expand Down Expand Up @@ -53,7 +56,8 @@ def __init__(
client: Optional[LangSmithClient] = None,
**client_kwargs: Any,
) -> None:
"""
"""Create a LangSmith loader.

Args:
dataset_id: The ID of the dataset to filter by. Defaults to None.
dataset_name: The name of the dataset to filter by. Defaults to None.
Expand All @@ -74,6 +78,7 @@ def __init__(
inline_s3_urls: Whether to inline S3 URLs. Defaults to True.
offset: The offset to start from. Defaults to 0.
limit: The maximum number of examples to return.
metadata: Metadata to filter by. Defaults to None.
filter: A structured filter string to apply to the examples.
client: LangSmith Client. If not provided will be initialized from below args.
client_kwargs: Keyword args to pass to LangSmith client init. Should only be
Expand All @@ -95,6 +100,7 @@ def __init__(
self.metadata = metadata
self.filter = filter

@override
def lazy_load(self) -> Iterator[Document]:
for example in self._client.list_examples(
dataset_id=self.dataset_id,
Expand Down
4 changes: 3 additions & 1 deletion libs/core/langchain_core/documents/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""**Document** module is a collection of classes that handle documents
"""Documents module.

**Document** module is a collection of classes that handle documents
and their transformations.

"""
Expand Down
12 changes: 11 additions & 1 deletion libs/core/langchain_core/documents/base.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Base classes for media and documents."""

from __future__ import annotations

import contextlib
Expand Down Expand Up @@ -43,6 +45,11 @@ class BaseMedia(Serializable):

@field_validator("id", mode="before")
def cast_id_to_str(cls, id_value: Any) -> Optional[str]:
"""Coerce the id field to a string.

Args:
id_value: The id value to coerce.
"""
if id_value is not None:
return str(id_value)
else:
Expand Down Expand Up @@ -291,7 +298,10 @@ def is_lc_serializable(cls) -> bool:

@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object."""
"""Get the namespace of the langchain object.

Default namespace is ["langchain", "schema", "document"].
"""
return ["langchain", "schema", "document"]

def __str__(self) -> str:
Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/documents/compressor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Document compressor."""

from __future__ import annotations

from abc import ABC, abstractmethod
Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/documents/transformers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Document transformers."""

from __future__ import annotations

from abc import ABC, abstractmethod
Expand Down
Loading
Loading