The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(core): add mypy `warn_unreachable` (#38109)
Christophe Bornet62f255980d3f
diff --git a/libs/core/langchain_core/_api/beta_decorator.py b/libs/core/langchain_core/_api/beta_decorator.pyindex 94671a1122..398092495b 100644--- a/libs/core/langchain_core/_api/beta_decorator.py+++ b/libs/core/langchain_core/_api/beta_decorator.py@@ -26,7 +26,7 @@ class LangChainBetaWarning(DeprecationWarning):# PUBLIC API-T = TypeVar("T", bound=Callable[..., Any] | type)+T = TypeVar("T", bound=Callable[..., Any] | type | property)def beta(@@ -145,27 +145,40 @@ def beta(if not _obj_type:_obj_type = "attribute"wrapped = None- _name = _name or obj.fget.__qualname__+ _name = _name or (obj.fget and obj.fget.__qualname__) or "<property>"old_doc = obj.__doc__+ # `obj.fget`/`fset`/`fdel` are typed `Callable | None`, so the `and`+ # short-circuits guard the calls for the type checker. Each wrapper is+ # only installed when its accessor is truthy (see `finalize` below), so+ # the guards never short-circuit at runtime — do not "simplify" them+ # away or mypy's `warn_unreachable` will flag the accessor as `None`.def _fget(instance: Any) -> Any:if instance is not None:emit_warning()- return obj.fget(instance)+ return obj.fget and obj.fget(instance)def _fset(instance: Any, value: Any) -> None:if instance is not None:emit_warning()- obj.fset(instance, value)+ obj.fset and obj.fset(instance, value)def _fdel(instance: Any) -> None:if instance is not None:emit_warning()- obj.fdel(instance)+ obj.fdel and obj.fdel(instance)- def finalize(_: Callable[..., Any], new_doc: str, /) -> Any:+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:"""Finalize the property."""- return property(fget=_fget, fset=_fset, fdel=_fdel, doc=new_doc)+ return cast(+ "T",+ property(+ fget=_fget if obj.fget else None,+ fset=_fset if obj.fset else None,+ fdel=_fdel if obj.fdel else None,+ doc=new_doc,+ ),+ )else:_name = _name or obj.__qualname__diff --git a/libs/core/langchain_core/_security/_policy.py b/libs/core/langchain_core/_security/_policy.pyindex 79cf437c89..9b4566cbe4 100644--- a/libs/core/langchain_core/_security/_policy.py+++ b/libs/core/langchain_core/_security/_policy.py@@ -144,19 +144,19 @@ def _ip_in_blocked_networks(# @functools.lru_cache (key on (addr, id(policy))).if isinstance(addr, ipaddress.IPv4Address):if policy.block_private_ips:- for net in _BLOCKED_IPV4_NETWORKS:- if addr in net:+ for blocked_ipv4_net in _BLOCKED_IPV4_NETWORKS:+ if addr in blocked_ipv4_net:return "private IP range"- for net in policy.additional_blocked_cidrs: # type: ignore[assignment]- if isinstance(net, ipaddress.IPv4Network) and addr in net:+ for blocked_cidr in policy.additional_blocked_cidrs:+ if isinstance(blocked_cidr, ipaddress.IPv4Network) and addr in blocked_cidr:return "blocked CIDR"else:if policy.block_private_ips:- for net in _BLOCKED_IPV6_NETWORKS: # type: ignore[assignment]- if addr in net:+ for blocked_ipv6_net in _BLOCKED_IPV6_NETWORKS:+ if addr in blocked_ipv6_net:return "private IP range"- for net in policy.additional_blocked_cidrs: # type: ignore[assignment]- if isinstance(net, ipaddress.IPv6Network) and addr in net:+ for blocked_cidr in policy.additional_blocked_cidrs:+ if isinstance(blocked_cidr, ipaddress.IPv6Network) and addr in blocked_cidr:return "blocked CIDR"# Loopback check — independent of block_private_ips so that@@ -176,7 +176,7 @@ def _ip_in_blocked_networks(if policy.block_cloud_metadata:if str(addr) in _CLOUD_METADATA_IPS:return "cloud metadata endpoint"- for net in _CLOUD_METADATA_NETWORKS: # type: ignore[assignment]+ for net in _CLOUD_METADATA_NETWORKS:if addr in net:return "cloud metadata endpoint"diff --git a/libs/core/langchain_core/indexing/api.py b/libs/core/langchain_core/indexing/api.pyindex b4af08b8b5..19f1a47baf 100644--- a/libs/core/langchain_core/indexing/api.py+++ b/libs/core/langchain_core/indexing/api.py@@ -129,7 +129,7 @@ def _get_source_id_assigner(return lambda doc: doc.metadata[source_id_key]if callable(source_id_key):return source_id_key- msg = (+ msg = ( # type: ignore[unreachable]f"source_id_key should be either None, a string or a callable. "f"Got {source_id_key} of type {type(source_id_key)}.")@@ -168,7 +168,7 @@ def _calculate_hash(return hashlib.sha256(text.encode("utf-8")).hexdigest()if algorithm == "sha512":return hashlib.sha512(text.encode("utf-8")).hexdigest()- msg = f"Unsupported hashing algorithm: {algorithm}"+ msg = f"Unsupported hashing algorithm: {algorithm}" # type: ignore[unreachable]raise ValueError(msg)@@ -270,7 +270,7 @@ def _delete(msg = "The delete operation to DocumentIndex failed."raise IndexingException(msg)else:- msg = (+ msg = ( # type: ignore[unreachable]f"Vectorstore should be either a VectorStore or a DocumentIndex. "f"Got {type(vector_store)}.")@@ -443,7 +443,7 @@ def index(elif isinstance(destination, DocumentIndex):passelse:- msg = (+ msg = ( # type: ignore[unreachable]f"Vectorstore should be either a VectorStore or a DocumentIndex. "f"Got {type(destination)}.")@@ -625,7 +625,7 @@ async def _adelete(msg = "The delete operation to DocumentIndex failed."raise IndexingException(msg)else:- msg = (+ msg = ( # type: ignore[unreachable]f"Vectorstore should be either a VectorStore or a DocumentIndex. "f"Got {type(vector_store)}.")@@ -786,7 +786,7 @@ async def aindex(elif isinstance(destination, DocumentIndex):passelse:- msg = (+ msg = ( # type: ignore[unreachable]f"Vectorstore should be either a VectorStore or a DocumentIndex. "f"Got {type(destination)}.")diff --git a/libs/core/langchain_core/language_models/_compat_bridge.py b/libs/core/langchain_core/language_models/_compat_bridge.pyindex 43490f0717..4b62389fd6 100644--- a/libs/core/langchain_core/language_models/_compat_bridge.py+++ b/libs/core/langchain_core/language_models/_compat_bridge.py@@ -189,7 +189,7 @@ def _iter_protocol_blocks(msg: BaseMessage) -> list[tuple[Any, CompatBlock]]:result: list[tuple[Any, CompatBlock]] = []for i, block in enumerate(raw):if not isinstance(block, dict):- continue+ continue # type: ignore[unreachable]explicit_idx = block.get("index")if explicit_idx is None:# No source-side identity. Bucket by (sentinel, block type,diff --git a/libs/core/langchain_core/language_models/chat_model_stream.py b/libs/core/langchain_core/language_models/chat_model_stream.pyindex 82da8c28ac..a5e9a0a2af 100644--- a/libs/core/langchain_core/language_models/chat_model_stream.py+++ b/libs/core/langchain_core/language_models/chat_model_stream.py@@ -647,7 +647,7 @@ class _ChatModelStreamBase:tcc = cast("ToolCallChunk", fields)idx = data.get("index")if idx is None:- idx = tcc.get("index", len(self._tool_call_chunks))+ idx = tcc.get("index", len(self._tool_call_chunks)) # type: ignore[unreachable]_merge_block_delta_into_store(self._tool_call_chunks, idx, dict(tcc))chunk_block: ToolCallChunk = {"type": "tool_call_chunk",@@ -662,7 +662,7 @@ class _ChatModelStreamBase:stcc = cast("ServerToolCallChunk", fields)idx = data.get("index")if idx is None:- idx = len(self._server_tool_call_chunks)+ idx = len(self._server_tool_call_chunks) # type: ignore[unreachable]_merge_block_delta_into_store(self._server_tool_call_chunks,idx,@@ -677,7 +677,7 @@ class _ChatModelStreamBase:tcc = cast("ToolCallChunk", fields)idx = data.get("index")if idx is None:- idx = tcc.get("index", len(self._tool_call_chunks))+ idx = tcc.get("index", len(self._tool_call_chunks)) # type: ignore[unreachable]_merge_chunk_into_store(self._tool_call_chunks, idx, dict(tcc))legacy_chunk_block: ToolCallChunk = {"type": "tool_call_chunk",@@ -692,7 +692,7 @@ class _ChatModelStreamBase:stcc = cast("ServerToolCallChunk", fields)idx = data.get("index")if idx is None:- idx = len(self._server_tool_call_chunks)+ idx = len(self._server_tool_call_chunks) # type: ignore[unreachable]_merge_chunk_into_store(self._server_tool_call_chunks,idx,@@ -715,7 +715,7 @@ class _ChatModelStreamBase:tcc = cast("ToolCallChunk", block)idx = data.get("index")if idx is None:- idx = tcc.get("index", len(self._tool_call_chunks))+ idx = tcc.get("index", len(self._tool_call_chunks)) # type: ignore[unreachable]_merge_chunk_into_store(self._tool_call_chunks, idx, dict(tcc))fallback_chunk_block: ToolCallChunk = {"type": "tool_call_chunk",diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.pyindex a0e8f42bef..01737308eb 100644--- a/libs/core/langchain_core/language_models/chat_models.py+++ b/libs/core/langchain_core/language_models/chat_models.py@@ -453,7 +453,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):return StringPromptValue(text=model_input)if isinstance(model_input, Sequence):return ChatPromptValue(messages=convert_to_messages(model_input))- msg = (+ msg = ( # type: ignore[unreachable]f"Invalid input type {type(model_input)}. ""Must be a PromptValue, str, or list of BaseMessages.")@@ -1223,7 +1223,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):async with start_lock:if stream._producer_task is not None: # noqa: SLF001- return+ return # type: ignore[unreachable](run_manager,) = await callback_manager.on_chat_model_start(self._serialized,diff --git a/libs/core/langchain_core/language_models/fake_chat_models.py b/libs/core/langchain_core/language_models/fake_chat_models.pyindex 12e5a73fdf..1898f22c4c 100644--- a/libs/core/langchain_core/language_models/fake_chat_models.py+++ b/libs/core/langchain_core/language_models/fake_chat_models.py@@ -274,7 +274,7 @@ class GenericFakeChatModel(BaseChatModel):messages, stop=stop, run_manager=run_manager, **kwargs)if not isinstance(chat_result, ChatResult):- msg = (+ msg = ( # type: ignore[unreachable]f"Expected generate to return a ChatResult, "f"but got {type(chat_result)} instead.")diff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.pyindex b2f070e3e6..14b09ac29b 100644--- a/libs/core/langchain_core/language_models/llms.py+++ b/libs/core/langchain_core/language_models/llms.py@@ -151,7 +151,7 @@ def _resolve_cache(*, cache: BaseCache | bool | None) -> BaseCache | None:elif cache is False:llm_cache = Noneelse:- msg = f"Unsupported cache value {cache}"+ msg = f"Unsupported cache value {cache}" # type: ignore[unreachable]raise ValueError(msg)return llm_cache@@ -325,7 +325,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):return StringPromptValue(text=model_input)if isinstance(model_input, Sequence):return ChatPromptValue(messages=convert_to_messages(model_input))- msg = (+ msg = ( # type: ignore[unreachable]f"Invalid input type {type(model_input)}. ""Must be a PromptValue, str, or list of BaseMessages.")@@ -906,7 +906,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):input prompt and additional model provider-specific output."""if not isinstance(prompts, list):- msg = (+ msg = ( # type: ignore[unreachable]"Argument 'prompts' is expected to be of type list[str], received"f" argument of type {type(prompts)}.")diff --git a/libs/core/langchain_core/language_models/model_profile.py b/libs/core/langchain_core/language_models/model_profile.pyindex 441cd37675..e5eedef071 100644--- a/libs/core/langchain_core/language_models/model_profile.py+++ b/libs/core/langchain_core/language_models/model_profile.py@@ -143,7 +143,7 @@ def _warn_unknown_profile_keys(profile: ModelProfile) -> None:profile: The model profile dict to check for undeclared keys."""if not isinstance(profile, dict):- return+ return # type: ignore[unreachable]try:declared = frozenset(get_type_hints(ModelProfile).keys())diff --git a/libs/core/langchain_core/load/load.py b/libs/core/langchain_core/load/load.pyindex 5bb93d0887..030cafc221 100644--- a/libs/core/langchain_core/load/load.py+++ b/libs/core/langchain_core/load/load.py@@ -321,7 +321,7 @@ def _compute_allowed_class_paths(if not isinstance(allowed_obj, type) or not issubclass(allowed_obj, Serializable):- msg = "allowed_objects must contain Serializable subclasses."+ msg = "allowed_objects must contain Serializable subclasses." # type: ignore[unreachable]raise TypeError(msg)class_path = tuple(allowed_obj.lc_id())diff --git a/libs/core/langchain_core/messages/block_translators/google_genai.py b/libs/core/langchain_core/messages/block_translators/google_genai.pyindex 321de2f2df..c2070334c9 100644--- a/libs/core/langchain_core/messages/block_translators/google_genai.py+++ b/libs/core/langchain_core/messages/block_translators/google_genai.py@@ -356,7 +356,7 @@ def _convert_to_v1_from_genai(message: AIMessage) -> list[types.ContentBlock]:if not isinstance(message.content, list):# Unexpected content type, attempt to represent as text- return [{"type": "text", "text": str(message.content)}]+ return [{"type": "text", "text": str(message.content)}] # type: ignore[unreachable]converted_blocks: list[types.ContentBlock] = []@@ -485,7 +485,7 @@ def _convert_to_v1_from_genai(message: AIMessage) -> list[types.ContentBlock]:converted_blocks.append({"type": "non_standard", "value": item})else:# Non-dict, non-string content- converted_blocks.append({"type": "non_standard", "value": item})+ converted_blocks.append({"type": "non_standard", "value": item}) # type: ignore[unreachable]grounding_metadata = message.response_metadata.get("grounding_metadata")if grounding_metadata:diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.pyindex c1657145cc..cc9cfa93a7 100644--- a/libs/core/langchain_core/messages/utils.py+++ b/libs/core/langchain_core/messages/utils.py@@ -772,7 +772,7 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:msg_type, msg_content, **msg_kwargs)else:- msg = f"Unsupported message type: {type(message)}"+ msg = f"Unsupported message type: {type(message)}" # type: ignore[unreachable]msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raise NotImplementedError(msg)@@ -1477,7 +1477,7 @@ def trim_messages(else:list_token_counter = actual_token_counterelse:- msg = (+ msg = ( # type: ignore[unreachable]f"'token_counter' expected to be a model that implements "f"'get_num_tokens_from_messages()' or a function. Received object of type "f"{type(actual_token_counter)}."@@ -1512,7 +1512,7 @@ def trim_messages(end_on=end_on,text_splitter=text_splitter_fn,)- msg = f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'."+ msg = f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'." # type: ignore[unreachable]raise ValueError(msg)@@ -2329,10 +2329,10 @@ def count_tokens_approximately(message_chars += len(repr(block))else:# Fallback for unexpected block types- message_chars += len(repr(block))+ message_chars += len(repr(block)) # type: ignore[unreachable]else:# Fallback for other content types- content = repr(message.content)+ content = repr(message.content) # type: ignore[unreachable]message_chars += len(content)if (diff --git a/libs/core/langchain_core/output_parsers/openai_functions.py b/libs/core/langchain_core/output_parsers/openai_functions.pyindex 812af64292..794f0b16ae 100644--- a/libs/core/langchain_core/output_parsers/openai_functions.py+++ b/libs/core/langchain_core/output_parsers/openai_functions.py@@ -2,7 +2,6 @@import copyimport json-from types import GenericAliasfrom typing import Anyimport jsonpatch # type: ignore[import-untyped]@@ -17,6 +16,7 @@ from langchain_core.output_parsers import ()from langchain_core.output_parsers.json import parse_partial_jsonfrom langchain_core.outputs import ChatGeneration, Generation+from langchain_core.utils.pydantic import PydanticBaseModel, TypeBaseModelclass OutputFunctionsParser(BaseGenerationOutputParser[Any]):@@ -219,7 +219,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):"""- pydantic_schema: type[BaseModel] | dict[str, type[BaseModel]]+ pydantic_schema: TypeBaseModel | dict[str, TypeBaseModel]"""The Pydantic schema to parse the output with.If multiple schemas are provided, then the function name will be used to@@ -242,10 +242,8 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):"""schema = values["pydantic_schema"]if "args_only" not in values:- values["args_only"] = (- isinstance(schema, type)- and not isinstance(schema, GenericAlias)- and issubclass(schema, BaseModel)+ values["args_only"] = isinstance(schema, type) and issubclass(+ schema, BaseModel)elif values["args_only"] and isinstance(schema, dict):msg = (@@ -270,11 +268,24 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):The parsed JSON object."""result_ = super().parse_result(result)+ pydantic_args: PydanticBaseModelif self.args_only:- if hasattr(self.pydantic_schema, "model_validate_json"):+ if isinstance(self.pydantic_schema, dict):+ msg = (+ "Dict Pydantic schema unsupported with args_only: "+ f"{self.pydantic_schema}"+ )+ raise ValueError(msg)+ if issubclass(self.pydantic_schema, BaseModel):pydantic_args = self.pydantic_schema.model_validate_json(result_)+ elif issubclass(self.pydantic_schema, BaseModelV1):+ pydantic_args = self.pydantic_schema.parse_raw(result_)else:- pydantic_args = self.pydantic_schema.parse_raw(result_) # type: ignore[attr-defined]+ msg = ( # type: ignore[unreachable]+ "Unsupported Pydantic schema with args_only: "+ f"{self.pydantic_schema}"+ )+ raise ValueError(msg)else:fn_name = result_["name"]args = result_["arguments"]@@ -287,7 +298,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):elif issubclass(pydantic_schema, BaseModelV1):pydantic_args = pydantic_schema.parse_raw(args)else:- msg = f"Unsupported Pydantic schema: {pydantic_schema}"+ msg = f"Unsupported Pydantic schema: {pydantic_schema}" # type: ignore[unreachable]raise ValueError(msg)return pydantic_argsdiff --git a/libs/core/langchain_core/output_parsers/pydantic.py b/libs/core/langchain_core/output_parsers/pydantic.pyindex ab89c91754..3f8130e1e3 100644--- a/libs/core/langchain_core/output_parsers/pydantic.py+++ b/libs/core/langchain_core/output_parsers/pydantic.py@@ -28,8 +28,10 @@ class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):return self.pydantic_object.model_validate(obj)if issubclass(self.pydantic_object, pydantic.v1.BaseModel):return self.pydantic_object.parse_obj(obj)- msg = f"Unsupported model version for PydanticOutputParser: \- {self.pydantic_object.__class__}"+ msg = ( # type: ignore[unreachable]+ "Unsupported model version for PydanticOutputParser: "+ f"{self.pydantic_object.__class__}"+ )raise OutputParserException(msg)except (pydantic.ValidationError, pydantic.v1.ValidationError) as e:raise self._parser_exception(e, obj) from ediff --git a/libs/core/langchain_core/outputs/generation.py b/libs/core/langchain_core/outputs/generation.pyindex 246b68c1fc..d03a677bf8 100644--- a/libs/core/langchain_core/outputs/generation.py+++ b/libs/core/langchain_core/outputs/generation.py@@ -76,5 +76,5 @@ class GenerationChunk(Generation):text=self.text + other.text,generation_info=generation_info or None,)- msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'" # type: ignore[unreachable]raise TypeError(msg)diff --git a/libs/core/langchain_core/prompts/chat.py b/libs/core/langchain_core/prompts/chat.pyindex 4a912f64b6..3cc59e5b6a 100644--- a/libs/core/langchain_core/prompts/chat.py+++ b/libs/core/langchain_core/prompts/chat.py@@ -510,7 +510,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):template_format=template_format,)else:- msg = f"Invalid image template: {tmpl}"+ msg = f"Invalid image template: {tmpl}" # type: ignore[unreachable]raise ValueError(msg)prompt.append(img_template_obj)elif isinstance(tmpl, dict):@@ -527,10 +527,10 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):)prompt.append(data_template_obj)else:- msg = f"Invalid template: {tmpl}"+ msg = f"Invalid template: {tmpl}" # type: ignore[unreachable]raise ValueError(msg)return cls(prompt=prompt, **kwargs)- msg = f"Invalid template: {template}"+ msg = f"Invalid template: {template}" # type: ignore[unreachable]raise ValueError(msg)@classmethod@@ -1195,7 +1195,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):message = message_template.format_messages(**kwargs)result.extend(message)else:- msg = f"Unexpected input: {message_template}"+ msg = f"Unexpected input: {message_template}" # type: ignore[unreachable]raise ValueError(msg) # noqa: TRY004return result@@ -1223,7 +1223,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):message = await message_template.aformat_messages(**kwargs)result.extend(message)else:- msg = f"Unexpected input: {message_template}"+ msg = f"Unexpected input: {message_template}" # type: ignore[unreachable]raise ValueError(msg) # noqa:TRY004return result@@ -1340,7 +1340,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):def _create_template_from_message_type(message_type: str,- template: str | list[str | dict[str, Any]],+ template: str | list[str | dict[str, Any] | bool],template_format: PromptTemplateFormat = "f-string",) -> BaseMessagePromptTemplate:"""Create a message prompt template from a message type and template string.@@ -1358,7 +1358,7 @@ def _create_template_from_message_type("""if message_type in {"human", "user"}:message: BaseMessagePromptTemplate = HumanMessagePromptTemplate.from_template(- template, template_format=template_format+ cast("str", template), template_format=template_format)elif message_type in {"ai", "assistant"}:message = AIMessagePromptTemplate.from_template(@@ -1462,7 +1462,7 @@ def _convert_to_message_template(template = message["content"]else:if len(message) != 2: # noqa: PLR2004- msg = f"Expected 2-tuple of (role, template), got {message}"+ msg = f"Expected 2-tuple of (role, template), got {message}" # type: ignore[unreachable]raise ValueError(msg)message_type_str, template = message@@ -1485,7 +1485,7 @@ def _convert_to_message_template())else:- msg = f"Unsupported message type: {type(message)}"+ msg = f"Unsupported message type: {type(message)}" # type: ignore[unreachable]raise NotImplementedError(msg)return message_diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.pyindex 231553dc81..2631319f28 100644--- a/libs/core/langchain_core/runnables/base.py+++ b/libs/core/langchain_core/runnables/base.py@@ -1651,7 +1651,7 @@ class Runnable(ABC, Generic[Input, Output]):**kwargs,)else:- msg = f"Unsupported version: {version!r}. Expected 'v1', 'v2', or 'v3'."+ msg = f"Unsupported version: {version!r}. Expected 'v1', 'v2', or 'v3'." # type: ignore[unreachable]raise NotImplementedError(msg)async with aclosing(event_stream):@@ -4930,7 +4930,7 @@ class RunnableLambda(Runnable[Input, Output]):self.func = cast("Callable[[Input], Output]", func)func_for_name = funcelse:- msg = (+ msg = ( # type: ignore[unreachable]"Expected a callable type for `func`."f"Instead got an unsupported type: {type(func)}")@@ -5718,7 +5718,7 @@ class RunnableEachBase(RunnableSerializable[Sequence[Input], list[Output]]):async def _astream_events_unsupported_v1_v2(self) -> AsyncIterator[StreamEvent]:msg = "RunnableEach does not support astream_events yet."raise NotImplementedError(msg)- yield # makes this an async generator (never reached)+ yield # type: ignore[unreachable] # makes this an async generator (never reached)class RunnableEach(RunnableEachBase[Input, Output]):diff --git a/libs/core/langchain_core/runnables/graph_mermaid.py b/libs/core/langchain_core/runnables/graph_mermaid.pyindex 1499d6d1fa..941211dad9 100644--- a/libs/core/langchain_core/runnables/graph_mermaid.py+++ b/libs/core/langchain_core/runnables/graph_mermaid.py@@ -321,7 +321,7 @@ def draw_mermaid_png(proxies=proxies,)else:- supported_methods = ", ".join([m.value for m in MermaidDrawMethod])+ supported_methods = ", ".join([m.value for m in MermaidDrawMethod]) # type: ignore[unreachable]msg = (f"Invalid draw method: {draw_method}. "f"Supported draw methods are: {supported_methods}"diff --git a/libs/core/langchain_core/runnables/passthrough.py b/libs/core/langchain_core/runnables/passthrough.pyindex f6dc04ab12..c52731ceb7 100644--- a/libs/core/langchain_core/runnables/passthrough.py+++ b/libs/core/langchain_core/runnables/passthrough.py@@ -487,7 +487,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):**kwargs: Any,) -> dict[str, Any]:if not isinstance(value, dict):- msg = "The input to RunnablePassthrough.assign() must be a dict."+ msg = "The input to RunnablePassthrough.assign() must be a dict." # type: ignore[unreachable]raise ValueError(msg) # noqa: TRY004return {@@ -516,7 +516,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):**kwargs: Any,) -> dict[str, Any]:if not isinstance(value, dict):- msg = "The input to RunnablePassthrough.assign() must be a dict."+ msg = "The input to RunnablePassthrough.assign() must be a dict." # type: ignore[unreachable]raise ValueError(msg) # noqa: TRY004return {@@ -570,7 +570,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):# consume passthrough streamfor chunk in for_passthrough:if not isinstance(chunk, dict):- msg = "The input to RunnablePassthrough.assign() must be a dict."+ msg = "The input to RunnablePassthrough.assign() must be a dict." # type: ignore[unreachable]raise ValueError(msg) # noqa: TRY004# remove mapper keys from passthrough chunk, to be overwritten by mapfiltered = AddableDict(@@ -623,7 +623,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):# consume passthrough streamasync for chunk in for_passthrough:if not isinstance(chunk, dict):- msg = "The input to RunnablePassthrough.assign() must be a dict."+ msg = "The input to RunnablePassthrough.assign() must be a dict." # type: ignore[unreachable]raise ValueError(msg) # noqa: TRY004# remove mapper keys from passthrough chunk, to be overwritten by map output@@ -749,7 +749,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], Any]):def _pick(self, value: dict[str, Any]) -> Any:if not isinstance(value, dict):- msg = "The input to RunnablePassthrough.assign() must be a dict."+ msg = "The input to RunnablePassthrough.assign() must be a dict." # type: ignore[unreachable]raise ValueError(msg) # noqa: TRY004if isinstance(self.keys, str):diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.pyindex ce9486a75c..080c6d01cb 100644--- a/libs/core/langchain_core/runnables/utils.py+++ b/libs/core/langchain_core/runnables/utils.py@@ -147,16 +147,15 @@ def coro_with_context(Args:coro: The coroutine to await.context: The context to use.- create_task: Whether to create a task.+ create_task: Kept for compatibility; this helper always creates a task.Returns:The coroutine with the context."""if asyncio_accepts_context():return asyncio.create_task(coro, context=context) # type: ignore[arg-type,call-arg,unused-ignore]- if create_task:- return asyncio.create_task(coro) # type: ignore[arg-type]- return coro+ del create_task+ return context.run(asyncio.create_task, coro) # type: ignore[arg-type]class IsLocalDict(ast.NodeVisitor):diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.pyindex 66744e1ffe..4b26e1b39f 100644--- a/libs/core/langchain_core/tools/base.py+++ b/libs/core/langchain_core/tools/base.py@@ -685,7 +685,7 @@ class ChildTool(BaseTool):elif issubclass(input_args, BaseModelV1):input_args.parse_obj({key_: tool_input})else:- msg = f"args_schema must be a Pydantic BaseModel, got {input_args}"+ msg = f"args_schema must be a Pydantic BaseModel, got {input_args}" # type: ignore[unreachable]raise TypeError(msg)return tool_input@@ -728,7 +728,7 @@ class ChildTool(BaseTool):result_dict = result_v1.dict()result = result_v1else:- msg = (+ msg = ( # type: ignore[unreachable]f"args_schema must be a Pydantic BaseModel, got {self.args_schema}")raise NotImplementedError(msg)@@ -873,7 +873,7 @@ class ChildTool(BaseTool):# the callback manager.return (), tool_input.copy()# This code path is not expected to be reachable.- msg = f"Invalid tool input type: {type(tool_input)}"+ msg = f"Invalid tool input type: {type(tool_input)}" # type: ignore[unreachable]raise TypeError(msg)def run(@@ -1172,7 +1172,7 @@ def _handle_validation_error(elif callable(flag):content = flag(e)else:- msg = (+ msg = ( # type: ignore[unreachable]f"Got unexpected type of `handle_validation_error`. Expected bool, "f"str or callable. Received: {flag}")diff --git a/libs/core/langchain_core/tracers/event_stream.py b/libs/core/langchain_core/tracers/event_stream.pyindex 7d5db9cc8f..6e406827db 100644--- a/libs/core/langchain_core/tracers/event_stream.py+++ b/libs/core/langchain_core/tracers/event_stream.py@@ -1045,7 +1045,7 @@ async def _astream_events_implementation_v2(callbacks.add_handler(event_streamer, inherit=True)config["callbacks"] = callbackselse:- msg = (+ msg = ( # type: ignore[unreachable]f"Unexpected type for callbacks: {callbacks}.""Expected None, list or AsyncCallbackManager.")diff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.pyindex cf94189c9d..3bb2889b9d 100644--- a/libs/core/langchain_core/tracers/log_stream.py+++ b/libs/core/langchain_core/tracers/log_stream.py@@ -705,7 +705,7 @@ async def _astream_log_implementation(callbacks.add_handler(stream, inherit=True)config["callbacks"] = callbackselse:- msg = (+ msg = ( # type: ignore[unreachable]f"Unexpected type for callbacks: {callbacks}.""Expected None, list or AsyncCallbackManager.")diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.pyindex eae4a8c8a0..e2e21ddc28 100644--- a/libs/core/langchain_core/utils/function_calling.py+++ b/libs/core/langchain_core/utils/function_calling.py@@ -349,7 +349,7 @@ def _format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:return _convert_pydantic_to_openai_function(tool.tool_call_schema, name=tool.name, description=tool.description)- error_msg = (+ error_msg = ( # type: ignore[unreachable]f"Unsupported tool call schema: {tool.tool_call_schema}. ""Tool call schema must be a JSON schema dict or a Pydantic model.")diff --git a/libs/core/langchain_core/utils/mustache.py b/libs/core/langchain_core/utils/mustache.pyindex e8282b0f38..41d690330f 100644--- a/libs/core/langchain_core/utils/mustache.py+++ b/libs/core/langchain_core/utils/mustache.py@@ -384,7 +384,9 @@ def _get_key(if scope in (0, False):return scope- resolved_scope = scope+ resolved_scope: Literal[False, 0] | Mapping[str, Any] | Sequence[Any] = (+ scope+ )# For every dot separated keyfor child in key.split("."):# Return an empty string if falsy, with two exceptionsdiff --git a/libs/core/langchain_core/utils/pydantic.py b/libs/core/langchain_core/utils/pydantic.pyindex 9d78932263..ed6b3027cb 100644--- a/libs/core/langchain_core/utils/pydantic.py+++ b/libs/core/langchain_core/utils/pydantic.py@@ -343,7 +343,7 @@ def get_fields(return model.model_fieldsif issubclass(model, BaseModelV1):return model.__fields__- msg = f"Expected a Pydantic model. Got {model}"+ msg = f"Expected a Pydantic model. Got {model}" # type: ignore[unreachable]raise TypeError(msg)@@ -364,7 +364,7 @@ def model_json_schema(model: TypeBaseModel) -> dict[str, Any]:return model.model_json_schema()if issubclass(model, BaseModelV1):return model.schema()- msg = f"Expected a Pydantic model. Got {model}"+ msg = f"Expected a Pydantic model. Got {model}" # type: ignore[unreachable]raise TypeError(msg)@@ -386,7 +386,7 @@ def model_validate(model: TypeBaseModel, obj: Any) -> PydanticBaseModel:return model.model_validate(obj)if issubclass(model, BaseModelV1):return model.parse_obj(obj)- msg = f"Expected a Pydantic model. Got {model}"+ msg = f"Expected a Pydantic model. Got {model}" # type: ignore[unreachable]raise TypeError(msg)@@ -444,11 +444,7 @@ def _create_root_model(base_class_attributes["root"] = default_with warnings.catch_warnings():try:- if (- isinstance(type_, type)- and not isinstance(type_, GenericAlias)- and issubclass(type_, BaseModelV1)- ):+ if isinstance(type_, type) and issubclass(type_, BaseModelV1):warnings.filterwarnings(action="ignore", category=PydanticDeprecationWarning)diff --git a/libs/core/pyproject.toml b/libs/core/pyproject.tomlindex be02fd91b3..63b11114c2 100644--- a/libs/core/pyproject.toml+++ b/libs/core/pyproject.toml@@ -90,10 +90,7 @@ langchain-text-splitters = { path = "../text-splitters" }plugins = ["pydantic.mypy"]strict = trueenable_error_code = "deprecated"-# `warn_unreachable` is intentionally NOT enabled here (unlike the other strict-# libs). Under mypy 2.x it false-flags intentional defensive runtime checks as-# unreachable — most notably the SSRF / IP-policy guards in-# `langchain_core/_security/` — which we do not want to delete or blanket-ignore.+warn_unreachable = true# TODO: activate for 'strict' checkingdisallow_any_generics = falsediff --git a/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py b/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.pyindex 1d7a3063ad..6370f4a7c4 100644--- a/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py+++ b/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py@@ -178,7 +178,7 @@ class _EmptyStreamModel(BaseChatModel):) -> Iterator[ChatGenerationChunk]:del messages, stop, run_manager, kwargsif False:- yield ChatGenerationChunk(message=AIMessageChunk(content=""))+ yield ChatGenerationChunk(message=AIMessageChunk(content="")) # type: ignore[unreachable]async def _astream(self,@@ -189,7 +189,7 @@ class _EmptyStreamModel(BaseChatModel):) -> AsyncIterator[ChatGenerationChunk]:del messages, stop, run_manager, kwargsif False:- yield ChatGenerationChunk(message=AIMessageChunk(content=""))+ yield ChatGenerationChunk(message=AIMessageChunk(content="")) # type: ignore[unreachable]class TestCallbacks:diff --git a/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py b/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.pyindex ec8f89c801..4682f0e568 100644--- a/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py+++ b/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py@@ -168,7 +168,8 @@ class TestChatModelStream:def test_finish(self) -> None:stream = ChatModelStream()- assert not stream.done+ done = stream.done+ assert not doneusage = UsageInfo(input_tokens=10, output_tokens=5, total_tokens=15)stream._finish(MessageFinishData(event="message-finish", usage=usage))assert stream.donediff --git a/libs/core/tests/unit_tests/pydantic_utils.py b/libs/core/tests/unit_tests/pydantic_utils.pyindex 0499d9a321..813f77e41b 100644--- a/libs/core/tests/unit_tests/pydantic_utils.py+++ b/libs/core/tests/unit_tests/pydantic_utils.py@@ -108,7 +108,7 @@ def _schema(obj: Any) -> dict[str, Any]:raise TypeError(msg)-def _remove_additionalproperties(schema: dict[str, Any]) -> dict[str, Any]:+def _remove_additionalproperties(schema: Any) -> Any:"""Remove `"additionalProperties": True` from dicts in the schema.Pydantic 2.11 and later versions include `"additionalProperties": True` whendiff --git a/libs/core/tests/unit_tests/runnables/test_runnable.py b/libs/core/tests/unit_tests/runnables/test_runnable.pyindex 2bd9f4bd24..580b89bc9b 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable.py@@ -3826,7 +3826,8 @@ def _empty_mapper_assign() -> RunnableAssign:async for _ in it:passreturn- yield # pragma: no cover # make this an async generator function+ # make this an async generator function+ yield # type: ignore[unreachable] # pragma: no coverreturn RunnablePassthrough.assign(foo=RunnableGenerator(empty_gen, aempty_gen))diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.pyindex e1989a9724..1c572e956c 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py@@ -562,9 +562,7 @@ async def test_astream_events_from_model() -> None:@RunnableLambdadef i_dont_stream(value: Any, config: RunnableConfig) -> Any:- if sys.version_info >= (3, 11):- return model.invoke(value)- return model.invoke(value, config)+ return model.invoke(value, config if sys.version_info >= (3, 11) else None)events = await _collect_events(i_dont_stream.astream_events("hello", version="v1"))_assert_events_equal_allow_superset_metadata(@@ -694,9 +692,9 @@ async def test_astream_events_from_model() -> None:@RunnableLambdaasync def ai_dont_stream(value: Any, config: RunnableConfig) -> Any:- if sys.version_info >= (3, 11):- return await model.ainvoke(value)- return await model.ainvoke(value, config)+ return await model.ainvoke(+ value, config if sys.version_info >= (3, 11) else None+ )events = await _collect_events(ai_dont_stream.astream_events("hello", version="v1"))_assert_events_equal_allow_superset_metadata(diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.pyindex a9fb009aef..0871406e77 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py@@ -629,9 +629,7 @@ async def test_astream_with_model_in_chain() -> None:@RunnableLambdadef i_dont_stream(value: Any, config: RunnableConfig) -> Any:- if sys.version_info >= (3, 11):- return model.invoke(value)- return model.invoke(value, config)+ return model.invoke(value, config if sys.version_info >= (3, 11) else None)events = await _collect_events(i_dont_stream.astream_events("hello", version="v2"))_assert_events_equal_allow_superset_metadata(@@ -745,9 +743,9 @@ async def test_astream_with_model_in_chain() -> None:@RunnableLambdaasync def ai_dont_stream(value: Any, config: RunnableConfig) -> Any:- if sys.version_info >= (3, 11):- return await model.ainvoke(value)- return await model.ainvoke(value, config)+ return await model.ainvoke(+ value, config if sys.version_info >= (3, 11) else None+ )events = await _collect_events(ai_dont_stream.astream_events("hello", version="v2"))_assert_events_equal_allow_superset_metadata(diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.pyindex 76c72d2770..991a2f6ffb 100644--- a/libs/core/tests/unit_tests/test_tools.py+++ b/libs/core/tests/unit_tests/test_tools.py@@ -73,6 +73,7 @@ from langchain_core.utils.pydantic import (TypeBaseModel,_create_subset_model,create_model_v2,+ model_json_schema,)from tests.unit_tests.fake.callbacks import FakeCallbackHandlerfrom tests.unit_tests.pydantic_utils import (@@ -98,7 +99,7 @@ def _get_tool_call_json_schema(tool: BaseTool) -> dict[str, Any]:return tool_schema.model_json_schema()if issubclass(tool_schema, BaseModelV1):return tool_schema.schema()- return {}+ return {} # type: ignore[unreachable]def test_unnamed_decorator() -> None:@@ -2091,13 +2092,7 @@ def test_args_schema_as_pydantic(pydantic_model: Any) -> None:}input_schema = tool.get_input_schema()- if issubclass(input_schema, BaseModel):- input_json_schema = input_schema.model_json_schema()- elif issubclass(input_schema, BaseModelV1):- input_json_schema = input_schema.schema()- else:- msg = "Unknown input schema type"- raise TypeError(msg)+ input_json_schema = model_json_schema(input_schema)assert input_json_schema == {"properties": {@@ -2268,14 +2263,9 @@ def test_structured_tool_with_different_pydantic_versions(pydantic_model: Any) -assert foo_tool.invoke({"a": 5, "b": "hello"}) == "foo"- args_schema = cast("type[BaseModel]", foo_tool.args_schema)- if issubclass(args_schema, BaseModel):- args_json_schema = args_schema.model_json_schema()- elif issubclass(args_schema, BaseModelV1):- args_json_schema = args_schema.schema()- else:- msg = "Unknown input schema type"- raise TypeError(msg)+ args_schema = cast("TypeBaseModel", foo_tool.args_schema)+ args_json_schema = model_json_schema(args_schema)+assert args_json_schema == {"properties": {"a": {"title": "A", "type": "integer"},@@ -2287,13 +2277,8 @@ def test_structured_tool_with_different_pydantic_versions(pydantic_model: Any) -}input_schema = foo_tool.get_input_schema()- if issubclass(input_schema, BaseModel):- input_json_schema = input_schema.model_json_schema()- elif issubclass(input_schema, BaseModelV1):- input_json_schema = input_schema.schema()- else:- msg = "Unknown input schema type"- raise TypeError(msg)+ input_json_schema = model_json_schema(input_schema)+assert input_json_schema == {"properties": {"a": {"title": "A", "type": "integer"},@@ -2364,20 +2349,21 @@ def test__get_all_basemodel_annotations_v2(*, use_v1_namespace: bool) -> None:if use_v1_namespace:if sys.version_info >= (3, 14):pytest.skip("pydantic.v1 namespace not supported with Python 3.14+")+ else:- class ModelA(BaseModelV1, Generic[A], extra="allow"):- a: A+ class ModelA(BaseModelV1, Generic[A], extra="allow"):+ a: A- class EmptyModel(BaseModelV1, Generic[A], extra="allow"):- pass+ class EmptyModel(BaseModelV1, Generic[A], extra="allow"):+ passelse:- class ModelA(BaseModel, Generic[A]): # type: ignore[no-redef]+ class ModelA(BaseModel, Generic[A]): # type: ignore[no-redef, unused-ignore]a: Amodel_config = ConfigDict(arbitrary_types_allowed=True, extra="allow")- class EmptyModel(BaseModel, Generic[A]): # type: ignore[no-redef]+ class EmptyModel(BaseModel, Generic[A]): # type: ignore[no-redef, unused-ignore]model_config = ConfigDict(arbitrary_types_allowed=True, extra="allow")class ModelB(ModelA[str]):