The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
core: Add ruff rules TC (#29268)
Christophe Bornetb3885c124fea
diff --git a/libs/core/langchain_core/callbacks/base.py b/libs/core/langchain_core/callbacks/base.pyindex 98fd824ec1..1c0fd19de5 100644--- a/libs/core/langchain_core/callbacks/base.py+++ b/libs/core/langchain_core/callbacks/base.py@@ -3,13 +3,14 @@from __future__ import annotationsimport logging-from collections.abc import Sequencefrom typing import TYPE_CHECKING, Any, Optional, TypeVar, Union-from uuid import UUID--from tenacity import RetryCallStateif TYPE_CHECKING:+ from collections.abc import Sequence+ from uuid import UUID++ from tenacity import RetryCallState+from langchain_core.agents import AgentAction, AgentFinishfrom langchain_core.documents import Documentfrom langchain_core.messages import BaseMessagediff --git a/libs/core/langchain_core/callbacks/file.py b/libs/core/langchain_core/callbacks/file.pyindex 961b0c9bc2..f7fe7e0959 100644--- a/libs/core/langchain_core/callbacks/file.py+++ b/libs/core/langchain_core/callbacks/file.py@@ -2,12 +2,14 @@from __future__ import annotations-from typing import Any, Optional, TextIO, cast+from typing import TYPE_CHECKING, Any, Optional, TextIO, cast-from langchain_core.agents import AgentAction, AgentFinishfrom langchain_core.callbacks import BaseCallbackHandlerfrom langchain_core.utils.input import print_text+if TYPE_CHECKING:+ from langchain_core.agents import AgentAction, AgentFinish+class FileCallbackHandler(BaseCallbackHandler):"""Callback Handler that writes to a file.diff --git a/libs/core/langchain_core/callbacks/manager.py b/libs/core/langchain_core/callbacks/manager.pyindex f675b230c8..689003de3e 100644--- a/libs/core/langchain_core/callbacks/manager.py+++ b/libs/core/langchain_core/callbacks/manager.py@@ -5,7 +5,6 @@ import functoolsimport loggingimport uuidfrom abc import ABC, abstractmethod-from collections.abc import AsyncGenerator, Coroutine, Generator, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanager, contextmanagerfrom contextvars import copy_context@@ -21,7 +20,6 @@ from typing import (from uuid import UUIDfrom langsmith.run_helpers import get_tracing_context-from tenacity import RetryCallStatefrom langchain_core.callbacks.base import (BaseCallbackHandler,@@ -39,6 +37,10 @@ from langchain_core.tracers.schemas import Runfrom langchain_core.utils.env import env_var_is_setif TYPE_CHECKING:+ from collections.abc import AsyncGenerator, Coroutine, Generator, Sequence++ from tenacity import RetryCallState+from langchain_core.agents import AgentAction, AgentFinishfrom langchain_core.documents import Documentfrom langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResultdiff --git a/libs/core/langchain_core/chat_history.py b/libs/core/langchain_core/chat_history.pyindex 1b5c1e7f78..9e74dfca2b 100644--- a/libs/core/langchain_core/chat_history.py+++ b/libs/core/langchain_core/chat_history.py@@ -17,8 +17,7 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Sequence-from typing import Union+from typing import TYPE_CHECKING, Unionfrom pydantic import BaseModel, Field@@ -29,6 +28,9 @@ from langchain_core.messages import (get_buffer_string,)+if TYPE_CHECKING:+ from collections.abc import Sequence+class BaseChatMessageHistory(ABC):"""Abstract base class for storing chat message history.diff --git a/libs/core/langchain_core/document_loaders/base.py b/libs/core/langchain_core/document_loaders/base.pyindex b2cd20038e..d889fbec8f 100644--- a/libs/core/langchain_core/document_loaders/base.py+++ b/libs/core/langchain_core/document_loaders/base.py@@ -3,16 +3,17 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import AsyncIterator, Iteratorfrom typing import TYPE_CHECKING, Optional-from langchain_core.documents import Documentfrom langchain_core.runnables import run_in_executorif TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator+from langchain_text_splitters import TextSplitter-from langchain_core.documents.base import Blob+ from langchain_core.documents import Document+ from langchain_core.documents.base import Blobclass BaseLoader(ABC): # noqa: B024diff --git a/libs/core/langchain_core/document_loaders/blob_loaders.py b/libs/core/langchain_core/document_loaders/blob_loaders.pyindex 3c0d1986f7..098c325a50 100644--- a/libs/core/langchain_core/document_loaders/blob_loaders.py+++ b/libs/core/langchain_core/document_loaders/blob_loaders.py@@ -8,12 +8,15 @@ In addition, content loading code should provide a lazy loading interface by deffrom __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Iterable+from typing import TYPE_CHECKING# Re-export Blob and PathLike for backwards compatibilityfrom langchain_core.documents.base import Blob as Blobfrom langchain_core.documents.base import PathLike as PathLike+if TYPE_CHECKING:+ from collections.abc import Iterable+class BlobLoader(ABC):"""Abstract interface for blob loaders implementation.diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.pyindex 2adfe1a718..fb4fcd0987 100644--- a/libs/core/langchain_core/documents/base.py+++ b/libs/core/langchain_core/documents/base.py@@ -2,15 +2,17 @@ from __future__ import annotationsimport contextlibimport mimetypes-from collections.abc import Generatorfrom io import BufferedReader, BytesIOfrom pathlib import PurePath-from typing import Any, Literal, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Literal, Optional, Union, castfrom pydantic import ConfigDict, Field, field_validator, model_validatorfrom langchain_core.load.serializable import Serializable+if TYPE_CHECKING:+ from collections.abc import Generator+PathLike = Union[str, PurePath]diff --git a/libs/core/langchain_core/documents/compressor.py b/libs/core/langchain_core/documents/compressor.pyindex 31ae2901a7..3c9217e4f7 100644--- a/libs/core/langchain_core/documents/compressor.py+++ b/libs/core/langchain_core/documents/compressor.py@@ -1,15 +1,18 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Sequence-from typing import Optional+from typing import TYPE_CHECKING, Optionalfrom pydantic import BaseModel-from langchain_core.callbacks import Callbacks-from langchain_core.documents import Documentfrom langchain_core.runnables import run_in_executor+if TYPE_CHECKING:+ from collections.abc import Sequence++ from langchain_core.callbacks import Callbacks+ from langchain_core.documents import Document+class BaseDocumentCompressor(BaseModel, ABC):"""Base class for document compressors.diff --git a/libs/core/langchain_core/documents/transformers.py b/libs/core/langchain_core/documents/transformers.pyindex 12167f820f..5be5e98c06 100644--- a/libs/core/langchain_core/documents/transformers.py+++ b/libs/core/langchain_core/documents/transformers.py@@ -1,12 +1,13 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Sequencefrom typing import TYPE_CHECKING, Anyfrom langchain_core.runnables.config import run_in_executorif TYPE_CHECKING:+ from collections.abc import Sequence+from langchain_core.documents import Documentdiff --git a/libs/core/langchain_core/example_selectors/semantic_similarity.py b/libs/core/langchain_core/example_selectors/semantic_similarity.pyindex b27122ec36..cd6f82bc8c 100644--- a/libs/core/langchain_core/example_selectors/semantic_similarity.py+++ b/libs/core/langchain_core/example_selectors/semantic_similarity.py@@ -7,11 +7,11 @@ from typing import TYPE_CHECKING, Any, Optionalfrom pydantic import BaseModel, ConfigDict-from langchain_core.documents import Documentfrom langchain_core.example_selectors.base import BaseExampleSelectorfrom langchain_core.vectorstores import VectorStoreif TYPE_CHECKING:+ from langchain_core.documents import Documentfrom langchain_core.embeddings import Embeddingsdiff --git a/libs/core/langchain_core/indexing/base.py b/libs/core/langchain_core/indexing/base.pyindex d2a7d09e58..62e0a720c0 100644--- a/libs/core/langchain_core/indexing/base.py+++ b/libs/core/langchain_core/indexing/base.py@@ -3,14 +3,17 @@ from __future__ import annotationsimport abcimport timefrom abc import ABC, abstractmethod-from collections.abc import Sequence-from typing import Any, Optional, TypedDict+from typing import TYPE_CHECKING, Any, Optional, TypedDictfrom langchain_core._api import beta-from langchain_core.documents import Documentfrom langchain_core.retrievers import BaseRetrieverfrom langchain_core.runnables import run_in_executor+if TYPE_CHECKING:+ from collections.abc import Sequence++ from langchain_core.documents import Document+class RecordManager(ABC):"""Abstract base class representing the interface for a record manager.diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.pyindex 1bba3ffd5c..d380833ae4 100644--- a/libs/core/langchain_core/language_models/chat_models.py+++ b/libs/core/langchain_core/language_models/chat_models.py@@ -4,7 +4,6 @@ import asyncioimport inspectimport jsonimport typing-import uuidimport warningsfrom abc import ABC, abstractmethodfrom collections.abc import AsyncIterator, Iterator, Sequence@@ -70,6 +69,8 @@ from langchain_core.utils.function_calling import convert_to_openai_toolfrom langchain_core.utils.pydantic import TypeBaseModel, is_basemodel_subclassif TYPE_CHECKING:+ import uuid+from langchain_core.output_parsers.base import OutputParserLikefrom langchain_core.runnables import Runnable, RunnableConfigfrom langchain_core.tools import BaseTooldiff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.pyindex 4ba16f5169..9af4d4e9ac 100644--- a/libs/core/langchain_core/language_models/llms.py+++ b/libs/core/langchain_core/language_models/llms.py@@ -7,12 +7,12 @@ import functoolsimport inspectimport jsonimport logging-import uuidimport warningsfrom abc import ABC, abstractmethodfrom collections.abc import AsyncIterator, Iterator, Sequencefrom pathlib import Pathfrom typing import (+ TYPE_CHECKING,Any,Callable,Optional,@@ -61,6 +61,9 @@ from langchain_core.prompt_values import ChatPromptValue, PromptValue, StringProfrom langchain_core.runnables import RunnableConfig, ensure_config, get_config_listfrom langchain_core.runnables.config import run_in_executor+if TYPE_CHECKING:+ import uuid+logger = logging.getLogger(__name__)diff --git a/libs/core/langchain_core/messages/base.py b/libs/core/langchain_core/messages/base.pyindex 5614f6fb7d..a4693e48c3 100644--- a/libs/core/langchain_core/messages/base.py+++ b/libs/core/langchain_core/messages/base.py@@ -1,6 +1,5 @@from __future__ import annotations-from collections.abc import Sequencefrom typing import TYPE_CHECKING, Any, Optional, Union, castfrom pydantic import ConfigDict, Field, field_validator@@ -11,6 +10,8 @@ from langchain_core.utils._merge import merge_dicts, merge_listsfrom langchain_core.utils.interactive_env import is_interactive_envif TYPE_CHECKING:+ from collections.abc import Sequence+from langchain_core.prompts.chat import ChatPromptTemplatediff --git a/libs/core/langchain_core/output_parsers/list.py b/libs/core/langchain_core/output_parsers/list.pyindex bedbdf47b7..6977079f5a 100644--- a/libs/core/langchain_core/output_parsers/list.py+++ b/libs/core/langchain_core/output_parsers/list.py@@ -4,14 +4,16 @@ import csvimport refrom abc import abstractmethodfrom collections import deque-from collections.abc import AsyncIterator, Iteratorfrom io import StringIO+from typing import TYPE_CHECKING, TypeVar, Unionfrom typing import Optional as Optional-from typing import TypeVar, Unionfrom langchain_core.messages import BaseMessagefrom langchain_core.output_parsers.transform import BaseTransformOutputParser+if TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator+T = TypeVar("T")diff --git a/libs/core/langchain_core/output_parsers/transform.py b/libs/core/langchain_core/output_parsers/transform.pyindex 0636d2d661..d484b6d06c 100644--- a/libs/core/langchain_core/output_parsers/transform.py+++ b/libs/core/langchain_core/output_parsers/transform.py@@ -1,6 +1,5 @@from __future__ import annotations-from collections.abc import AsyncIterator, Iteratorfrom typing import (TYPE_CHECKING,Any,@@ -19,6 +18,8 @@ from langchain_core.outputs import (from langchain_core.runnables.config import run_in_executorif TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator+from langchain_core.runnables import RunnableConfigdiff --git a/libs/core/langchain_core/outputs/chat_generation.py b/libs/core/langchain_core/outputs/chat_generation.pyindex d40e1fd536..9eac7514d4 100644--- a/libs/core/langchain_core/outputs/chat_generation.py+++ b/libs/core/langchain_core/outputs/chat_generation.py@@ -1,14 +1,16 @@from __future__ import annotations-from typing import Literal, Union+from typing import TYPE_CHECKING, Literal, Unionfrom pydantic import model_validator-from typing_extensions import Selffrom langchain_core.messages import BaseMessage, BaseMessageChunkfrom langchain_core.outputs.generation import Generationfrom langchain_core.utils._merge import merge_dicts+if TYPE_CHECKING:+ from typing_extensions import Self+class ChatGeneration(Generation):"""A single chat generation output.diff --git a/libs/core/langchain_core/prompts/chat.py b/libs/core/langchain_core/prompts/chat.pyindex 80d427c8be..c819bbe06d 100644--- a/libs/core/langchain_core/prompts/chat.py+++ b/libs/core/langchain_core/prompts/chat.py@@ -3,9 +3,8 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Sequence-from pathlib import Pathfrom typing import (+ TYPE_CHECKING,Annotated,Any,Optional,@@ -47,6 +46,10 @@ from langchain_core.prompts.string import (from langchain_core.utils import get_colored_textfrom langchain_core.utils.interactive_env import is_interactive_env+if TYPE_CHECKING:+ from collections.abc import Sequence+ from pathlib import Path+class BaseMessagePromptTemplate(Serializable, ABC):"""Base class for message prompt templates."""diff --git a/libs/core/langchain_core/prompts/few_shot.py b/libs/core/langchain_core/prompts/few_shot.pyindex 5794a91332..f14699b47b 100644--- a/libs/core/langchain_core/prompts/few_shot.py+++ b/libs/core/langchain_core/prompts/few_shot.py@@ -2,8 +2,7 @@from __future__ import annotations-from pathlib import Path-from typing import Any, Literal, Optional, Union+from typing import TYPE_CHECKING, Any, Literal, Optional, Unionfrom pydantic import (BaseModel,@@ -11,7 +10,6 @@ from pydantic import (Field,model_validator,)-from typing_extensions import Selffrom langchain_core.example_selectors import BaseExampleSelectorfrom langchain_core.messages import BaseMessage, get_buffer_string@@ -27,6 +25,11 @@ from langchain_core.prompts.string import (get_template_variables,)+if TYPE_CHECKING:+ from pathlib import Path++ from typing_extensions import Self+class _FewShotPromptTemplateMixin(BaseModel):"""Prompt template that contains few shot examples."""diff --git a/libs/core/langchain_core/prompts/prompt.py b/libs/core/langchain_core/prompts/prompt.pyindex 37f7eda64a..888fc9ccbc 100644--- a/libs/core/langchain_core/prompts/prompt.py+++ b/libs/core/langchain_core/prompts/prompt.py@@ -3,8 +3,7 @@from __future__ import annotationsimport warnings-from pathlib import Path-from typing import Any, Optional, Union+from typing import TYPE_CHECKING, Any, Optional, Unionfrom pydantic import BaseModel, model_validator@@ -16,7 +15,11 @@ from langchain_core.prompts.string import (get_template_variables,mustache_schema,)-from langchain_core.runnables.config import RunnableConfig++if TYPE_CHECKING:+ from pathlib import Path++ from langchain_core.runnables.config import RunnableConfigclass PromptTemplate(StringPromptTemplate):diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.pyindex 1840e3dbe7..33f1213777 100644--- a/libs/core/langchain_core/runnables/base.py+++ b/libs/core/langchain_core/runnables/base.py@@ -60,7 +60,6 @@ from langchain_core.runnables.config import (run_in_executor,)from langchain_core.runnables.graph import Graph-from langchain_core.runnables.schema import StreamEventfrom langchain_core.runnables.utils import (AddableDict,AnyConfigurableField,@@ -94,6 +93,7 @@ if TYPE_CHECKING:from langchain_core.runnables.fallbacks import (RunnableWithFallbacks as RunnableWithFallbacksT,)+ from langchain_core.runnables.schema import StreamEventfrom langchain_core.tools import BaseToolfrom langchain_core.tracers.log_stream import (RunLog,diff --git a/libs/core/langchain_core/runnables/configurable.py b/libs/core/langchain_core/runnables/configurable.pyindex b59d0239fb..79473e5d26 100644--- a/libs/core/langchain_core/runnables/configurable.py+++ b/libs/core/langchain_core/runnables/configurable.py@@ -7,6 +7,7 @@ from collections.abc import AsyncIterator, Iterator, Sequencefrom collections.abc import Mapping as Mappingfrom functools import wrapsfrom typing import (+ TYPE_CHECKING,Any,Callable,Optional,@@ -26,7 +27,6 @@ from langchain_core.runnables.config import (get_executor_for_config,merge_configs,)-from langchain_core.runnables.graph import Graphfrom langchain_core.runnables.utils import (AnyConfigurableField,ConfigurableField,@@ -39,6 +39,9 @@ from langchain_core.runnables.utils import (get_unique_config_specs,)+if TYPE_CHECKING:+ from langchain_core.runnables.graph import Graph+class DynamicRunnable(RunnableSerializable[Input, Output]):"""Serializable Runnable that can be dynamically configured.diff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.pyindex 84b86994db..99bcae5abf 100644--- a/libs/core/langchain_core/runnables/graph.py+++ b/libs/core/langchain_core/runnables/graph.py@@ -2,7 +2,6 @@ from __future__ import annotationsimport inspectfrom collections import defaultdict-from collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import (@@ -18,11 +17,13 @@ from typing import ()from uuid import UUID, uuid4-from pydantic import BaseModel-from langchain_core.utils.pydantic import _IgnoreUnserializable, is_basemodel_subclassif TYPE_CHECKING:+ from collections.abc import Sequence++ from pydantic import BaseModel+from langchain_core.runnables.base import Runnable as RunnableTypediff --git a/libs/core/langchain_core/runnables/passthrough.py b/libs/core/langchain_core/runnables/passthrough.pyindex b0da175ae3..95c27e7bcc 100644--- a/libs/core/langchain_core/runnables/passthrough.py+++ b/libs/core/langchain_core/runnables/passthrough.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport asyncioimport inspectimport threading-from collections.abc import AsyncIterator, Awaitable, Iterator, Mapping+from collections.abc import Awaitablefrom typing import (TYPE_CHECKING,Any,@@ -32,7 +32,6 @@ from langchain_core.runnables.config import (get_executor_for_config,patch_config,)-from langchain_core.runnables.graph import Graphfrom langchain_core.runnables.utils import (AddableDict,ConfigurableFieldSpec,@@ -42,10 +41,13 @@ from langchain_core.utils.iter import safeteefrom langchain_core.utils.pydantic import create_model_v2if TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator, Mapping+from langchain_core.callbacks.manager import (AsyncCallbackManagerForChainRun,CallbackManagerForChainRun,)+ from langchain_core.runnables.graph import Graphdef identity(x: Other) -> Other:diff --git a/libs/core/langchain_core/runnables/router.py b/libs/core/langchain_core/runnables/router.pyindex 29c6359c69..8d679ad35c 100644--- a/libs/core/langchain_core/runnables/router.py+++ b/libs/core/langchain_core/runnables/router.py@@ -1,8 +1,9 @@from __future__ import annotations-from collections.abc import AsyncIterator, Iterator, Mapping+from collections.abc import Mappingfrom itertools import starmapfrom typing import (+ TYPE_CHECKING,Any,Callable,Optional,@@ -31,6 +32,9 @@ from langchain_core.runnables.utils import (get_unique_config_specs,)+if TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator+class RouterInput(TypedDict):"""Router input.diff --git a/libs/core/langchain_core/runnables/schema.py b/libs/core/langchain_core/runnables/schema.pyindex dcfd32b8b3..20ad580070 100644--- a/libs/core/langchain_core/runnables/schema.py+++ b/libs/core/langchain_core/runnables/schema.py@@ -2,11 +2,13 @@from __future__ import annotations-from collections.abc import Sequence-from typing import Any, Literal, Union+from typing import TYPE_CHECKING, Any, Literal, Unionfrom typing_extensions import NotRequired, TypedDict+if TYPE_CHECKING:+ from collections.abc import Sequence+class EventData(TypedDict, total=False):"""Data associated with a streaming event."""diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.pyindex 75063c7db5..6ed4e7d681 100644--- a/libs/core/langchain_core/runnables/utils.py+++ b/libs/core/langchain_core/runnables/utils.py@@ -6,19 +6,11 @@ import astimport asyncioimport inspectimport textwrap-from collections.abc import (- AsyncIterable,- AsyncIterator,- Awaitable,- Coroutine,- Iterable,- Mapping,- Sequence,-)from functools import lru_cachefrom inspect import signaturefrom itertools import groupbyfrom typing import (+ TYPE_CHECKING,Any,Callable,NamedTuple,@@ -30,11 +22,22 @@ from typing import (from typing_extensions import TypeGuard, override-from langchain_core.runnables.schema import StreamEvent-# Re-export create-model for backwards compatibilityfrom langchain_core.utils.pydantic import create_model as create_model+if TYPE_CHECKING:+ from collections.abc import (+ AsyncIterable,+ AsyncIterator,+ Awaitable,+ Coroutine,+ Iterable,+ Mapping,+ Sequence,+ )++ from langchain_core.runnables.schema import StreamEvent+Input = TypeVar("Input", contravariant=True)# Output type should implement __concat__, as eg str, list, dict doOutput = TypeVar("Output", covariant=True)diff --git a/libs/core/langchain_core/structured_query.py b/libs/core/langchain_core/structured_query.pyindex 8aacbfbcc6..c0c502da00 100644--- a/libs/core/langchain_core/structured_query.py+++ b/libs/core/langchain_core/structured_query.py@@ -3,12 +3,14 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from collections.abc import Sequencefrom enum import Enum-from typing import Any, Optional, Union+from typing import TYPE_CHECKING, Any, Optional, Unionfrom pydantic import BaseModel+if TYPE_CHECKING:+ from collections.abc import Sequence+class Visitor(ABC):"""Defines interface for IR translation using a visitor pattern."""diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.pyindex 5a618f6a16..5e1a8a4752 100644--- a/libs/core/langchain_core/tools/base.py+++ b/libs/core/langchain_core/tools/base.py@@ -4,13 +4,12 @@ import asyncioimport functoolsimport inspectimport json-import uuidimport warningsfrom abc import ABC, abstractmethod-from collections.abc import Sequencefrom contextvars import copy_contextfrom inspect import signaturefrom typing import (+ TYPE_CHECKING,Annotated,Any,Callable,@@ -68,6 +67,10 @@ from langchain_core.utils.pydantic import (is_pydantic_v2_subclass,)+if TYPE_CHECKING:+ import uuid+ from collections.abc import Sequence+FILTERED_ARGS = ("run_manager", "callbacks")diff --git a/libs/core/langchain_core/tools/retriever.py b/libs/core/langchain_core/tools/retriever.pyindex b1036058ca..0bc26ce2a7 100644--- a/libs/core/langchain_core/tools/retriever.py+++ b/libs/core/langchain_core/tools/retriever.py@@ -1,21 +1,23 @@from __future__ import annotationsfrom functools import partial-from typing import Literal, Optional, Union+from typing import TYPE_CHECKING, Literal, Optional, Unionfrom pydantic import BaseModel, Field-from langchain_core.callbacks import Callbacks-from langchain_core.documents import Documentfrom langchain_core.prompts import (BasePromptTemplate,PromptTemplate,aformat_document,format_document,)-from langchain_core.retrievers import BaseRetrieverfrom langchain_core.tools.simple import Tool+if TYPE_CHECKING:+ from langchain_core.callbacks import Callbacks+ from langchain_core.documents import Document+ from langchain_core.retrievers import BaseRetriever+class RetrieverInput(BaseModel):"""Input to the retriever."""diff --git a/libs/core/langchain_core/tools/simple.py b/libs/core/langchain_core/tools/simple.pyindex 370d2091a6..d9806c3e94 100644--- a/libs/core/langchain_core/tools/simple.py+++ b/libs/core/langchain_core/tools/simple.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom collections.abc import Awaitablefrom inspect import signaturefrom typing import (+ TYPE_CHECKING,Any,Callable,Optional,@@ -13,7 +14,6 @@ from langchain_core.callbacks import (AsyncCallbackManagerForToolRun,CallbackManagerForToolRun,)-from langchain_core.messages import ToolCallfrom langchain_core.runnables import RunnableConfig, run_in_executorfrom langchain_core.tools.base import (ArgsSchema,@@ -22,6 +22,9 @@ from langchain_core.tools.base import (_get_runnable_config_param,)+if TYPE_CHECKING:+ from langchain_core.messages import ToolCall+class Tool(BaseTool):"""Tool that takes in function or coroutine directly."""diff --git a/libs/core/langchain_core/tools/structured.py b/libs/core/langchain_core/tools/structured.pyindex f168289ecd..6d7620e762 100644--- a/libs/core/langchain_core/tools/structured.py+++ b/libs/core/langchain_core/tools/structured.py@@ -4,6 +4,7 @@ import textwrapfrom collections.abc import Awaitablefrom inspect import signaturefrom typing import (+ TYPE_CHECKING,Annotated,Any,Callable,@@ -18,7 +19,6 @@ from langchain_core.callbacks import (AsyncCallbackManagerForToolRun,CallbackManagerForToolRun,)-from langchain_core.messages import ToolCallfrom langchain_core.runnables import RunnableConfig, run_in_executorfrom langchain_core.tools.base import (FILTERED_ARGS,@@ -29,6 +29,9 @@ from langchain_core.tools.base import ()from langchain_core.utils.pydantic import is_basemodel_subclass+if TYPE_CHECKING:+ from langchain_core.messages import ToolCall+class StructuredTool(BaseTool):"""Tool that can operate on any number of inputs."""diff --git a/libs/core/langchain_core/tracers/base.py b/libs/core/langchain_core/tracers/base.pyindex f3ae965f60..f452d586f5 100644--- a/libs/core/langchain_core/tracers/base.py+++ b/libs/core/langchain_core/tracers/base.py@@ -5,26 +5,27 @@ from __future__ import annotationsimport asyncioimport loggingfrom abc import ABC, abstractmethod-from collections.abc import Sequencefrom typing import (TYPE_CHECKING,Any,Optional,Union,)-from uuid import UUID--from tenacity import RetryCallStatefrom langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackHandlerfrom langchain_core.exceptions import TracerException # noqa-from langchain_core.messages import BaseMessage-from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResultfrom langchain_core.tracers.core import _TracerCore-from langchain_core.tracers.schemas import Runif TYPE_CHECKING:+ from collections.abc import Sequence+ from uuid import UUID++ from tenacity import RetryCallState+from langchain_core.documents import Document+ from langchain_core.messages import BaseMessage+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult+ from langchain_core.tracers.schemas import Runlogger = logging.getLogger(__name__)diff --git a/libs/core/langchain_core/tracers/context.py b/libs/core/langchain_core/tracers/context.pyindex d36adc9bc8..a947f162fc 100644--- a/libs/core/langchain_core/tracers/context.py+++ b/libs/core/langchain_core/tracers/context.py@@ -1,6 +1,5 @@from __future__ import annotations-from collections.abc import Generatorfrom contextlib import contextmanagerfrom contextvars import ContextVarfrom typing import (@@ -18,13 +17,15 @@ from langsmith import utils as ls_utilsfrom langchain_core.tracers.langchain import LangChainTracerfrom langchain_core.tracers.run_collector import RunCollectorCallbackHandler-from langchain_core.tracers.schemas import TracerSessionV1if TYPE_CHECKING:+ from collections.abc import Generator+from langsmith import Client as LangSmithClientfrom langchain_core.callbacks.base import BaseCallbackHandler, Callbacksfrom langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager+ from langchain_core.tracers.schemas import TracerSessionV1# for backwards partial compatibility if this is imported by users but unusedtracing_callback_var: Any = Nonediff --git a/libs/core/langchain_core/tracers/core.py b/libs/core/langchain_core/tracers/core.pyindex d3544df04e..599c4000cd 100644--- a/libs/core/langchain_core/tracers/core.py+++ b/libs/core/langchain_core/tracers/core.py@@ -6,7 +6,6 @@ import loggingimport sysimport tracebackfrom abc import ABC, abstractmethod-from collections.abc import Coroutine, Sequencefrom datetime import datetime, timezonefrom typing import (TYPE_CHECKING,@@ -16,13 +15,9 @@ from typing import (Union,cast,)-from uuid import UUID--from tenacity import RetryCallStatefrom langchain_core.exceptions import TracerExceptionfrom langchain_core.load import dumpd-from langchain_core.messages import BaseMessagefrom langchain_core.outputs import (ChatGeneration,ChatGenerationChunk,@@ -32,7 +27,13 @@ from langchain_core.outputs import (from langchain_core.tracers.schemas import Runif TYPE_CHECKING:+ from collections.abc import Coroutine, Sequence+ from uuid import UUID++ from tenacity import RetryCallState+from langchain_core.documents import Document+ from langchain_core.messages import BaseMessagelogger = logging.getLogger(__name__)diff --git a/libs/core/langchain_core/tracers/evaluation.py b/libs/core/langchain_core/tracers/evaluation.pyindex 425c1c0122..0a918cd2e9 100644--- a/libs/core/langchain_core/tracers/evaluation.py+++ b/libs/core/langchain_core/tracers/evaluation.py@@ -5,9 +5,8 @@ from __future__ import annotationsimport loggingimport threadingimport weakref-from collections.abc import Sequencefrom concurrent.futures import Future, ThreadPoolExecutor, wait-from typing import Any, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Optional, Union, castfrom uuid import UUIDimport langsmith@@ -17,7 +16,11 @@ from langchain_core.tracers import langchain as langchain_tracerfrom langchain_core.tracers.base import BaseTracerfrom langchain_core.tracers.context import tracing_v2_enabledfrom langchain_core.tracers.langchain import _get_executor-from langchain_core.tracers.schemas import Run++if TYPE_CHECKING:+ from collections.abc import Sequence++ from langchain_core.tracers.schemas import Runlogger = logging.getLogger(__name__)diff --git a/libs/core/langchain_core/tracers/event_stream.py b/libs/core/langchain_core/tracers/event_stream.pyindex b7f3db8595..2a5f6b5f84 100644--- a/libs/core/langchain_core/tracers/event_stream.py+++ b/libs/core/langchain_core/tracers/event_stream.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging-from collections.abc import AsyncIterator, Iterator, Sequencefrom typing import (TYPE_CHECKING,Any,@@ -37,13 +36,15 @@ from langchain_core.runnables.utils import (_RootEventFilter,)from langchain_core.tracers._streaming import _StreamingCallbackHandler-from langchain_core.tracers.log_stream import LogEntryfrom langchain_core.tracers.memory_stream import _MemoryStreamfrom langchain_core.utils.aiter import aclosing, py_anextif TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator, Sequence+from langchain_core.documents import Documentfrom langchain_core.runnables import Runnable, RunnableConfig+ from langchain_core.tracers.log_stream import LogEntrylogger = logging.getLogger(__name__)diff --git a/libs/core/langchain_core/tracers/langchain.py b/libs/core/langchain_core/tracers/langchain.pyindex 56981bc81d..7cdf5c92a3 100644--- a/libs/core/langchain_core/tracers/langchain.py+++ b/libs/core/langchain_core/tracers/langchain.py@@ -22,12 +22,12 @@ from tenacity import (from langchain_core.env import get_runtime_environmentfrom langchain_core.load import dumpd-from langchain_core.outputs import ChatGenerationChunk, GenerationChunkfrom langchain_core.tracers.base import BaseTracerfrom langchain_core.tracers.schemas import Runif TYPE_CHECKING:from langchain_core.messages import BaseMessage+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunklogger = logging.getLogger(__name__)_LOGGED = set()diff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.pyindex 2284ff7022..1e0c26aa79 100644--- a/libs/core/langchain_core/tracers/log_stream.py+++ b/libs/core/langchain_core/tracers/log_stream.py@@ -5,8 +5,8 @@ import contextlibimport copyimport threadingfrom collections import defaultdict-from collections.abc import AsyncIterator, Iterator, Sequencefrom typing import (+ TYPE_CHECKING,Any,Literal,Optional,@@ -14,7 +14,6 @@ from typing import (Union,overload,)-from uuid import UUIDimport jsonpatch # type: ignore[import]from typing_extensions import NotRequired, TypedDict@@ -23,11 +22,16 @@ from langchain_core.load import dumpsfrom langchain_core.load.load import loadfrom langchain_core.outputs import ChatGenerationChunk, GenerationChunkfrom langchain_core.runnables import Runnable, RunnableConfig, ensure_config-from langchain_core.runnables.utils import Input, Outputfrom langchain_core.tracers._streaming import _StreamingCallbackHandlerfrom langchain_core.tracers.base import BaseTracerfrom langchain_core.tracers.memory_stream import _MemoryStream-from langchain_core.tracers.schemas import Run++if TYPE_CHECKING:+ from collections.abc import AsyncIterator, Iterator, Sequence+ from uuid import UUID++ from langchain_core.runnables.utils import Input, Output+ from langchain_core.tracers.schemas import Runclass LogEntry(TypedDict):diff --git a/libs/core/langchain_core/tracers/root_listeners.py b/libs/core/langchain_core/tracers/root_listeners.pyindex 1530598fb7..c08861164a 100644--- a/libs/core/langchain_core/tracers/root_listeners.py+++ b/libs/core/langchain_core/tracers/root_listeners.py@@ -1,6 +1,5 @@from collections.abc import Awaitable-from typing import Callable, Optional, Union-from uuid import UUID+from typing import TYPE_CHECKING, Callable, Optional, Unionfrom langchain_core.runnables.config import (RunnableConfig,@@ -10,6 +9,9 @@ from langchain_core.runnables.config import (from langchain_core.tracers.base import AsyncBaseTracer, BaseTracerfrom langchain_core.tracers.schemas import Run+if TYPE_CHECKING:+ from uuid import UUID+Listener = Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]AsyncListener = Union[Callable[[Run], Awaitable[None]], Callable[[Run, RunnableConfig], Awaitable[None]]diff --git a/libs/core/langchain_core/utils/json_schema.py b/libs/core/langchain_core/utils/json_schema.pyindex 38fab58990..72f20c38d2 100644--- a/libs/core/langchain_core/utils/json_schema.py+++ b/libs/core/langchain_core/utils/json_schema.py@@ -1,8 +1,10 @@from __future__ import annotations-from collections.abc import Sequencefrom copy import deepcopy-from typing import Any, Optional+from typing import TYPE_CHECKING, Any, Optional++if TYPE_CHECKING:+ from collections.abc import Sequencedef _retrieve_ref(path: str, schema: dict) -> dict:diff --git a/libs/core/langchain_core/utils/mustache.py b/libs/core/langchain_core/utils/mustache.pyindex ee2ed8f252..4c42c47fed 100644--- a/libs/core/langchain_core/utils/mustache.py+++ b/libs/core/langchain_core/utils/mustache.py@@ -8,6 +8,7 @@ import loggingfrom collections.abc import Iterator, Mapping, Sequencefrom types import MappingProxyTypefrom typing import (+ TYPE_CHECKING,Any,Literal,Optional,@@ -15,7 +16,8 @@ from typing import (cast,)-from typing_extensions import TypeAlias+if TYPE_CHECKING:+ from typing_extensions import TypeAliaslogger = logging.getLogger(__name__)diff --git a/libs/core/langchain_core/utils/pydantic.py b/libs/core/langchain_core/utils/pydantic.pyindex 6c4b4cb8c2..0aff29c1bb 100644--- a/libs/core/langchain_core/utils/pydantic.py+++ b/libs/core/langchain_core/utils/pydantic.py@@ -9,6 +9,7 @@ from contextlib import nullcontextfrom functools import lru_cache, wrapsfrom types import GenericAliasfrom typing import (+ TYPE_CHECKING,Any,Callable,Optional,@@ -29,13 +30,16 @@ from pydantic import (from pydantic import (create_model as _create_model_base,)+from pydantic.fields import FieldInfo as FieldInfoV2from pydantic.json_schema import (DEFAULT_REF_TEMPLATE,GenerateJsonSchema,JsonSchemaMode,JsonSchemaValue,)-from pydantic_core import core_schema++if TYPE_CHECKING:+ from pydantic_core import core_schemadef get_pydantic_major_version() -> int:@@ -71,8 +75,8 @@ elif PYDANTIC_MAJOR_VERSION == 2:from pydantic.v1.fields import FieldInfo as FieldInfoV1 # type: ignore[assignment]# Union type needs to be last assignment to PydanticBaseModel to make mypy happy.- PydanticBaseModel = Union[BaseModel, pydantic.BaseModel] # type: ignore- TypeBaseModel = Union[type[BaseModel], type[pydantic.BaseModel]] # type: ignore+ PydanticBaseModel = Union[BaseModel, pydantic.BaseModel] # type: ignore[assignment,misc]+ TypeBaseModel = Union[type[BaseModel], type[pydantic.BaseModel]] # type: ignore[misc]else:msg = f"Unsupported Pydantic version: {PYDANTIC_MAJOR_VERSION}"raise ValueError(msg)@@ -357,7 +361,6 @@ def _create_subset_model(if PYDANTIC_MAJOR_VERSION == 2:from pydantic import BaseModel as BaseModelV2- from pydantic.fields import FieldInfo as FieldInfoV2from pydantic.v1 import BaseModel as BaseModelV1@overloaddiff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.pyindex b154a14b98..1cf1fd529f 100644--- a/libs/core/langchain_core/vectorstores/base.py+++ b/libs/core/langchain_core/vectorstores/base.py@@ -25,7 +25,6 @@ import loggingimport mathimport warningsfrom abc import ABC, abstractmethod-from collections.abc import Collection, Iterable, Iterator, Sequencefrom itertools import cyclefrom typing import (TYPE_CHECKING,@@ -43,6 +42,8 @@ from langchain_core.retrievers import BaseRetriever, LangSmithRetrieverParamsfrom langchain_core.runnables.config import run_in_executorif TYPE_CHECKING:+ from collections.abc import Collection, Iterable, Iterator, Sequence+from langchain_core.callbacks.manager import (AsyncCallbackManagerForRetrieverRun,CallbackManagerForRetrieverRun,diff --git a/libs/core/langchain_core/vectorstores/in_memory.py b/libs/core/langchain_core/vectorstores/in_memory.pyindex 5fb385a21c..daf1dcdfc6 100644--- a/libs/core/langchain_core/vectorstores/in_memory.py+++ b/libs/core/langchain_core/vectorstores/in_memory.py@@ -2,7 +2,6 @@ from __future__ import annotationsimport jsonimport uuid-from collections.abc import Iterator, Sequencefrom pathlib import Pathfrom typing import (TYPE_CHECKING,@@ -13,13 +12,15 @@ from typing import (from langchain_core._api import deprecatedfrom langchain_core.documents import Document-from langchain_core.embeddings import Embeddingsfrom langchain_core.load import dumpd, loadfrom langchain_core.vectorstores import VectorStorefrom langchain_core.vectorstores.utils import _cosine_similarity as cosine_similarityfrom langchain_core.vectorstores.utils import maximal_marginal_relevanceif TYPE_CHECKING:+ from collections.abc import Iterator, Sequence++ from langchain_core.embeddings import Embeddingsfrom langchain_core.indexing import UpsertResponsediff --git a/libs/core/pyproject.toml b/libs/core/pyproject.tomlindex bfd3eec1d4..dc4a8bbc47 100644--- a/libs/core/pyproject.toml+++ b/libs/core/pyproject.toml@@ -77,8 +77,9 @@ target-version = "py39"[tool.ruff.lint]-select = [ "ANN", "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TID", "TRY", "UP", "W", "YTT",]-ignore = [ "ANN401", "COM812", "UP007", "S110", "S112",]+select = [ "ANN", "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TC", "TID", "TRY", "UP", "W", "YTT",]+ignore = [ "ANN401", "COM812", "UP007", "S110", "S112", "TC001", "TC002", "TC003"]+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 = trueflake8-annotations.mypy-init-return = truediff --git a/libs/core/tests/unit_tests/language_models/chat_models/test_base.py b/libs/core/tests/unit_tests/language_models/chat_models/test_base.pyindex 420b60cebf..284ffb23d1 100644--- a/libs/core/tests/unit_tests/language_models/chat_models/test_base.py+++ b/libs/core/tests/unit_tests/language_models/chat_models/test_base.py@@ -2,7 +2,7 @@import uuidfrom collections.abc import AsyncIterator, Iterator-from typing import Any, Literal, Optional, Union+from typing import TYPE_CHECKING, Any, Literal, Optional, Unionimport pytest@@ -30,6 +30,9 @@ from tests.unit_tests.fake.callbacks import ()from tests.unit_tests.stubs import _any_id_ai_message, _any_id_ai_message_chunk+if TYPE_CHECKING:+ from langchain_core.outputs.llm_result import LLMResult+@pytest.fixturedef messages() -> list:diff --git a/libs/core/tests/unit_tests/vectorstores/test_vectorstore.py b/libs/core/tests/unit_tests/vectorstores/test_vectorstore.pyindex c9c6592545..2ebee79cf9 100644--- a/libs/core/tests/unit_tests/vectorstores/test_vectorstore.py+++ b/libs/core/tests/unit_tests/vectorstores/test_vectorstore.py@@ -7,8 +7,7 @@ the relevant methods.from __future__ import annotationsimport uuid-from collections.abc import Iterable, Sequence-from typing import Any, Optional+from typing import TYPE_CHECKING, Any, Optionalimport pytest@@ -16,6 +15,9 @@ from langchain_core.documents import Documentfrom langchain_core.embeddings import Embeddings, FakeEmbeddingsfrom langchain_core.vectorstores import VectorStore+if TYPE_CHECKING:+ from collections.abc import Iterable, Sequence+class CustomAddTextsVectorstore(VectorStore):"""A vectorstore that only implements add texts."""