Skip to content

The agent engineering platform.

core: Add ruff rules D (docstring) (#29406)

Christophe Bornet88b4233fa1cd
diff --git a/libs/core/langchain_core/_api/deprecation.py b/libs/core/langchain_core/_api/deprecation.py
index ac1f1e0616..52ce92075e 100644
--- a/libs/core/langchain_core/_api/deprecation.py
+++ b/libs/core/langchain_core/_api/deprecation.py
@@ -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.
@@ -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:
@@ -434,6 +438,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.
@@ -446,6 +452,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:
diff --git a/libs/core/langchain_core/agents.py b/libs/core/langchain_core/agents.py
index 3a7fea6d32..5365bc6757 100644
--- a/libs/core/langchain_core/agents.py
+++ b/libs/core/langchain_core/agents.py
@@ -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"]
@@ -148,7 +158,10 @@ class AgentFinish(Serializable):
@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
diff --git a/libs/core/langchain_core/beta/runnables/__init__.py b/libs/core/langchain_core/beta/runnables/__init__.py
index e69de29bb2..72d18c1597 100644
--- a/libs/core/langchain_core/beta/runnables/__init__.py
+++ b/libs/core/langchain_core/beta/runnables/__init__.py
@@ -0,0 +1 @@
+"""Runnables."""
diff --git a/libs/core/langchain_core/beta/runnables/context.py b/libs/core/langchain_core/beta/runnables/context.py
index 2be721387c..d6d88ab20b 100644
--- a/libs/core/langchain_core/beta/runnables/context.py
+++ b/libs/core/langchain_core/beta/runnables/context.py
@@ -1,3 +1,5 @@
+"""Context management for runnables."""
+
import asyncio
import threading
from collections import defaultdict
@@ -13,6 +15,7 @@ from typing import (
)
from pydantic import ConfigDict
+from typing_extensions import override
from langchain_core._api.beta_decorator import beta
from langchain_core.runnables.base import (
@@ -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 [
@@ -174,6 +179,7 @@ class ContextGet(RunnableSerializable):
]
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return super().config_specs + [
ConfigurableFieldSpec(
@@ -183,6 +189,7 @@ class ContextGet(RunnableSerializable):
for id_ in self.ids
]
+ @override
def invoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
@@ -193,6 +200,7 @@ class ContextGet(RunnableSerializable):
else:
return configurable[self.ids[0]]()
+ @override
async def ainvoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
@@ -238,6 +246,14 @@ class ContextSet(RunnableSerializable):
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]
@@ -248,11 +264,13 @@ class ContextSet(RunnableSerializable):
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}"
@@ -260,6 +278,7 @@ class ContextSet(RunnableSerializable):
]
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
mapper_config_specs = [
s
@@ -281,6 +300,7 @@ class ContextSet(RunnableSerializable):
for id_ in self.ids
]
+ @override
def invoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
@@ -293,6 +313,7 @@ class ContextSet(RunnableSerializable):
configurable[id_](input)
return input
+ @override
async def ainvoke(
self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Any:
@@ -361,6 +382,11 @@ class Context:
@staticmethod
def getter(key: Union[str, list[str]], /) -> ContextGet:
+ """Return a context getter.
+
+ Args:
+ key: The context getter key.
+ """
return ContextGet(key=key)
@staticmethod
@@ -370,6 +396,13 @@ class Context:
/,
**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)
@@ -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(
@@ -391,6 +434,13 @@ class PrefixContext:
/,
**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)
diff --git a/libs/core/langchain_core/caches.py b/libs/core/langchain_core/caches.py
index d534d70d25..4805a74759 100644
--- a/libs/core/langchain_core/caches.py
+++ b/libs/core/langchain_core/caches.py
@@ -1,4 +1,5 @@
-"""
+"""Cache classes.
+
.. warning::
Beta Feature!
diff --git a/libs/core/langchain_core/callbacks/base.py b/libs/core/langchain_core/callbacks/base.py
index 1c0fd19de5..8374372307 100644
--- a/libs/core/langchain_core/callbacks/base.py
+++ b/libs/core/langchain_core/callbacks/base.py
@@ -907,6 +907,8 @@ class BaseCallbackManager(CallbackManagerMixin):
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] = (
diff --git a/libs/core/langchain_core/callbacks/manager.py b/libs/core/langchain_core/callbacks/manager.py
index d1c534d27c..f7268c17e3 100644
--- a/libs/core/langchain_core/callbacks/manager.py
+++ b/libs/core/langchain_core/callbacks/manager.py
@@ -1,3 +1,5 @@
+"""Run managers."""
+
from __future__ import annotations
import asyncio
@@ -68,6 +70,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.
@@ -148,6 +151,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.
diff --git a/libs/core/langchain_core/callbacks/usage.py b/libs/core/langchain_core/callbacks/usage.py
index 930b6f5280..2e7b493f0d 100644
--- a/libs/core/langchain_core/callbacks/usage.py
+++ b/libs/core/langchain_core/callbacks/usage.py
@@ -6,6 +6,8 @@ from contextlib import contextmanager
from contextvars import ContextVar
from typing import Any, Optional
+from typing_extensions import override
+
from langchain_core._api import beta
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import AIMessage
@@ -47,10 +49,12 @@ class UsageMetadataCallbackHandler(BaseCallbackHandler):
"""
def __init__(self) -> None:
+ """Initialize the UsageMetadataCallbackHandler."""
super().__init__()
self._lock = threading.Lock()
self.usage_metadata: dict[str, UsageMetadata] = {}
+ @override
def __repr__(self) -> str:
return str(self.usage_metadata)
@@ -89,7 +93,9 @@ class UsageMetadataCallbackHandler(BaseCallbackHandler):
def get_usage_metadata_callback(
name: str = "usage_metadata_callback",
) -> Generator[UsageMetadataCallbackHandler, None, None]:
- """Get context manager for tracking usage metadata across chat model calls using
+ """Get usage metadata callback.
+
+ Get context manager for tracking usage metadata across chat model calls using
``AIMessage.usage_metadata``.
Args:
diff --git a/libs/core/langchain_core/chat_loaders.py b/libs/core/langchain_core/chat_loaders.py
index 51e6513316..dfb01eb872 100644
--- a/libs/core/langchain_core/chat_loaders.py
+++ b/libs/core/langchain_core/chat_loaders.py
@@ -1,3 +1,5 @@
+"""Chat loaders."""
+
from abc import ABC, abstractmethod
from collections.abc import Iterator
diff --git a/libs/core/langchain_core/chat_sessions.py b/libs/core/langchain_core/chat_sessions.py
index 6cbc19fd10..23c60f3fe6 100644
--- a/libs/core/langchain_core/chat_sessions.py
+++ b/libs/core/langchain_core/chat_sessions.py
@@ -7,8 +7,9 @@ from langchain_core.messages import BaseMessage
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]
diff --git a/libs/core/langchain_core/document_loaders/__init__.py b/libs/core/langchain_core/document_loaders/__init__.py
index e8b6fde5be..f85bcc454e 100644
--- a/libs/core/langchain_core/document_loaders/__init__.py
+++ b/libs/core/langchain_core/document_loaders/__init__.py
@@ -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
diff --git a/libs/core/langchain_core/document_loaders/langsmith.py b/libs/core/langchain_core/document_loaders/langsmith.py
index 39fda02af5..0705c780bd 100644
--- a/libs/core/langchain_core/document_loaders/langsmith.py
+++ b/libs/core/langchain_core/document_loaders/langsmith.py
@@ -1,3 +1,5 @@
+"""LangSmith document loader."""
+
import datetime
import json
import uuid
@@ -5,6 +7,7 @@ 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
@@ -53,7 +56,8 @@ class LangSmithLoader(BaseLoader):
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.
@@ -74,6 +78,7 @@ class LangSmithLoader(BaseLoader):
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
@@ -95,6 +100,7 @@ class LangSmithLoader(BaseLoader):
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,
diff --git a/libs/core/langchain_core/documents/__init__.py b/libs/core/langchain_core/documents/__init__.py
index 5430d24f54..1d9b3d6389 100644
--- a/libs/core/langchain_core/documents/__init__.py
+++ b/libs/core/langchain_core/documents/__init__.py
@@ -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.
"""
diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.py
index d1710499ed..8985d66c6c 100644
--- a/libs/core/langchain_core/documents/base.py
+++ b/libs/core/langchain_core/documents/base.py
@@ -1,3 +1,5 @@
+"""Base classes for media and documents."""
+
from __future__ import annotations
import contextlib
@@ -45,6 +47,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:
@@ -291,7 +298,10 @@ class Document(BaseMedia):
@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:
diff --git a/libs/core/langchain_core/documents/compressor.py b/libs/core/langchain_core/documents/compressor.py
index 3c9217e4f7..707d96cf08 100644
--- a/libs/core/langchain_core/documents/compressor.py
+++ b/libs/core/langchain_core/documents/compressor.py
@@ -1,3 +1,5 @@
+"""Document compressor."""
+
from __future__ import annotations
from abc import ABC, abstractmethod
diff --git a/libs/core/langchain_core/documents/transformers.py b/libs/core/langchain_core/documents/transformers.py
index 5be5e98c06..171a98b458 100644
--- a/libs/core/langchain_core/documents/transformers.py
+++ b/libs/core/langchain_core/documents/transformers.py
@@ -1,3 +1,5 @@
+"""Document transformers."""
+
from __future__ import annotations
from abc import ABC, abstractmethod
diff --git a/libs/core/langchain_core/embeddings/__init__.py b/libs/core/langchain_core/embeddings/__init__.py
index 532950f2ad..2ef05597db 100644
--- a/libs/core/langchain_core/embeddings/__init__.py
+++ b/libs/core/langchain_core/embeddings/__init__.py
@@ -1,3 +1,5 @@
+"""Embeddings."""
+
from langchain_core.embeddings.embeddings import Embeddings
from langchain_core.embeddings.fake import DeterministicFakeEmbedding, FakeEmbeddings
diff --git a/libs/core/langchain_core/embeddings/fake.py b/libs/core/langchain_core/embeddings/fake.py
index 6f7c4241d5..d11ea9bd30 100644
--- a/libs/core/langchain_core/embeddings/fake.py
+++ b/libs/core/langchain_core/embeddings/fake.py
@@ -4,6 +4,7 @@
import hashlib
from pydantic import BaseModel
+from typing_extensions import override
from langchain_core.embeddings import Embeddings
@@ -55,9 +56,11 @@ class FakeEmbeddings(Embeddings, BaseModel):
return list(np.random.default_rng().normal(size=self.size))
+ @override
def embed_documents(self, texts: list[str]) -> list[list[float]]:
return [self._get_embedding() for _ in texts]
+ @override
def embed_query(self, text: str) -> list[float]:
return self._get_embedding()
@@ -116,8 +119,10 @@ class DeterministicFakeEmbedding(Embeddings, BaseModel):
"""Get a seed for the random generator, using the hash of the text."""
return int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % 10**8
+ @override
def embed_documents(self, texts: list[str]) -> list[list[float]]:
return [self._get_embedding(seed=self._get_seed(_)) for _ in texts]
+ @override
def embed_query(self, text: str) -> list[float]:
return self._get_embedding(seed=self._get_seed(text))
diff --git a/libs/core/langchain_core/env.py b/libs/core/langchain_core/env.py
index 9539ff54e8..fd619bc1d9 100644
--- a/libs/core/langchain_core/env.py
+++ b/libs/core/langchain_core/env.py
@@ -1,3 +1,5 @@
+"""Utilities for getting information about the runtime environment."""
+
import platform
from functools import lru_cache
diff --git a/libs/core/langchain_core/example_selectors/__init__.py b/libs/core/langchain_core/example_selectors/__init__.py
index f4c033c0b6..68f454fd2d 100644
--- a/libs/core/langchain_core/example_selectors/__init__.py
+++ b/libs/core/langchain_core/example_selectors/__init__.py
@@ -1,5 +1,6 @@
-"""**Example selector** implements logic for selecting examples to include them
-in prompts.
+"""Example selectors.
+
+**Example selector** implements logic for selecting examples to include them in prompts.
This allows us to select examples that are most relevant to the input.
"""
diff --git a/libs/core/langchain_core/example_selectors/semantic_similarity.py b/libs/core/langchain_core/example_selectors/semantic_similarity.py
index cd6f82bc8c..41ec8881c4 100644
--- a/libs/core/langchain_core/example_selectors/semantic_similarity.py
+++ b/libs/core/langchain_core/example_selectors/semantic_similarity.py
@@ -328,8 +328,7 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
vectorstore_kwargs: Optional[dict] = None,
**vectorstore_cls_kwargs: Any,
) -> MaxMarginalRelevanceExampleSelector:
- """Asynchronously create k-shot example selector using example list and
- embeddings.
+ """Create k-shot example selector using example list and embeddings.
Reshuffles examples dynamically based on Max Marginal Relevance.
diff --git a/libs/core/langchain_core/exceptions.py b/libs/core/langchain_core/exceptions.py
index 71ddaab5b6..a2acfc9b64 100644
--- a/libs/core/langchain_core/exceptions.py
+++ b/libs/core/langchain_core/exceptions.py
@@ -19,18 +19,6 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
that also may arise inside the output parser. OutputParserExceptions will be
available to catch and handle in ways to fix the parsing error, while other
errors will be raised.
-
- Parameters:
- error: The error that's being re-raised or an error message.
- observation: String explanation of error which can be passed to a
- model to try and remediate the issue. Defaults to None.
- llm_output: String model output which is error-ing.
- Defaults to None.
- send_to_llm: Whether to send the observation and llm_output back to an Agent
- after an OutputParserException has been raised. This gives the underlying
- model driving the agent the context that the previous output was improperly
- structured, in the hopes that it will update the output to the correct
- format. Defaults to False.
"""
def __init__(
@@ -40,6 +28,21 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
llm_output: Optional[str] = None,
send_to_llm: bool = False,
):
+ """Create an OutputParserException.
+
+ Args:
+ error: The error that's being re-raised or an error message.
+ observation: String explanation of error which can be passed to a
+ model to try and remediate the issue. Defaults to None.
+ llm_output: String model output which is error-ing.
+ Defaults to None.
+ send_to_llm: Whether to send the observation and llm_output back to an Agent
+ after an OutputParserException has been raised.
+ This gives the underlying model driving the agent the context that the
+ previous output was improperly structured, in the hopes that it will
+ update the output to the correct format.
+ Defaults to False.
+ """
if isinstance(error, str):
error = create_message(
message=error, error_code=ErrorCode.OUTPUT_PARSING_FAILURE
@@ -57,6 +60,8 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
class ErrorCode(Enum):
+ """Error codes."""
+
INVALID_PROMPT_INPUT = "INVALID_PROMPT_INPUT"
INVALID_TOOL_RESULTS = "INVALID_TOOL_RESULTS"
MESSAGE_COERCION_FAILURE = "MESSAGE_COERCION_FAILURE"
@@ -67,6 +72,12 @@ class ErrorCode(Enum):
def create_message(*, message: str, error_code: ErrorCode) -> str:
+ """Create a message with a link to the LangChain troubleshooting guide.
+
+ Args:
+ message: The message to display.
+ error_code: The error code to display.
+ """
return (
f"{message}\n"
"For troubleshooting, visit: https://python.langchain.com/docs/"
diff --git a/libs/core/langchain_core/indexing/base.py b/libs/core/langchain_core/indexing/base.py
index 62e0a720c0..79e2701d7a 100644
--- a/libs/core/langchain_core/indexing/base.py
+++ b/libs/core/langchain_core/indexing/base.py
@@ -1,3 +1,5 @@
+"""Base classes for indexing."""
+
from __future__ import annotations
import abc
@@ -252,9 +254,7 @@ class InMemoryRecordManager(RecordManager):
"""In-memory schema creation is simply ensuring the structure is initialized."""
async def acreate_schema(self) -> None:
- """Async in-memory schema creation is simply ensuring
- the structure is initialized.
- """
+ """Async in-memory schema creation is simply ensuring the structure is initialized.""" # noqa: E501
def get_time(self) -> float:
"""Get the current server time as a high resolution timestamp!"""
diff --git a/libs/core/langchain_core/indexing/in_memory.py b/libs/core/langchain_core/indexing/in_memory.py
index e166f5b158..a216d27813 100644
--- a/libs/core/langchain_core/indexing/in_memory.py
+++ b/libs/core/langchain_core/indexing/in_memory.py
@@ -1,3 +1,5 @@
+"""In memory document index."""
+
import operator
import uuid
from collections.abc import Sequence
diff --git a/libs/core/langchain_core/language_models/__init__.py b/libs/core/langchain_core/language_models/__init__.py
index 2b3c6b40ef..37ac295314 100644
--- a/libs/core/langchain_core/language_models/__init__.py
+++ b/libs/core/langchain_core/language_models/__init__.py
@@ -1,4 +1,6 @@
-"""**Language Model** is a type of model that can generate text or complete
+"""Language models.
+
+**Language Model** is a type of model that can generate text or complete
text prompts.
LangChain has two main classes to work with language models: **Chat Models**
diff --git a/libs/core/langchain_core/language_models/base.py b/libs/core/langchain_core/language_models/base.py
index ae2ab439e8..5e7a2ed7b4 100644
--- a/libs/core/langchain_core/language_models/base.py
+++ b/libs/core/langchain_core/language_models/base.py
@@ -1,3 +1,5 @@
+"""Base language models class."""
+
from __future__ import annotations
import warnings
diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py
index bde6052992..9fa53ddf19 100644
--- a/libs/core/langchain_core/language_models/chat_models.py
+++ b/libs/core/langchain_core/language_models/chat_models.py
@@ -1,3 +1,5 @@
+"""Chat models for conversational AI."""
+
from __future__ import annotations
import asyncio
@@ -293,6 +295,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
)
raise ValueError(msg) # noqa: TRY004
+ @override
def invoke(
self,
input: LanguageModelInput,
@@ -316,6 +319,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
).generations[0][0],
).message
+ @override
async def ainvoke(
self,
input: LanguageModelInput,
@@ -372,6 +376,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
handlers = run_manager.handlers if run_manager else []
return any(isinstance(h, _StreamingCallbackHandler) for h in handlers)
+ @override
def stream(
self,
input: LanguageModelInput,
@@ -454,6 +459,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+ @override
async def astream(
self,
input: LanguageModelInput,
@@ -638,6 +644,10 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
first occurrence of any of these substrings.
callbacks: Callbacks to pass through. Used for executing additional
functionality, such as logging or streaming, throughout generation.
+ tags: The tags to apply.
+ metadata: The metadata to apply.
+ run_name: The name of the run.
+ run_id: The ID of the run.
**kwargs: Arbitrary additional keyword arguments. These are usually passed
to the model provider API call.
@@ -736,6 +746,10 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
first occurrence of any of these substrings.
callbacks: Callbacks to pass through. Used for executing additional
functionality, such as logging or streaming, throughout generation.
+ tags: The tags to apply.
+ metadata: The metadata to apply.
+ run_name: The name of the run.
+ run_id: The ID of the run.
**kwargs: Arbitrary additional keyword arguments. These are usually passed
to the model provider API call.
@@ -833,6 +847,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
]
return output
+ @override
def generate_prompt(
self,
prompts: list[PromptValue],
@@ -843,6 +858,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
prompt_messages = [p.to_messages() for p in prompts]
return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs)
+ @override
async def agenerate_prompt(
self,
prompts: list[PromptValue],
@@ -1072,6 +1088,20 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
callbacks: Callbacks = None,
**kwargs: Any,
) -> BaseMessage:
+ """Call the model.
+
+ Args:
+ messages: List of messages.
+ stop: Stop words to use when generating. Model output is cut off at the
+ first occurrence of any of these substrings.
+ callbacks: Callbacks to pass through. Used for executing additional
+ functionality, such as logging or streaming, throughout generation.
+ **kwargs: Arbitrary additional keyword arguments. These are usually passed
+ to the model provider API call.
+
+ Returns:
+ The model output message.
+ """
generation = self.generate(
[messages], stop=stop, callbacks=callbacks, **kwargs
).generations[0][0]
@@ -1102,12 +1132,37 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
def call_as_llm(
self, message: str, stop: Optional[list[str]] = None, **kwargs: Any
) -> str:
+ """Call the model.
+
+ Args:
+ message: The input message.
+ stop: Stop words to use when generating. Model output is cut off at the
+ first occurrence of any of these substrings.
+ **kwargs: Arbitrary additional keyword arguments. These are usually passed
+ to the model provider API call.
+
+ Returns:
+ The model output string.
+ """
return self.predict(message, stop=stop, **kwargs)
@deprecated("0.1.7", alternative="invoke", removal="1.0")
+ @override
def predict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
+ """Predict the next message.
+
+ Args:
+ text: The input message.
+ stop: Stop words to use when generating. Model output is cut off at the
+ first occurrence of any of these substrings.
+ **kwargs: Arbitrary additional keyword arguments. These are usually passed
+ to the model provider API call.
+
+ Returns:
+ The predicted output string.
+ """
_stop = None if stop is None else list(stop)
result = self([HumanMessage(content=text)], stop=_stop, **kwargs)
if isinstance(result.content, str):
@@ -1117,6 +1172,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
raise ValueError(msg) # noqa: TRY004
@deprecated("0.1.7", alternative="invoke", removal="1.0")
+ @override
def predict_messages(
self,
messages: list[BaseMessage],
@@ -1128,6 +1184,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
return self(messages, stop=_stop, **kwargs)
@deprecated("0.1.7", alternative="ainvoke", removal="1.0")
+ @override
async def apredict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@@ -1142,6 +1199,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
raise ValueError(msg) # noqa: TRY004
@deprecated("0.1.7", alternative="ainvoke", removal="1.0")
+ @override
async def apredict_messages(
self,
messages: list[BaseMessage],
@@ -1172,6 +1230,15 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
tool_choice: Optional[Union[str, Literal["any"]]] = None,
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
+ """Bind tools to the model.
+
+ Args:
+ tools: Sequence of tools to bind to the model.
+ tool_choice: The tool to use. If "any" then any tool can be used.
+
+ Returns:
+ A Runnable that returns a message.
+ """
raise NotImplementedError
def with_structured_output(
diff --git a/libs/core/langchain_core/language_models/fake.py b/libs/core/langchain_core/language_models/fake.py
index 64bb637068..72366302ba 100644
--- a/libs/core/langchain_core/language_models/fake.py
+++ b/libs/core/langchain_core/language_models/fake.py
@@ -1,8 +1,12 @@
+"""Fake LLMs for testing purposes."""
+
import asyncio
import time
from collections.abc import AsyncIterator, Iterator, Mapping
from typing import Any, Optional
+from typing_extensions import override
+
from langchain_core.callbacks import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
@@ -31,10 +35,12 @@ class FakeListLLM(LLM):
"""
@property
+ @override
def _llm_type(self) -> str:
"""Return type of llm."""
return "fake-list"
+ @override
def _call(
self,
prompt: str,
@@ -50,6 +56,7 @@ class FakeListLLM(LLM):
self.i = 0
return response
+ @override
async def _acall(
self,
prompt: str,
@@ -66,6 +73,7 @@ class FakeListLLM(LLM):
return response
@property
+ @override
def _identifying_params(self) -> Mapping[str, Any]:
return {"responses": self.responses}
@@ -86,6 +94,7 @@ class FakeStreamingListLLM(FakeListLLM):
error_on_chunk_number: Optional[int] = None
"""If set, will raise an exception on the specified chunk number."""
+ @override
def stream(
self,
input: LanguageModelInput,
@@ -106,6 +115,7 @@ class FakeStreamingListLLM(FakeListLLM):
raise FakeListLLMError
yield c
+ @override
async def astream(
self,
input: LanguageModelInput,
diff --git a/libs/core/langchain_core/language_models/fake_chat_models.py b/libs/core/langchain_core/language_models/fake_chat_models.py
index 5a6a659046..acce241835 100644
--- a/libs/core/langchain_core/language_models/fake_chat_models.py
+++ b/libs/core/langchain_core/language_models/fake_chat_models.py
@@ -6,6 +6,8 @@ import time
from collections.abc import AsyncIterator, Iterator
from typing import Any, Optional, Union, cast
+from typing_extensions import override
+
from langchain_core.callbacks import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
@@ -26,6 +28,7 @@ class FakeMessagesListChatModel(BaseChatModel):
i: int = 0
"""Internally incremented after every model invocation."""
+ @override
def _generate(
self,
messages: list[BaseMessage],
@@ -42,12 +45,13 @@ class FakeMessagesListChatModel(BaseChatModel):
return ChatResult(generations=[generation])
@property
+ @override
def _llm_type(self) -> str:
return "fake-messages-list-chat-model"
class FakeListChatModelError(Exception):
- pass
+ """Fake error for testing purposes."""
class FakeListChatModel(SimpleChatModel):
@@ -62,9 +66,11 @@ class FakeListChatModel(SimpleChatModel):
"""Internally incremented after every model invocation."""
@property
+ @override
def _llm_type(self) -> str:
return "fake-list-chat-model"
+ @override
def _call(
self,
messages: list[BaseMessage],
@@ -80,6 +86,7 @@ class FakeListChatModel(SimpleChatModel):
self.i = 0
return response
+ @override
def _stream(
self,
messages: list[BaseMessage],
@@ -103,6 +110,7 @@ class FakeListChatModel(SimpleChatModel):
yield ChatGenerationChunk(message=AIMessageChunk(content=c))
+ @override
async def _astream(
self,
messages: list[BaseMessage],
@@ -126,9 +134,11 @@ class FakeListChatModel(SimpleChatModel):
yield ChatGenerationChunk(message=AIMessageChunk(content=c))
@property
+ @override
def _identifying_params(self) -> dict[str, Any]:
return {"responses": self.responses}
+ @override
# manually override batch to preserve batch ordering with no concurrency
def batch(
self,
@@ -142,6 +152,7 @@ class FakeListChatModel(SimpleChatModel):
return [self.invoke(m, c, **kwargs) for m, c in zip(inputs, config)]
return [self.invoke(m, config, **kwargs) for m in inputs]
+ @override
async def abatch(
self,
inputs: list[Any],
diff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.py
index 5049842fd4..e15d17e831 100644
--- a/libs/core/langchain_core/language_models/llms.py
+++ b/libs/core/langchain_core/language_models/llms.py
@@ -80,8 +80,7 @@ def create_base_retry_decorator(
Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
] = None,
) -> Callable[[Any], Any]:
- """Create a retry decorator for a given LLM and provided
- a list of error types.
+ """Create a retry decorator for a given LLM and provided a list of error types.
Args:
error_types: List of error types to retry on.
@@ -377,6 +376,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return ls_params
+ @override
def invoke(
self,
input: LanguageModelInput,
@@ -401,6 +401,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
.text
)
+ @override
async def ainvoke(
self,
input: LanguageModelInput,
@@ -422,6 +423,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
)
return llm_result.generations[0][0].text
+ @override
def batch(
self,
inputs: list[LanguageModelInput],
@@ -469,6 +471,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
)
]
+ @override
async def abatch(
self,
inputs: list[LanguageModelInput],
@@ -515,6 +518,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
)
]
+ @override
def stream(
self,
input: LanguageModelInput,
@@ -581,6 +585,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+ @override
async def astream(
self,
input: LanguageModelInput,
@@ -752,6 +757,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
break
yield item # type: ignore[misc]
+ @override
def generate_prompt(
self,
prompts: list[PromptValue],
@@ -762,6 +768,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
prompt_strings = [p.to_string() for p in prompts]
return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs)
+ @override
async def agenerate_prompt(
self,
prompts: list[PromptValue],
@@ -1336,6 +1343,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return result.generations[0][0].text
@deprecated("0.1.7", alternative="invoke", removal="1.0")
+ @override
def predict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@@ -1343,6 +1351,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return self(text, stop=_stop, **kwargs)
@deprecated("0.1.7", alternative="invoke", removal="1.0")
+ @override
def predict_messages(
self,
messages: list[BaseMessage],
@@ -1356,6 +1365,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return AIMessage(content=content)
@deprecated("0.1.7", alternative="ainvoke", removal="1.0")
+ @override
async def apredict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@@ -1363,6 +1373,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return await self._call_async(text, stop=_stop, **kwargs)
@deprecated("0.1.7", alternative="ainvoke", removal="1.0")
+ @override
async def apredict_messages(
self,
messages: list[BaseMessage],
diff --git a/libs/core/langchain_core/load/dump.py b/libs/core/langchain_core/load/dump.py
index 7d878b7fd4..252ccc8110 100644
--- a/libs/core/langchain_core/load/dump.py
+++ b/libs/core/langchain_core/load/dump.py
@@ -1,3 +1,5 @@
+"""Dump objects to json."""
+
import json
from typing import Any
@@ -7,8 +9,7 @@ from langchain_core.load.serializable import Serializable, to_json_not_implement
def default(obj: Any) -> Any:
- """Return a default value for a Serializable object or
- a SerializedNotImplemented object.
+ """Return a default value for an object.
Args:
obj: The object to serialize to json if it is a Serializable object.
diff --git a/libs/core/langchain_core/load/load.py b/libs/core/langchain_core/load/load.py
index 6ceb2d3d7c..a5c37afd25 100644
--- a/libs/core/langchain_core/load/load.py
+++ b/libs/core/langchain_core/load/load.py
@@ -1,3 +1,5 @@
+"""Load LangChain objects from JSON strings or objects."""
+
import importlib
import json
import os
@@ -87,6 +89,7 @@ class Reviver:
)
def __call__(self, value: dict[str, Any]) -> Any:
+ """Revive the value."""
if (
value.get("lc") == 1
and value.get("type") == "secret"
@@ -169,6 +172,7 @@ def loads(
additional_import_mappings: Optional[dict[tuple[str, ...], tuple[str, ...]]] = None,
) -> Any:
"""Revive a LangChain class from a JSON string.
+
Equivalent to `load(json.loads(text))`.
Args:
@@ -204,8 +208,10 @@ def load(
secrets_from_env: bool = True,
additional_import_mappings: Optional[dict[tuple[str, ...], tuple[str, ...]]] = None,
) -> Any:
- """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`.
+ """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`.
Args:
obj: The object to load.
diff --git a/libs/core/langchain_core/load/mapping.py b/libs/core/langchain_core/load/mapping.py
index eb7f2553c1..b4201c18b3 100644
--- a/libs/core/langchain_core/load/mapping.py
+++ b/libs/core/langchain_core/load/mapping.py
@@ -1,4 +1,6 @@
-"""This file contains a mapping between the lc_namespace path for a given
+"""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.
diff --git a/libs/core/langchain_core/load/serializable.py b/libs/core/langchain_core/load/serializable.py
index c551e630bc..a9a031823e 100644
--- a/libs/core/langchain_core/load/serializable.py
+++ b/libs/core/langchain_core/load/serializable.py
@@ -1,3 +1,5 @@
+"""Serializable base class."""
+
import contextlib
from abc import ABC
from typing import (
@@ -11,7 +13,7 @@ from typing import (
from pydantic import BaseModel, ConfigDict
from pydantic.fields import FieldInfo
-from typing_extensions import NotRequired
+from typing_extensions import NotRequired, override
class BaseSerialized(TypedDict):
@@ -121,7 +123,7 @@ class Serializable(BaseModel, ABC):
# Remove default BaseModel init docstring.
def __init__(self, *args: Any, **kwargs: Any) -> None:
- """"""
+ """""" # noqa: D419
super().__init__(*args, **kwargs)
@classmethod
@@ -187,6 +189,7 @@ class Serializable(BaseModel, ABC):
extra="ignore",
)
+ @override
def __repr_args__(self) -> Any:
return [
(k, v)
@@ -270,6 +273,7 @@ class Serializable(BaseModel, ABC):
}
def to_json_not_implemented(self) -> SerializedNotImplemented:
+ """Serialize a "not implemented" object."""
return to_json_not_implemented(self)
diff --git a/libs/core/langchain_core/messages/ai.py b/libs/core/langchain_core/messages/ai.py
index 38ff432afd..46c838ab48 100644
--- a/libs/core/langchain_core/messages/ai.py
+++ b/libs/core/langchain_core/messages/ai.py
@@ -1,9 +1,11 @@
+"""AI message."""
+
import json
import operator
from typing import Any, Literal, Optional, Union, cast
from pydantic import model_validator
-from typing_extensions import NotRequired, Self, TypedDict
+from typing_extensions import NotRequired, Self, TypedDict, override
from langchain_core.messages.base import (
BaseMessage,
@@ -178,16 +180,6 @@ class AIMessage(BaseMessage):
"""
super().__init__(content=content, **kwargs)
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
-
- Returns:
- The namespace of the langchain object.
- Defaults to ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
@property
def lc_attributes(self) -> dict:
"""Attrs to be serialized even if they are derived from other init args."""
@@ -306,16 +298,6 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
tool_call_chunks: list[ToolCallChunk] = []
"""If provided, tool call chunks associated with the message."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
-
- Returns:
- The namespace of the langchain object.
- Defaults to ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
@property
def lc_attributes(self) -> dict:
"""Attrs to be serialized even if they are derived from other init args."""
@@ -393,6 +375,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
self.invalid_tool_calls = invalid_tool_calls
return self
+ @override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
if isinstance(other, AIMessageChunk):
return add_ai_message_chunks(self, other)
diff --git a/libs/core/langchain_core/messages/base.py b/libs/core/langchain_core/messages/base.py
index 423687426d..ccdef4ba7e 100644
--- a/libs/core/langchain_core/messages/base.py
+++ b/libs/core/langchain_core/messages/base.py
@@ -1,3 +1,5 @@
+"""Base message."""
+
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Union, cast
@@ -60,6 +62,7 @@ class BaseMessage(Serializable):
@field_validator("id", mode="before")
def cast_id_to_str(cls, id_value: Any) -> Optional[str]:
+ """Coerce the id field to a string."""
if id_value is not None:
return str(id_value)
else:
@@ -72,23 +75,22 @@ class BaseMessage(Serializable):
Args:
content: The string contents of the message.
- kwargs: Additional fields to pass to the
"""
super().__init__(content=content, **kwargs)
@classmethod
def is_lc_serializable(cls) -> bool:
- """Return whether this class is serializable. This is used to determine
- whether the class should be included in the langchain schema.
+ """BaseMessage is serializable.
Returns:
- True if the class is serializable, False otherwise.
+ True
"""
return True
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
+
Default is ["langchain", "schema", "messages"].
"""
return ["langchain", "schema", "messages"]
@@ -138,6 +140,7 @@ class BaseMessage(Serializable):
return f"{title}\n\n{self.content}"
def pretty_print(self) -> None:
+ """Print a pretty representation of the message."""
print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
@@ -185,13 +188,6 @@ def merge_content(
class BaseMessageChunk(BaseMessage):
"""Message chunk, which can be concatenated with other Message chunks."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
"""Message chunks support concatenation with other message chunks.
diff --git a/libs/core/langchain_core/messages/chat.py b/libs/core/langchain_core/messages/chat.py
index 73aafd8834..b69f9f1114 100644
--- a/libs/core/langchain_core/messages/chat.py
+++ b/libs/core/langchain_core/messages/chat.py
@@ -1,5 +1,9 @@
+"""Chat Message."""
+
from typing import Any, Literal
+from typing_extensions import override
+
from langchain_core.messages.base import (
BaseMessage,
BaseMessageChunk,
@@ -17,13 +21,6 @@ class ChatMessage(BaseMessage):
type: Literal["chat"] = "chat"
"""The type of the message (used during serialization). Defaults to "chat"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
ChatMessage.model_rebuild()
@@ -38,13 +35,7 @@ class ChatMessageChunk(ChatMessage, BaseMessageChunk):
"""The type of the message (used during serialization).
Defaults to "ChatMessageChunk"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
+ @override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
if isinstance(other, ChatMessageChunk):
if self.role != other.role:
diff --git a/libs/core/langchain_core/messages/function.py b/libs/core/langchain_core/messages/function.py
index 2cc346de81..c08555dfdd 100644
--- a/libs/core/langchain_core/messages/function.py
+++ b/libs/core/langchain_core/messages/function.py
@@ -1,5 +1,9 @@
+"""Function Message."""
+
from typing import Any, Literal
+from typing_extensions import override
+
from langchain_core.messages.base import (
BaseMessage,
BaseMessageChunk,
@@ -25,13 +29,6 @@ class FunctionMessage(BaseMessage):
type: Literal["function"] = "function"
"""The type of the message (used for serialization). Defaults to "function"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
FunctionMessage.model_rebuild()
@@ -46,13 +43,7 @@ class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
"""The type of the message (used for serialization).
Defaults to "FunctionMessageChunk"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
+ @override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
if isinstance(other, FunctionMessageChunk):
if self.name != other.name:
diff --git a/libs/core/langchain_core/messages/human.py b/libs/core/langchain_core/messages/human.py
index 825e62af4b..5baa3a3885 100644
--- a/libs/core/langchain_core/messages/human.py
+++ b/libs/core/langchain_core/messages/human.py
@@ -1,3 +1,5 @@
+"""Human message."""
+
from typing import Any, Literal, Union
from langchain_core.messages.base import BaseMessage, BaseMessageChunk
@@ -38,13 +40,6 @@ class HumanMessage(BaseMessage):
type: Literal["human"] = "human"
"""The type of the message (used for serialization). Defaults to "human"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
def __init__(
self, content: Union[str, list[Union[str, dict]]], **kwargs: Any
) -> None:
@@ -69,10 +64,3 @@ class HumanMessageChunk(HumanMessage, BaseMessageChunk):
type: Literal["HumanMessageChunk"] = "HumanMessageChunk" # type: ignore[assignment]
"""The type of the message (used for serialization).
Defaults to "HumanMessageChunk"."""
-
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
diff --git a/libs/core/langchain_core/messages/modifier.py b/libs/core/langchain_core/messages/modifier.py
index 89d33332e6..59a76d2fe2 100644
--- a/libs/core/langchain_core/messages/modifier.py
+++ b/libs/core/langchain_core/messages/modifier.py
@@ -1,3 +1,5 @@
+"""Message responsible for deleting other messages."""
+
from typing import Any, Literal
from langchain_core.messages.base import BaseMessage
@@ -25,12 +27,5 @@ class RemoveMessage(BaseMessage):
return super().__init__("", id=id, **kwargs)
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
RemoveMessage.model_rebuild()
diff --git a/libs/core/langchain_core/messages/system.py b/libs/core/langchain_core/messages/system.py
index bb04d1a93b..f29f2c85b1 100644
--- a/libs/core/langchain_core/messages/system.py
+++ b/libs/core/langchain_core/messages/system.py
@@ -1,3 +1,5 @@
+"""System message."""
+
from typing import Any, Literal, Union
from langchain_core.messages.base import BaseMessage, BaseMessageChunk
@@ -32,13 +34,6 @@ class SystemMessage(BaseMessage):
type: Literal["system"] = "system"
"""The type of the message (used for serialization). Defaults to "system"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
def __init__(
self, content: Union[str, list[Union[str, dict]]], **kwargs: Any
) -> None:
@@ -63,10 +58,3 @@ class SystemMessageChunk(SystemMessage, BaseMessageChunk):
type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment]
"""The type of the message (used for serialization).
Defaults to "SystemMessageChunk"."""
-
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
diff --git a/libs/core/langchain_core/messages/tool.py b/libs/core/langchain_core/messages/tool.py
index 5c14ae045a..4f6e156edb 100644
--- a/libs/core/langchain_core/messages/tool.py
+++ b/libs/core/langchain_core/messages/tool.py
@@ -1,9 +1,11 @@
+"""Messages for tools."""
+
import json
from typing import Any, Literal, Optional, Union
from uuid import UUID
from pydantic import Field, model_validator
-from typing_extensions import NotRequired, TypedDict
+from typing_extensions import NotRequired, TypedDict, override
from langchain_core.messages.base import BaseMessage, BaseMessageChunk, merge_content
from langchain_core.utils._merge import merge_dicts, merge_obj
@@ -86,16 +88,14 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
response_metadata: dict = Field(default_factory=dict, repr=False)
"""Currently inherited from BaseMessage, but not used."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- Default is ["langchain", "schema", "messages"].
- """
- return ["langchain", "schema", "messages"]
-
@model_validator(mode="before")
@classmethod
def coerce_args(cls, values: dict) -> dict:
+ """Coerce the model arguments to the correct types.
+
+ Args:
+ values: The model arguments.
+ """
content = values["content"]
if isinstance(content, tuple):
content = list(content)
@@ -137,6 +137,12 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
def __init__(
self, content: Union[str, list[Union[str, dict]]], **kwargs: Any
) -> None:
+ """Create a ToolMessage.
+
+ Args:
+ content: The string contents of the message.
+ **kwargs: Additional fields.
+ """
super().__init__(content=content, **kwargs)
@@ -151,11 +157,7 @@ class ToolMessageChunk(ToolMessage, BaseMessageChunk):
# non-chunk variant.
type: Literal["ToolMessageChunk"] = "ToolMessageChunk" # type: ignore[assignment]
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "messages"]
-
+ @override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
if isinstance(other, ToolMessageChunk):
if self.tool_call_id != other.tool_call_id:
@@ -210,6 +212,13 @@ class ToolCall(TypedDict):
def tool_call(*, name: str, args: dict[str, Any], id: Optional[str]) -> ToolCall:
+ """Create a tool call.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call.
+ id: An identifier associated with the tool call.
+ """
return ToolCall(name=name, args=args, id=id, type="tool_call")
@@ -251,6 +260,14 @@ def tool_call_chunk(
id: Optional[str] = None,
index: Optional[int] = None,
) -> ToolCallChunk:
+ """Create a tool call chunk.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call.
+ id: An identifier associated with the tool call.
+ index: The index of the tool call in a sequence.
+ """
return ToolCallChunk(
name=name, args=args, id=id, index=index, type="tool_call_chunk"
)
@@ -281,6 +298,14 @@ def invalid_tool_call(
id: Optional[str] = None,
error: Optional[str] = None,
) -> InvalidToolCall:
+ """Create an invalid tool call.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call.
+ id: An identifier associated with the tool call.
+ error: An error message associated with the tool call.
+ """
return InvalidToolCall(
name=name, args=args, id=id, error=error, type="invalid_tool_call"
)
diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py
index ce645f0ee6..5f3ea3c233 100644
--- a/libs/core/langchain_core/messages/utils.py
+++ b/libs/core/langchain_core/messages/utils.py
@@ -83,7 +83,7 @@ AnyMessage = Annotated[
def get_buffer_string(
messages: Sequence[BaseMessage], human_prefix: str = "Human", ai_prefix: str = "AI"
) -> str:
- """Convert a sequence of Messages to strings and concatenate them into one string.
+ r"""Convert a sequence of Messages to strings and concatenate them into one string.
Args:
messages: Messages to be converted to strings.
@@ -532,7 +532,7 @@ def merge_message_runs(
*,
chunk_separator: str = "\n",
) -> list[BaseMessage]:
- """Merge consecutive Messages of the same type.
+ r"""Merge consecutive Messages of the same type.
**NOTE**: ToolMessages are not merged, as each has a distinct tool call id that
can't be merged.
@@ -682,7 +682,7 @@ def trim_messages(
BaseLanguageModel.get_num_tokens_from_messages() will be used.
Set to `len` to count the number of **messages** in the chat history.
- Note:
+ .. note::
Use `count_tokens_approximately` to get fast, approximate token counts.
This is recommended for using `trim_messages` on the hot path, where
exact token counting is not necessary.
diff --git a/libs/core/langchain_core/output_parsers/base.py b/libs/core/langchain_core/output_parsers/base.py
index 9d080cef30..8f42edd6e0 100644
--- a/libs/core/langchain_core/output_parsers/base.py
+++ b/libs/core/langchain_core/output_parsers/base.py
@@ -1,3 +1,5 @@
+"""Base parser for language model outputs."""
+
from __future__ import annotations
import contextlib
@@ -79,6 +81,7 @@ class BaseGenerationOutputParser(
# it is good enough for pydantic to build the schema from
return T # type: ignore[misc]
+ @override
def invoke(
self,
input: Union[str, BaseMessage],
@@ -102,6 +105,7 @@ class BaseGenerationOutputParser(
run_type="parser",
)
+ @override
async def ainvoke(
self,
input: Union[str, BaseMessage],
@@ -183,6 +187,7 @@ class BaseOutputParser(
)
raise TypeError(msg)
+ @override
def invoke(
self,
input: Union[str, BaseMessage],
@@ -206,6 +211,7 @@ class BaseOutputParser(
run_type="parser",
)
+ @override
async def ainvoke(
self,
input: Union[str, BaseMessage],
diff --git a/libs/core/langchain_core/output_parsers/json.py b/libs/core/langchain_core/output_parsers/json.py
index 642387e7a1..ded392033b 100644
--- a/libs/core/langchain_core/output_parsers/json.py
+++ b/libs/core/langchain_core/output_parsers/json.py
@@ -1,3 +1,5 @@
+"""Parser for JSON output."""
+
from __future__ import annotations
import json
diff --git a/libs/core/langchain_core/output_parsers/list.py b/libs/core/langchain_core/output_parsers/list.py
index 8461d08f7e..c06b157b32 100644
--- a/libs/core/langchain_core/output_parsers/list.py
+++ b/libs/core/langchain_core/output_parsers/list.py
@@ -1,3 +1,5 @@
+"""Parsers for list output."""
+
from __future__ import annotations
import csv
@@ -8,6 +10,8 @@ from io import StringIO
from typing import TYPE_CHECKING, TypeVar, Union
from typing import Optional as Optional
+from typing_extensions import override
+
from langchain_core.messages import BaseMessage
from langchain_core.output_parsers.transform import BaseTransformOutputParser
@@ -190,6 +194,7 @@ class NumberedListOutputParser(ListOutputParser):
pattern: str = r"\d+\.\s([^\n]+)"
"""The pattern to match a numbered list item."""
+ @override
def get_format_instructions(self) -> str:
return (
"Your response should be a numbered list with each item on a new line. "
diff --git a/libs/core/langchain_core/output_parsers/openai_functions.py b/libs/core/langchain_core/output_parsers/openai_functions.py
index 118090bc69..07be88f222 100644
--- a/libs/core/langchain_core/output_parsers/openai_functions.py
+++ b/libs/core/langchain_core/output_parsers/openai_functions.py
@@ -1,3 +1,5 @@
+"""Parsers for OpenAI functions output."""
+
import copy
import json
from types import GenericAlias
diff --git a/libs/core/langchain_core/output_parsers/openai_tools.py b/libs/core/langchain_core/output_parsers/openai_tools.py
index da1d8609fe..618197469c 100644
--- a/libs/core/langchain_core/output_parsers/openai_tools.py
+++ b/libs/core/langchain_core/output_parsers/openai_tools.py
@@ -1,3 +1,5 @@
+"""Parse tools for OpenAI tools output."""
+
import copy
import json
from json import JSONDecodeError
diff --git a/libs/core/langchain_core/output_parsers/pydantic.py b/libs/core/langchain_core/output_parsers/pydantic.py
index a23bdc24aa..ff8695070f 100644
--- a/libs/core/langchain_core/output_parsers/pydantic.py
+++ b/libs/core/langchain_core/output_parsers/pydantic.py
@@ -1,3 +1,5 @@
+"""Output parsers using Pydantic."""
+
import json
from typing import Annotated, Generic, Optional
diff --git a/libs/core/langchain_core/output_parsers/string.py b/libs/core/langchain_core/output_parsers/string.py
index 1d594dfb91..5485e4a45b 100644
--- a/libs/core/langchain_core/output_parsers/string.py
+++ b/libs/core/langchain_core/output_parsers/string.py
@@ -1,3 +1,5 @@
+"""String output parser."""
+
from typing import Optional as Optional
from langchain_core.output_parsers.transform import BaseTransformOutputParser
@@ -8,12 +10,19 @@ class StrOutputParser(BaseTransformOutputParser[str]):
@classmethod
def is_lc_serializable(cls) -> bool:
- """Return whether this class is serializable."""
+ """StrOutputParser is serializable.
+
+ Returns:
+ True
+ """
return True
@classmethod
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
+ """Get the namespace of the langchain object.
+
+ Default is ["langchain", "schema", "output_parser"].
+ """
return ["langchain", "schema", "output_parser"]
@property
diff --git a/libs/core/langchain_core/output_parsers/transform.py b/libs/core/langchain_core/output_parsers/transform.py
index d484b6d06c..253556df54 100644
--- a/libs/core/langchain_core/output_parsers/transform.py
+++ b/libs/core/langchain_core/output_parsers/transform.py
@@ -1,3 +1,5 @@
+"""Base classes for output parsers that can handle streaming input."""
+
from __future__ import annotations
from typing import (
@@ -97,8 +99,9 @@ class BaseCumulativeTransformOutputParser(BaseTransformOutputParser[T]):
"""
def _diff(self, prev: Optional[T], next: T) -> T:
- """Convert parsed outputs into a diff format. The semantics of this are
- up to the output parser.
+ """Convert parsed outputs into a diff format.
+
+ The semantics of this are up to the output parser.
Args:
prev: The previous parsed output.
diff --git a/libs/core/langchain_core/output_parsers/xml.py b/libs/core/langchain_core/output_parsers/xml.py
index 4fef349c49..085fdcf727 100644
--- a/libs/core/langchain_core/output_parsers/xml.py
+++ b/libs/core/langchain_core/output_parsers/xml.py
@@ -1,3 +1,5 @@
+"""Output parser for XML format."""
+
import contextlib
import re
import xml
diff --git a/libs/core/langchain_core/outputs/__init__.py b/libs/core/langchain_core/outputs/__init__.py
index db075994c7..f7b737eb1a 100644
--- a/libs/core/langchain_core/outputs/__init__.py
+++ b/libs/core/langchain_core/outputs/__init__.py
@@ -1,4 +1,6 @@
-"""**Output** classes are used to represent the output of a language model call
+"""Output classes.
+
+**Output** classes are used to represent the output of a language model call
and the output of a chat.
The top container for information is the `LLMResult` object. `LLMResult` is used by
diff --git a/libs/core/langchain_core/outputs/chat_generation.py b/libs/core/langchain_core/outputs/chat_generation.py
index 9eac7514d4..ef3eab3e08 100644
--- a/libs/core/langchain_core/outputs/chat_generation.py
+++ b/libs/core/langchain_core/outputs/chat_generation.py
@@ -1,3 +1,5 @@
+"""Chat generation output classes."""
+
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, Union
@@ -71,15 +73,11 @@ class ChatGeneration(Generation):
raise ValueError(msg) from e
return self
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "output"]
-
class ChatGenerationChunk(ChatGeneration):
- """ChatGeneration chunk, which can be concatenated with other
- ChatGeneration chunks.
+ """ChatGeneration chunk.
+
+ ChatGeneration chunks can be concatenated with other ChatGeneration chunks.
"""
message: BaseMessageChunk
@@ -88,14 +86,15 @@ class ChatGenerationChunk(ChatGeneration):
type: Literal["ChatGenerationChunk"] = "ChatGenerationChunk" # type: ignore[assignment]
"""Type is used exclusively for serialization purposes."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "output"]
-
def __add__(
self, other: Union[ChatGenerationChunk, list[ChatGenerationChunk]]
) -> ChatGenerationChunk:
+ """Concatenate two ChatGenerationChunks.
+
+ Args:
+ other: The other ChatGenerationChunk or list of ChatGenerationChunks to
+ concatenate.
+ """
if isinstance(other, ChatGenerationChunk):
generation_info = merge_dicts(
self.generation_info or {},
diff --git a/libs/core/langchain_core/outputs/chat_result.py b/libs/core/langchain_core/outputs/chat_result.py
index 3098736438..3e6a5076c8 100644
--- a/libs/core/langchain_core/outputs/chat_result.py
+++ b/libs/core/langchain_core/outputs/chat_result.py
@@ -1,3 +1,5 @@
+"""Chat result schema."""
+
from typing import Optional
from pydantic import BaseModel
diff --git a/libs/core/langchain_core/outputs/generation.py b/libs/core/langchain_core/outputs/generation.py
index ce2dd36390..2d3523bfb3 100644
--- a/libs/core/langchain_core/outputs/generation.py
+++ b/libs/core/langchain_core/outputs/generation.py
@@ -1,3 +1,5 @@
+"""Generation output schema."""
+
from __future__ import annotations
from typing import Any, Literal, Optional
@@ -41,19 +43,18 @@ class Generation(Serializable):
@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", "output"].
+ """
return ["langchain", "schema", "output"]
class GenerationChunk(Generation):
"""Generation chunk, which can be concatenated with other Generation chunks."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "output"]
-
def __add__(self, other: GenerationChunk) -> GenerationChunk:
+ """Concatenate two GenerationChunks."""
if isinstance(other, GenerationChunk):
generation_info = merge_dicts(
self.generation_info or {},
diff --git a/libs/core/langchain_core/outputs/llm_result.py b/libs/core/langchain_core/outputs/llm_result.py
index c28d630b16..62d7daede4 100644
--- a/libs/core/langchain_core/outputs/llm_result.py
+++ b/libs/core/langchain_core/outputs/llm_result.py
@@ -1,3 +1,5 @@
+"""LLMResult class."""
+
from __future__ import annotations
from copy import deepcopy
diff --git a/libs/core/langchain_core/outputs/run_info.py b/libs/core/langchain_core/outputs/run_info.py
index 4b20c9bd70..c12550977d 100644
--- a/libs/core/langchain_core/outputs/run_info.py
+++ b/libs/core/langchain_core/outputs/run_info.py
@@ -1,3 +1,5 @@
+"""RunInfo class."""
+
from __future__ import annotations
from uuid import UUID
diff --git a/libs/core/langchain_core/prompt_values.py b/libs/core/langchain_core/prompt_values.py
index 220550de8e..7652bd76e3 100644
--- a/libs/core/langchain_core/prompt_values.py
+++ b/libs/core/langchain_core/prompt_values.py
@@ -36,6 +36,7 @@ class PromptValue(Serializable, ABC):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
+
This is used to determine the namespace of the object when serializing.
Defaults to ["langchain", "schema", "prompt"].
"""
@@ -60,6 +61,7 @@ class StringPromptValue(PromptValue):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
+
This is used to determine the namespace of the object when serializing.
Defaults to ["langchain", "prompts", "base"].
"""
@@ -94,6 +96,7 @@ class ChatPromptValue(PromptValue):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
+
This is used to determine the namespace of the object when serializing.
Defaults to ["langchain", "prompts", "chat"].
"""
@@ -129,6 +132,7 @@ class ImagePromptValue(PromptValue):
class ChatPromptValueConcrete(ChatPromptValue):
"""Chat prompt value which explicitly lists out the message types it accepts.
+
For use in external schemas.
"""
@@ -136,11 +140,3 @@ class ChatPromptValueConcrete(ChatPromptValue):
"""Sequence of messages."""
type: Literal["ChatPromptValueConcrete"] = "ChatPromptValueConcrete"
-
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object.
- This is used to determine the namespace of the object when serializing.
- Defaults to ["langchain", "prompts", "chat"].
- """
- return ["langchain", "prompts", "chat"]
diff --git a/libs/core/langchain_core/prompts/base.py b/libs/core/langchain_core/prompts/base.py
index 16f0058d36..cf89f83b5a 100644
--- a/libs/core/langchain_core/prompts/base.py
+++ b/libs/core/langchain_core/prompts/base.py
@@ -1,3 +1,5 @@
+"""Base class for prompt templates."""
+
from __future__ import annotations
import contextlib
@@ -98,6 +100,7 @@ class BasePromptTemplate(
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
+
Returns ["langchain", "schema", "prompt_template"].
"""
return ["langchain", "schema", "prompt_template"]
@@ -105,6 +108,7 @@ class BasePromptTemplate(
@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this class is serializable.
+
Returns True.
"""
return True
@@ -190,6 +194,7 @@ class BasePromptTemplate(
_inner_input = self._validate_input(inner_input)
return await self.aformat_prompt(**_inner_input)
+ @override
def invoke(
self, input: dict, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> PromptValue:
@@ -215,6 +220,7 @@ class BasePromptTemplate(
serialized=self._serialized,
)
+ @override
async def ainvoke(
self, input: dict, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> PromptValue:
diff --git a/libs/core/langchain_core/prompts/chat.py b/libs/core/langchain_core/prompts/chat.py
index a7ef3d36c2..454e9e9eb5 100644
--- a/libs/core/langchain_core/prompts/chat.py
+++ b/libs/core/langchain_core/prompts/chat.py
@@ -22,6 +22,7 @@ from pydantic import (
SkipValidation,
model_validator,
)
+from typing_extensions import override
from langchain_core._api import deprecated
from langchain_core.load import Serializable
@@ -57,13 +58,17 @@ class BaseMessagePromptTemplate(Serializable, ABC):
@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether or not the class is serializable.
+
Returns: True.
"""
return True
@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", "prompts", "chat"].
+ """
return ["langchain", "prompts", "chat"]
@abstractmethod
@@ -79,7 +84,6 @@ class BaseMessagePromptTemplate(Serializable, ABC):
async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
"""Async format messages from kwargs.
- Should return a list of BaseMessages.
Args:
**kwargs: Keyword arguments to use for formatting.
@@ -211,14 +215,18 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
"""Maximum number of messages to include. If None, then will include all.
Defaults to None."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "prompts", "chat"]
-
def __init__(
self, variable_name: str, *, optional: bool = False, **kwargs: Any
) -> None:
+ """Create a messages placeholder.
+
+ Args:
+ variable_name: Name of variable to use as messages.
+ optional: If True format_messages can be called with no arguments and will
+ return an empty list. If False then a named argument with name
+ `variable_name` must be passed in, even if the value is an empty list.
+ Defaults to False.]
+ """
# mypy can't detect the init which is defined in the parent class
# b/c these are BaseModel classes.
super().__init__( # type: ignore
@@ -294,11 +302,6 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
additional_kwargs: dict = Field(default_factory=dict)
"""Additional keyword arguments to pass to the prompt template."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "prompts", "chat"]
-
@classmethod
def from_template(
cls: type[MessagePromptTemplateT],
@@ -424,11 +427,6 @@ class ChatMessagePromptTemplate(BaseStringMessagePromptTemplate):
role: str
"""Role of the message."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "prompts", "chat"]
-
def format(self, **kwargs: Any) -> BaseMessage:
"""Format the prompt template.
@@ -483,11 +481,6 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
_msg_class: type[BaseMessage]
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "prompts", "chat"]
-
@classmethod
def from_template(
cls: type[_StringImageMessagePromptTemplateT],
@@ -719,34 +712,22 @@ class AIMessagePromptTemplate(_StringImageMessagePromptTemplate):
_msg_class: type[BaseMessage] = AIMessage
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "prompts", "chat"]
-
class SystemMessagePromptTemplate(_StringImageMessagePromptTemplate):
"""System message prompt template.
+
This is a message that is not sent to the user.
"""
_msg_class: type[BaseMessage] = SystemMessage
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "prompts", "chat"]
-
class BaseChatPromptTemplate(BasePromptTemplate, ABC):
"""Base class for chat prompt templates."""
@property
+ @override
def lc_attributes(self) -> dict:
- """Return a list of attribute names that should be included in the
- serialized kwargs. These attributes must be accepted by the
- constructor.
- """
return {"input_variables": self.input_variables}
def format(self, **kwargs: Any) -> str:
@@ -968,8 +949,9 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
input_variables: A list of the names of the variables whose values are
required as inputs to the prompt.
optional_variables: A list of the names of the variables for placeholder
- or MessagePlaceholder that are optional. These variables are auto inferred
- from the prompt and user need not provide them.
+ or MessagePlaceholder that are optional.
+ These variables are auto inferred from the prompt and user need not
+ provide them.
partial_variables: A dictionary of the partial variables the prompt
template carries. Partial variables populate the template so that you
don't need to pass them in every time you call the prompt.
diff --git a/libs/core/langchain_core/prompts/image.py b/libs/core/langchain_core/prompts/image.py
index 334e2b85ae..7c2fc4feef 100644
--- a/libs/core/langchain_core/prompts/image.py
+++ b/libs/core/langchain_core/prompts/image.py
@@ -1,3 +1,5 @@
+"""Image prompt template for a multimodal model."""
+
from typing import Any
from pydantic import Field
@@ -21,6 +23,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
Options are: 'f-string', 'mustache', 'jinja2'."""
def __init__(self, **kwargs: Any) -> None:
+ """Create an image prompt template."""
if "input_variables" not in kwargs:
kwargs["input_variables"] = []
diff --git a/libs/core/langchain_core/prompts/pipeline.py b/libs/core/langchain_core/prompts/pipeline.py
index 6124acb405..82ab7cb6c9 100644
--- a/libs/core/langchain_core/prompts/pipeline.py
+++ b/libs/core/langchain_core/prompts/pipeline.py
@@ -1,3 +1,5 @@
+"""[DEPRECATED] Pipeline prompt template."""
+
from typing import Any
from typing import Optional as Optional
@@ -23,7 +25,9 @@ def _get_inputs(inputs: dict, input_variables: list[str]) -> dict:
),
)
class PipelinePromptTemplate(BasePromptTemplate):
- """This has been deprecated in favor of chaining individual prompts together in your
+ """[DEPRECATED] Pipeline prompt template.
+
+ This has been deprecated in favor of chaining individual prompts together in your
code. E.g. using a for loop, you could do:
.. code-block:: python
diff --git a/libs/core/langchain_core/prompts/prompt.py b/libs/core/langchain_core/prompts/prompt.py
index 1aded63ad7..c60d77fb6d 100644
--- a/libs/core/langchain_core/prompts/prompt.py
+++ b/libs/core/langchain_core/prompts/prompt.py
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional, Union
from pydantic import BaseModel, model_validator
+from typing_extensions import override
from langchain_core.prompts.string import (
DEFAULT_FORMATTER_MAPPING,
@@ -58,14 +59,15 @@ class PromptTemplate(StringPromptTemplate):
"""
@property
+ @override
def lc_attributes(self) -> dict[str, Any]:
return {
"template_format": self.template_format,
}
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "prompts", "prompt"]
template: str
@@ -116,6 +118,7 @@ class PromptTemplate(StringPromptTemplate):
return values
+ @override
def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
"""Get the input schema for the prompt.
diff --git a/libs/core/langchain_core/prompts/string.py b/libs/core/langchain_core/prompts/string.py
index 61fc1d35d4..3259cccccd 100644
--- a/libs/core/langchain_core/prompts/string.py
+++ b/libs/core/langchain_core/prompts/string.py
@@ -65,6 +65,7 @@ def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
def validate_jinja2(template: str, input_variables: list[str]) -> None:
"""Validate that the input variables are valid for the template.
+
Issues a warning if missing or extra variables are found.
Args:
diff --git a/libs/core/langchain_core/prompts/structured.py b/libs/core/langchain_core/prompts/structured.py
index 1f38695760..4dc72b861a 100644
--- a/libs/core/langchain_core/prompts/structured.py
+++ b/libs/core/langchain_core/prompts/structured.py
@@ -1,3 +1,5 @@
+"""Structured prompt template for a language model."""
+
from collections.abc import Iterator, Mapping, Sequence
from typing import (
Any,
@@ -7,6 +9,7 @@ from typing import (
)
from pydantic import BaseModel, Field
+from typing_extensions import override
from langchain_core._api.beta_decorator import beta
from langchain_core.language_models.base import BaseLanguageModel
@@ -41,6 +44,14 @@ class StructuredPrompt(ChatPromptTemplate):
template_format: PromptTemplateFormat = "f-string",
**kwargs: Any,
) -> None:
+ """Create a structured prompt template.
+
+ Args:
+ messages: sequence of messages.
+ schema_: schema for the structured prompt.
+ structured_output_kwargs: additional kwargs for structured output.
+ template_format: template format for the prompt.
+ """
schema_ = schema_ or kwargs.pop("schema")
structured_output_kwargs = structured_output_kwargs or {}
for k in set(kwargs).difference(get_pydantic_field_names(self.__class__)):
@@ -107,6 +118,7 @@ class StructuredPrompt(ChatPromptTemplate):
"""
return cls(messages, schema, **kwargs)
+ @override
def __or__(
self,
other: Union[
diff --git a/libs/core/langchain_core/pydantic_v1/__init__.py b/libs/core/langchain_core/pydantic_v1/__init__.py
index b70686f1f4..5422482eff 100644
--- a/libs/core/langchain_core/pydantic_v1/__init__.py
+++ b/libs/core/langchain_core/pydantic_v1/__init__.py
@@ -1,3 +1,5 @@
+"""Pydantic v1 compatibility shim."""
+
from importlib import metadata
from langchain_core._api.deprecation import warn_deprecated
diff --git a/libs/core/langchain_core/pydantic_v1/dataclasses.py b/libs/core/langchain_core/pydantic_v1/dataclasses.py
index 824da7d6b3..903bd865b9 100644
--- a/libs/core/langchain_core/pydantic_v1/dataclasses.py
+++ b/libs/core/langchain_core/pydantic_v1/dataclasses.py
@@ -1,3 +1,5 @@
+"""Pydantic v1 compatibility shim."""
+
from langchain_core._api import warn_deprecated
try:
diff --git a/libs/core/langchain_core/pydantic_v1/main.py b/libs/core/langchain_core/pydantic_v1/main.py
index 3449832620..51e57df96e 100644
--- a/libs/core/langchain_core/pydantic_v1/main.py
+++ b/libs/core/langchain_core/pydantic_v1/main.py
@@ -1,3 +1,5 @@
+"""Pydantic v1 compatibility shim."""
+
from langchain_core._api import warn_deprecated
try:
diff --git a/libs/core/langchain_core/retrievers.py b/libs/core/langchain_core/retrievers.py
index 47b6b2b616..e8af9d8d7c 100644
--- a/libs/core/langchain_core/retrievers.py
+++ b/libs/core/langchain_core/retrievers.py
@@ -27,7 +27,7 @@ from inspect import signature
from typing import TYPE_CHECKING, Any, Optional
from pydantic import ConfigDict
-from typing_extensions import Self, TypedDict
+from typing_extensions import Self, TypedDict, override
from langchain_core._api import deprecated
from langchain_core.documents import Document
@@ -148,6 +148,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
use case.
"""
+ @override
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
# Version upgrade for old retrievers that implemented the public
diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py
index b713b89a99..700b1fc616 100644
--- a/libs/core/langchain_core/runnables/base.py
+++ b/libs/core/langchain_core/runnables/base.py
@@ -1,3 +1,5 @@
+"""Base classes and utilities for Runnables."""
+
from __future__ import annotations
import asyncio
@@ -686,6 +688,7 @@ class Runnable(Generic[Input, Output], ABC):
],
) -> RunnableSerializable[Any, Any]:
"""Assigns new fields to the dict output of this Runnable.
+
Returns a new Runnable.
.. code-block:: python
@@ -725,7 +728,7 @@ class Runnable(Generic[Input, Output], ABC):
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
- """Transform a single input into an output. Override to implement.
+ """Transform a single input into an output.
Args:
input: The input to the Runnable.
@@ -815,8 +818,9 @@ class Runnable(Generic[Input, Output], ABC):
return_exceptions: bool = False,
**kwargs: Optional[Any],
) -> Iterator[tuple[int, Union[Output, Exception]]]:
- """Run invoke in parallel on a list of inputs,
- yielding results as they complete.
+ """Run invoke in parallel on a list of inputs.
+
+ Yields results as they complete.
"""
if not inputs:
return
@@ -931,8 +935,9 @@ class Runnable(Generic[Input, Output], ABC):
return_exceptions: bool = False,
**kwargs: Optional[Any],
) -> AsyncIterator[tuple[int, Union[Output, Exception]]]:
- """Run ainvoke in parallel on a list of inputs,
- yielding results as they complete.
+ """Run ainvoke in parallel on a list of inputs.
+
+ Yields results as they complete.
Args:
inputs: A list of inputs to the Runnable.
@@ -987,6 +992,7 @@ class Runnable(Generic[Input, Output], ABC):
**kwargs: Optional[Any],
) -> Iterator[Output]:
"""Default implementation of stream, which calls invoke.
+
Subclasses should override this method if they support streaming output.
Args:
@@ -1006,6 +1012,7 @@ class Runnable(Generic[Input, Output], ABC):
**kwargs: Optional[Any],
) -> AsyncIterator[Output]:
"""Default implementation of astream, which calls ainvoke.
+
Subclasses should override this method if they support streaming output.
Args:
@@ -1068,6 +1075,7 @@ class Runnable(Generic[Input, Output], ABC):
**kwargs: Any,
) -> Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]:
"""Stream all output from a Runnable, as reported to the callback system.
+
This includes all inner runs of LLMs, Retrievers, Tools, etc.
Output is streamed as Log objects, which include a list of
@@ -1437,6 +1445,7 @@ class Runnable(Generic[Input, Output], ABC):
**kwargs: Optional[Any],
) -> AsyncIterator[Output]:
"""Default implementation of atransform, which buffers input and calls astream.
+
Subclasses should override this method if they can start producing output while
input is still being generated.
@@ -1800,8 +1809,9 @@ class Runnable(Generic[Input, Output], ABC):
)
def map(self) -> Runnable[list[Input], list[Output]]:
- """Return a new Runnable that maps a list of inputs to a list of outputs,
- by calling invoke() with each input.
+ """Return a new Runnable that maps a list of inputs to a list of outputs.
+
+ Calls invoke() with each input.
Returns:
A new Runnable that maps a list of inputs to a list of outputs.
@@ -1905,8 +1915,9 @@ class Runnable(Generic[Input, Output], ABC):
serialized: Optional[dict[str, Any]] = None,
**kwargs: Optional[Any],
) -> Output:
- """Helper method to transform an Input value to an Output value,
- with callbacks. Use this method to implement invoke() in subclasses.
+ """Helper method to transform an Input value to an Output value, with callbacks.
+
+ Use this method to implement invoke() in subclasses.
"""
config = ensure_config(config)
callback_manager = get_callback_manager_for_config(config)
@@ -1954,8 +1965,9 @@ class Runnable(Generic[Input, Output], ABC):
serialized: Optional[dict[str, Any]] = None,
**kwargs: Optional[Any],
) -> Output:
- """Helper method to transform an Input value to an Output value,
- with callbacks. Use this method to implement ainvoke() in subclasses.
+ """Helper method to transform an Input value to an Output value, with callbacks.
+
+ Use this method to implement ainvoke() in subclasses.
"""
config = ensure_config(config)
callback_manager = get_async_callback_manager_for_config(config)
@@ -2003,7 +2015,9 @@ class Runnable(Generic[Input, Output], ABC):
run_type: Optional[str] = None,
**kwargs: Optional[Any],
) -> list[Output]:
- """Helper method to transform an Input value to an Output value,
+ """Transform a list of inputs to a list of outputs, with callbacks.
+
+ Helper method to transform an Input value to an Output value,
with callbacks. Use this method to implement invoke() in subclasses.
"""
if not input:
@@ -2076,8 +2090,11 @@ class Runnable(Generic[Input, Output], ABC):
run_type: Optional[str] = None,
**kwargs: Optional[Any],
) -> list[Output]:
- """Helper method to transform an Input value to an Output value,
- with callbacks. Use this method to implement invoke() in subclasses.
+ """Transform a list of inputs to a list of outputs, with callbacks.
+
+ Helper method to transform an Input value to an Output value,
+ with callbacks.
+ Use this method to implement invoke() in subclasses.
"""
if not input:
return []
@@ -2149,7 +2166,9 @@ class Runnable(Generic[Input, Output], ABC):
run_type: Optional[str] = None,
**kwargs: Optional[Any],
) -> Iterator[Output]:
- """Helper method to transform an Iterator of Input values into an Iterator of
+ """Transform a stream with config.
+
+ Helper method to transform an Iterator of Input values into an Iterator of
Output values, with callbacks.
Use this to implement `stream()` or `transform()` in Runnable subclasses.
"""
@@ -2251,7 +2270,9 @@ class Runnable(Generic[Input, Output], ABC):
run_type: Optional[str] = None,
**kwargs: Optional[Any],
) -> AsyncIterator[Output]:
- """Helper method to transform an Async Iterator of Input values into an Async
+ """Transform a stream with config.
+
+ Helper method to transform an Async Iterator of Input values into an Async
Iterator of Output values, with callbacks.
Use this to implement `astream()` or `atransform()` in Runnable subclasses.
"""
@@ -2465,6 +2486,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
protected_namespaces=(),
)
+ @override
def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]:
"""Serialize the Runnable to JSON.
@@ -2787,8 +2809,8 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
)
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
@property
@@ -2801,6 +2823,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
return [self.first] + self.middle + [self.last]
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
"""Check if the object is serializable.
@@ -2826,6 +2849,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
"""The type of the output of the Runnable."""
return self.last.OutputType
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -2839,6 +2863,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
"""
return _seq_input_schema(self.steps, config)
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -2853,6 +2878,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
return _seq_output_schema(self.steps, config)
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
"""Get the config specs of the Runnable.
@@ -2903,6 +2929,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
return get_unique_config_specs(spec for spec, _ in all_specs)
+ @override
def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
"""Get the graph representation of the Runnable.
@@ -2934,12 +2961,14 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
return graph
+ @override
def __repr__(self) -> str:
return "\n| ".join(
repr(s) if i == 0 else indent_lines_after_first(repr(s), "| ")
for i, s in enumerate(self.steps)
)
+ @override
def __or__(
self,
other: Union[
@@ -2968,6 +2997,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
name=self.name,
)
+ @override
def __ror__(
self,
other: Union[
@@ -2996,6 +3026,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
name=self.name,
)
+ @override
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -3032,6 +3063,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
run_manager.on_chain_end(input)
return cast("Output", input)
+ @override
async def ainvoke(
self,
input: Input,
@@ -3075,6 +3107,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
await run_manager.on_chain_end(input)
return cast("Output", input)
+ @override
def batch(
self,
inputs: list[Input],
@@ -3202,6 +3235,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
else:
raise first_exception
+ @override
async def abatch(
self,
inputs: list[Input],
@@ -3388,6 +3422,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
async for output in final_pipeline:
yield output
+ @override
def transform(
self,
input: Iterator[Input],
@@ -3401,6 +3436,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
**kwargs,
)
+ @override
def stream(
self,
input: Input,
@@ -3409,6 +3445,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
) -> Iterator[Output]:
yield from self.transform(iter([input]), config, **kwargs)
+ @override
async def atransform(
self,
input: AsyncIterator[Input],
@@ -3423,6 +3460,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
):
yield chunk
+ @override
async def astream(
self,
input: Input,
@@ -3437,8 +3475,9 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
- """Runnable that runs a mapping of Runnables in parallel, and returns a mapping
- of their outputs.
+ """Runnable that runs a mapping of Runnables in parallel.
+
+ Returns a mapping of their outputs.
RunnableParallel is one of the two main composition primitives for the LCEL,
alongside RunnableSequence. It invokes Runnables concurrently, providing the same
@@ -3536,6 +3575,12 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
Mapping[str, Union[Runnable[Input, Any], Callable[[Input], Any]]],
],
) -> None:
+ """Create a RunnableParallel.
+
+ Args:
+ steps__: The steps to include. Defaults to None.
+ **kwargs: Additional steps to include.
+ """
merged = {**steps__} if steps__ is not None else {}
merged.update(kwargs)
super().__init__( # type: ignore[call-arg]
@@ -3543,18 +3588,20 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
)
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
+ @override
def get_name(
self, suffix: Optional[str] = None, *, name: Optional[str] = None
) -> str:
@@ -3580,6 +3627,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
return Any
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -3609,6 +3657,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
return super().get_input_schema(config)
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -3624,6 +3673,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
return create_model_v2(self.get_name("Output"), field_definitions=fields)
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
"""Get the config specs of the Runnable.
@@ -3634,6 +3684,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
spec for step in self.steps__.values() for spec in step.config_specs
)
+ @override
def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
"""Get the graph representation of the Runnable.
@@ -3670,6 +3721,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
return graph
+ @override
def __repr__(self) -> str:
map_for_repr = ",\n ".join(
f"{k}: {indent_lines_after_first(repr(v), ' ' + k + ': ')}"
@@ -3677,6 +3729,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
)
return "{\n " + map_for_repr + "\n}"
+ @override
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> dict[str, Any]:
@@ -3735,6 +3788,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
run_manager.on_chain_end(output)
return output
+ @override
async def ainvoke(
self,
input: Input,
@@ -3839,6 +3893,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
except StopIteration:
pass
+ @override
def transform(
self,
input: Iterator[Input],
@@ -3849,6 +3904,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
input, self._transform, config, **kwargs
)
+ @override
def stream(
self,
input: Input,
@@ -3908,6 +3964,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
except StopAsyncIteration:
pass
+ @override
async def atransform(
self,
input: AsyncIterator[Input],
@@ -3919,6 +3976,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
):
yield chunk
+ @override
async def astream(
self,
input: Input,
@@ -4039,6 +4097,7 @@ class RunnableGenerator(Runnable[Input, Output]):
Args:
transform: The transform function.
atransform: The async transform function. Defaults to None.
+ name: The name of the Runnable. Defaults to None.
Raises:
TypeError: If the transform is not a generator function.
@@ -4079,6 +4138,7 @@ class RunnableGenerator(Runnable[Input, Output]):
except ValueError:
return Any
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -4120,6 +4180,7 @@ class RunnableGenerator(Runnable[Input, Output]):
except ValueError:
return Any
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -4146,6 +4207,7 @@ class RunnableGenerator(Runnable[Input, Output]):
module_name=module,
)
+ @override
def __eq__(self, other: Any) -> bool:
if isinstance(other, RunnableGenerator):
if hasattr(self, "_transform") and hasattr(other, "_transform"):
@@ -4157,9 +4219,11 @@ class RunnableGenerator(Runnable[Input, Output]):
else:
return False
+ @override
def __repr__(self) -> str:
return f"RunnableGenerator({self.name})"
+ @override
def transform(
self,
input: Iterator[Input],
@@ -4176,6 +4240,7 @@ class RunnableGenerator(Runnable[Input, Output]):
**kwargs, # type: ignore[arg-type]
)
+ @override
def stream(
self,
input: Input,
@@ -4184,6 +4249,7 @@ class RunnableGenerator(Runnable[Input, Output]):
) -> Iterator[Output]:
return self.transform(iter([input]), config, **kwargs)
+ @override
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -4192,6 +4258,7 @@ class RunnableGenerator(Runnable[Input, Output]):
final = output if final is None else final + output # type: ignore[operator]
return cast("Output", final)
+ @override
def atransform(
self,
input: AsyncIterator[Input],
@@ -4206,6 +4273,7 @@ class RunnableGenerator(Runnable[Input, Output]):
input, self._atransform, config, **kwargs
)
+ @override
def astream(
self,
input: Input,
@@ -4217,6 +4285,7 @@ class RunnableGenerator(Runnable[Input, Output]):
return self.atransform(input_aiter(), config, **kwargs)
+ @override
async def ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -4371,6 +4440,7 @@ class RunnableLambda(Runnable[Input, Output]):
except ValueError:
return Any
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -4440,6 +4510,7 @@ class RunnableLambda(Runnable[Input, Output]):
except ValueError:
return Any
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -4490,11 +4561,13 @@ class RunnableLambda(Runnable[Input, Output]):
return deps
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return get_unique_config_specs(
spec for dep in self.deps for spec in dep.config_specs
)
+ @override
def get_graph(self, config: RunnableConfig | None = None) -> Graph:
if deps := self.deps:
graph = Graph()
@@ -4521,6 +4594,7 @@ class RunnableLambda(Runnable[Input, Output]):
return graph
+ @override
def __eq__(self, other: Any) -> bool:
if isinstance(other, RunnableLambda):
if hasattr(self, "func") and hasattr(other, "func"):
@@ -4697,6 +4771,7 @@ class RunnableLambda(Runnable[Input, Output]):
) -> RunnableConfig:
return ensure_config(config)
+ @override
def invoke(
self,
input: Input,
@@ -4730,6 +4805,7 @@ class RunnableLambda(Runnable[Input, Output]):
)
raise TypeError(msg)
+ @override
async def ainvoke(
self,
input: Input,
@@ -4816,6 +4892,7 @@ class RunnableLambda(Runnable[Input, Output]):
# Otherwise, just yield it
yield cast("Output", output)
+ @override
def transform(
self,
input: Iterator[Input],
@@ -4836,6 +4913,7 @@ class RunnableLambda(Runnable[Input, Output]):
)
raise TypeError(msg)
+ @override
def stream(
self,
input: Input,
@@ -4943,6 +5021,7 @@ class RunnableLambda(Runnable[Input, Output]):
# Otherwise, just yield it
yield cast("Output", output)
+ @override
async def atransform(
self,
input: AsyncIterator[Input],
@@ -4957,6 +5036,7 @@ class RunnableLambda(Runnable[Input, Output]):
):
yield output
+ @override
async def astream(
self,
input: Input,
@@ -4971,8 +5051,7 @@ class RunnableLambda(Runnable[Input, Output]):
class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
- """Runnable that delegates calls to another Runnable
- with each element of the input sequence.
+ """Runnable that calls another Runnable for each element of the input sequence.
Use only if creating a new RunnableEach subclass with different __init__ args.
@@ -4990,6 +5069,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
def InputType(self) -> Any:
return list[self.bound.InputType] # type: ignore[name-defined]
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -5014,6 +5094,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
def OutputType(self) -> type[list[Output]]:
return list[self.bound.OutputType] # type: ignore[name-defined]
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -5032,19 +5113,22 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
)
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return self.bound.config_specs
+ @override
def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
return self.bound.get_graph(config)
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
def _invoke(
@@ -5059,6 +5143,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
]
return self.bound.batch(inputs, configs, **kwargs)
+ @override
def invoke(
self, input: list[Input], config: Optional[RunnableConfig] = None, **kwargs: Any
) -> list[Output]:
@@ -5076,11 +5161,13 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
]
return await self.bound.abatch(inputs, configs, **kwargs)
+ @override
async def ainvoke(
self, input: list[Input], config: Optional[RunnableConfig] = None, **kwargs: Any
) -> list[Output]:
return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+ @override
async def astream_events(
self,
input: Input,
@@ -5094,8 +5181,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
class RunnableEach(RunnableEachBase[Input, Output]):
- """Runnable that delegates calls to another Runnable
- with each element of the input sequence.
+ """Runnable that calls another Runnable for each element of the input sequence.
It allows you to call multiple inputs with the bounded Runnable.
@@ -5121,25 +5207,24 @@ class RunnableEach(RunnableEachBase[Input, Output]):
print(output) # noqa: T201
"""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "runnable"]
-
+ @override
def get_name(
self, suffix: Optional[str] = None, *, name: Optional[str] = None
) -> str:
name = name or self.name or f"RunnableEach<{self.bound.get_name()}>"
return super().get_name(suffix, name=name)
+ @override
def bind(self, **kwargs: Any) -> RunnableEach[Input, Output]:
return RunnableEach(bound=self.bound.bind(**kwargs))
+ @override
def with_config(
self, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> RunnableEach[Input, Output]:
return RunnableEach(bound=self.bound.with_config(config, **kwargs))
+ @override
def with_listeners(
self,
*,
@@ -5297,6 +5382,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
# fields even though total=False on the typed dict.
self.config = config or {}
+ @override
def get_name(
self, suffix: Optional[str] = None, *, name: Optional[str] = None
) -> str:
@@ -5320,6 +5406,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
else self.bound.OutputType
)
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -5327,6 +5414,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
return super().get_input_schema(config)
return self.bound.get_input_schema(merge_configs(self.config, config))
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -5335,25 +5423,33 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
return self.bound.get_output_schema(merge_configs(self.config, config))
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return self.bound.config_specs
+ @override
def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
return self.bound.get_graph(self._merge_configs(config))
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
+ """Get the namespace of the langchain object.
+
+ Defaults to ["langchain", "schema", "runnable"].
+ """
return ["langchain", "schema", "runnable"]
def _merge_configs(self, *configs: Optional[RunnableConfig]) -> RunnableConfig:
config = merge_configs(self.config, *configs)
return merge_configs(config, *(f(config) for f in self.config_factories))
+ @override
def invoke(
self,
input: Input,
@@ -5366,6 +5462,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**{**self.kwargs, **kwargs},
)
+ @override
async def ainvoke(
self,
input: Input,
@@ -5378,6 +5475,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**{**self.kwargs, **kwargs},
)
+ @override
def batch(
self,
inputs: list[Input],
@@ -5400,6 +5498,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**{**self.kwargs, **kwargs},
)
+ @override
async def abatch(
self,
inputs: list[Input],
@@ -5442,6 +5541,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**kwargs: Any,
) -> Iterator[tuple[int, Union[Output, Exception]]]: ...
+ @override
def batch_as_completed(
self,
inputs: Sequence[Input],
@@ -5493,6 +5593,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**kwargs: Optional[Any],
) -> AsyncIterator[tuple[int, Union[Output, Exception]]]: ...
+ @override
async def abatch_as_completed(
self,
inputs: Sequence[Input],
@@ -5525,6 +5626,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
):
yield item
+ @override
def stream(
self,
input: Input,
@@ -5537,6 +5639,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**{**self.kwargs, **kwargs},
)
+ @override
async def astream(
self,
input: Input,
@@ -5550,6 +5653,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
):
yield item
+ @override
async def astream_events(
self,
input: Input,
@@ -5561,6 +5665,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
):
yield item
+ @override
def transform(
self,
input: Iterator[Input],
@@ -5573,6 +5678,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
**{**self.kwargs, **kwargs},
)
+ @override
async def atransform(
self,
input: AsyncIterator[Input],
@@ -5638,11 +5744,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
"""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "runnable"]
-
+ @override
def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
"""Bind additional kwargs to a Runnable, returning a new Runnable.
@@ -5661,6 +5763,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
custom_output_type=self.custom_output_type,
)
+ @override
def with_config(
self,
config: Optional[RunnableConfig] = None,
@@ -5675,6 +5778,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
custom_output_type=self.custom_output_type,
)
+ @override
def with_listeners(
self,
*,
@@ -5725,6 +5829,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
custom_output_type=self.custom_output_type,
)
+ @override
def with_types(
self,
input_type: Optional[Union[type[Input], BaseModel]] = None,
@@ -5742,6 +5847,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
),
)
+ @override
def with_retry(self, **kwargs: Any) -> Runnable[Input, Output]:
return self.__class__(
bound=self.bound.with_retry(**kwargs),
@@ -5749,7 +5855,8 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
config=self.config,
)
- def __getattr__(self, name: str) -> Any:
+ @override
+ def __getattr__(self, name: str) -> Any: # type: ignore[misc]
attr = getattr(self.bound, name)
if callable(attr) and (
@@ -5884,6 +5991,7 @@ def chain(
],
) -> Runnable[Input, Output]:
"""Decorate a function to make it a Runnable.
+
Sets the name of the Runnable to the name of the function.
Any runnables called by the function will be traced as dependencies.
diff --git a/libs/core/langchain_core/runnables/branch.py b/libs/core/langchain_core/runnables/branch.py
index 788e90f703..26a14edf16 100644
--- a/libs/core/langchain_core/runnables/branch.py
+++ b/libs/core/langchain_core/runnables/branch.py
@@ -1,3 +1,5 @@
+"""Runnable that selects which branch to run based on a condition."""
+
from collections.abc import AsyncIterator, Awaitable, Iterator, Mapping, Sequence
from typing import (
Any,
@@ -8,6 +10,7 @@ from typing import (
)
from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
from langchain_core.runnables.base import (
Runnable,
@@ -144,10 +147,11 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -167,6 +171,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
return super().get_input_schema(config)
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
from langchain_core.beta.runnables.context import (
CONTEXT_CONFIG_PREFIX,
@@ -203,9 +208,6 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
Returns:
The output of the branch that was run.
-
- Raises:
-
"""
config = ensure_config(config)
callback_manager = get_callback_manager_for_config(config)
@@ -306,8 +308,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
config: Optional[RunnableConfig] = None,
**kwargs: Optional[Any],
) -> Iterator[Output]:
- """First evaluates the condition,
- then delegate to true or false branch.
+ """First evaluates the condition, then delegate to true or false branch.
Args:
input: The input to the Runnable.
@@ -393,8 +394,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
config: Optional[RunnableConfig] = None,
**kwargs: Optional[Any],
) -> AsyncIterator[Output]:
- """First evaluates the condition,
- then delegate to true or false branch.
+ """First evaluates the condition, then delegate to true or false branch.
Args:
input: The input to the Runnable.
diff --git a/libs/core/langchain_core/runnables/config.py b/libs/core/langchain_core/runnables/config.py
index 3c0a8d3308..aea0c6050c 100644
--- a/libs/core/langchain_core/runnables/config.py
+++ b/libs/core/langchain_core/runnables/config.py
@@ -1,3 +1,5 @@
+"""Configuration utilities for Runnables."""
+
from __future__ import annotations
import asyncio
@@ -407,18 +409,14 @@ def call_func_with_variable_args(
"""Call function that may optionally accept a run_manager and/or config.
Args:
- func (Union[Callable[[Input], Output],
- Callable[[Input, CallbackManagerForChainRun], Output],
- Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]):
- The function to call.
- input (Input): The input to the function.
- config (RunnableConfig): The config to pass to the function.
- run_manager (CallbackManagerForChainRun): The run manager to
- pass to the function. Defaults to None.
- **kwargs (Any): The keyword arguments to pass to the function.
+ func: The function to call.
+ input: The input to the function.
+ config: The config to pass to the function.
+ run_manager: The run manager to pass to the function. Defaults to None.
+ **kwargs: The keyword arguments to pass to the function.
Returns:
- Output: The output of the function.
+ The output of the function.
"""
if accepts_config(func):
if run_manager is not None:
@@ -448,18 +446,14 @@ def acall_func_with_variable_args(
"""Async call function that may optionally accept a run_manager and/or config.
Args:
- func (Union[Callable[[Input], Awaitable[Output]], Callable[[Input,
- AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,
- AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):
- The function to call.
- input (Input): The input to the function.
- config (RunnableConfig): The config to pass to the function.
- run_manager (AsyncCallbackManagerForChainRun): The run manager
- to pass to the function. Defaults to None.
- **kwargs (Any): The keyword arguments to pass to the function.
+ func: The function to call.
+ input: The input to the function.
+ config: The config to pass to the function.
+ run_manager: The run manager to pass to the function. Defaults to None.
+ **kwargs: The keyword arguments to pass to the function.
Returns:
- Output: The output of the function.
+ The output of the function.
"""
if accepts_config(func):
if run_manager is not None:
diff --git a/libs/core/langchain_core/runnables/configurable.py b/libs/core/langchain_core/runnables/configurable.py
index 5a67ad691c..563b2d1a58 100644
--- a/libs/core/langchain_core/runnables/configurable.py
+++ b/libs/core/langchain_core/runnables/configurable.py
@@ -1,3 +1,5 @@
+"""Runnables that can be dynamically configured."""
+
from __future__ import annotations
import enum
@@ -63,12 +65,13 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
)
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
@property
@@ -81,22 +84,26 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
def OutputType(self) -> type[Output]:
return self.default.OutputType
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
runnable, config = self.prepare(config)
return runnable.get_input_schema(config)
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
runnable, config = self.prepare(config)
return runnable.get_output_schema(config)
+ @override
def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph:
runnable, config = self.prepare(config)
return runnable.get_graph(config)
+ @override
def with_config(
self,
config: Optional[RunnableConfig] = None,
@@ -129,18 +136,21 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
self, config: Optional[RunnableConfig] = None
) -> tuple[Runnable[Input, Output], RunnableConfig]: ...
+ @override
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
runnable, config = self.prepare(config)
return runnable.invoke(input, config, **kwargs)
+ @override
async def ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
runnable, config = self.prepare(config)
return await runnable.ainvoke(input, config, **kwargs)
+ @override
def batch(
self,
inputs: list[Input],
@@ -183,6 +193,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
with get_executor_for_config(configs[0]) as executor:
return cast("list[Output]", list(executor.map(invoke, prepared, inputs)))
+ @override
async def abatch(
self,
inputs: list[Input],
@@ -221,6 +232,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
coros = map(ainvoke, prepared, inputs)
return await gather_with_concurrency(configs[0].get("max_concurrency"), *coros)
+ @override
def stream(
self,
input: Input,
@@ -230,6 +242,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
runnable, config = self.prepare(config)
return runnable.stream(input, config, **kwargs)
+ @override
async def astream(
self,
input: Input,
@@ -240,6 +253,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
async for chunk in runnable.astream(input, config, **kwargs):
yield chunk
+ @override
def transform(
self,
input: Iterator[Input],
@@ -249,6 +263,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
runnable, config = self.prepare(config)
return runnable.transform(input, config, **kwargs)
+ @override
async def atransform(
self,
input: AsyncIterator[Input],
@@ -259,7 +274,8 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
async for chunk in runnable.atransform(input, config, **kwargs):
yield chunk
- def __getattr__(self, name: str) -> Any:
+ @override
+ def __getattr__(self, name: str) -> Any: # type: ignore[misc]
attr = getattr(self.default, name)
if callable(attr):
@@ -364,11 +380,6 @@ class RunnableConfigurableFields(DynamicRunnable[Input, Output]):
fields: dict[str, AnyConfigurableField]
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "runnable"]
-
@property
def config_specs(self) -> list[ConfigurableFieldSpec]:
"""Get the configuration specs for the RunnableConfigurableFields.
@@ -402,12 +413,10 @@ class RunnableConfigurableFields(DynamicRunnable[Input, Output]):
return get_unique_config_specs(config_specs)
+ @override
def configurable_fields(
self, **kwargs: AnyConfigurableField
) -> RunnableSerializable[Input, Output]:
- """Get a new RunnableConfigurableFields with the specified
- configurable fields.
- """
return self.default.configurable_fields(**{**self.fields, **kwargs})
def _prepare(
@@ -544,12 +553,8 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
of the form <which.id>==<alternative_key>, eg. a key named "temperature" used by
the alternative named "gpt3" becomes "model==gpt3/temperature"."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "runnable"]
-
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
with _enums_for_spec_lock:
if which_enum := _enums_for_spec.get(self.which):
@@ -597,6 +602,7 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
]
)
+ @override
def configurable_fields(
self, **kwargs: AnyConfigurableField
) -> RunnableSerializable[Input, Output]:
@@ -677,8 +683,7 @@ def make_options_spec(
spec: Union[ConfigurableFieldSingleOption, ConfigurableFieldMultiOption],
description: Optional[str],
) -> ConfigurableFieldSpec:
- """Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or
- ConfigurableFieldMultiOption.
+ """Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.
Args:
spec: The ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.
@@ -686,7 +691,7 @@ def make_options_spec(
Returns:
The ConfigurableFieldSpec.
- """
+ """ # noqa: E501
with _enums_for_spec_lock:
if enum := _enums_for_spec.get(spec):
pass
diff --git a/libs/core/langchain_core/runnables/fallbacks.py b/libs/core/langchain_core/runnables/fallbacks.py
index 10c8a4adba..7c1ac281b7 100644
--- a/libs/core/langchain_core/runnables/fallbacks.py
+++ b/libs/core/langchain_core/runnables/fallbacks.py
@@ -1,3 +1,5 @@
+"""Runnable that can fallback to other Runnables if it fails."""
+
import asyncio
import inspect
import typing
@@ -115,17 +117,20 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
def OutputType(self) -> type[Output]:
return self.runnable.OutputType
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
return self.runnable.get_input_schema(config)
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
return self.runnable.get_output_schema(config)
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return get_unique_config_specs(
spec
@@ -134,19 +139,26 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
)
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
+ """Get the namespace of the langchain object.
+
+ Defaults to ["langchain", "schema", "runnable"].
+ """
return ["langchain", "schema", "runnable"]
@property
def runnables(self) -> Iterator[Runnable[Input, Output]]:
+ """Iterator over the Runnable and its fallbacks."""
yield self.runnable
yield from self.fallbacks
+ @override
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -196,6 +208,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
run_manager.on_chain_error(first_error)
raise first_error
+ @override
async def ainvoke(
self,
input: Input,
@@ -248,6 +261,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
await run_manager.on_chain_error(first_error)
raise first_error
+ @override
def batch(
self,
inputs: list[Input],
@@ -341,6 +355,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
to_return.update(handled_exceptions)
return [output for _, output in sorted(to_return.items())]
+ @override
async def abatch(
self,
inputs: list[Input],
@@ -442,13 +457,13 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
to_return.update(handled_exceptions)
return [output for _, output in sorted(to_return.items())] # type: ignore
+ @override
def stream(
self,
input: Input,
config: Optional[RunnableConfig] = None,
**kwargs: Optional[Any],
) -> Iterator[Output]:
- """"""
if self.exception_key is not None and not isinstance(input, dict):
msg = (
"If 'exception_key' is specified then input must be a dictionary."
@@ -506,6 +521,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
raise
run_manager.on_chain_end(output)
+ @override
async def astream(
self,
input: Input,
diff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.py
index 384c19d238..6bec1fd1fc 100644
--- a/libs/core/langchain_core/runnables/graph.py
+++ b/libs/core/langchain_core/runnables/graph.py
@@ -1,3 +1,5 @@
+"""Graph used in Runnables."""
+
from __future__ import annotations
import inspect
@@ -28,7 +30,10 @@ if TYPE_CHECKING:
class Stringifiable(Protocol):
- def __str__(self) -> str: ...
+ """Protocol for objects that can be converted to a string."""
+
+ def __str__(self) -> str:
+ """Convert the object to a string."""
class LabelsDict(TypedDict):
@@ -303,11 +308,13 @@ class Graph:
}
def __bool__(self) -> bool:
+ """Return whether the graph has any nodes."""
return bool(self.nodes)
def next_id(self) -> str:
- """Return a new unique node
- identifier that can be used to add a node to the graph.
+ """Return a new unique node identifier.
+
+ It that can be used to add a node to the graph.
"""
return uuid4().hex
@@ -389,6 +396,7 @@ class Graph:
self, graph: Graph, *, prefix: str = ""
) -> tuple[Optional[Node], Optional[Node]]:
"""Add all nodes and edges from another graph.
+
Note this doesn't check for duplicates, nor does it connect the graphs.
Args:
@@ -423,8 +431,9 @@ class Graph:
)
def reid(self) -> Graph:
- """Return a new graph with all nodes re-identified,
- using their unique, readable names where possible.
+ """Return a new graph with all nodes re-identified.
+
+ Uses their unique, readable names where possible.
"""
node_name_to_ids = defaultdict(list)
for node in self.nodes.values():
@@ -459,6 +468,7 @@ class Graph:
def first_node(self) -> Optional[Node]:
"""Find the single node that is not a target of any edge.
+
If there is no such node, or there are multiple, return None.
When drawing the graph, this node would be the origin.
"""
@@ -466,13 +476,15 @@ class Graph:
def last_node(self) -> Optional[Node]:
"""Find the single node that is not a source of any edge.
+
If there is no such node, or there are multiple, return None.
When drawing the graph, this node would be the destination.
"""
return _last_node(self)
def trim_first_node(self) -> None:
- """Remove the first node if it exists and has a single outgoing edge,
+ """Remove the first node if it exists and has a single outgoing edge.
+
i.e., if removing it would not leave the graph without a "first" node.
"""
first_node = self.first_node()
@@ -484,7 +496,8 @@ class Graph:
self.remove_node(first_node)
def trim_last_node(self) -> None:
- """Remove the last node if it exists and has a single incoming edge,
+ """Remove the last node if it exists and has a single incoming edge.
+
i.e., if removing it would not leave the graph without a "last" node.
"""
last_node = self.last_node()
@@ -579,8 +592,10 @@ class Graph:
See more here: https://mermaid.js.org/config/configuration.html.
- Example:
- ```python
+ Example config:
+
+ .. code-block:: python
+
{
"config": {
"theme": "neutral",
@@ -588,7 +603,7 @@ class Graph:
"themeVariables": { "primaryColor": "#e2e2e2"},
}
}
- ```
+
Returns:
The Mermaid syntax string.
@@ -642,8 +657,10 @@ class Graph:
See more here: https://mermaid.js.org/config/configuration.html.
- Example:
- ```python
+ Example config:
+
+ .. code-block:: python
+
{
"config": {
"theme": "neutral",
@@ -651,7 +668,6 @@ class Graph:
"themeVariables": { "primaryColor": "#e2e2e2"},
}
}
- ```
Returns:
The PNG image as bytes.
@@ -675,6 +691,7 @@ class Graph:
def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Optional[Node]:
"""Find the single node that is not a target of any edge.
+
Exclude nodes/sources with ids in the exclude list.
If there is no such node, or there are multiple, return None.
When drawing the graph, this node would be the origin.
@@ -689,6 +706,7 @@ def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Optional[Node]:
def _last_node(graph: Graph, exclude: Sequence[str] = ()) -> Optional[Node]:
"""Find the single node that is not a source of any edge.
+
Exclude nodes/targets with ids in the exclude list.
If there is no such node, or there are multiple, return None.
When drawing the graph, this node would be the destination.
diff --git a/libs/core/langchain_core/runnables/graph_ascii.py b/libs/core/langchain_core/runnables/graph_ascii.py
index c10e42bd0f..723042950c 100644
--- a/libs/core/langchain_core/runnables/graph_ascii.py
+++ b/libs/core/langchain_core/runnables/graph_ascii.py
@@ -1,4 +1,5 @@
"""Draws DAG in ASCII.
+
Adapted from https://github.com/iterative/dvc/blob/main/dvc/dagascii.py.
"""
@@ -11,17 +12,21 @@ from langchain_core.runnables.graph import Edge as LangEdge
class VertexViewer:
- """Class to define vertex box boundaries that will be accounted for during
- graph building by grandalf.
+ """VertexViewer class.
- Args:
- name (str): name of the vertex.
+ Class to define vertex box boundaries that will be accounted for during
+ graph building by grandalf.
"""
HEIGHT = 3 # top and bottom box edges + text
"""Height of the box."""
def __init__(self, name: str) -> None:
+ """Create a VertexViewer.
+
+ Args:
+ name: name of the vertex.
+ """
self._h = self.HEIGHT # top and bottom box edges + text
self._w = len(name) + 2 # right and left bottom edges + text
@@ -37,16 +42,17 @@ class VertexViewer:
class AsciiCanvas:
- """Class for drawing in ASCII.
-
- Args:
- cols (int): number of columns in the canvas. Should be > 1.
- lines (int): number of lines in the canvas. Should be > 1.
- """
+ """Class for drawing in ASCII."""
TIMEOUT = 10
def __init__(self, cols: int, lines: int) -> None:
+ """Create an ASCII canvas.
+
+ Args:
+ cols (int): number of columns in the canvas. Should be > 1.
+ lines (int): number of lines in the canvas. Should be > 1.
+ """
if cols <= 1 or lines <= 1:
msg = "Canvas dimensions should be > 1"
raise ValueError(msg)
diff --git a/libs/core/langchain_core/runnables/graph_mermaid.py b/libs/core/langchain_core/runnables/graph_mermaid.py
index 8c2ff5faf4..56dc4d925b 100644
--- a/libs/core/langchain_core/runnables/graph_mermaid.py
+++ b/libs/core/langchain_core/runnables/graph_mermaid.py
@@ -1,3 +1,5 @@
+"""Mermaid graph drawing utilities."""
+
import asyncio
import base64
import re
@@ -52,8 +54,10 @@ def draw_mermaid(
See more here: https://mermaid.js.org/config/configuration.html.
- Example:
- ```python
+ Example config:
+
+ .. code-block:: python
+
{
"config": {
"theme": "neutral",
@@ -61,7 +65,6 @@ def draw_mermaid(
"themeVariables": { "primaryColor": "#e2e2e2"},
}
}
- ```
Returns:
str: Mermaid graph syntax.
diff --git a/libs/core/langchain_core/runnables/graph_png.py b/libs/core/langchain_core/runnables/graph_png.py
index 98aa50dd80..116bb28917 100644
--- a/libs/core/langchain_core/runnables/graph_png.py
+++ b/libs/core/langchain_core/runnables/graph_png.py
@@ -1,3 +1,5 @@
+"""Helper class to draw a state graph into a PNG file."""
+
from typing import Any, Optional
from langchain_core.runnables.graph import Graph, LabelsDict
diff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.py
index d2040a3f3f..5112534e55 100644
--- a/libs/core/langchain_core/runnables/history.py
+++ b/libs/core/langchain_core/runnables/history.py
@@ -1,3 +1,5 @@
+"""Runnable that manages chat message history for another Runnable."""
+
from __future__ import annotations
import inspect
@@ -236,11 +238,6 @@ class RunnableWithMessageHistory(RunnableBindingBase):
history_messages_key: Optional[str] = None
history_factory_config: Sequence[ConfigurableFieldSpec]
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "runnable"]
-
def __init__(
self,
runnable: Union[
@@ -365,12 +362,14 @@ class RunnableWithMessageHistory(RunnableBindingBase):
self._history_chain = history_chain
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
"""Get the configuration specs for the RunnableWithMessageHistory."""
return get_unique_config_specs(
super().config_specs + list(self.history_factory_config)
)
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
diff --git a/libs/core/langchain_core/runnables/passthrough.py b/libs/core/langchain_core/runnables/passthrough.py
index 718e855229..3f87f6b22e 100644
--- a/libs/core/langchain_core/runnables/passthrough.py
+++ b/libs/core/langchain_core/runnables/passthrough.py
@@ -85,13 +85,6 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
chains. The chains rely on simple lambdas to make the examples easy to execute
and experiment with.
- Parameters:
- func (Callable[[Other], None], optional): Function to be called with the input.
- afunc (Callable[[Other], Awaitable[None]], optional): Async function to
- be called with the input.
- input_type (Optional[Type[Other]], optional): Type of the input.
- **kwargs (Any): Additional keyword arguments.
-
Examples:
.. code-block:: python
@@ -154,6 +147,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
]
] = None
+ @override
def __repr_args__(self) -> Any:
# Without this repr(self) raises a RecursionError
# See https://github.com/pydantic/pydantic/issues/7327
@@ -180,6 +174,13 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
input_type: Optional[type[Other]] = None,
**kwargs: Any,
) -> None:
+ """Create e RunnablePassthrough.
+
+ Args:
+ func: Function to be called with the input.
+ afunc: Async function to be called with the input.
+ input_type: Type of the input.
+ """
if inspect.iscoroutinefunction(func):
afunc = func
func = None
@@ -187,12 +188,13 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs) # type: ignore[call-arg]
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
@property
@@ -206,6 +208,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
return self.input_type or Any
@classmethod
+ @override
def assign(
cls,
**kwargs: Union[
@@ -229,6 +232,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
"""
return RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
+ @override
def invoke(
self, input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Other:
@@ -238,6 +242,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
)
return self._call_with_config(identity, input, config)
+ @override
async def ainvoke(
self,
input: Other,
@@ -254,6 +259,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
)
return await self._acall_with_config(aidentity, input, config)
+ @override
def transform(
self,
input: Iterator[Other],
@@ -284,6 +290,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
self.func, final, ensure_config(config), **kwargs
)
+ @override
async def atransform(
self,
input: AsyncIterator[Other],
@@ -326,6 +333,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
elif self.func is not None:
call_func_with_variable_args(self.func, final, config, **kwargs)
+ @override
def stream(
self,
input: Other,
@@ -334,6 +342,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
) -> Iterator[Other]:
return self.transform(iter([input]), config, **kwargs)
+ @override
async def astream(
self,
input: Other,
@@ -358,10 +367,6 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
these with the original data, introducing new key-value pairs based
on the mapper's logic.
- Parameters:
- mapper (RunnableParallel[Dict[str, Any]]): A `RunnableParallel` instance
- that will be used to transform the input dictionary.
-
Examples:
.. code-block:: python
@@ -394,17 +399,25 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
mapper: RunnableParallel
def __init__(self, mapper: RunnableParallel[dict[str, Any]], **kwargs: Any) -> None:
+ """Create a RunnableAssign.
+
+ Args:
+ mapper: A ``RunnableParallel`` instance that will be used to transform the
+ input dictionary.
+ """
super().__init__(mapper=mapper, **kwargs) # type: ignore[call-arg]
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
+ @override
def get_name(
self, suffix: Optional[str] = None, *, name: Optional[str] = None
) -> str:
@@ -415,6 +428,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
)
return super().get_name(suffix, name=name)
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -425,6 +439,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
return super().get_input_schema(config)
+ @override
def get_output_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -452,9 +467,11 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
return super().get_output_schema(config)
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return self.mapper.config_specs
+ @override
def get_graph(self, config: RunnableConfig | None = None) -> Graph:
# get graph from mapper
graph = self.mapper.get_graph(config)
@@ -487,6 +504,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
),
}
+ @override
def invoke(
self,
input: dict[str, Any],
@@ -515,6 +533,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
),
}
+ @override
async def ainvoke(
self,
input: dict[str, Any],
@@ -569,6 +588,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
for chunk in map_output:
yield chunk
+ @override
def transform(
self,
input: Iterator[dict[str, Any]],
@@ -620,6 +640,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
async for chunk in map_output:
yield chunk
+ @override
async def atransform(
self,
input: AsyncIterator[dict[str, Any]],
@@ -631,6 +652,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
):
yield chunk
+ @override
def stream(
self,
input: dict[str, Any],
@@ -639,6 +661,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
) -> Iterator[dict[str, Any]]:
return self.transform(iter([input]), config, **kwargs)
+ @override
async def astream(
self,
input: dict[str, Any],
@@ -660,11 +683,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
from the input dictionary. It returns a new dictionary containing only
the selected keys.
- Parameters:
- keys (Union[str, List[str]]): A single key or a list of keys to pick from
- the input dictionary.
-
- Example :
+ Example:
.. code-block:: python
from langchain_core.runnables.passthrough import RunnablePick
@@ -686,17 +705,25 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
keys: Union[str, list[str]]
def __init__(self, keys: Union[str, list[str]], **kwargs: Any) -> None:
+ """Create a RunnablePick.
+
+ Args:
+ keys: A single key or a list of keys to pick from the input dictionary.
+ """
super().__init__(keys=keys, **kwargs) # type: ignore[call-arg]
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
+ @override
def get_name(
self, suffix: Optional[str] = None, *, name: Optional[str] = None
) -> str:
@@ -727,6 +754,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
) -> dict[str, Any]:
return self._pick(input)
+ @override
def invoke(
self,
input: dict[str, Any],
@@ -741,6 +769,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
) -> dict[str, Any]:
return self._pick(input)
+ @override
async def ainvoke(
self,
input: dict[str, Any],
@@ -758,6 +787,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
if picked is not None:
yield picked
+ @override
def transform(
self,
input: Iterator[dict[str, Any]],
@@ -777,6 +807,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
if picked is not None:
yield picked
+ @override
async def atransform(
self,
input: AsyncIterator[dict[str, Any]],
@@ -788,6 +819,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
):
yield chunk
+ @override
def stream(
self,
input: dict[str, Any],
@@ -796,6 +828,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
) -> Iterator[dict[str, Any]]:
return self.transform(iter([input]), config, **kwargs)
+ @override
async def astream(
self,
input: dict[str, Any],
diff --git a/libs/core/langchain_core/runnables/retry.py b/libs/core/langchain_core/runnables/retry.py
index 5d7a74685c..cbbb9da077 100644
--- a/libs/core/langchain_core/runnables/retry.py
+++ b/libs/core/langchain_core/runnables/retry.py
@@ -1,3 +1,5 @@
+"""Runnable that retries a Runnable if it fails."""
+
from typing import (
TYPE_CHECKING,
Any,
@@ -16,6 +18,7 @@ from tenacity import (
stop_after_attempt,
wait_exponential_jitter,
)
+from typing_extensions import override
from langchain_core.runnables.base import Input, Output, RunnableBindingBase
from langchain_core.runnables.config import RunnableConfig, patch_config
@@ -109,11 +112,6 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
max_attempt_number: int = 3
"""The maximum number of attempts to retry the Runnable."""
- @classmethod
- def get_lc_namespace(cls) -> list[str]:
- """Get the namespace of the langchain object."""
- return ["langchain", "schema", "runnable"]
-
@property
def _kwargs_retrying(self) -> dict[str, Any]:
kwargs: dict[str, Any] = {}
@@ -173,6 +171,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
attempt.retry_state.set_result(result)
return result
+ @override
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -196,6 +195,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
attempt.retry_state.set_result(result)
return result
+ @override
async def ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -255,6 +255,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
outputs.append(result.pop(0))
return outputs
+ @override
def batch(
self,
inputs: list[Input],
@@ -321,6 +322,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
outputs.append(result.pop(0))
return outputs
+ @override
async def abatch(
self,
inputs: list[Input],
diff --git a/libs/core/langchain_core/runnables/router.py b/libs/core/langchain_core/runnables/router.py
index 856bec5df7..9d57eb76b2 100644
--- a/libs/core/langchain_core/runnables/router.py
+++ b/libs/core/langchain_core/runnables/router.py
@@ -1,3 +1,5 @@
+"""Runnable that routes to a set of Runnables."""
+
from __future__ import annotations
from collections.abc import Mapping
@@ -12,7 +14,7 @@ from typing import (
)
from pydantic import ConfigDict
-from typing_extensions import TypedDict
+from typing_extensions import TypedDict, override
from langchain_core.runnables.base import (
Input,
@@ -50,28 +52,27 @@ class RouterInput(TypedDict):
class RouterRunnable(RunnableSerializable[RouterInput, Output]):
"""Runnable that routes to a set of Runnables based on Input['key'].
- Returns the output of the selected Runnable.
- Parameters:
- runnables: A mapping of keys to Runnables.
+ Returns the output of the selected Runnable.
- For example,
+ Example:
- .. code-block:: python
+ .. code-block:: python
- from langchain_core.runnables.router import RouterRunnable
- from langchain_core.runnables import RunnableLambda
+ from langchain_core.runnables.router import RouterRunnable
+ from langchain_core.runnables import RunnableLambda
- add = RunnableLambda(func=lambda x: x + 1)
- square = RunnableLambda(func=lambda x: x**2)
+ add = RunnableLambda(func=lambda x: x + 1)
+ square = RunnableLambda(func=lambda x: x**2)
- router = RouterRunnable(runnables={"add": add, "square": square})
- router.invoke({"key": "square", "input": 3})
+ router = RouterRunnable(runnables={"add": add, "square": square})
+ router.invoke({"key": "square", "input": 3})
"""
runnables: Mapping[str, Runnable[Any, Output]]
@property
+ @override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return get_unique_config_specs(
spec for step in self.runnables.values() for spec in step.config_specs
@@ -81,6 +82,11 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
self,
runnables: Mapping[str, Union[Runnable[Any, Output], Callable[[Any], Output]]],
) -> None:
+ """Create a RouterRunnable.
+
+ Args:
+ runnables: A mapping of keys to Runnables.
+ """
super().__init__( # type: ignore[call-arg]
runnables={key: coerce_to_runnable(r) for key, r in runnables.items()}
)
@@ -90,15 +96,18 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
)
@classmethod
+ @override
def is_lc_serializable(cls) -> bool:
"""Return whether this class is serializable."""
return True
@classmethod
+ @override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object."""
return ["langchain", "schema", "runnable"]
+ @override
def invoke(
self, input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
@@ -111,6 +120,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
runnable = self.runnables[key]
return runnable.invoke(actual_input, config)
+ @override
async def ainvoke(
self,
input: RouterInput,
@@ -126,6 +136,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
runnable = self.runnables[key]
return await runnable.ainvoke(actual_input, config)
+ @override
def batch(
self,
inputs: list[RouterInput],
@@ -162,6 +173,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
list(executor.map(invoke, runnables, actual_inputs, configs)),
)
+ @override
async def abatch(
self,
inputs: list[RouterInput],
@@ -197,6 +209,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
*starmap(ainvoke, zip(runnables, actual_inputs, configs)),
)
+ @override
def stream(
self,
input: RouterInput,
@@ -212,6 +225,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
runnable = self.runnables[key]
yield from runnable.stream(actual_input, config)
+ @override
async def astream(
self,
input: RouterInput,
diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.py
index 6ed4e7d681..fecc546dcc 100644
--- a/libs/core/langchain_core/runnables/utils.py
+++ b/libs/core/langchain_core/runnables/utils.py
@@ -122,6 +122,7 @@ def accepts_context(callable: Callable[..., Any]) -> bool:
@lru_cache(maxsize=1)
def asyncio_accepts_context() -> bool:
+ """Cache the result of checking if asyncio.create_task accepts a ``context`` arg."""
return accepts_context(asyncio.create_task)
@@ -185,6 +186,7 @@ class IsFunctionArgDict(ast.NodeVisitor):
"""Check if the first argument of a function is a dict."""
def __init__(self) -> None:
+ """Create a IsFunctionArgDict visitor."""
self.keys: set[str] = set()
@override
@@ -237,6 +239,7 @@ class NonLocals(ast.NodeVisitor):
"""Get nonlocal variables accessed."""
def __init__(self) -> None:
+ """Create a NonLocals visitor."""
self.loads: set[str] = set()
self.stores: set[str] = set()
@@ -294,6 +297,7 @@ class FunctionNonLocals(ast.NodeVisitor):
"""Get the nonlocal variables accessed of a function."""
def __init__(self) -> None:
+ """Create a FunctionNonLocals visitor."""
self.nonlocals: set[str] = set()
@override
@@ -469,6 +473,11 @@ class AddableDict(dict[str, Any]):
"""Dictionary that can be added to another dictionary."""
def __add__(self, other: AddableDict) -> AddableDict:
+ """Add a dictionary to this dictionary.
+
+ Args:
+ other: The other dictionary to add.
+ """
chunk = AddableDict(self)
for key in other:
if key not in chunk or chunk[key] is None:
@@ -482,6 +491,11 @@ class AddableDict(dict[str, Any]):
return chunk
def __radd__(self, other: AddableDict) -> AddableDict:
+ """Add this dictionary to another dictionary.
+
+ Args:
+ other: The other dictionary to be added to.
+ """
chunk = AddableDict(other)
for key in self:
if key not in chunk or chunk[key] is None:
@@ -502,7 +516,8 @@ _T_contra = TypeVar("_T_contra", contravariant=True)
class SupportsAdd(Protocol[_T_contra, _T_co]):
"""Protocol for objects that support addition."""
- def __add__(self, __x: _T_contra) -> _T_co: ...
+ def __add__(self, __x: _T_contra) -> _T_co:
+ """Add the object to another object."""
Addable = TypeVar("Addable", bound=SupportsAdd[Any, Any])
@@ -556,6 +571,7 @@ class ConfigurableField(NamedTuple):
annotation: Optional[Any] = None
is_shared: bool = False
+ @override
def __hash__(self) -> int:
return hash((self.id, self.annotation))
@@ -580,6 +596,7 @@ class ConfigurableFieldSingleOption(NamedTuple):
description: Optional[str] = None
is_shared: bool = False
+ @override
def __hash__(self) -> int:
return hash((self.id, tuple(self.options.keys()), self.default))
@@ -604,6 +621,7 @@ class ConfigurableFieldMultiOption(NamedTuple):
description: Optional[str] = None
is_shared: bool = False
+ @override
def __hash__(self) -> int:
return hash((self.id, tuple(self.options.keys()), tuple(self.default)))
diff --git a/libs/core/langchain_core/structured_query.py b/libs/core/langchain_core/structured_query.py
index c0c502da00..746174e5d3 100644
--- a/libs/core/langchain_core/structured_query.py
+++ b/libs/core/langchain_core/structured_query.py
@@ -123,21 +123,25 @@ class FilterDirective(Expr, ABC):
class Comparison(FilterDirective):
- """Comparison to a value.
-
- Parameters:
- comparator: The comparator to use.
- attribute: The attribute to compare.
- value: The value to compare to.
- """
+ """Comparison to a value."""
comparator: Comparator
+ """The comparator to use."""
attribute: str
+ """The attribute to compare."""
value: Any
+ """The value to compare to."""
def __init__(
self, comparator: Comparator, attribute: str, value: Any, **kwargs: Any
) -> None:
+ """Create a Comparison.
+
+ Args:
+ comparator: The comparator to use.
+ attribute: The attribute to compare.
+ value: The value to compare to.
+ """
# super exists from BaseModel
super().__init__( # type: ignore[call-arg]
comparator=comparator, attribute=attribute, value=value, **kwargs
@@ -145,19 +149,22 @@ class Comparison(FilterDirective):
class Operation(FilterDirective):
- """Logical operation over other directives.
-
- Parameters:
- operator: The operator to use.
- arguments: The arguments to the operator.
- """
+ """Logical operation over other directives."""
operator: Operator
+ """The operator to use."""
arguments: list[FilterDirective]
+ """The arguments to the operator."""
def __init__(
self, operator: Operator, arguments: list[FilterDirective], **kwargs: Any
) -> None:
+ """Create an Operation.
+
+ Args:
+ operator: The operator to use.
+ arguments: The arguments to the operator.
+ """
# super exists from BaseModel
super().__init__( # type: ignore[call-arg]
operator=operator, arguments=arguments, **kwargs
@@ -181,6 +188,13 @@ class StructuredQuery(Expr):
limit: Optional[int] = None,
**kwargs: Any,
) -> None:
+ """Create a StructuredQuery.
+
+ Args:
+ query: The query string.
+ filter: The filtering expression.
+ limit: The limit on the number of results.
+ """
# super exists from BaseModel
super().__init__( # type: ignore[call-arg]
query=query, filter=filter, limit=limit, **kwargs
diff --git a/libs/core/langchain_core/sys_info.py b/libs/core/langchain_core/sys_info.py
index 532b4e6380..6520e0b99d 100644
--- a/libs/core/langchain_core/sys_info.py
+++ b/libs/core/langchain_core/sys_info.py
@@ -1,6 +1,4 @@
-"""**sys_info** prints information about the system and langchain packages
-for debugging purposes.
-"""
+"""**sys_info** prints information about the system and langchain packages for debugging purposes.""" # noqa: E501
from collections.abc import Sequence
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index 11078e3d3b..dc9edc4557 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -1,3 +1,5 @@
+"""Base for Tools."""
+
from __future__ import annotations
import asyncio
@@ -35,6 +37,7 @@ from pydantic import (
from pydantic.v1 import BaseModel as BaseModelV1
from pydantic.v1 import ValidationError as ValidationErrorV1
from pydantic.v1 import validate_arguments as validate_arguments_v1
+from typing_extensions import override
from langchain_core._api import deprecated
from langchain_core.callbacks import (
@@ -451,6 +454,7 @@ class ChildTool(BaseTool):
@property
def args(self) -> dict:
+ """The arguments of the tool."""
if isinstance(self.args_schema, dict):
json_schema = self.args_schema
else:
@@ -460,6 +464,7 @@ class ChildTool(BaseTool):
@property
def tool_call_schema(self) -> ArgsSchema:
+ """The schema for a tool call."""
if isinstance(self.args_schema, dict):
if self.description:
return {
@@ -480,6 +485,7 @@ class ChildTool(BaseTool):
# --- Runnable ---
+ @override
def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> type[BaseModel]:
@@ -498,6 +504,7 @@ class ChildTool(BaseTool):
else:
return create_schema_from_function(self.name, self._run)
+ @override
def invoke(
self,
input: Union[str, dict, ToolCall],
@@ -507,6 +514,7 @@ class ChildTool(BaseTool):
tool_input, kwargs = _prep_run_args(input, config, **kwargs)
return self.run(tool_input, **kwargs)
+ @override
async def ainvoke(
self,
input: Union[str, dict, ToolCall],
@@ -525,6 +533,7 @@ class ChildTool(BaseTool):
Args:
tool_input: The input to the tool.
+ tool_call_id: The id of the tool call.
"""
input_args = self.args_schema
if isinstance(tool_input, str):
@@ -1040,7 +1049,7 @@ class InjectedToolArg:
class InjectedToolCallId(InjectedToolArg):
- r'''Annotation for injecting the tool_call_id.
+ """Annotation for injecting the tool_call_id.
Example:
..code-block:: python
@@ -1052,9 +1061,9 @@ class InjectedToolCallId(InjectedToolArg):
@tool
def foo(x: int, tool_call_id: Annotated[str, InjectedToolCallID]) -> ToolMessage:
- """Return x."""
+ \"\"\"Return x.\"\"\"
return ToolMessage(str(x), artifact=x, name="foo", tool_call_id=tool_call_id)
- ''' # noqa: E501
+ """ # noqa: E501
def _is_injected_arg_type(
@@ -1071,6 +1080,12 @@ def _is_injected_arg_type(
def get_all_basemodel_annotations(
cls: Union[TypeBaseModel, Any], *, default_to_bound: bool = True
) -> dict[str, type]:
+ """Get all annotations from a Pydantic BaseModel and its parents.
+
+ Args:
+ cls: The Pydantic BaseModel class.
+ default_to_bound: Whether to default to the bound of a TypeVar if it exists.
+ """
# cls has no subscript: cls = FooBar
if isinstance(cls, type):
annotations: dict[str, type] = {}
diff --git a/libs/core/langchain_core/tools/convert.py b/libs/core/langchain_core/tools/convert.py
index c8568765b6..8e45d2ddd5 100644
--- a/libs/core/langchain_core/tools/convert.py
+++ b/libs/core/langchain_core/tools/convert.py
@@ -1,3 +1,5 @@
+"""Convert functions and runnables to tools."""
+
import inspect
from typing import Any, Callable, Literal, Optional, Union, get_type_hints, overload
@@ -96,6 +98,7 @@ def tool(
(used even if `args_schema` is provided)
- `args_schema` description
(used only if `description` / docstring are not provided)
+ *args: Extra positional arguments. Must be empty.
return_direct: Whether to return directly from the tool rather
than continuing the agent loop. Defaults to False.
args_schema: optional argument schema for user to specify.
@@ -211,7 +214,7 @@ def tool(
monkey: The baz.
\"\"\"
return bar
- """
+ """ # noqa: D214,D405,D410,D411,D412,D416
def _create_tool_factory(
tool_name: str,
diff --git a/libs/core/langchain_core/tools/render.py b/libs/core/langchain_core/tools/render.py
index d59aef4230..eeb6f3d5c8 100644
--- a/libs/core/langchain_core/tools/render.py
+++ b/libs/core/langchain_core/tools/render.py
@@ -1,3 +1,5 @@
+"""Utilities to render tools."""
+
from __future__ import annotations
from inspect import signature
diff --git a/libs/core/langchain_core/tools/retriever.py b/libs/core/langchain_core/tools/retriever.py
index 0bc26ce2a7..002fa5e80d 100644
--- a/libs/core/langchain_core/tools/retriever.py
+++ b/libs/core/langchain_core/tools/retriever.py
@@ -1,3 +1,5 @@
+"""Retriever tool."""
+
from __future__ import annotations
from functools import partial
@@ -71,7 +73,7 @@ def create_retriever_tool(
document_separator: str = "\n\n",
response_format: Literal["content", "content_and_artifact"] = "content",
) -> Tool:
- """Create a tool to do retrieval of documents.
+ r"""Create a tool to do retrieval of documents.
Args:
retriever: The retriever to use for the retrieval
@@ -82,10 +84,10 @@ def create_retriever_tool(
document_prompt: The prompt to use for the document. Defaults to None.
document_separator: The separator to use between documents. Defaults to "\n\n".
response_format: The tool response format. If "content" then the output of
- the tool is interpreted as the contents of a ToolMessage. If
- "content_and_artifact" then the output is expected to be a two-tuple
- corresponding to the (content, artifact) of a ToolMessage (artifact
- being a list of documents in this case). Defaults to "content".
+ the tool is interpreted as the contents of a ToolMessage. If
+ "content_and_artifact" then the output is expected to be a two-tuple
+ corresponding to the (content, artifact) of a ToolMessage (artifact
+ being a list of documents in this case). Defaults to "content".
Returns:
Tool class to pass to an agent.
diff --git a/libs/core/langchain_core/tools/simple.py b/libs/core/langchain_core/tools/simple.py
index d9806c3e94..21f1e61f5b 100644
--- a/libs/core/langchain_core/tools/simple.py
+++ b/libs/core/langchain_core/tools/simple.py
@@ -1,3 +1,5 @@
+"""Tool that takes in function or coroutine directly."""
+
from __future__ import annotations
from collections.abc import Awaitable
@@ -10,6 +12,8 @@ from typing import (
Union,
)
+from typing_extensions import override
+
from langchain_core.callbacks import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
@@ -37,6 +41,7 @@ class Tool(BaseTool):
# --- Runnable ---
+ @override
async def ainvoke(
self,
input: Union[str, dict, ToolCall],
diff --git a/libs/core/langchain_core/tools/structured.py b/libs/core/langchain_core/tools/structured.py
index 6d7620e762..e8ebea8be3 100644
--- a/libs/core/langchain_core/tools/structured.py
+++ b/libs/core/langchain_core/tools/structured.py
@@ -1,3 +1,5 @@
+"""Structured tool."""
+
from __future__ import annotations
import textwrap
@@ -14,6 +16,7 @@ from typing import (
)
from pydantic import Field, SkipValidation
+from typing_extensions import override
from langchain_core.callbacks import (
AsyncCallbackManagerForToolRun,
@@ -49,6 +52,7 @@ class StructuredTool(BaseTool):
# --- Runnable ---
# TODO: Is this needed?
+ @override
async def ainvoke(
self,
input: Union[str, dict, ToolCall],
diff --git a/libs/core/langchain_core/tracers/base.py b/libs/core/langchain_core/tracers/base.py
index f452d586f5..2a44655527 100644
--- a/libs/core/langchain_core/tracers/base.py
+++ b/libs/core/langchain_core/tracers/base.py
@@ -12,6 +12,8 @@ from typing import (
Union,
)
+from typing_extensions import override
+
from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackHandler
from langchain_core.exceptions import TracerException # noqa
from langchain_core.tracers.core import _TracerCore
@@ -528,9 +530,11 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
"""Async Base interface for tracers."""
@abstractmethod
+ @override
async def _persist_run(self, run: Run) -> None:
"""Persist a run."""
+ @override
async def _start_trace(self, run: Run) -> None:
"""Start a trace for a run.
@@ -540,6 +544,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
super()._start_trace(run)
await self._on_run_create(run)
+ @override
async def _end_trace(self, run: Run) -> None:
"""End a trace for a run.
@@ -551,6 +556,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
self.run_map.pop(str(run.id))
await self._on_run_update(run)
+ @override
async def on_chat_model_start(
self,
serialized: dict[str, Any],
@@ -580,6 +586,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
await asyncio.gather(*tasks)
return chat_model_run
+ @override
async def on_llm_start(
self,
serialized: dict[str, Any],
@@ -603,6 +610,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._start_trace(llm_run), self._on_llm_start(llm_run)]
await asyncio.gather(*tasks)
+ @override
async def on_llm_new_token(
self,
token: str,
@@ -621,6 +629,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
)
await self._on_llm_new_token(llm_run, token, chunk)
+ @override
async def on_retry(
self,
retry_state: RetryCallState,
@@ -633,6 +642,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
run_id=run_id,
)
+ @override
async def on_llm_end(
self,
response: LLMResult,
@@ -649,6 +659,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._on_llm_end(llm_run), self._end_trace(llm_run)]
await asyncio.gather(*tasks)
+ @override
async def on_llm_error(
self,
error: BaseException,
@@ -665,6 +676,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._on_llm_error(llm_run), self._end_trace(llm_run)]
await asyncio.gather(*tasks)
+ @override
async def on_chain_start(
self,
serialized: dict[str, Any],
@@ -692,6 +704,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._start_trace(chain_run), self._on_chain_start(chain_run)]
await asyncio.gather(*tasks)
+ @override
async def on_chain_end(
self,
outputs: dict[str, Any],
@@ -709,6 +722,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._end_trace(chain_run), self._on_chain_end(chain_run)]
await asyncio.gather(*tasks)
+ @override
async def on_chain_error(
self,
error: BaseException,
@@ -726,6 +740,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._end_trace(chain_run), self._on_chain_error(chain_run)]
await asyncio.gather(*tasks)
+ @override
async def on_tool_start(
self,
serialized: dict[str, Any],
@@ -752,6 +767,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._start_trace(tool_run), self._on_tool_start(tool_run)]
await asyncio.gather(*tasks)
+ @override
async def on_tool_end(
self,
output: Any,
@@ -767,6 +783,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._end_trace(tool_run), self._on_tool_end(tool_run)]
await asyncio.gather(*tasks)
+ @override
async def on_tool_error(
self,
error: BaseException,
@@ -783,6 +800,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
tasks = [self._end_trace(tool_run), self._on_tool_error(tool_run)]
await asyncio.gather(*tasks)
+ @override
async def on_retriever_start(
self,
serialized: dict[str, Any],
@@ -810,6 +828,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
]
await asyncio.gather(*tasks)
+ @override
async def on_retriever_error(
self,
error: BaseException,
@@ -830,6 +849,7 @@ class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
]
await asyncio.gather(*tasks)
+ @override
async def on_retriever_end(
self,
documents: Sequence[Document],
diff --git a/libs/core/langchain_core/tracers/context.py b/libs/core/langchain_core/tracers/context.py
index 5d31bd334b..06520c9fe9 100644
--- a/libs/core/langchain_core/tracers/context.py
+++ b/libs/core/langchain_core/tracers/context.py
@@ -1,3 +1,5 @@
+"""Context management for tracers."""
+
from __future__ import annotations
from contextlib import contextmanager
diff --git a/libs/core/langchain_core/tracers/evaluation.py b/libs/core/langchain_core/tracers/evaluation.py
index 7771b5b3f2..111f94433a 100644
--- a/libs/core/langchain_core/tracers/evaluation.py
+++ b/libs/core/langchain_core/tracers/evaluation.py
@@ -37,17 +37,6 @@ def wait_for_all_evaluators() -> None:
class EvaluatorCallbackHandler(BaseTracer):
"""Tracer that runs a run evaluator whenever a run is persisted.
- Args:
- evaluators : Sequence[RunEvaluator]
- The run evaluators to apply to all top level runs.
- client : LangSmith Client, optional
- The LangSmith client instance to use for evaluating the runs.
- If not specified, a new instance will be created.
- example_id : Union[UUID, str], optional
- The example ID to be associated with the runs.
- project_name : str, optional
- The LangSmith project name to be organize eval chain runs under.
-
Attributes:
example_id : Union[UUID, None]
The example ID associated with the runs.
@@ -78,6 +67,23 @@ class EvaluatorCallbackHandler(BaseTracer):
max_concurrency: Optional[int] = None,
**kwargs: Any,
) -> None:
+ """Create an EvaluatorCallbackHandler.
+
+ Args:
+ evaluators : Sequence[RunEvaluator]
+ The run evaluators to apply to all top level runs.
+ client : LangSmith Client, optional
+ The LangSmith client instance to use for evaluating the runs.
+ If not specified, a new instance will be created.
+ example_id : Union[UUID, str], optional
+ The example ID to be associated with the runs.
+ skip_unfinished: bool, optional
+ Whether to skip unfinished runs.
+ project_name : str, optional
+ The LangSmith project name to be organize eval chain runs under.
+ max_concurrency : int, optional
+ The maximum number of concurrent evaluators to run.
+ """
super().__init__(**kwargs)
self.example_id = (
UUID(example_id) if isinstance(example_id, str) else example_id
diff --git a/libs/core/langchain_core/tracers/langchain_v1.py b/libs/core/langchain_core/tracers/langchain_v1.py
index 706dfb02ed..504b74dbed 100644
--- a/libs/core/langchain_core/tracers/langchain_v1.py
+++ b/libs/core/langchain_core/tracers/langchain_v1.py
@@ -1,3 +1,8 @@
+"""This module is deprecated and will be removed in a future release.
+
+Please use LangChainTracer instead.
+"""
+
from typing import Any
diff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.py
index 1e0c26aa79..bac4bca8cc 100644
--- a/libs/core/langchain_core/tracers/log_stream.py
+++ b/libs/core/langchain_core/tracers/log_stream.py
@@ -1,3 +1,5 @@
+"""Tracer that streams run logs to a stream."""
+
from __future__ import annotations
import asyncio
@@ -16,7 +18,7 @@ from typing import (
)
import jsonpatch # type: ignore[import]
-from typing_extensions import NotRequired, TypedDict
+from typing_extensions import NotRequired, TypedDict, override
from langchain_core.load import dumps
from langchain_core.load.load import load
@@ -100,9 +102,15 @@ class RunLogPatch:
see https://jsonpatch.com for more information."""
def __init__(self, *ops: dict[str, Any]) -> None:
+ """Create a RunLogPatch.
+
+ Args:
+ *ops: The operations to apply to the state.
+ """
self.ops = list(ops)
def __add__(self, other: Union[RunLogPatch, Any]) -> RunLog:
+ """Combine two RunLogPatch instances."""
if type(other) is RunLogPatch:
ops = self.ops + other.ops
state = jsonpatch.apply_patch(None, copy.deepcopy(ops))
@@ -111,12 +119,14 @@ class RunLogPatch:
msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
raise TypeError(msg)
+ @override
def __repr__(self) -> str:
from pprint import pformat
# 1:-1 to get rid of the [] around the list
return f"RunLogPatch({pformat(self.ops)[1:-1]})"
+ @override
def __eq__(self, other: object) -> bool:
return isinstance(other, RunLogPatch) and self.ops == other.ops
@@ -128,10 +138,17 @@ class RunLog(RunLogPatch):
"""Current state of the log, obtained from applying all ops in sequence."""
def __init__(self, *ops: dict[str, Any], state: RunState) -> None:
+ """Create a RunLog.
+
+ Args:
+ *ops: The operations to apply to the state.
+ state: The initial state of the run log.
+ """
super().__init__(*ops)
self.state = state
def __add__(self, other: Union[RunLogPatch, Any]) -> RunLog:
+ """Combine two RunLogs."""
if type(other) is RunLogPatch:
ops = self.ops + other.ops
state = jsonpatch.apply_patch(self.state, other.ops)
@@ -140,12 +157,15 @@ class RunLog(RunLogPatch):
msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
raise TypeError(msg)
+ @override
def __repr__(self) -> str:
from pprint import pformat
return f"RunLog({pformat(self.state)})"
+ @override
def __eq__(self, other: object) -> bool:
+ """Check if two RunLogs are equal."""
# First compare that the state is the same
if not isinstance(other, RunLog):
return False
@@ -224,6 +244,7 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
self.root_id: Optional[UUID] = None
def __aiter__(self) -> AsyncIterator[RunLogPatch]:
+ """Iterate over the stream of run logs."""
return self.receive_stream.__aiter__()
def send(self, *ops: dict[str, Any]) -> bool:
@@ -532,7 +553,7 @@ def _get_standardized_outputs(
Standardizes the outputs based on the type of the runnable used.
Args:
- log: The log entry.
+ run: the run object.
schema_format: The schema format to use.
Returns:
diff --git a/libs/core/langchain_core/tracers/root_listeners.py b/libs/core/langchain_core/tracers/root_listeners.py
index c08861164a..c8050d4b6b 100644
--- a/libs/core/langchain_core/tracers/root_listeners.py
+++ b/libs/core/langchain_core/tracers/root_listeners.py
@@ -1,3 +1,5 @@
+"""Tracers that call listeners."""
+
from collections.abc import Awaitable
from typing import TYPE_CHECKING, Callable, Optional, Union
diff --git a/libs/core/langchain_core/tracers/stdout.py b/libs/core/langchain_core/tracers/stdout.py
index 3643724f9e..c3f5d629f1 100644
--- a/libs/core/langchain_core/tracers/stdout.py
+++ b/libs/core/langchain_core/tracers/stdout.py
@@ -1,3 +1,5 @@
+"""Tracers that print to the console."""
+
import json
from typing import Any, Callable
@@ -48,6 +50,11 @@ class FunctionCallbackHandler(BaseTracer):
Default is "function_callback_handler"."""
def __init__(self, function: Callable[[str], None], **kwargs: Any) -> None:
+ """Create a FunctionCallbackHandler.
+
+ Args:
+ function: The callback function to call.
+ """
super().__init__(**kwargs)
self.function_callback = function
@@ -192,4 +199,5 @@ class ConsoleCallbackHandler(FunctionCallbackHandler):
name: str = "console_callback_handler"
def __init__(self, **kwargs: Any) -> None:
+ """Create a ConsoleCallbackHandler."""
super().__init__(function=print, **kwargs)
diff --git a/libs/core/langchain_core/utils/_merge.py b/libs/core/langchain_core/utils/_merge.py
index 9e86777eff..806a77a59a 100644
--- a/libs/core/langchain_core/utils/_merge.py
+++ b/libs/core/langchain_core/utils/_merge.py
@@ -4,7 +4,9 @@ from typing import Any, Optional
def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:
- """Merge many dicts, handling specific scenarios where a key exists in both
+ r"""Merge dictionaries.
+
+ Merge many dicts, handling specific scenarios where a key exists in both
dictionaries but has a value of None in 'left'. In such cases, the method uses the
value from 'right' for that key in the merged dictionary.
diff --git a/libs/core/langchain_core/utils/aiter.py b/libs/core/langchain_core/utils/aiter.py
index 4e82d9fb3c..9dd658681e 100644
--- a/libs/core/langchain_core/utils/aiter.py
+++ b/libs/core/langchain_core/utils/aiter.py
@@ -1,4 +1,6 @@
-"""Adapted from
+"""Asynchronous iterator utilities.
+
+Adapted from
https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
MIT License.
"""
@@ -24,6 +26,8 @@ from typing import (
overload,
)
+from typing_extensions import override
+
T = TypeVar("T")
_no_default = object()
@@ -82,9 +86,10 @@ class NoLock:
"""Dummy lock that provides the proper interface but no protection."""
async def __aenter__(self) -> None:
- pass
+ """Do nothing."""
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
+ """Exception not handled."""
return False
@@ -188,6 +193,14 @@ class Tee(Generic[T]):
*,
lock: Optional[AbstractAsyncContextManager[Any]] = None,
):
+ """Create a ``tee``.
+
+ Args:
+ iterable: The iterable to split.
+ n: The number of iterators to create. Defaults to 2.
+ lock: The lock to synchronise access to the shared buffers.
+ Defaults to None.
+ """
self._iterator = iterable.__aiter__() # before 3.10 aiter() doesn't exist
self._buffers: list[deque[T]] = [deque() for _ in range(n)]
self._children = tuple(
@@ -201,6 +214,7 @@ class Tee(Generic[T]):
)
def __len__(self) -> int:
+ """Return the number of child iterators."""
return len(self._children)
@overload
@@ -212,15 +226,19 @@ class Tee(Generic[T]):
def __getitem__(
self, item: Union[int, slice]
) -> Union[AsyncIterator[T], tuple[AsyncIterator[T], ...]]:
+ """Return the child iterator(s) for the given index or slice."""
return self._children[item]
def __iter__(self) -> Iterator[AsyncIterator[T]]:
+ """Iterate over the child iterators."""
yield from self._children
async def __aenter__(self) -> "Tee[T]":
+ """Return the tee instance."""
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
+ """Close all child iterators."""
await self.aclose()
return False
@@ -234,8 +252,7 @@ atee = Tee
class aclosing(AbstractAsyncContextManager): # noqa: N801
- """Async context manager for safely finalizing an asynchronously cleaned-up
- resource such as an async generator, calling its ``aclose()`` method.
+ """Async context manager to wrap an AsyncGenerator that has a ``aclose()`` method.
Code like this:
@@ -255,11 +272,18 @@ class aclosing(AbstractAsyncContextManager): # noqa: N801
def __init__(
self, thing: Union[AsyncGenerator[Any, Any], AsyncIterator[Any]]
) -> None:
+ """Create the context manager.
+
+ Args:
+ thing: The resource to wrap.
+ """
self.thing = thing
+ @override
async def __aenter__(self) -> Union[AsyncGenerator[Any, Any], AsyncIterator[Any]]:
return self.thing
+ @override
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
diff --git a/libs/core/langchain_core/utils/env.py b/libs/core/langchain_core/utils/env.py
index ac018b0208..6398edc01e 100644
--- a/libs/core/langchain_core/utils/env.py
+++ b/libs/core/langchain_core/utils/env.py
@@ -1,3 +1,5 @@
+"""Utilities for environment variables."""
+
from __future__ import annotations
import os
diff --git a/libs/core/langchain_core/utils/html.py b/libs/core/langchain_core/utils/html.py
index 3b7a3b1896..15f39ee20c 100644
--- a/libs/core/langchain_core/utils/html.py
+++ b/libs/core/langchain_core/utils/html.py
@@ -1,3 +1,5 @@
+"""Utilities for working with HTML."""
+
import logging
import re
from collections.abc import Sequence
diff --git a/libs/core/langchain_core/utils/image.py b/libs/core/langchain_core/utils/image.py
index f46ee599d3..8931f0bc2e 100644
--- a/libs/core/langchain_core/utils/image.py
+++ b/libs/core/langchain_core/utils/image.py
@@ -1,3 +1,5 @@
+"""Utilities for image processing."""
+
from typing import Any
diff --git a/libs/core/langchain_core/utils/interactive_env.py b/libs/core/langchain_core/utils/interactive_env.py
index 7752b6b403..12676d0bd5 100644
--- a/libs/core/langchain_core/utils/interactive_env.py
+++ b/libs/core/langchain_core/utils/interactive_env.py
@@ -1,3 +1,6 @@
+"""Utilities for working with interactive environments."""
+
+
def is_interactive_env() -> bool:
"""Determine if running within IPython or Jupyter."""
import sys
diff --git a/libs/core/langchain_core/utils/iter.py b/libs/core/langchain_core/utils/iter.py
index 7868119cae..445280dff3 100644
--- a/libs/core/langchain_core/utils/iter.py
+++ b/libs/core/langchain_core/utils/iter.py
@@ -1,3 +1,5 @@
+"""Utilities for working with iterators."""
+
from collections import deque
from collections.abc import Generator, Iterable, Iterator
from contextlib import AbstractContextManager
@@ -20,9 +22,10 @@ class NoLock:
"""Dummy lock that provides the proper interface but no protection."""
def __enter__(self) -> None:
- pass
+ """Do nothing."""
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Literal[False]:
+ """Exception not handled."""
return False
@@ -126,7 +129,7 @@ class Tee(Generic[T]):
*,
lock: Optional[AbstractContextManager[Any]] = None,
):
- """Create a new ``tee``.
+ """Create a ``tee``.
Args:
iterable: The iterable to split.
@@ -147,6 +150,7 @@ class Tee(Generic[T]):
)
def __len__(self) -> int:
+ """Return the number of child iterators."""
return len(self._children)
@overload
@@ -158,19 +162,24 @@ class Tee(Generic[T]):
def __getitem__(
self, item: Union[int, slice]
) -> Union[Iterator[T], tuple[Iterator[T], ...]]:
+ """Return the child iterator(s) at the given index or slice."""
return self._children[item]
def __iter__(self) -> Iterator[Iterator[T]]:
+ """Return an iterator over the child iterators."""
yield from self._children
def __enter__(self) -> "Tee[T]":
+ """Return Tee instance."""
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Literal[False]:
+ """Close all child iterators."""
self.close()
return False
def close(self) -> None:
+ """Close all child iterators."""
for child in self._children:
child.close()
diff --git a/libs/core/langchain_core/utils/json.py b/libs/core/langchain_core/utils/json.py
index 28154c62b9..c9972a6e8d 100644
--- a/libs/core/langchain_core/utils/json.py
+++ b/libs/core/langchain_core/utils/json.py
@@ -1,3 +1,5 @@
+"""Utilities for JSON."""
+
from __future__ import annotations
import json
@@ -18,7 +20,9 @@ def _replace_new_line(match: re.Match[str]) -> str:
def _custom_parser(multiline_string: str) -> str:
- """The LLM response for `action_input` may be a multiline
+ r"""Custom parser for multiline strings.
+
+ The LLM response for `action_input` may be a multiline
string containing unescaped newlines, tabs or quotes. This function
replaces those characters with their escaped counterparts.
(newlines in JSON must be double-escaped: `\\n`).
@@ -132,6 +136,7 @@ def parse_json_markdown(
Args:
json_string: The Markdown string.
+ parser: The parser to use. Defaults to `parse_partial_json`.
Returns:
The parsed JSON object as a Python dictionary.
@@ -165,8 +170,9 @@ def _parse_json(
def parse_and_check_json_markdown(text: str, expected_keys: list[str]) -> dict:
- """Parse a JSON string from a Markdown string and check that it
- contains the expected keys.
+ """Parse and check a JSON string from a Markdown string.
+
+ Checks that it contains the expected keys.
Args:
text: The Markdown string.
diff --git a/libs/core/langchain_core/utils/json_schema.py b/libs/core/langchain_core/utils/json_schema.py
index 72f20c38d2..a55ae4b104 100644
--- a/libs/core/langchain_core/utils/json_schema.py
+++ b/libs/core/langchain_core/utils/json_schema.py
@@ -1,3 +1,5 @@
+"""Utilities for JSON Schema."""
+
from __future__ import annotations
from copy import deepcopy
diff --git a/libs/core/langchain_core/utils/loading.py b/libs/core/langchain_core/utils/loading.py
index ae911c4f4d..27db390a16 100644
--- a/libs/core/langchain_core/utils/loading.py
+++ b/libs/core/langchain_core/utils/loading.py
@@ -19,6 +19,7 @@ def try_load_from_hub(
*args: Any,
**kwargs: Any,
) -> Any:
+ """[DEPRECATED] Try to load from the old Hub."""
warnings.warn(
"Loading from the deprecated github-based Hub is no longer supported. "
"Please use the new LangChain Hub at https://smith.langchain.com/hub instead.",
diff --git a/libs/core/langchain_core/utils/mustache.py b/libs/core/langchain_core/utils/mustache.py
index 2cc2a4a336..3f631efe0f 100644
--- a/libs/core/langchain_core/utils/mustache.py
+++ b/libs/core/langchain_core/utils/mustache.py
@@ -1,4 +1,5 @@
-"""Adapted from https://github.com/noahmorrison/chevron
+"""Adapted from https://github.com/noahmorrison/chevron.
+
MIT License.
"""
diff --git a/libs/core/langchain_core/utils/strings.py b/libs/core/langchain_core/utils/strings.py
index e7a79761f9..aa6199d2bc 100644
--- a/libs/core/langchain_core/utils/strings.py
+++ b/libs/core/langchain_core/utils/strings.py
@@ -1,3 +1,5 @@
+"""String utilities."""
+
from typing import Any
diff --git a/libs/core/langchain_core/utils/usage.py b/libs/core/langchain_core/utils/usage.py
index 38c38209a5..95ee2ca063 100644
--- a/libs/core/langchain_core/utils/usage.py
+++ b/libs/core/langchain_core/utils/usage.py
@@ -1,3 +1,5 @@
+"""Usage utilities."""
+
from typing import Callable
diff --git a/libs/core/langchain_core/utils/utils.py b/libs/core/langchain_core/utils/utils.py
index 17114268ed..1a3ad0acb8 100644
--- a/libs/core/langchain_core/utils/utils.py
+++ b/libs/core/langchain_core/utils/utils.py
@@ -115,8 +115,9 @@ def mock_now(dt_value: datetime.datetime) -> Iterator[type]:
def guard_import(
module_name: str, *, pip_name: Optional[str] = None, package: Optional[str] = None
) -> Any:
- """Dynamically import a module and raise an exception if the module is not
- installed.
+ """Dynamically import a module.
+
+ Raise an exception if the module is not installed.
Args:
module_name (str): The name of the module to import.
diff --git a/libs/core/langchain_core/vectorstores/__init__.py b/libs/core/langchain_core/vectorstores/__init__.py
index c80958679f..632d530962 100644
--- a/libs/core/langchain_core/vectorstores/__init__.py
+++ b/libs/core/langchain_core/vectorstores/__init__.py
@@ -1,3 +1,5 @@
+"""Vector stores."""
+
from langchain_core.vectorstores.base import VST, VectorStore, VectorStoreRetriever
from langchain_core.vectorstores.in_memory import InMemoryVectorStore
diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.py
index 41e14dbed4..4492a4ac9f 100644
--- a/libs/core/langchain_core/vectorstores/base.py
+++ b/libs/core/langchain_core/vectorstores/base.py
@@ -294,8 +294,7 @@ class VectorStore(ABC):
async def aadd_documents(
self, documents: list[Document], **kwargs: Any
) -> list[str]:
- """Async run more documents through the embeddings and add to
- the vectorstore.
+ """Async run more documents through the embeddings and add to the vectorstore.
Args:
documents: Documents to add to the vectorstore.
@@ -434,7 +433,8 @@ class VectorStore(ABC):
return -1.0 * distance
def _select_relevance_score_fn(self) -> Callable[[float], float]:
- """The 'correct' relevance function
+ """The 'correct' relevance function.
+
may differ depending on a few things, including:
- the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
@@ -484,8 +484,9 @@ class VectorStore(ABC):
k: int = 4,
**kwargs: Any,
) -> list[tuple[Document, float]]:
- """Default similarity search with relevance scores. Modify if necessary
- in subclass.
+ """Default similarity search with relevance scores.
+
+ Modify if necessary in subclass.
Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
@@ -510,8 +511,9 @@ class VectorStore(ABC):
k: int = 4,
**kwargs: Any,
) -> list[tuple[Document, float]]:
- """Default similarity search with relevance scores. Modify if necessary
- in subclass.
+ """Default similarity search with relevance scores.
+
+ Modify if necessary in subclass.
Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
@@ -732,6 +734,7 @@ class VectorStore(ABC):
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
+ **kwargs: Arguments to pass to the search method.
Returns:
List of Documents selected by maximal marginal relevance.
diff --git a/libs/core/langchain_core/vectorstores/in_memory.py b/libs/core/langchain_core/vectorstores/in_memory.py
index daf1dcdfc6..a8b9f3e3d3 100644
--- a/libs/core/langchain_core/vectorstores/in_memory.py
+++ b/libs/core/langchain_core/vectorstores/in_memory.py
@@ -1,3 +1,5 @@
+"""In-memory vector store."""
+
from __future__ import annotations
import json
@@ -10,6 +12,8 @@ from typing import (
Optional,
)
+from typing_extensions import override
+
from langchain_core._api import deprecated
from langchain_core.documents import Document
from langchain_core.load import dumpd, load
@@ -165,17 +169,21 @@ class InMemoryVectorStore(VectorStore):
self.embedding = embedding
@property
+ @override
def embeddings(self) -> Embeddings:
return self.embedding
+ @override
def delete(self, ids: Optional[Sequence[str]] = None, **kwargs: Any) -> None:
if ids:
for _id in ids:
self.store.pop(_id, None)
+ @override
async def adelete(self, ids: Optional[Sequence[str]] = None, **kwargs: Any) -> None:
self.delete(ids)
+ @override
def add_documents(
self,
documents: list[Document],
@@ -212,6 +220,7 @@ class InMemoryVectorStore(VectorStore):
return ids_
+ @override
async def aadd_documents(
self, documents: list[Document], ids: Optional[list[str]] = None, **kwargs: Any
) -> list[str]:
@@ -244,6 +253,7 @@ class InMemoryVectorStore(VectorStore):
return ids_
+ @override
def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
"""Get documents by their ids.
@@ -276,6 +286,14 @@ class InMemoryVectorStore(VectorStore):
removal="1.0",
)
def upsert(self, items: Sequence[Document], /, **kwargs: Any) -> UpsertResponse:
+ """[DEPRECATED] Upsert documents into the store.
+
+ Args:
+ items: The documents to upsert.
+
+ Returns:
+ The upsert response.
+ """
vectors = self.embedding.embed_documents([item.page_content for item in items])
ids = []
for item, vector in zip(items, vectors):
@@ -303,6 +321,14 @@ class InMemoryVectorStore(VectorStore):
async def aupsert(
self, items: Sequence[Document], /, **kwargs: Any
) -> UpsertResponse:
+ """[DEPRECATED] Upsert documents into the store.
+
+ Args:
+ items: The documents to upsert.
+
+ Returns:
+ The upsert response.
+ """
vectors = await self.embedding.aembed_documents(
[item.page_content for item in items]
)
@@ -321,6 +347,7 @@ class InMemoryVectorStore(VectorStore):
"failed": [],
}
+ @override
async def aget_by_ids(self, ids: Sequence[str], /) -> list[Document]:
"""Async get documents by their ids.
@@ -379,6 +406,16 @@ class InMemoryVectorStore(VectorStore):
filter: Optional[Callable[[Document], bool]] = None,
**kwargs: Any,
) -> list[tuple[Document, float]]:
+ """Search for the most similar documents to the given embedding.
+
+ Args:
+ embedding: The embedding to search for.
+ k: The number of documents to return.
+ filter: A function to filter the documents.
+
+ Returns:
+ A list of tuples of Document objects and their similarity scores.
+ """
return [
(doc, similarity)
for doc, similarity, _ in self._similarity_search_with_score_by_vector(
@@ -386,6 +423,7 @@ class InMemoryVectorStore(VectorStore):
)
]
+ @override
def similarity_search_with_score(
self,
query: str,
@@ -400,6 +438,7 @@ class InMemoryVectorStore(VectorStore):
)
return docs
+ @override
async def asimilarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> list[tuple[Document, float]]:
@@ -411,6 +450,7 @@ class InMemoryVectorStore(VectorStore):
)
return docs
+ @override
def similarity_search_by_vector(
self,
embedding: list[float],
@@ -424,16 +464,19 @@ class InMemoryVectorStore(VectorStore):
)
return [doc for doc, _ in docs_and_scores]
+ @override
async def asimilarity_search_by_vector(
self, embedding: list[float], k: int = 4, **kwargs: Any
) -> list[Document]:
return self.similarity_search_by_vector(embedding, k, **kwargs)
+ @override
def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> list[Document]:
return [doc for doc, _ in self.similarity_search_with_score(query, k, **kwargs)]
+ @override
async def asimilarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> list[Document]:
@@ -442,6 +485,7 @@ class InMemoryVectorStore(VectorStore):
for doc, _ in await self.asimilarity_search_with_score(query, k, **kwargs)
]
+ @override
def max_marginal_relevance_search_by_vector(
self,
embedding: list[float],
@@ -473,6 +517,7 @@ class InMemoryVectorStore(VectorStore):
)
return [prefetch_hits[idx][0] for idx in mmr_chosen_indices]
+ @override
def max_marginal_relevance_search(
self,
query: str,
@@ -490,6 +535,7 @@ class InMemoryVectorStore(VectorStore):
**kwargs,
)
+ @override
async def amax_marginal_relevance_search(
self,
query: str,
@@ -508,6 +554,7 @@ class InMemoryVectorStore(VectorStore):
)
@classmethod
+ @override
def from_texts(
cls,
texts: list[str],
@@ -522,6 +569,7 @@ class InMemoryVectorStore(VectorStore):
return store
@classmethod
+ @override
async def afrom_texts(
cls,
texts: list[str],
diff --git a/libs/core/pyproject.toml b/libs/core/pyproject.toml
index a2d8113c24..93f3494d99 100644
--- a/libs/core/pyproject.toml
+++ b/libs/core/pyproject.toml
@@ -94,7 +94,6 @@ ignore = [
"ANN401",
"ARG",
"BLE",
- "D",
"ERA",
"DTZ",
"FBT",
@@ -116,6 +115,8 @@ ignore = [
flake8-type-checking.runtime-evaluated-base-classes = ["pydantic.BaseModel","langchain_core.load.serializable.Serializable","langchain_core.runnables.base.RunnableSerializable"]
flake8-annotations.allow-star-arg-any = true
flake8-annotations.mypy-init-return = true
+pydocstyle.convention = "google"
+pydocstyle.ignore-var-parameters = true
[tool.coverage.run]
omit = [ "tests/*",]
@@ -135,5 +136,5 @@ classmethod-decorators = [ "classmethod", "langchain_core.utils.pydantic.pre_ini
"tests/unit_tests/prompts/test_chat.py" = [ "E501",]
"tests/unit_tests/runnables/test_runnable.py" = [ "E501",]
"tests/unit_tests/runnables/test_graph.py" = [ "E501",]
-"tests/**" = [ "S",]
+"tests/**" = [ "D", "S",]
"scripts/**" = [ "INP", "S",]
diff --git a/libs/core/scripts/check_imports.py b/libs/core/scripts/check_imports.py
index fa189a7117..f64c91a541 100644
--- a/libs/core/scripts/check_imports.py
+++ b/libs/core/scripts/check_imports.py
@@ -1,3 +1,5 @@
+"""Script to check if python modules can be imported."""
+
import random
import string
import sys
diff --git a/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr b/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr
index cadfa74d9a..b1519bc3f7 100644
--- a/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr
+++ b/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr
@@ -3743,6 +3743,7 @@
'ChatPromptValueConcrete': dict({
'description': '''
Chat prompt value which explicitly lists out the message types it accepts.
+
For use in external schemas.
''',
'properties': dict({
@@ -5247,6 +5248,7 @@
'ChatPromptValueConcrete': dict({
'description': '''
Chat prompt value which explicitly lists out the message types it accepts.
+
For use in external schemas.
''',
'properties': dict({
@@ -8142,6 +8144,7 @@
'ChatPromptValueConcrete': dict({
'description': '''
Chat prompt value which explicitly lists out the message types it accepts.
+
For use in external schemas.
''',
'properties': dict({
@@ -10990,6 +10993,7 @@
'ChatPromptValueConcrete': dict({
'description': '''
Chat prompt value which explicitly lists out the message types it accepts.
+
For use in external schemas.
''',
'properties': dict({
@@ -12455,6 +12459,7 @@
'ChatPromptValueConcrete': dict({
'description': '''
Chat prompt value which explicitly lists out the message types it accepts.
+
For use in external schemas.
''',
'properties': dict({
diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.py
index f65e68bc13..95594ea925 100644
--- a/libs/core/tests/unit_tests/test_tools.py
+++ b/libs/core/tests/unit_tests/test_tools.py
@@ -137,7 +137,7 @@ def test_structured_args() -> None:
def test_misannotated_base_tool_raises_error() -> None:
- """Test that a BaseTool with the incorrect typehint raises an exception.""" ""
+ """Test that a BaseTool with the incorrect typehint raises an exception."""
with pytest.raises(SchemaAnnotationError):
class _MisAnnotatedTool(BaseTool):
@@ -156,7 +156,7 @@ def test_misannotated_base_tool_raises_error() -> None:
def test_forward_ref_annotated_base_tool_accepted() -> None:
- """Test that a using forward ref annotation syntax is accepted.""" ""
+ """Test that a using forward ref annotation syntax is accepted."""
class _ForwardRefAnnotatedTool(BaseTool):
name: str = "structured_api"
@@ -1309,7 +1309,8 @@ def test_docstring_parsing() -> None:
def test_tool_invalid_docstrings() -> None:
- # Test invalid docstrings
+ """Test invalid docstrings"""
+
def foo3(bar: str, baz: int) -> str:
"""The foo."""
return bar
@@ -1524,7 +1525,7 @@ def test_convert_from_runnable_other() -> None:
@tool("foo", parse_docstring=True)
def injected_tool(x: int, y: Annotated[str, InjectedToolArg]) -> str:
- """foo.
+ """Foo.
Args:
x: abc
@@ -1538,7 +1539,7 @@ class InjectedTool(BaseTool):
description: str = "foo."
def _run(self, x: int, y: Annotated[str, InjectedToolArg]) -> Any:
- """foo.
+ """Foo.
Args:
x: abc
@@ -1574,7 +1575,7 @@ def injected_tool_with_schema(x: int, y: str) -> str:
def test_tool_injected_arg_without_schema(tool_: BaseTool) -> None:
assert _schema(tool_.get_input_schema()) == {
"title": "foo",
- "description": "foo.\n\nArgs:\n x: abc\n y: 123",
+ "description": "Foo.\n\nArgs:\n x: abc\n y: 123",
"type": "object",
"properties": {
"x": {"title": "X", "type": "integer"},
@@ -1667,7 +1668,7 @@ def test_tool_injected_arg() -> None:
tool_ = injected_tool
assert _schema(tool_.get_input_schema()) == {
"title": "foo",
- "description": "foo.",
+ "description": "Foo.",
"type": "object",
"properties": {
"x": {"description": "abc", "title": "X", "type": "integer"},
@@ -1677,7 +1678,7 @@ def test_tool_injected_arg() -> None:
}
assert _schema(tool_.tool_call_schema) == {
"title": "foo",
- "description": "foo.",
+ "description": "Foo.",
"type": "object",
"properties": {"x": {"description": "abc", "title": "X", "type": "integer"}},
"required": ["x"],
@@ -1699,7 +1700,7 @@ def test_tool_injected_arg() -> None:
assert convert_to_openai_function(tool_) == {
"name": "foo",
- "description": "foo.",
+ "description": "Foo.",
"parameters": {
"type": "object",
"properties": {"x": {"type": "integer", "description": "abc"}},