The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
core: Ruff preview fixes (#31877)
Christophe Bornet03e8327e0125
diff --git a/libs/core/langchain_core/_api/deprecation.py b/libs/core/langchain_core/_api/deprecation.pyindex 355d9d2274..63d04cd720 100644--- a/libs/core/langchain_core/_api/deprecation.py+++ b/libs/core/langchain_core/_api/deprecation.py@@ -469,7 +469,7 @@ def warn_deprecated(if not message:message = ""- _package = (+ package_ = (package or name.split(".")[0].replace("_", "-")if "." in nameelse "LangChain"@@ -483,14 +483,14 @@ def warn_deprecated(if pending:message += " will be deprecated in a future version"else:- message += f" was deprecated in {_package} {since}"+ message += f" was deprecated in {package_} {since}"if removal:message += f" and will be removed {removal}"if alternative_import:alt_package = alternative_import.split(".")[0].replace("_", "-")- if alt_package == _package:+ if alt_package == package_:message += f". Use {alternative_import} instead."else:alt_module, alt_name = alternative_import.rsplit(".", 1)diff --git a/libs/core/langchain_core/caches.py b/libs/core/langchain_core/caches.pyindex 2ccbf06bfe..b53816335c 100644--- a/libs/core/langchain_core/caches.py+++ b/libs/core/langchain_core/caches.py@@ -194,7 +194,7 @@ class InMemoryCache(BaseCache):"""if self._maxsize is not None and len(self._cache) == self._maxsize:del self._cache[next(iter(self._cache))]- self._cache[(prompt, llm_string)] = return_val+ self._cache[prompt, llm_string] = return_val@overridedef clear(self, **kwargs: Any) -> None:diff --git a/libs/core/langchain_core/document_loaders/base.py b/libs/core/langchain_core/document_loaders/base.pyindex f76edc873f..0d4054c2b9 100644--- a/libs/core/langchain_core/document_loaders/base.py+++ b/libs/core/langchain_core/document_loaders/base.py@@ -60,11 +60,11 @@ class BaseLoader(ABC): # noqa: B024)raise ImportError(msg) from e- _text_splitter: TextSplitter = RecursiveCharacterTextSplitter()+ text_splitter_: TextSplitter = RecursiveCharacterTextSplitter()else:- _text_splitter = text_splitter+ text_splitter_ = text_splitterdocs = self.load()- return _text_splitter.split_documents(docs)+ return text_splitter_.split_documents(docs)# Attention: This method will be upgraded into an abstractmethod once it's# implemented in all the existing subclasses.diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.pyindex 0323bb1e88..3b7f963762 100644--- a/libs/core/langchain_core/documents/base.py+++ b/libs/core/langchain_core/documents/base.py@@ -201,14 +201,14 @@ class Blob(BaseMedia):Blob instance"""if mime_type is None and guess_type:- _mimetype = mimetypes.guess_type(path)[0] if guess_type else None+ mimetype = mimetypes.guess_type(path)[0] if guess_type else Noneelse:- _mimetype = mime_type+ mimetype = mime_type# We do not load the data immediately, instead we treat the blob as a# reference to the underlying data.return cls(data=None,- mimetype=_mimetype,+ mimetype=mimetype,encoding=encoding,path=path,metadata=metadata if metadata is not None else {},diff --git a/libs/core/langchain_core/indexing/api.py b/libs/core/langchain_core/indexing/api.pyindex 9e1fc23785..657151013a 100644--- a/libs/core/langchain_core/indexing/api.py+++ b/libs/core/langchain_core/indexing/api.py@@ -273,7 +273,7 @@ def index(vector_store: Union[VectorStore, DocumentIndex],*,batch_size: int = 100,- cleanup: Literal["incremental", "full", "scoped_full", None] = None,+ cleanup: Optional[Literal["incremental", "full", "scoped_full"]] = None,source_id_key: Union[str, Callable[[Document], str], None] = None,cleanup_batch_size: int = 1_000,force_update: bool = False,@@ -540,10 +540,10 @@ def index()raise AssertionError(msg)- _source_ids = cast("Sequence[str]", source_ids)+ source_ids_ = cast("Sequence[str]", source_ids)while uids_to_delete := record_manager.list_keys(- group_ids=_source_ids, before=index_start_dt, limit=cleanup_batch_size+ group_ids=source_ids_, before=index_start_dt, limit=cleanup_batch_size):# Then delete from vector store._delete(destination, uids_to_delete)@@ -609,7 +609,7 @@ async def aindex(vector_store: Union[VectorStore, DocumentIndex],*,batch_size: int = 100,- cleanup: Literal["incremental", "full", "scoped_full", None] = None,+ cleanup: Optional[Literal["incremental", "full", "scoped_full"]] = None,source_id_key: Union[str, Callable[[Document], str], None] = None,cleanup_batch_size: int = 1_000,force_update: bool = False,@@ -881,10 +881,10 @@ async def aindex()raise AssertionError(msg)- _source_ids = cast("Sequence[str]", source_ids)+ source_ids_ = cast("Sequence[str]", source_ids)while uids_to_delete := await record_manager.alist_keys(- group_ids=_source_ids, before=index_start_dt, limit=cleanup_batch_size+ group_ids=source_ids_, before=index_start_dt, limit=cleanup_batch_size):# Then delete from vector store.await _adelete(destination, uids_to_delete)diff --git a/libs/core/langchain_core/language_models/_utils.py b/libs/core/langchain_core/language_models/_utils.pyindex 8b2a6776ab..3b7c0c5deb 100644--- a/libs/core/langchain_core/language_models/_utils.py+++ b/libs/core/langchain_core/language_models/_utils.py@@ -123,7 +123,7 @@ def _normalize_messages(messages: Sequence[BaseMessage]) -> list[BaseMessage]:# Subset to (PDF) files and audio, as most relevant chat models# support images in OAI format (and some may not yet support the# standard data block format)- and block.get("type") in ("file", "input_audio")+ and block.get("type") in {"file", "input_audio"}and _is_openai_data_block(block)):if formatted_message is message:diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.pyindex 2afa3bafea..db02058400 100644--- a/libs/core/langchain_core/language_models/chat_models.py+++ b/libs/core/langchain_core/language_models/chat_models.py@@ -1263,8 +1263,8 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):Returns:The predicted output string."""- _stop = None if stop is None else list(stop)- result = self([HumanMessage(content=text)], stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ result = self([HumanMessage(content=text)], stop=stop_, **kwargs)if isinstance(result.content, str):return result.contentmsg = "Cannot use predict when output is not a string."@@ -1279,17 +1279,17 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):stop: Optional[Sequence[str]] = None,**kwargs: Any,) -> BaseMessage:- _stop = None if stop is None else list(stop)- return self(messages, stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ return self(messages, stop=stop_, **kwargs)@deprecated("0.1.7", alternative="ainvoke", removal="1.0")@overrideasync def apredict(self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) -> str:- _stop = None if stop is None else list(stop)+ stop_ = None if stop is None else list(stop)result = await self._call_async(- [HumanMessage(content=text)], stop=_stop, **kwargs+ [HumanMessage(content=text)], stop=stop_, **kwargs)if isinstance(result.content, str):return result.content@@ -1305,8 +1305,8 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):stop: Optional[Sequence[str]] = None,**kwargs: Any,) -> BaseMessage:- _stop = None if stop is None else list(stop)- return await self._call_async(messages, stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ return await self._call_async(messages, stop=stop_, **kwargs)@property@abstractmethoddiff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.pyindex 7483e1a4aa..ff5a14dcd1 100644--- a/libs/core/langchain_core/language_models/llms.py+++ b/libs/core/langchain_core/language_models/llms.py@@ -93,10 +93,10 @@ def create_base_retry_decorator(Raises:ValueError: If the cache is not set and cache is True."""- _logging = before_sleep_log(logger, logging.WARNING)+ logging_ = before_sleep_log(logger, logging.WARNING)def _before_sleep(retry_state: RetryCallState) -> None:- _logging(retry_state)+ logging_(retry_state)if run_manager:if isinstance(run_manager, AsyncCallbackManagerForLLMRun):coro = run_manager.on_retry(retry_state)@@ -119,7 +119,7 @@ def create_base_retry_decorator(# 4 seconds, then up to 10 seconds, then 10 seconds afterwardsretry_instance: retry_base = retry_if_exception_type(error_types[0])for error in error_types[1:]:- retry_instance = retry_instance | retry_if_exception_type(error)+ retry_instance |= retry_if_exception_type(error)return retry(reraise=True,stop=stop_after_attempt(max_retries),@@ -155,7 +155,7 @@ def _resolve_cache(*, cache: Union[BaseCache, bool, None]) -> Optional[BaseCachedef get_prompts(params: dict[str, Any],prompts: list[str],- cache: Optional[Union[BaseCache, bool, None]] = None, # noqa: FBT001+ cache: Union[BaseCache, bool, None] = None, # noqa: FBT001) -> tuple[dict[int, list], str, list[int], list[str]]:"""Get prompts that are already cached.@@ -191,7 +191,7 @@ def get_prompts(async def aget_prompts(params: dict[str, Any],prompts: list[str],- cache: Optional[Union[BaseCache, bool, None]] = None, # noqa: FBT001+ cache: Union[BaseCache, bool, None] = None, # noqa: FBT001) -> tuple[dict[int, list], str, list[int], list[str]]:"""Get prompts that are already cached. Async version.@@ -877,8 +877,6 @@ class BaseLLM(BaseLanguageModel[str], ABC):**(metadata or {}),**self._get_ls_params(stop=stop, **kwargs),}- else:- passif (isinstance(callbacks, list)and callbacks@@ -1132,8 +1130,6 @@ class BaseLLM(BaseLanguageModel[str], ABC):**(metadata or {}),**self._get_ls_params(stop=stop, **kwargs),}- else:- pass# Create callback managersif isinstance(callbacks, list) and (isinstance(callbacks[0], (list, BaseCallbackManager))@@ -1352,8 +1348,8 @@ class BaseLLM(BaseLanguageModel[str], ABC):def predict(self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) -> str:- _stop = None if stop is None else list(stop)- return self(text, stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ return self(text, stop=stop_, **kwargs)@deprecated("0.1.7", alternative="invoke", removal="1.0")@override@@ -1365,8 +1361,8 @@ class BaseLLM(BaseLanguageModel[str], ABC):**kwargs: Any,) -> BaseMessage:text = get_buffer_string(messages)- _stop = None if stop is None else list(stop)- content = self(text, stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ content = self(text, stop=stop_, **kwargs)return AIMessage(content=content)@deprecated("0.1.7", alternative="ainvoke", removal="1.0")@@ -1374,8 +1370,8 @@ class BaseLLM(BaseLanguageModel[str], ABC):async def apredict(self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) -> str:- _stop = None if stop is None else list(stop)- return await self._call_async(text, stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ return await self._call_async(text, stop=stop_, **kwargs)@deprecated("0.1.7", alternative="ainvoke", removal="1.0")@override@@ -1387,8 +1383,8 @@ class BaseLLM(BaseLanguageModel[str], ABC):**kwargs: Any,) -> BaseMessage:text = get_buffer_string(messages)- _stop = None if stop is None else list(stop)- content = await self._call_async(text, stop=_stop, **kwargs)+ stop_ = None if stop is None else list(stop)+ content = await self._call_async(text, stop=stop_, **kwargs)return AIMessage(content=content)def __str__(self) -> str:diff --git a/libs/core/langchain_core/load/serializable.py b/libs/core/langchain_core/load/serializable.pyindex 9da23152f6..fde77e6993 100644--- a/libs/core/langchain_core/load/serializable.py+++ b/libs/core/langchain_core/load/serializable.py@@ -355,19 +355,19 @@ def to_json_not_implemented(obj: object) -> SerializedNotImplemented:Returns:SerializedNotImplemented"""- _id: list[str] = []+ id_: list[str] = []try:if hasattr(obj, "__name__"):- _id = [*obj.__module__.split("."), obj.__name__]+ id_ = [*obj.__module__.split("."), obj.__name__]elif hasattr(obj, "__class__"):- _id = [*obj.__class__.__module__.split("."), obj.__class__.__name__]+ id_ = [*obj.__class__.__module__.split("."), obj.__class__.__name__]except Exception:logger.debug("Failed to serialize object", exc_info=True)result: SerializedNotImplemented = {"lc": 1,"type": "not_implemented",- "id": _id,+ "id": id_,"repr": None,}with contextlib.suppress(Exception):diff --git a/libs/core/langchain_core/messages/tool.py b/libs/core/langchain_core/messages/tool.pyindex 553006e06e..09c9eb04f2 100644--- a/libs/core/langchain_core/messages/tool.py+++ b/libs/core/langchain_core/messages/tool.py@@ -126,8 +126,6 @@ class ToolMessage(BaseMessage, ToolOutputMixin):raise ValueError(msg) from eelse:values["content"].append(x)- else:- passtool_call_id = values["tool_call_id"]if isinstance(tool_call_id, (UUID, int, float)):@@ -366,4 +364,4 @@ def default_tool_chunk_parser(raw_tool_calls: list[dict]) -> list[ToolCallChunk]def _merge_status(left: Literal["success", "error"], right: Literal["success", "error"]) -> Literal["success", "error"]:- return "error" if "error" in (left, right) else "success"+ return "error" if "error" in {left, right} else "success"diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.pyindex 8c004aee53..21815d7626 100644--- a/libs/core/langchain_core/messages/utils.py+++ b/libs/core/langchain_core/messages/utils.py@@ -138,34 +138,34 @@ def get_buffer_string(def _message_from_dict(message: dict) -> BaseMessage:- _type = message["type"]- if _type == "human":+ type_ = message["type"]+ if type_ == "human":return HumanMessage(**message["data"])- if _type == "ai":+ if type_ == "ai":return AIMessage(**message["data"])- if _type == "system":+ if type_ == "system":return SystemMessage(**message["data"])- if _type == "chat":+ if type_ == "chat":return ChatMessage(**message["data"])- if _type == "function":+ if type_ == "function":return FunctionMessage(**message["data"])- if _type == "tool":+ if type_ == "tool":return ToolMessage(**message["data"])- if _type == "remove":+ if type_ == "remove":return RemoveMessage(**message["data"])- if _type == "AIMessageChunk":+ if type_ == "AIMessageChunk":return AIMessageChunk(**message["data"])- if _type == "HumanMessageChunk":+ if type_ == "HumanMessageChunk":return HumanMessageChunk(**message["data"])- if _type == "FunctionMessageChunk":+ if type_ == "FunctionMessageChunk":return FunctionMessageChunk(**message["data"])- if _type == "ToolMessageChunk":+ if type_ == "ToolMessageChunk":return ToolMessageChunk(**message["data"])- if _type == "SystemMessageChunk":+ if type_ == "SystemMessageChunk":return SystemMessageChunk(**message["data"])- if _type == "ChatMessageChunk":+ if type_ == "ChatMessageChunk":return ChatMessageChunk(**message["data"])- msg = f"Got unexpected message type: {_type}"+ msg = f"Got unexpected message type: {type_}"raise ValueError(msg)@@ -263,15 +263,15 @@ def _create_message_from_message_type()else:kwargs["tool_calls"].append(tool_call)- if message_type in ("human", "user"):+ if message_type in {"human", "user"}:if example := kwargs.get("additional_kwargs", {}).pop("example", False):kwargs["example"] = examplemessage: BaseMessage = HumanMessage(content=content, **kwargs)- elif message_type in ("ai", "assistant"):+ elif message_type in {"ai", "assistant"}:if example := kwargs.get("additional_kwargs", {}).pop("example", False):kwargs["example"] = examplemessage = AIMessage(content=content, **kwargs)- elif message_type in ("system", "developer"):+ elif message_type in {"system", "developer"}:if message_type == "developer":kwargs["additional_kwargs"] = kwargs.get("additional_kwargs") or {}kwargs["additional_kwargs"]["__openai_role__"] = "developer"@@ -315,13 +315,13 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:ValueError: if the message dict does not contain the required keys."""if isinstance(message, BaseMessage):- _message = message+ message_ = messageelif isinstance(message, str):- _message = _create_message_from_message_type("human", message)+ message_ = _create_message_from_message_type("human", message)elif isinstance(message, Sequence) and len(message) == 2:# mypy doesn't realise this can't be a string given the previous branchmessage_type_str, template = message # type: ignore[misc]- _message = _create_message_from_message_type(message_type_str, template)+ message_ = _create_message_from_message_type(message_type_str, template)elif isinstance(message, dict):msg_kwargs = message.copy()try:@@ -337,7 +337,7 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raise ValueError(msg) from e- _message = _create_message_from_message_type(+ message_ = _create_message_from_message_type(msg_type, msg_content, **msg_kwargs)else:@@ -345,7 +345,7 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raise NotImplementedError(msg)- return _message+ return message_def convert_to_messages(@@ -370,7 +370,7 @@ def convert_to_messages(def _runnable_support(func: Callable) -> Callable:@overloaddef wrapped(- messages: Literal[None] = None, **kwargs: Any+ messages: None = None, **kwargs: Any) -> Runnable[Sequence[MessageLikeRepresentation], list[BaseMessage]]: ...@overload@@ -519,8 +519,6 @@ def filter_messages(or (include_ids and msg.id in include_ids)):filtered.append(msg)- else:- passreturn filtered@@ -1000,7 +998,7 @@ def convert_to_openai_messages(.. versionadded:: 0.3.11""" # noqa: E501- if text_format not in ("string", "block"):+ if text_format not in {"string", "block"}:err = f"Unrecognized {text_format=}, expected one of 'string' or 'block'."raise ValueError(err)@@ -1125,8 +1123,7 @@ def convert_to_openai_messages("type": "image_url","image_url": {"url": (- f"data:image/{image['format']};"- f"base64,{b64_image}"+ f"data:image/{image['format']};base64,{b64_image}")},}diff --git a/libs/core/langchain_core/output_parsers/base.py b/libs/core/langchain_core/output_parsers/base.pyindex 5554fbc5bc..11737b7470 100644--- a/libs/core/langchain_core/output_parsers/base.py+++ b/libs/core/langchain_core/output_parsers/base.py@@ -28,7 +28,7 @@ T = TypeVar("T")OutputParserLike = Runnable[LanguageModelOutput, T]-class BaseLLMOutputParser(Generic[T], ABC):+class BaseLLMOutputParser(ABC, Generic[T]):"""Abstract base class for parsing the outputs of a model."""@abstractmethoddiff --git a/libs/core/langchain_core/output_parsers/openai_functions.py b/libs/core/langchain_core/output_parsers/openai_functions.pyindex a9e1f5f58f..708eb5bd81 100644--- a/libs/core/langchain_core/output_parsers/openai_functions.py+++ b/libs/core/langchain_core/output_parsers/openai_functions.py@@ -263,23 +263,23 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):Returns:The parsed JSON object."""- _result = super().parse_result(result)+ result_ = super().parse_result(result)if self.args_only:if hasattr(self.pydantic_schema, "model_validate_json"):- pydantic_args = self.pydantic_schema.model_validate_json(_result)+ pydantic_args = self.pydantic_schema.model_validate_json(result_)else:- pydantic_args = self.pydantic_schema.parse_raw(_result) # type: ignore[attr-defined]+ pydantic_args = self.pydantic_schema.parse_raw(result_) # type: ignore[attr-defined]else:- fn_name = _result["name"]- _args = _result["arguments"]+ fn_name = result_["name"]+ args = result_["arguments"]if isinstance(self.pydantic_schema, dict):pydantic_schema = self.pydantic_schema[fn_name]else:pydantic_schema = self.pydantic_schemaif issubclass(pydantic_schema, BaseModel):- pydantic_args = pydantic_schema.model_validate_json(_args)+ pydantic_args = pydantic_schema.model_validate_json(args)elif issubclass(pydantic_schema, BaseModelV1):- pydantic_args = pydantic_schema.parse_raw(_args)+ pydantic_args = pydantic_schema.parse_raw(args)else:msg = f"Unsupported pydantic schema: {pydantic_schema}"raise ValueError(msg)diff --git a/libs/core/langchain_core/output_parsers/xml.py b/libs/core/langchain_core/output_parsers/xml.pyindex 9f16319a1b..c6a46f3de1 100644--- a/libs/core/langchain_core/output_parsers/xml.py+++ b/libs/core/langchain_core/output_parsers/xml.py@@ -61,10 +61,10 @@ class _StreamingParser:"You can install it with `pip install defusedxml` ")raise ImportError(msg) from e- _parser = XMLParser(target=TreeBuilder())+ parser_ = XMLParser(target=TreeBuilder())else:- _parser = None- self.pull_parser = ET.XMLPullParser(["start", "end"], _parser=_parser)+ parser_ = None+ self.pull_parser = ET.XMLPullParser(["start", "end"], _parser=parser_)self.xml_start_re = re.compile(r"<[a-zA-Z:_]")self.current_path: list[str] = []self.current_path_has_children = False@@ -218,9 +218,9 @@ class XMLOutputParser(BaseTransformOutputParser):"See https://github.com/tiran/defusedxml for more details")raise ImportError(msg) from e- _et = ElementTree # Use the defusedxml parser+ et = ElementTree # Use the defusedxml parserelse:- _et = ET # Use the standard library parser+ et = ET # Use the standard library parsermatch = re.search(r"```(xml)?(.*)```", text, re.DOTALL)if match is not None:@@ -232,9 +232,9 @@ class XMLOutputParser(BaseTransformOutputParser):text = text.strip()try:- root = _et.fromstring(text)+ root = et.fromstring(text)return self._root_to_dict(root)- except _et.ParseError as e:+ except et.ParseError as e:msg = f"Failed to parse XML format from completion {text}. Got: {e}"raise OutputParserException(msg, llm_output=text) from ediff --git a/libs/core/langchain_core/outputs/chat_generation.py b/libs/core/langchain_core/outputs/chat_generation.pyindex a3480eb605..c36ae18a4a 100644--- a/libs/core/langchain_core/outputs/chat_generation.py+++ b/libs/core/langchain_core/outputs/chat_generation.py@@ -60,8 +60,6 @@ class ChatGeneration(Generation):if isinstance(block, dict) and "text" in block:text = block["text"]break- else:- passself.text = textreturn selfdiff --git a/libs/core/langchain_core/prompts/base.py b/libs/core/langchain_core/prompts/base.pyindex d880971750..e8d05bb1a6 100644--- a/libs/core/langchain_core/prompts/base.py+++ b/libs/core/langchain_core/prompts/base.py@@ -43,7 +43,7 @@ FormatOutputType = TypeVar("FormatOutputType")class BasePromptTemplate(- RunnableSerializable[dict, PromptValue], Generic[FormatOutputType], ABC+ RunnableSerializable[dict, PromptValue], ABC, Generic[FormatOutputType]):"""Base class for all prompt templates, returning a prompt."""@@ -186,14 +186,14 @@ class BasePromptTemplate(return inner_inputdef _format_prompt_with_error_handling(self, inner_input: dict) -> PromptValue:- _inner_input = self._validate_input(inner_input)- return self.format_prompt(**_inner_input)+ inner_input_ = self._validate_input(inner_input)+ return self.format_prompt(**inner_input_)async def _aformat_prompt_with_error_handling(self, inner_input: dict) -> PromptValue:- _inner_input = self._validate_input(inner_input)- return await self.aformat_prompt(**_inner_input)+ inner_input_ = self._validate_input(inner_input)+ return await self.aformat_prompt(**inner_input_)@overridedef invoke(diff --git a/libs/core/langchain_core/prompts/chat.py b/libs/core/langchain_core/prompts/chat.pyindex 633465bb50..2b912b1383 100644--- a/libs/core/langchain_core/prompts/chat.py+++ b/libs/core/langchain_core/prompts/chat.py@@ -545,6 +545,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):A new instance of this class."""template = Path(template_file).read_text()+ # TODO: .read_text(encoding="utf-8") for v0.4return cls.from_template(template, input_variables=input_variables, **kwargs)def format_messages(self, **kwargs: Any) -> list[BaseMessage]:@@ -946,7 +947,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):])"""- _messages = [+ messages_ = [_convert_to_message_template(message, template_format)for message in messages]@@ -955,7 +956,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):input_vars: set[str] = set()optional_variables: set[str] = set()partial_vars: dict[str, Any] = {}- for _message in _messages:+ for _message in messages_:if isinstance(_message, MessagesPlaceholder) and _message.optional:partial_vars[_message.variable_name] = []optional_variables.add(_message.variable_name)@@ -970,7 +971,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):"partial_variables": partial_vars,**kwargs,}- cast("type[ChatPromptTemplate]", super()).__init__(messages=_messages, **kwargs)+ cast("type[ChatPromptTemplate]", super()).__init__(messages=messages_, **kwargs)@classmethoddef get_lc_namespace(cls) -> list[str]:@@ -1005,8 +1006,8 @@ class ChatPromptTemplate(BaseChatPromptTemplate):**partials)if isinstance(other, (list, tuple)):- _other = ChatPromptTemplate.from_messages(other)- return ChatPromptTemplate(messages=self.messages + _other.messages).partial(+ other_ = ChatPromptTemplate.from_messages(other)+ return ChatPromptTemplate(messages=self.messages + other_.messages).partial(**partials)if isinstance(other, str):@@ -1053,9 +1054,9 @@ class ChatPromptTemplate(BaseChatPromptTemplate):if message.variable_name not in input_types:input_types[message.variable_name] = list[AnyMessage]if "partial_variables" in values:- input_vars = input_vars - set(values["partial_variables"])+ input_vars -= set(values["partial_variables"])if optional_variables:- input_vars = input_vars - optional_variables+ input_vars -= optional_variablesif "input_variables" in values and values.get("validate_template"):if input_vars != set(values["input_variables"]):msg = (@@ -1338,11 +1339,11 @@ def _create_template_from_message_type(Raises:ValueError: If unexpected message type."""- if message_type in ("human", "user"):+ if message_type in {"human", "user"}:message: BaseMessagePromptTemplate = HumanMessagePromptTemplate.from_template(template, template_format=template_format)- elif message_type in ("ai", "assistant"):+ elif message_type in {"ai", "assistant"}:message = AIMessagePromptTemplate.from_template(cast("str", template), template_format=template_format)@@ -1417,13 +1418,13 @@ def _convert_to_message_template(ValueError: If 2-tuple does not have 2 elements."""if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):- _message: Union[+ message_: Union[BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate] = messageelif isinstance(message, BaseMessage):- _message = message+ message_ = messageelif isinstance(message, str):- _message = _create_template_from_message_type(+ message_ = _create_template_from_message_type("human", message, template_format=template_format)elif isinstance(message, (tuple, dict)):@@ -1440,11 +1441,11 @@ def _convert_to_message_template(raise ValueError(msg)message_type_str, template = messageif isinstance(message_type_str, str):- _message = _create_template_from_message_type(+ message_ = _create_template_from_message_type(message_type_str, template, template_format=template_format)else:- _message = message_type_str(+ message_ = message_type_str(prompt=PromptTemplate.from_template(cast("str", template), template_format=template_format)@@ -1453,7 +1454,7 @@ def _convert_to_message_template(msg = f"Unsupported message type: {type(message)}"raise NotImplementedError(msg)- return _message+ return message_# For backwards compat:diff --git a/libs/core/langchain_core/prompts/dict.py b/libs/core/langchain_core/prompts/dict.pyindex 79882fc47f..0b5ee5072a 100644--- a/libs/core/langchain_core/prompts/dict.py+++ b/libs/core/langchain_core/prompts/dict.py@@ -100,8 +100,6 @@ def _get_input_variables(input_variables += get_template_variables(x, template_format)elif isinstance(x, dict):input_variables += _get_input_variables(x, template_format)- else:- passreturn list(set(input_variables))diff --git a/libs/core/langchain_core/prompts/pipeline.py b/libs/core/langchain_core/prompts/pipeline.pyindex 3c771b2dab..f1f5786f1e 100644--- a/libs/core/langchain_core/prompts/pipeline.py+++ b/libs/core/langchain_core/prompts/pipeline.py@@ -81,13 +81,13 @@ class PipelinePromptTemplate(BasePromptTemplate):A formatted string."""for k, prompt in self.pipeline_prompts:- _inputs = _get_inputs(kwargs, prompt.input_variables)+ inputs = _get_inputs(kwargs, prompt.input_variables)if isinstance(prompt, BaseChatPromptTemplate):- kwargs[k] = prompt.format_messages(**_inputs)+ kwargs[k] = prompt.format_messages(**inputs)else:- kwargs[k] = prompt.format(**_inputs)- _inputs = _get_inputs(kwargs, self.final_prompt.input_variables)- return self.final_prompt.format_prompt(**_inputs)+ kwargs[k] = prompt.format(**inputs)+ inputs = _get_inputs(kwargs, self.final_prompt.input_variables)+ return self.final_prompt.format_prompt(**inputs)async def aformat_prompt(self, **kwargs: Any) -> PromptValue:"""Async format the prompt with the inputs.@@ -99,13 +99,13 @@ class PipelinePromptTemplate(BasePromptTemplate):A formatted string."""for k, prompt in self.pipeline_prompts:- _inputs = _get_inputs(kwargs, prompt.input_variables)+ inputs = _get_inputs(kwargs, prompt.input_variables)if isinstance(prompt, BaseChatPromptTemplate):- kwargs[k] = await prompt.aformat_messages(**_inputs)+ kwargs[k] = await prompt.aformat_messages(**inputs)else:- kwargs[k] = await prompt.aformat(**_inputs)- _inputs = _get_inputs(kwargs, self.final_prompt.input_variables)- return await self.final_prompt.aformat_prompt(**_inputs)+ kwargs[k] = await prompt.aformat(**inputs)+ inputs = _get_inputs(kwargs, self.final_prompt.input_variables)+ return await self.final_prompt.aformat_prompt(**inputs)def format(self, **kwargs: Any) -> str:"""Format the prompt with the inputs.diff --git a/libs/core/langchain_core/prompts/prompt.py b/libs/core/langchain_core/prompts/prompt.pyindex 190b0aab3a..6b77a4e71c 100644--- a/libs/core/langchain_core/prompts/prompt.py+++ b/libs/core/langchain_core/prompts/prompt.py@@ -287,17 +287,17 @@ class PromptTemplate(StringPromptTemplate):The prompt template loaded from the template."""input_variables = get_template_variables(template, template_format)- _partial_variables = partial_variables or {}+ partial_variables_ = partial_variables or {}- if _partial_variables:+ if partial_variables_:input_variables = [- var for var in input_variables if var not in _partial_variables+ var for var in input_variables if var not in partial_variables_]return cls(input_variables=input_variables,template=template,template_format=template_format,- partial_variables=_partial_variables,+ partial_variables=partial_variables_,**kwargs,)diff --git a/libs/core/langchain_core/prompts/string.py b/libs/core/langchain_core/prompts/string.pyindex 084dd09f1f..69b3fd64c8 100644--- a/libs/core/langchain_core/prompts/string.py+++ b/libs/core/langchain_core/prompts/string.py@@ -131,12 +131,12 @@ def mustache_template_vars(if type_ == "end":section_depth -= 1elif (- type_ in ("variable", "section", "inverted section", "no escape")+ type_ in {"variable", "section", "inverted section", "no escape"}and key != "."and section_depth == 0):variables.add(key.split(".")[0])- if type_ in ("section", "inverted section"):+ if type_ in {"section", "inverted section"}:section_depth += 1return variables@@ -164,11 +164,11 @@ def mustache_schema(if type_ == "end":if section_stack:prefix = section_stack.pop()- elif type_ in ("section", "inverted section"):+ elif type_ in {"section", "inverted section"}:section_stack.append(prefix)prefix = prefix + tuple(key.split("."))fields[prefix] = False- elif type_ in ("variable", "no escape"):+ elif type_ in {"variable", "no escape"}:fields[prefix + tuple(key.split("."))] = Truedefs: Defs = {} # None means leaf nodewhile fields:diff --git a/libs/core/langchain_core/retrievers.py b/libs/core/langchain_core/retrievers.pyindex 557599a5ac..a532d6368f 100644--- a/libs/core/langchain_core/retrievers.py+++ b/libs/core/langchain_core/retrievers.py@@ -254,13 +254,13 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):run_id=kwargs.pop("run_id", None),)try:- _kwargs = kwargs if self._expects_other_args else {}+ kwargs_ = kwargs if self._expects_other_args else {}if self._new_arg_supported:result = self._get_relevant_documents(- input, run_manager=run_manager, **_kwargs+ input, run_manager=run_manager, **kwargs_)else:- result = self._get_relevant_documents(input, **_kwargs)+ result = self._get_relevant_documents(input, **kwargs_)except Exception as e:run_manager.on_retriever_error(e)raise@@ -318,13 +318,13 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):run_id=kwargs.pop("run_id", None),)try:- _kwargs = kwargs if self._expects_other_args else {}+ kwargs_ = kwargs if self._expects_other_args else {}if self._new_arg_supported:result = await self._aget_relevant_documents(- input, run_manager=run_manager, **_kwargs+ input, run_manager=run_manager, **kwargs_)else:- result = await self._aget_relevant_documents(input, **_kwargs)+ result = await self._aget_relevant_documents(input, **kwargs_)except Exception as e:await run_manager.on_retriever_error(e)raisediff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.pyindex 7a36db9da4..5b093a205b 100644--- a/libs/core/langchain_core/runnables/base.py+++ b/libs/core/langchain_core/runnables/base.py@@ -108,7 +108,7 @@ if TYPE_CHECKING:Other = TypeVar("Other")-class Runnable(Generic[Input, Output], ABC):+class Runnable(ABC, Generic[Input, Output]):"""A unit of work that can be invoked, batched, streamed, transformed and composed.Key Methods@@ -4486,10 +4486,10 @@ class RunnableLambda(Runnable[Input, Output]):sig = inspect.signature(func)if sig.return_annotation != inspect.Signature.empty:# unwrap iterator types- if getattr(sig.return_annotation, "__origin__", None) in (+ if getattr(sig.return_annotation, "__origin__", None) in {collections.abc.Iterator,collections.abc.AsyncIterator,- ):+ }:return getattr(sig.return_annotation, "__args__", (Any,))[0]return sig.return_annotationexcept ValueError:diff --git a/libs/core/langchain_core/runnables/branch.py b/libs/core/langchain_core/runnables/branch.pyindex b34f312e0a..b6f9d5f443 100644--- a/libs/core/langchain_core/runnables/branch.py+++ b/libs/core/langchain_core/runnables/branch.py@@ -111,7 +111,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):"Runnable[Input, Output]", coerce_to_runnable(cast("RunnableLike", default)))- _branches = []+ branches_ = []for branch in branches[:-1]:if not isinstance(branch, (tuple, list)):@@ -130,10 +130,10 @@ class RunnableBranch(RunnableSerializable[Input, Output]):condition, runnable = branchcondition = cast("Runnable[Input, bool]", coerce_to_runnable(condition))runnable = coerce_to_runnable(runnable)- _branches.append((condition, runnable))+ branches_.append((condition, runnable))super().__init__(- branches=_branches,+ branches=branches_,default=default_,) # type: ignore[call-arg]diff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.pyindex daee67b516..713fbfdb13 100644--- a/libs/core/langchain_core/runnables/graph.py+++ b/libs/core/langchain_core/runnables/graph.py@@ -361,7 +361,7 @@ class Graph:"""self.nodes.pop(node.id)self.edges = [- edge for edge in self.edges if node.id not in (edge.source, edge.target)+ edge for edge in self.edges if node.id not in {edge.source, edge.target}]def add_edge(diff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.pyindex 53288b5160..659a83f9cc 100644--- a/libs/core/langchain_core/runnables/history.py+++ b/libs/core/langchain_core/runnables/history.py@@ -339,10 +339,10 @@ class RunnableWithMessageHistory(RunnableBindingBase):).with_config(run_name="RunnableWithMessageHistory")if history_factory_config:- _config_specs = history_factory_config+ config_specs = history_factory_configelse:# If not provided, then we'll use the default session_id field- _config_specs = [+ config_specs = [ConfigurableFieldSpec(id="session_id",annotation=str,@@ -359,7 +359,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):output_messages_key=output_messages_key,bound=bound,history_messages_key=history_messages_key,- history_factory_config=_config_specs,+ history_factory_config=config_specs,**kwargs,)self._history_chain = history_chaindiff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.pyindex 7e5b68d01d..3a740e868e 100644--- a/libs/core/langchain_core/runnables/utils.py+++ b/libs/core/langchain_core/runnables/utils.py@@ -194,7 +194,7 @@ class IsLocalDict(ast.NodeVisitor):and isinstance(node.func.value, ast.Name)and node.func.value.id == self.nameand node.func.attr == "get"- and len(node.args) in (1, 2)+ and len(node.args) in {1, 2}and isinstance(node.args[0], ast.Constant)and isinstance(node.args[0].value, str)):diff --git a/libs/core/langchain_core/stores.py b/libs/core/langchain_core/stores.pyindex 2d40a6330d..860fa1edc3 100644--- a/libs/core/langchain_core/stores.py+++ b/libs/core/langchain_core/stores.py@@ -23,7 +23,7 @@ K = TypeVar("K")V = TypeVar("V")-class BaseStore(Generic[K, V], ABC):+class BaseStore(ABC, Generic[K, V]):"""Abstract interface for a key-value store.This is an interface that's meant to abstract away the details ofdiff --git a/libs/core/langchain_core/sys_info.py b/libs/core/langchain_core/sys_info.pyindex 8443a23e55..96deed97dd 100644--- a/libs/core/langchain_core/sys_info.py+++ b/libs/core/langchain_core/sys_info.py@@ -8,7 +8,7 @@ def _get_sub_deps(packages: Sequence[str]) -> list[str]:from importlib import metadatasub_deps = set()- _underscored_packages = {pkg.replace("-", "_") for pkg in packages}+ underscored_packages = {pkg.replace("-", "_") for pkg in packages}for pkg in packages:try:@@ -21,7 +21,7 @@ def _get_sub_deps(packages: Sequence[str]) -> list[str]:for req in required:cleaned_req = req.split(" ")[0]- if cleaned_req.replace("-", "_") not in _underscored_packages:+ if cleaned_req.replace("-", "_") not in underscored_packages:sub_deps.add(cleaned_req)return sorted(sub_deps, key=lambda x: x.lower())diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.pyindex fdc01ddc11..11fc5014c5 100644--- a/libs/core/langchain_core/tools/base.py+++ b/libs/core/langchain_core/tools/base.py@@ -134,7 +134,7 @@ def _get_filtered_args(k: schema[k]for i, (k, param) in enumerate(valid_keys.items())if k not in filter_args- and (i > 0 or param.name not in ("self", "cls"))+ and (i > 0 or param.name not in {"self", "cls"})and (include_injected or not _is_injected_arg_type(param.annotation))}@@ -336,7 +336,7 @@ def create_schema_from_function(else:# Handle classmethods and instance methodsexisting_params: list[str] = list(sig.parameters.keys())- if existing_params and existing_params[0] in ("self", "cls") and in_class:+ if existing_params and existing_params[0] in {"self", "cls"} and in_class:filter_args_ = [existing_params[0], *list(FILTERED_ARGS)]else:filter_args_ = list(FILTERED_ARGS)@@ -846,9 +846,9 @@ class ChildTool(BaseTool):tool_input, tool_call_id)if signature(self._run).parameters.get("run_manager"):- tool_kwargs = tool_kwargs | {"run_manager": run_manager}+ tool_kwargs |= {"run_manager": run_manager}if config_param := _get_runnable_config_param(self._run):- tool_kwargs = tool_kwargs | {config_param: config}+ tool_kwargs |= {config_param: config}response = context.run(self._run, *tool_args, **tool_kwargs)if self.response_format == "content_and_artifact":if not isinstance(response, tuple) or len(response) != 2:diff --git a/libs/core/langchain_core/tracers/core.py b/libs/core/langchain_core/tracers/core.pyindex 8d1287ef91..0a10b06eca 100644--- a/libs/core/langchain_core/tracers/core.py+++ b/libs/core/langchain_core/tracers/core.py@@ -165,7 +165,7 @@ class _TracerCore(ABC):**kwargs: Any,) -> Run:"""Create a chat model run."""- if self._schema_format not in ("streaming_events", "original+chat"):+ if self._schema_format not in {"streaming_events", "original+chat"}:# Please keep this un-implemented for backwards compatibility.# When it's unimplemented old tracers that use the "original" format# fallback on the on_llm_start method implementation if they@@ -352,7 +352,7 @@ class _TracerCore(ABC):def _get_chain_inputs(self, inputs: Any) -> Any:"""Get the inputs for a chain run."""- if self._schema_format in ("original", "original+chat"):+ if self._schema_format in {"original", "original+chat"}:return inputs if isinstance(inputs, dict) else {"input": inputs}if self._schema_format == "streaming_events":return {@@ -363,7 +363,7 @@ class _TracerCore(ABC):def _get_chain_outputs(self, outputs: Any) -> Any:"""Get the outputs for a chain run."""- if self._schema_format in ("original", "original+chat"):+ if self._schema_format in {"original", "original+chat"}:return outputs if isinstance(outputs, dict) else {"output": outputs}if self._schema_format == "streaming_events":return {@@ -423,7 +423,7 @@ class _TracerCore(ABC):if metadata:kwargs.update({"metadata": metadata})- if self._schema_format in ("original", "original+chat"):+ if self._schema_format in {"original", "original+chat"}:inputs = {"input": input_str}elif self._schema_format == "streaming_events":inputs = {"input": inputs}diff --git a/libs/core/langchain_core/tracers/event_stream.py b/libs/core/langchain_core/tracers/event_stream.pyindex dc81c9d01c..e510356e6b 100644--- a/libs/core/langchain_core/tracers/event_stream.py+++ b/libs/core/langchain_core/tracers/event_stream.py@@ -773,7 +773,7 @@ async def _astream_events_implementation_v1(run_log = RunLog(state=None) # type: ignore[arg-type]encountered_start_event = False- _root_event_filter = _RootEventFilter(+ root_event_filter = _RootEventFilter(include_names=include_names,include_types=include_types,include_tags=include_tags,@@ -796,7 +796,7 @@ async def _astream_events_implementation_v1(with_streamed_output_list=True,**kwargs,):- run_log = run_log + log+ run_log += logif not encountered_start_event:# Yield the start event for the root runnable.@@ -815,7 +815,7 @@ async def _astream_events_implementation_v1(parent_ids=[], # Not supported in v1)- if _root_event_filter.include_event(event, state["type"]):+ if root_event_filter.include_event(event, state["type"]):yield eventpaths = {@@ -901,7 +901,7 @@ async def _astream_events_implementation_v1(data=data,parent_ids=[], # Not supported in v1)- if _root_event_filter.include_event(event, state["type"]):+ if root_event_filter.include_event(event, state["type"]):yield eventstate = run_log.state@@ -918,7 +918,7 @@ async def _astream_events_implementation_v1(},parent_ids=[], # Not supported in v1)- if _root_event_filter.include_event(event, state["type"]):+ if root_event_filter.include_event(event, state["type"]):yield eventdiff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.pyindex aba99c3186..caae5d3188 100644--- a/libs/core/langchain_core/tracers/log_stream.py+++ b/libs/core/langchain_core/tracers/log_stream.py@@ -698,7 +698,7 @@ async def _astream_log_implementation(else:state = RunLog(state=None) # type: ignore[arg-type]async for log in stream:- state = state + log+ state += logyield statefinally:# Wait for the runnable to finish, if not cancelled (eg. by break)diff --git a/libs/core/langchain_core/utils/env.py b/libs/core/langchain_core/utils/env.pyindex 8c352f90cd..9f37b3c4f4 100644--- a/libs/core/langchain_core/utils/env.py+++ b/libs/core/langchain_core/utils/env.py@@ -15,12 +15,12 @@ def env_var_is_set(env_var: str) -> bool:Returns:bool: True if the environment variable is set, False otherwise."""- return env_var in os.environ and os.environ[env_var] not in (+ return env_var in os.environ and os.environ[env_var] not in {"","0","false","False",- )+ }def get_from_dict_or_env(diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.pyindex 729898fe9d..2d2fa6e408 100644--- a/libs/core/langchain_core/utils/function_calling.py+++ b/libs/core/langchain_core/utils/function_calling.py@@ -294,8 +294,6 @@ def _convert_any_typed_dicts_to_pydantic(raise ValueError(msg)if arg_desc := arg_descriptions.get(arg):field_kwargs["description"] = arg_desc- else:- passfields[arg] = (new_arg_type, Field_v1(**field_kwargs))else:new_arg_type = _convert_any_typed_dicts_to_pydantic(@@ -456,7 +454,7 @@ def convert_to_openai_function(oai_function = {k: vfor k, v in function.items()- if k in ("name", "description", "parameters", "strict")+ if k in {"name", "description", "parameters", "strict"}}# a JSON schema with title and descriptionelif isinstance(function, dict) and "title" in function:@@ -734,7 +732,7 @@ def _parse_google_docstring(docstring_blocks = docstring.split("\n\n")if error_on_invalid_docstring:filtered_annotations = {- arg for arg in args if arg not in ("run_manager", "callbacks", "return")+ arg for arg in args if arg not in {"run_manager", "callbacks", "return"}}if filtered_annotations and (len(docstring_blocks) < 2@@ -770,8 +768,8 @@ def _parse_google_docstring(if ":" in line:arg, desc = line.split(":", maxsplit=1)arg = arg.strip()- arg_name, _, _annotations = arg.partition(" ")- if _annotations.startswith("(") and _annotations.endswith(")"):+ arg_name, _, annotations_ = arg.partition(" ")+ if annotations_.startswith("(") and annotations_.endswith(")"):arg = arg_namearg_descriptions[arg] = desc.strip()elif arg:diff --git a/libs/core/langchain_core/utils/image.py b/libs/core/langchain_core/utils/image.pyindex 8931f0bc2e..2f2cce4ee1 100644--- a/libs/core/langchain_core/utils/image.py+++ b/libs/core/langchain_core/utils/image.py@@ -4,7 +4,7 @@ from typing import Anydef __getattr__(name: str) -> Any:- if name in ("encode_image", "image_to_data_url"):+ if name in {"encode_image", "image_to_data_url"}:msg = (f"'{name}' has been removed for security reasons.\n\n"f"Usage of this utility in environments with user-input paths is a "diff --git a/libs/core/langchain_core/utils/mustache.py b/libs/core/langchain_core/utils/mustache.pyindex ab0bc60407..be0739568c 100644--- a/libs/core/langchain_core/utils/mustache.py+++ b/libs/core/langchain_core/utils/mustache.py@@ -107,7 +107,7 @@ def r_sa_check(bool: Whether the tag could be a standalone."""# Check right side if we might be a standalone- if is_standalone and tag_type not in ["variable", "no escape"]:+ if is_standalone and tag_type not in {"variable", "no escape"}:on_newline = template.split("\n", 1)# If the stuff to the right of us are spaces we're a standalone@@ -255,7 +255,7 @@ def tokenize(l_del, r_del = dels[0], dels[-1]# If we are a section tag- elif tag_type in ["section", "inverted section"]:+ elif tag_type in {"section", "inverted section"}:# Then open a new sectionopen_sections.append(tag_key)_LAST_TAG_LINE = _CURRENT_LINE@@ -301,7 +301,7 @@ def tokenize(yield ("literal", literal)# Ignore comments and set delimiters- if tag_type not in ["comment", "set delimiter?"]:+ if tag_type not in {"comment", "set delimiter?"}:yield (tag_type, tag_key)# If there are any open sections when we're done@@ -486,7 +486,7 @@ def render(# If the current scope is falsy and not the only scopeelif not current_scope and len(scopes) != 1:- if tag in ["section", "inverted section"]:+ if tag in {"section", "inverted section"}:# Set the most recent scope to a falsy valuescopes.insert(0, False)diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.pyindex 0158e92d90..1b0c3e6a29 100644--- a/libs/core/langchain_core/vectorstores/base.py+++ b/libs/core/langchain_core/vectorstores/base.py@@ -1052,9 +1052,9 @@ class VectorStoreRetriever(BaseRetriever):def _get_ls_params(self, **kwargs: Any) -> LangSmithRetrieverParams:"""Get standard params for tracing."""- _kwargs = self.search_kwargs | kwargs+ kwargs_ = self.search_kwargs | kwargs- ls_params = super()._get_ls_params(**_kwargs)+ ls_params = super()._get_ls_params(**kwargs_)ls_params["ls_vector_store_provider"] = self.vectorstore.__class__.__name__if self.vectorstore.embeddings:@@ -1074,18 +1074,18 @@ class VectorStoreRetriever(BaseRetriever):def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any) -> list[Document]:- _kwargs = self.search_kwargs | kwargs+ kwargs_ = self.search_kwargs | kwargsif self.search_type == "similarity":- docs = self.vectorstore.similarity_search(query, **_kwargs)+ docs = self.vectorstore.similarity_search(query, **kwargs_)elif self.search_type == "similarity_score_threshold":docs_and_similarities = (self.vectorstore.similarity_search_with_relevance_scores(- query, **_kwargs+ query, **kwargs_))docs = [doc for doc, _ in docs_and_similarities]elif self.search_type == "mmr":- docs = self.vectorstore.max_marginal_relevance_search(query, **_kwargs)+ docs = self.vectorstore.max_marginal_relevance_search(query, **kwargs_)else:msg = f"search_type of {self.search_type} not allowed."raise ValueError(msg)@@ -1099,19 +1099,19 @@ class VectorStoreRetriever(BaseRetriever):run_manager: AsyncCallbackManagerForRetrieverRun,**kwargs: Any,) -> list[Document]:- _kwargs = self.search_kwargs | kwargs+ kwargs_ = self.search_kwargs | kwargsif self.search_type == "similarity":- docs = await self.vectorstore.asimilarity_search(query, **_kwargs)+ docs = await self.vectorstore.asimilarity_search(query, **kwargs_)elif self.search_type == "similarity_score_threshold":docs_and_similarities = (await self.vectorstore.asimilarity_search_with_relevance_scores(- query, **_kwargs+ query, **kwargs_))docs = [doc for doc, _ in docs_and_similarities]elif self.search_type == "mmr":docs = await self.vectorstore.amax_marginal_relevance_search(- query, **_kwargs+ query, **kwargs_)else:msg = f"search_type of {self.search_type} not allowed."diff --git a/libs/core/langchain_core/vectorstores/in_memory.py b/libs/core/langchain_core/vectorstores/in_memory.pyindex 383ac1d0a7..23eb412708 100644--- a/libs/core/langchain_core/vectorstores/in_memory.py+++ b/libs/core/langchain_core/vectorstores/in_memory.py@@ -596,8 +596,8 @@ class InMemoryVectorStore(VectorStore):Returns:A VectorStore object."""- _path: Path = Path(path)- with _path.open("r") as f:+ path_: Path = Path(path)+ with path_.open("r") as f:store = load(json.load(f))vectorstore = cls(embedding=embedding, **kwargs)vectorstore.store = store@@ -609,7 +609,7 @@ class InMemoryVectorStore(VectorStore):Args:path: The path to dump the vector store to."""- _path: Path = Path(path)- _path.parent.mkdir(exist_ok=True, parents=True)- with _path.open("w") as f:+ path_: Path = Path(path)+ path_.parent.mkdir(exist_ok=True, parents=True)+ with path_.open("w") as f:json.dump(dumpd(self.store), f, indent=2)diff --git a/libs/core/tests/unit_tests/indexing/test_in_memory_record_manager.py b/libs/core/tests/unit_tests/indexing/test_in_memory_record_manager.pyindex 991c66634c..a08f54626d 100644--- a/libs/core/tests/unit_tests/indexing/test_in_memory_record_manager.py+++ b/libs/core/tests/unit_tests/indexing/test_in_memory_record_manager.py@@ -242,11 +242,11 @@ async def test_list_keys(manager: InMemoryRecordManager) -> None:results = manager.list_keys(limit=1)assert len(results) == 1- assert results[0] in ["key1", "key2", "key3", "key4", "key5"]+ assert results[0] in {"key1", "key2", "key3", "key4", "key5"}results = await manager.alist_keys(limit=1)assert len(results) == 1- assert results[0] in ["key1", "key2", "key3", "key4", "key5"]+ assert results[0] in {"key1", "key2", "key3", "key4", "key5"}def test_delete_keys(manager: InMemoryRecordManager) -> None:diff --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 ed033896bc..41b197cd8c 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@@ -342,7 +342,7 @@ def test_disable_streaming(== expected)- expected = "invoke" if disable_streaming in ("tool_calling", True) else "stream"+ expected = "invoke" if disable_streaming in {"tool_calling", True} else "stream"assert next(model.stream([], tools=[{"type": "function"}])).content == expectedassert (model.invoke(@@ -368,7 +368,7 @@ async def test_disable_streaming_async(await model.ainvoke([], config={"callbacks": [_AstreamEventsCallbackHandler()]})).content == expected- expected = "invoke" if disable_streaming in ("tool_calling", True) else "stream"+ expected = "invoke" if disable_streaming in {"tool_calling", True} else "stream"async for c in model.astream([], tools=[{}]):assert c.content == expectedbreakdiff --git a/libs/core/tests/unit_tests/language_models/chat_models/test_cache.py b/libs/core/tests/unit_tests/language_models/chat_models/test_cache.pyindex 9705a01536..1cceb0a146 100644--- a/libs/core/tests/unit_tests/language_models/chat_models/test_cache.py+++ b/libs/core/tests/unit_tests/language_models/chat_models/test_cache.py@@ -29,7 +29,7 @@ class InMemoryCache(BaseCache):def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:"""Update cache based on prompt and llm_string."""- self._cache[(prompt, llm_string)] = return_val+ self._cache[prompt, llm_string] = return_val@overridedef clear(self, **kwargs: Any) -> None:diff --git a/libs/core/tests/unit_tests/language_models/llms/test_cache.py b/libs/core/tests/unit_tests/language_models/llms/test_cache.pyindex 65356e66c5..e8d489c055 100644--- a/libs/core/tests/unit_tests/language_models/llms/test_cache.py+++ b/libs/core/tests/unit_tests/language_models/llms/test_cache.py@@ -20,7 +20,7 @@ class InMemoryCache(BaseCache):def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:"""Update cache based on prompt and llm_string."""- self._cache[(prompt, llm_string)] = return_val+ self._cache[prompt, llm_string] = return_val@overridedef clear(self, **kwargs: Any) -> None:diff --git a/libs/core/tests/unit_tests/messages/test_utils.py b/libs/core/tests/unit_tests/messages/test_utils.pyindex a02d58b099..0898341dda 100644--- a/libs/core/tests/unit_tests/messages/test_utils.py+++ b/libs/core/tests/unit_tests/messages/test_utils.py@@ -423,7 +423,7 @@ def test_trim_messages_allow_partial_one_message() -> None:[HumanMessage("This is a funky text.", id="third")],max_tokens=2,token_counter=lambda messages: sum(len(m.content) for m in messages),- text_splitter=lambda x: list(x),+ text_splitter=list,strategy="first",allow_partial=True,)@@ -441,7 +441,7 @@ def test_trim_messages_last_allow_partial_one_message() -> None:[HumanMessage("This is a funky text.", id="third")],max_tokens=2,token_counter=lambda messages: sum(len(m.content) for m in messages),- text_splitter=lambda x: list(x),+ text_splitter=list,strategy="last",allow_partial=True,)diff --git a/libs/core/tests/unit_tests/prompts/test_chat.py b/libs/core/tests/unit_tests/prompts/test_chat.pyindex fad75ef232..da755b65e6 100644--- a/libs/core/tests/unit_tests/prompts/test_chat.py+++ b/libs/core/tests/unit_tests/prompts/test_chat.py@@ -380,7 +380,10 @@ def test_chat_prompt_template_with_messages(messages: list[BaseMessagePromptTemplate],) -> None:chat_prompt_template = ChatPromptTemplate.from_messages(- [*messages, HumanMessage(content="foo")]+ [+ *messages,+ HumanMessage(content="foo"),+ ])assert sorted(chat_prompt_template.input_variables) == sorted([@@ -882,7 +885,10 @@ def test_chat_prompt_message_placeholder_dict() -> None:def test_chat_prompt_message_dict() -> None:prompt = ChatPromptTemplate(- [{"role": "system", "content": "foo"}, {"role": "user", "content": "bar"}]+ [+ {"role": "system", "content": "foo"},+ {"role": "user", "content": "bar"},+ ])assert prompt.format_messages() == [SystemMessage(content="foo"),diff --git a/libs/core/tests/unit_tests/runnables/test_history.py b/libs/core/tests/unit_tests/runnables/test_history.pyindex 5db5957435..0a4b5326ff 100644--- a/libs/core/tests/unit_tests/runnables/test_history.py+++ b/libs/core/tests/unit_tests/runnables/test_history.py@@ -549,8 +549,8 @@ def test_using_custom_config_specs() -> None:user_id: str, conversation_id: str) -> InMemoryChatMessageHistory:if (user_id, conversation_id) not in store:- store[(user_id, conversation_id)] = InMemoryChatMessageHistory()- return store[(user_id, conversation_id)]+ store[user_id, conversation_id] = InMemoryChatMessageHistory()+ return store[user_id, conversation_id]with_message_history = RunnableWithMessageHistory(runnable,@@ -662,8 +662,8 @@ async def test_using_custom_config_specs_async() -> None:user_id: str, conversation_id: str) -> InMemoryChatMessageHistory:if (user_id, conversation_id) not in store:- store[(user_id, conversation_id)] = InMemoryChatMessageHistory()- return store[(user_id, conversation_id)]+ store[user_id, conversation_id] = InMemoryChatMessageHistory()+ return store[user_id, conversation_id]with_message_history = RunnableWithMessageHistory(runnable,@@ -807,7 +807,7 @@ class _RunnableLambdaWithRaiseError(RunnableLambda[Input, Output]):return RunnableBinding(bound=self,- config_factories=[lambda config: create_tracer(config)],+ config_factories=[create_tracer],)def with_alisteners(@@ -833,7 +833,7 @@ class _RunnableLambdaWithRaiseError(RunnableLambda[Input, Output]):return RunnableBinding(bound=self,- config_factories=[lambda config: create_tracer(config)],+ config_factories=[create_tracer],)diff --git a/libs/core/tests/unit_tests/runnables/test_runnable.py b/libs/core/tests/unit_tests/runnables/test_runnable.pyindex db7e898dc9..8ca68f06a6 100644--- a/libs/core/tests/unit_tests/runnables/test_runnable.py+++ b/libs/core/tests/unit_tests/runnables/test_runnable.py@@ -3870,14 +3870,14 @@ def test_retrying(mocker: MockerFixture) -> None:raise RuntimeError(msg)return x- _lambda_mock = mocker.Mock(side_effect=_lambda)- runnable = RunnableLambda(_lambda_mock)+ lambda_mock = mocker.Mock(side_effect=_lambda)+ runnable = RunnableLambda(lambda_mock)with pytest.raises(ValueError, match="x is 1"):runnable.invoke(1)- assert _lambda_mock.call_count == 1- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 1+ lambda_mock.reset_mock()with pytest.raises(ValueError, match="x is 1"):runnable.with_retry(@@ -3886,8 +3886,8 @@ def test_retrying(mocker: MockerFixture) -> None:exponential_jitter_params={"initial": 0.1},).invoke(1)- assert _lambda_mock.call_count == 2 # retried- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 2 # retried+ lambda_mock.reset_mock()with pytest.raises(RuntimeError):runnable.with_retry(@@ -3896,8 +3896,8 @@ def test_retrying(mocker: MockerFixture) -> None:retry_if_exception_type=(ValueError,),).invoke(2)- assert _lambda_mock.call_count == 1 # did not retry- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 1 # did not retry+ lambda_mock.reset_mock()with pytest.raises(ValueError, match="x is 1"):runnable.with_retry(@@ -3907,8 +3907,8 @@ def test_retrying(mocker: MockerFixture) -> None:).batch([1, 2, 0])# 3rd input isn't retried because it succeeded- assert _lambda_mock.call_count == 3 + 2- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 3 + 2+ lambda_mock.reset_mock()output = runnable.with_retry(stop_after_attempt=2,@@ -3917,12 +3917,12 @@ def test_retrying(mocker: MockerFixture) -> None:).batch([1, 2, 0], return_exceptions=True)# 3rd input isn't retried because it succeeded- assert _lambda_mock.call_count == 3 + 2+ assert lambda_mock.call_count == 3 + 2assert len(output) == 3assert isinstance(output[0], ValueError)assert isinstance(output[1], RuntimeError)assert output[2] == 0- _lambda_mock.reset_mock()+ lambda_mock.reset_mock()async def test_async_retrying(mocker: MockerFixture) -> None:@@ -3935,14 +3935,14 @@ async def test_async_retrying(mocker: MockerFixture) -> None:raise RuntimeError(msg)return x- _lambda_mock = mocker.Mock(side_effect=_lambda)- runnable = RunnableLambda(_lambda_mock)+ lambda_mock = mocker.Mock(side_effect=_lambda)+ runnable = RunnableLambda(lambda_mock)with pytest.raises(ValueError, match="x is 1"):await runnable.ainvoke(1)- assert _lambda_mock.call_count == 1- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 1+ lambda_mock.reset_mock()with pytest.raises(ValueError, match="x is 1"):await runnable.with_retry(@@ -3951,8 +3951,8 @@ async def test_async_retrying(mocker: MockerFixture) -> None:retry_if_exception_type=(ValueError, KeyError),).ainvoke(1)- assert _lambda_mock.call_count == 2 # retried- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 2 # retried+ lambda_mock.reset_mock()with pytest.raises(RuntimeError):await runnable.with_retry(@@ -3961,8 +3961,8 @@ async def test_async_retrying(mocker: MockerFixture) -> None:retry_if_exception_type=(ValueError,),).ainvoke(2)- assert _lambda_mock.call_count == 1 # did not retry- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 1 # did not retry+ lambda_mock.reset_mock()with pytest.raises(ValueError, match="x is 1"):await runnable.with_retry(@@ -3972,8 +3972,8 @@ async def test_async_retrying(mocker: MockerFixture) -> None:).abatch([1, 2, 0])# 3rd input isn't retried because it succeeded- assert _lambda_mock.call_count == 3 + 2- _lambda_mock.reset_mock()+ assert lambda_mock.call_count == 3 + 2+ lambda_mock.reset_mock()output = await runnable.with_retry(stop_after_attempt=2,@@ -3982,12 +3982,12 @@ async def test_async_retrying(mocker: MockerFixture) -> None:).abatch([1, 2, 0], return_exceptions=True)# 3rd input isn't retried because it succeeded- assert _lambda_mock.call_count == 3 + 2+ assert lambda_mock.call_count == 3 + 2assert len(output) == 3assert isinstance(output[0], ValueError)assert isinstance(output[1], RuntimeError)assert output[2] == 0- _lambda_mock.reset_mock()+ lambda_mock.reset_mock()def test_runnable_lambda_stream() -> None:@@ -5363,7 +5363,7 @@ async def test_astream_log_deep_copies() -> None:"""Get run log."""run_log = RunLog(state=None) # type: ignore[arg-type]for log_patch in run_log_patches:- run_log = run_log + log_patch+ run_log += log_patchreturn run_logdef add_one(x: int) -> int:diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.pyindex 87673dbcb5..e163ca15ba 100644--- a/libs/core/tests/unit_tests/test_tools.py+++ b/libs/core/tests/unit_tests/test_tools.py@@ -752,16 +752,16 @@ class _FakeExceptionTool(BaseTool):def test_exception_handling_bool() -> None:- _tool = _FakeExceptionTool(handle_tool_error=True)+ tool_ = _FakeExceptionTool(handle_tool_error=True)expected = "Tool execution error"- actual = _tool.run({})+ actual = tool_.run({})assert expected == actualdef test_exception_handling_str() -> None:expected = "foo bar"- _tool = _FakeExceptionTool(handle_tool_error=expected)- actual = _tool.run({})+ tool_ = _FakeExceptionTool(handle_tool_error=expected)+ actual = tool_.run({})assert expected == actual@@ -771,28 +771,28 @@ def test_exception_handling_callable() -> None:def handling(e: ToolException) -> str:return expected- _tool = _FakeExceptionTool(handle_tool_error=handling)- actual = _tool.run({})+ tool_ = _FakeExceptionTool(handle_tool_error=handling)+ actual = tool_.run({})assert expected == actualdef test_exception_handling_non_tool_exception() -> None:- _tool = _FakeExceptionTool(exception=ValueError("some error"))+ tool_ = _FakeExceptionTool(exception=ValueError("some error"))with pytest.raises(ValueError, match="some error"):- _tool.run({})+ tool_.run({})async def test_async_exception_handling_bool() -> None:- _tool = _FakeExceptionTool(handle_tool_error=True)+ tool_ = _FakeExceptionTool(handle_tool_error=True)expected = "Tool execution error"- actual = await _tool.arun({})+ actual = await tool_.arun({})assert expected == actualasync def test_async_exception_handling_str() -> None:expected = "foo bar"- _tool = _FakeExceptionTool(handle_tool_error=expected)- actual = await _tool.arun({})+ tool_ = _FakeExceptionTool(handle_tool_error=expected)+ actual = await tool_.arun({})assert expected == actual@@ -802,15 +802,15 @@ async def test_async_exception_handling_callable() -> None:def handling(e: ToolException) -> str:return expected- _tool = _FakeExceptionTool(handle_tool_error=handling)- actual = await _tool.arun({})+ tool_ = _FakeExceptionTool(handle_tool_error=handling)+ actual = await tool_.arun({})assert expected == actualasync def test_async_exception_handling_non_tool_exception() -> None:- _tool = _FakeExceptionTool(exception=ValueError("some error"))+ tool_ = _FakeExceptionTool(exception=ValueError("some error"))with pytest.raises(ValueError, match="some error"):- await _tool.arun({})+ await tool_.arun({})def test_structured_tool_from_function() -> None:@@ -850,16 +850,16 @@ def test_structured_tool_from_function() -> None:def test_validation_error_handling_bool() -> None:"""Test that validation errors are handled correctly."""expected = "Tool input validation error"- _tool = _MockStructuredTool(handle_validation_error=True)- actual = _tool.run({})+ tool_ = _MockStructuredTool(handle_validation_error=True)+ actual = tool_.run({})assert expected == actualdef test_validation_error_handling_str() -> None:"""Test that validation errors are handled correctly."""expected = "foo bar"- _tool = _MockStructuredTool(handle_validation_error=expected)- actual = _tool.run({})+ tool_ = _MockStructuredTool(handle_validation_error=expected)+ actual = tool_.run({})assert expected == actual@@ -870,8 +870,8 @@ def test_validation_error_handling_callable() -> None:def handling(e: Union[ValidationError, ValidationErrorV1]) -> str:return expected- _tool = _MockStructuredTool(handle_validation_error=handling)- actual = _tool.run({})+ tool_ = _MockStructuredTool(handle_validation_error=handling)+ actual = tool_.run({})assert expected == actual@@ -908,24 +908,24 @@ def test_validation_error_handling_non_validation_error(async def _arun(self) -> str:return "dummy"- _tool = _RaiseNonValidationErrorTool(handle_validation_error=handler)+ tool_ = _RaiseNonValidationErrorTool(handle_validation_error=handler)with pytest.raises(NotImplementedError):- _tool.run({})+ tool_.run({})async def test_async_validation_error_handling_bool() -> None:"""Test that validation errors are handled correctly."""expected = "Tool input validation error"- _tool = _MockStructuredTool(handle_validation_error=True)- actual = await _tool.arun({})+ tool_ = _MockStructuredTool(handle_validation_error=True)+ actual = await tool_.arun({})assert expected == actualasync def test_async_validation_error_handling_str() -> None:"""Test that validation errors are handled correctly."""expected = "foo bar"- _tool = _MockStructuredTool(handle_validation_error=expected)- actual = await _tool.arun({})+ tool_ = _MockStructuredTool(handle_validation_error=expected)+ actual = await tool_.arun({})assert expected == actual@@ -936,8 +936,8 @@ async def test_async_validation_error_handling_callable() -> None:def handling(e: Union[ValidationError, ValidationErrorV1]) -> str:return expected- _tool = _MockStructuredTool(handle_validation_error=handling)- actual = await _tool.arun({})+ tool_ = _MockStructuredTool(handle_validation_error=handling)+ actual = await tool_.arun({})assert expected == actual@@ -974,9 +974,9 @@ async def test_async_validation_error_handling_non_validation_error(async def _arun(self) -> str:return "dummy"- _tool = _RaiseNonValidationErrorTool(handle_validation_error=handler)+ tool_ = _RaiseNonValidationErrorTool(handle_validation_error=handler)with pytest.raises(NotImplementedError):- await _tool.arun({})+ await tool_.arun({})def test_optional_subset_model_rewrite() -> None:diff --git a/libs/core/tests/unit_tests/vectorstores/test_utils.py b/libs/core/tests/unit_tests/vectorstores/test_utils.pyindex 5f5d89950c..1bf4f9d7d9 100644--- a/libs/core/tests/unit_tests/vectorstores/test_utils.py+++ b/libs/core/tests/unit_tests/vectorstores/test_utils.py@@ -52,7 +52,11 @@ class TestCosineSimilarity:y: list[list[float]] = [[1, 0], [0, 1]]result = _cosine_similarity(x, y)expected = np.array(- [[1.0, 0.0], [0.0, 1.0], [1 / math.sqrt(2), 1 / math.sqrt(2)]]+ [+ [1.0, 0.0],+ [0.0, 1.0],+ [1 / math.sqrt(2), 1 / math.sqrt(2)],+ ])np.testing.assert_array_almost_equal(result, expected)