Skip to content

The agent engineering platform.

chore(core): fix some mypy `warn_unreachable` issues (#32560)

Christophe Bornete3b6c9bb66a9
diff --git a/libs/core/langchain_core/globals.py b/libs/core/langchain_core/globals.py
index 77375a2d07..faf26578f3 100644
--- a/libs/core/langchain_core/globals.py
+++ b/libs/core/langchain_core/globals.py
@@ -191,7 +191,7 @@ def set_llm_cache(value: Optional["BaseCache"]) -> None:
_llm_cache = value
-def get_llm_cache() -> "BaseCache":
+def get_llm_cache() -> Optional["BaseCache"]:
"""Get the value of the `llm_cache` global setting.
Returns:
diff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.py
index 5c24d516e7..10a5f06121 100644
--- a/libs/core/langchain_core/language_models/llms.py
+++ b/libs/core/langchain_core/language_models/llms.py
@@ -131,6 +131,7 @@ def create_base_retry_decorator(
def _resolve_cache(*, cache: Union[BaseCache, bool, None]) -> Optional[BaseCache]:
"""Resolve the cache."""
+ llm_cache: Optional[BaseCache]
if isinstance(cache, BaseCache):
llm_cache = cache
elif cache is None:
diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py
index e84dc6c019..2796707aa2 100644
--- a/libs/core/langchain_core/messages/utils.py
+++ b/libs/core/langchain_core/messages/utils.py
@@ -182,7 +182,7 @@ def messages_from_dict(messages: Sequence[dict]) -> list[BaseMessage]:
return [_message_from_dict(m) for m in messages]
-def message_chunk_to_message(chunk: BaseMessageChunk) -> BaseMessage:
+def message_chunk_to_message(chunk: BaseMessage) -> BaseMessage:
"""Convert a message chunk to a message.
Args:
diff --git a/libs/core/langchain_core/output_parsers/json.py b/libs/core/langchain_core/output_parsers/json.py
index 8d8e4d5276..5457703775 100644
--- a/libs/core/langchain_core/output_parsers/json.py
+++ b/libs/core/langchain_core/output_parsers/json.py
@@ -49,9 +49,7 @@ class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]):
def _get_schema(self, pydantic_object: type[TBaseModel]) -> dict[str, Any]:
if issubclass(pydantic_object, pydantic.BaseModel):
return pydantic_object.model_json_schema()
- if issubclass(pydantic_object, pydantic.v1.BaseModel):
- return pydantic_object.schema()
- return None
+ return pydantic_object.schema()
def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
"""Parse the result of an LLM call to a JSON object.
diff --git a/libs/core/langchain_core/prompts/few_shot.py b/libs/core/langchain_core/prompts/few_shot.py
index 1b42dcdc9c..a1d237e66c 100644
--- a/libs/core/langchain_core/prompts/few_shot.py
+++ b/libs/core/langchain_core/prompts/few_shot.py
@@ -153,7 +153,7 @@ class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
self.template_format,
self.input_variables + list(self.partial_variables),
)
- elif self.template_format or None:
+ elif self.template_format:
self.input_variables = [
var
for var in get_template_variables(
diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py
index 7b87278390..4da0a48441 100644
--- a/libs/core/langchain_core/runnables/base.py
+++ b/libs/core/langchain_core/runnables/base.py
@@ -5204,10 +5204,13 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
config: Optional[RunnableConfig] = None,
**kwargs: Optional[Any],
) -> AsyncIterator[StreamEvent]:
+ def _error_stream_event(message: str) -> StreamEvent:
+ raise NotImplementedError(message)
+
for _ in range(1):
- msg = "RunnableEach does not support astream_events yet."
- raise NotImplementedError(msg)
- yield
+ yield _error_stream_event(
+ "RunnableEach does not support astream_events yet."
+ )
class RunnableEach(RunnableEachBase[Input, Output]):
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index 34ca4b4da3..e93cb74dc6 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -1285,7 +1285,7 @@ class InjectedToolCallId(InjectedToolArg):
def _is_injected_arg_type(
- type_: type, injected_type: Optional[type[InjectedToolArg]] = None
+ type_: Union[type, TypeVar], injected_type: Optional[type[InjectedToolArg]] = None
) -> bool:
"""Check if a type annotation indicates an injected argument.
@@ -1306,7 +1306,7 @@ def _is_injected_arg_type(
def get_all_basemodel_annotations(
cls: Union[TypeBaseModel, Any], *, default_to_bound: bool = True
-) -> dict[str, type]:
+) -> dict[str, Union[type, TypeVar]]:
"""Get all annotations from a Pydantic BaseModel and its parents.
Args:
@@ -1319,7 +1319,7 @@ def get_all_basemodel_annotations(
fields = getattr(cls, "model_fields", {}) or getattr(cls, "__fields__", {})
alias_map = {field.alias: name for name, field in fields.items() if field.alias}
- annotations: dict[str, type] = {}
+ annotations: dict[str, Union[type, TypeVar]] = {}
for name, param in inspect.signature(cls).parameters.items():
# Exclude hidden init args added by pydantic Config. For example if
# BaseModel(extra="allow") then "extra_data" will part of init sig.
@@ -1373,11 +1373,11 @@ def get_all_basemodel_annotations(
def _replace_type_vars(
- type_: type,
+ type_: Union[type, TypeVar],
generic_map: Optional[dict[TypeVar, type]] = None,
*,
default_to_bound: bool = True,
-) -> type:
+) -> Union[type, TypeVar]:
"""Replace TypeVars in a type annotation with concrete types.
Args:
diff --git a/libs/core/langchain_core/utils/json.py b/libs/core/langchain_core/utils/json.py
index 4b12e85fe9..98450587e1 100644
--- a/libs/core/langchain_core/utils/json.py
+++ b/libs/core/langchain_core/utils/json.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
import re
-from typing import Any, Callable
+from typing import Any, Callable, Union
from langchain_core.exceptions import OutputParserException
@@ -19,7 +19,7 @@ def _replace_new_line(match: re.Match[str]) -> str:
return match.group(1) + value + match.group(3)
-def _custom_parser(multiline_string: str) -> str:
+def _custom_parser(multiline_string: Union[str, bytes, bytearray]) -> str:
r"""Custom parser for multiline strings.
The LLM response for `action_input` may be a multiline
diff --git a/libs/core/langchain_core/utils/json_schema.py b/libs/core/langchain_core/utils/json_schema.py
index 70cea60d09..5463c245b4 100644
--- a/libs/core/langchain_core/utils/json_schema.py
+++ b/libs/core/langchain_core/utils/json_schema.py
@@ -3,13 +3,13 @@
from __future__ import annotations
from copy import deepcopy
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Optional, Union
if TYPE_CHECKING:
from collections.abc import Sequence
-def _retrieve_ref(path: str, schema: dict) -> dict:
+def _retrieve_ref(path: str, schema: dict) -> Union[list, dict]:
components = path.split("/")
if components[0] != "#":
msg = (
@@ -17,9 +17,12 @@ def _retrieve_ref(path: str, schema: dict) -> dict:
"with #."
)
raise ValueError(msg)
- out = schema
+ out: Union[list, dict] = schema
for component in components[1:]:
if component in out:
+ if isinstance(out, list):
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
out = out[component]
elif component.isdigit():
index = int(component)
diff --git a/libs/core/tests/unit_tests/runnables/test_fallbacks.py b/libs/core/tests/unit_tests/runnables/test_fallbacks.py
index 3985facc54..c2e1c1af86 100644
--- a/libs/core/tests/unit_tests/runnables/test_fallbacks.py
+++ b/libs/core/tests/unit_tests/runnables/test_fallbacks.py
@@ -264,16 +264,18 @@ def _generate(_: Iterator) -> Iterator[str]:
yield from "foo bar"
-def _generate_immediate_error(_: Iterator) -> Iterator[str]:
- msg = "immmediate error"
+def _error(msg: str) -> None:
raise ValueError(msg)
+
+
+def _generate_immediate_error(_: Iterator) -> Iterator[str]:
+ _error("immmediate error")
yield ""
def _generate_delayed_error(_: Iterator) -> Iterator[str]:
yield ""
- msg = "delayed error"
- raise ValueError(msg)
+ _error("delayed error")
def test_fallbacks_stream() -> None:
@@ -295,15 +297,13 @@ async def _agenerate(_: AsyncIterator) -> AsyncIterator[str]:
async def _agenerate_immediate_error(_: AsyncIterator) -> AsyncIterator[str]:
- msg = "immmediate error"
- raise ValueError(msg)
+ _error("immediate error")
yield ""
async def _agenerate_delayed_error(_: AsyncIterator) -> AsyncIterator[str]:
yield ""
- msg = "delayed error"
- raise ValueError(msg)
+ _error("delayed error")
async def test_fallbacks_astream() -> None:
diff --git a/libs/core/tests/unit_tests/runnables/test_tracing_interops.py b/libs/core/tests/unit_tests/runnables/test_tracing_interops.py
index 08a846827f..2db895355e 100644
--- a/libs/core/tests/unit_tests/runnables/test_tracing_interops.py
+++ b/libs/core/tests/unit_tests/runnables/test_tracing_interops.py
@@ -221,7 +221,7 @@ async def test_config_traceable_async_handoff() -> None:
@pytest.mark.parametrize("enabled", [None, True, False])
@pytest.mark.parametrize("env", ["", "true"])
def test_tracing_enable_disable(
- mock_get_client: MagicMock, *, enabled: bool, env: str
+ mock_get_client: MagicMock, *, enabled: Optional[bool], env: str
) -> None:
mock_session = MagicMock()
mock_client_ = Client(
diff --git a/libs/core/uv.lock b/libs/core/uv.lock
index 4da1773205..a4bb351a56 100644
--- a/libs/core/uv.lock
+++ b/libs/core/uv.lock
@@ -1134,7 +1134,7 @@ typing = [
[[package]]
name = "langchain-tests"
-version = "0.3.20"
+version = "0.3.21"
source = { directory = "../standard-tests" }
dependencies = [
{ name = "httpx" },
@@ -1179,18 +1179,14 @@ typing = [
[[package]]
name = "langchain-text-splitters"
-version = "0.3.9"
+version = "0.3.11"
source = { directory = "../text-splitters" }
dependencies = [
{ name = "langchain-core" },
- { name = "pip" },
]
[package.metadata]
-requires-dist = [
- { name = "langchain-core", editable = "." },
- { name = "pip", specifier = ">=25.2" },
-]
+requires-dist = [{ name = "langchain-core", editable = "." }]
[package.metadata.requires-dev]
dev = [
@@ -1212,6 +1208,7 @@ test = [
{ name = "pytest-xdist", specifier = ">=3.6.1,<4.0.0" },
]
test-integration = [
+ { name = "en-core-web-sm", url = "https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl" },
{ name = "nltk", specifier = ">=3.9.1,<4.0.0" },
{ name = "sentence-transformers", specifier = ">=3.0.1" },
{ name = "spacy", specifier = ">=3.8.7,<4.0.0" },
@@ -1997,15 +1994,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
]
-[[package]]
-name = "pip"
-version = "25.2"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/20/16/650289cd3f43d5a2fadfd98c68bd1e1e7f2550a1a5326768cddfbcedb2c5/pip-25.2.tar.gz", hash = "sha256:578283f006390f85bb6282dffb876454593d637f5d1be494b5202ce4877e71f2", size = 1840021, upload-time = "2025-07-30T21:50:15.401Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/b7/3f/945ef7ab14dc4f9d7f40288d2df998d1837ee0888ec3659c813487572faa/pip-25.2-py3-none-any.whl", hash = "sha256:6d67a2b4e7f14d8b31b8b52648866fa717f45a1eb70e83002f4331d07e953717", size = 1752557, upload-time = "2025-07-30T21:50:13.323Z" },
-]
-
[[package]]
name = "platformdirs"
version = "4.3.8"