The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(langchain): add ruff rule BLE (#32868)
Christophe Bornet256a0b5f2fca
diff --git a/libs/langchain/langchain/agents/agent.py b/libs/langchain/langchain/agents/agent.pyindex 9d0db3ad8f..07ecf577b5 100644--- a/libs/langchain/langchain/agents/agent.py+++ b/libs/langchain/langchain/agents/agent.py@@ -1149,7 +1149,10 @@ class AgentExecutor(Chain):if agent and isinstance(agent, Runnable):try:output_type = agent.OutputType- except Exception as _:+ except TypeError:+ multi_action = False+ except Exception:+ logger.exception("Unexpected error getting OutputType from agent")multi_action = Falseelse:multi_action = output_type == Union[list[AgentAction], AgentFinish]diff --git a/libs/langchain/langchain/agents/format_scratchpad/openai_functions.py b/libs/langchain/langchain/agents/format_scratchpad/openai_functions.pyindex efd2884955..d77a575e00 100644--- a/libs/langchain/langchain/agents/format_scratchpad/openai_functions.py+++ b/libs/langchain/langchain/agents/format_scratchpad/openai_functions.py@@ -1,10 +1,13 @@import json+import loggingfrom collections.abc import Sequencefrom typing import Anyfrom langchain_core.agents import AgentAction, AgentActionMessageLogfrom langchain_core.messages import AIMessage, BaseMessage, FunctionMessage+_logger = logging.getLogger(__name__)+def _convert_agent_action_to_messages(agent_action: AgentAction,@@ -49,7 +52,10 @@ def _create_function_message(if not isinstance(observation, str):try:content = json.dumps(observation, ensure_ascii=False)+ except TypeError:+ content = str(observation)except Exception:+ _logger.exception("Unexpected error converting observation to string.")content = str(observation)else:content = observationdiff --git a/libs/langchain/langchain/agents/format_scratchpad/tools.py b/libs/langchain/langchain/agents/format_scratchpad/tools.pyindex b42fe4533d..2f59b23e2d 100644--- a/libs/langchain/langchain/agents/format_scratchpad/tools.py+++ b/libs/langchain/langchain/agents/format_scratchpad/tools.py@@ -1,4 +1,5 @@import json+import loggingfrom collections.abc import Sequencefrom typing import Any@@ -11,6 +12,8 @@ from langchain_core.messages import (from langchain.agents.output_parsers.tools import ToolAgentAction+_logger = logging.getLogger(__name__)+def _create_tool_message(agent_action: ToolAgentAction,@@ -31,7 +34,10 @@ def _create_tool_message(if not isinstance(observation, str):try:content = json.dumps(observation, ensure_ascii=False)+ except TypeError:+ content = str(observation)except Exception:+ _logger.exception("Unexpected error converting observation to string.")content = str(observation)else:content = observationdiff --git a/libs/langchain/langchain/chains/openai_functions/openapi.py b/libs/langchain/langchain/chains/openai_functions/openapi.pyindex 7fab3b7aaf..210a809ddd 100644--- a/libs/langchain/langchain/chains/openai_functions/openapi.py+++ b/libs/langchain/langchain/chains/openai_functions/openapi.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import loggingimport refrom collections import defaultdictfrom typing import TYPE_CHECKING, Any, Callable, Optional, Union@@ -12,7 +13,7 @@ from langchain_core.language_models import BaseLanguageModelfrom langchain_core.output_parsers.openai_functions import JsonOutputFunctionsParserfrom langchain_core.prompts import BasePromptTemplate, ChatPromptTemplatefrom langchain_core.utils.input import get_colored_text-from requests import Response+from requests import JSONDecodeError, Responsefrom typing_extensions import overridefrom langchain.chains.base import Chain@@ -23,6 +24,8 @@ if TYPE_CHECKING:from langchain_community.utilities.openapi import OpenAPISpecfrom openapi_pydantic import Parameter+_logger = logging.getLogger(__name__)+def _format_url(url: str, path_params: dict) -> str:expected_path_param = re.findall(r"{(.*?)}", url)@@ -237,7 +240,10 @@ class SimpleRequestChain(Chain):else:try:response = api_response.json()+ except JSONDecodeError:+ response = api_response.textexcept Exception:+ _logger.exception("Unexpected error parsing response as JSON")response = api_response.textreturn {self.output_key: response}@@ -373,8 +379,12 @@ def get_openapi_chain(breakexcept ImportError:raise- except Exception: # noqa: S110- pass+ except Exception: # noqa: BLE001+ _logger.debug(+ "Parse spec failed for OpenAPISpec.%s",+ conversion.__name__,+ exc_info=True,+ )if isinstance(spec, str):msg = f"Unable to parse spec from source {spec}"raise ValueError(msg) # noqa: TRY004diff --git a/libs/langchain/langchain/evaluation/parsing/base.py b/libs/langchain/langchain/evaluation/parsing/base.pyindex b39d1ea6f1..a334cec0f3 100644--- a/libs/langchain/langchain/evaluation/parsing/base.py+++ b/libs/langchain/langchain/evaluation/parsing/base.py@@ -1,6 +1,7 @@"""Evaluators for parsing strings."""import json+import loggingfrom operator import eqfrom typing import Any, Callable, Optional, Union, cast@@ -9,6 +10,8 @@ from typing_extensions import overridefrom langchain.evaluation.schema import StringEvaluator+_logger = logging.getLogger(__name__)+class JsonValidityEvaluator(StringEvaluator):"""Evaluate whether the prediction is valid JSON.@@ -75,7 +78,10 @@ class JsonValidityEvaluator(StringEvaluator):"""try:parse_json_markdown(prediction, parser=json.loads)+ except json.JSONDecodeError as e:+ return {"score": 0, "reasoning": str(e)}except Exception as e:+ _logger.exception("Passing JSON failed with unexpected error.")return {"score": 0, "reasoning": str(e)}return {"score": 1}diff --git a/libs/langchain/langchain/smith/evaluation/runner_utils.py b/libs/langchain/langchain/smith/evaluation/runner_utils.pyindex d584a52116..66eadd845f 100644--- a/libs/langchain/langchain/smith/evaluation/runner_utils.py+++ b/libs/langchain/langchain/smith/evaluation/runner_utils.py@@ -851,7 +851,7 @@ async def _arun_llm_or_chain(metadata=config.get("metadata"),)result = output- except Exception as e:+ except Exception as e: # noqa: BLE001logger.warning("%s failed for example %s with inputs %s\n%s",chain_or_llm,@@ -1014,7 +1014,7 @@ def _run_llm_or_chain(metadata=config.get("metadata"),)result = output- except Exception as e:+ except Exception as e: # noqa: BLE001error_type = type(e).__name__logger.warning("%s failed for example %s with inputs %s\nError Type: %s, Message: %s",@@ -1214,7 +1214,7 @@ class _DatasetRunContainer:try:agg_feedback = results.get_aggregate_feedback()_display_aggregate_results(agg_feedback)- except Exception as e:+ except Exception as e: # noqa: BLE001logger.debug("Failed to print aggregate feedback: %s", e, exc_info=True)try:# Closing the project permits name changing and metric optimizations@@ -1222,7 +1222,7 @@ class _DatasetRunContainer:self.project.id,end_time=datetime.now(timezone.utc),)- except Exception as e:+ except Exception as e: # noqa: BLE001logger.debug("Failed to close project: %s", e, exc_info=True)return resultsdiff --git a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.pyindex 202755e280..5440b565ec 100644--- a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py+++ b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py@@ -2,6 +2,7 @@from __future__ import annotations+import loggingimport uuidfrom abc import abstractmethodfrom typing import Any, Optional, Union, cast@@ -22,6 +23,8 @@ from langchain.chains.base import Chainfrom langchain.evaluation.schema import StringEvaluatorfrom langchain.schema import RUN_KEY+_logger = logging.getLogger(__name__)+def _get_messages_from_run_dict(messages: list[dict]) -> list[BaseMessage]:if not messages:@@ -373,6 +376,7 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):result = self({"run": run, "example": example}, include_run_info=True)return self._prepare_evaluator_output(result)except Exception as e:+ _logger.exception("Error evaluating run %s", run.id)return EvaluationResult(key=self.string_evaluator.evaluation_name,comment=f"Error evaluating run {run.id}: {e}",@@ -394,6 +398,7 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):)return self._prepare_evaluator_output(result)except Exception as e:+ _logger.exception("Error evaluating run %s", run.id)return EvaluationResult(key=self.string_evaluator.evaluation_name,comment=f"Error evaluating run {run.id}: {e}",diff --git a/libs/langchain/pyproject.toml b/libs/langchain/pyproject.tomlindex e50cb40557..04214bbc8d 100644--- a/libs/langchain/pyproject.toml+++ b/libs/langchain/pyproject.toml@@ -161,7 +161,6 @@ ignore = [# TODO rules"ANN401", # No type Any- "BLE", # Blind exceptions"D100", # pydocstyle: missing docstring in public module"D104", # pydocstyle: missing docstring in public package"PLC0415", # pylint: import-outside-top-leveldiff --git a/libs/langchain/scripts/check_imports.py b/libs/langchain/scripts/check_imports.pyindex 3d5e2beeb2..f3f4ec1542 100644--- a/libs/langchain/scripts/check_imports.py+++ b/libs/langchain/scripts/check_imports.py@@ -24,7 +24,7 @@ if __name__ == "__main__":for _ in range(20))SourceFileLoader(module_name, file).load_module()- except Exception:+ except Exception: # noqa: BLE001has_failure = Trueprint(file) # noqa: T201traceback.print_exc()diff --git a/libs/langchain/tests/unit_tests/chains/query_constructor/test_parser.py b/libs/langchain/tests/unit_tests/chains/query_constructor/test_parser.pyindex 4f4d02b77f..239817fe61 100644--- a/libs/langchain/tests/unit_tests/chains/query_constructor/test_parser.py+++ b/libs/langchain/tests/unit_tests/chains/query_constructor/test_parser.py@@ -143,27 +143,10 @@ def test_parse_date_value(x: str) -> None:'"2021-12-31T23:59:59Z"',{"datetime": "2021-12-31T23:59:59Z", "type": "datetime"},),- (- '"invalid-datetime"',- None, # Expecting failure or handling of invalid input- ),],)def test_parse_datetime_value(x: str, expected: Optional[dict[str, str]]) -> None:"""Test parsing of datetime values with ISO 8601 format."""- try:- parsed = cast("Comparison", DEFAULT_PARSER.parse(f'eq("publishedAt", {x})'))- actual = parsed.value- assert actual == expected, f"Expected {expected}, got {actual}"- except ValueError as e:- # Handling the case where parsing should fail- if expected is None:- assert True # Correctly raised an error for invalid input- else:- pytest.fail(f"Unexpected error {e} for input {x}")- except Exception as e:- # If any other unexpected exception type is raised- if expected is None:- assert True # Correctly identified that input was invalid- else:- pytest.fail(f"Unhandled exception {e} for input {x}")+ parsed = cast("Comparison", DEFAULT_PARSER.parse(f'eq("publishedAt", {x})'))+ actual = parsed.value+ assert actual == expected, f"Expected {expected}, got {actual}"diff --git a/libs/langchain/tests/unit_tests/conftest.py b/libs/langchain/tests/unit_tests/conftest.pyindex 69ca8245fa..368b130b4b 100644--- a/libs/langchain/tests/unit_tests/conftest.py+++ b/libs/langchain/tests/unit_tests/conftest.py@@ -110,11 +110,7 @@ def pytest_collection_modifyitems(# If we haven't yet checked whether the pkg is installed# let's check it and store the result.if pkg not in required_pkgs_info:- try:- installed = util.find_spec(pkg) is not None- except Exception:- installed = False- required_pkgs_info[pkg] = installed+ required_pkgs_info[pkg] = util.find_spec(pkg) is not Noneif not required_pkgs_info[pkg]:if only_extended:diff --git a/libs/langchain/tests/unit_tests/output_parsers/test_fix.py b/libs/langchain/tests/unit_tests/output_parsers/test_fix.pyindex ebb56956f3..3bdc489b49 100644--- a/libs/langchain/tests/unit_tests/output_parsers/test_fix.py+++ b/libs/langchain/tests/unit_tests/output_parsers/test_fix.py@@ -1,6 +1,6 @@from datetime import datetime as dtfrom datetime import timezone-from typing import Any, Callable, Optional, TypeVar+from typing import Any, TypeVarimport pytestfrom langchain_core.exceptions import OutputParserException@@ -220,15 +220,3 @@ async def test_output_fixing_parser_aparse_with_retry_chain(legacy=False,)assert (await parser.aparse(completion)) == expected---def _extract_exception(- func: Callable[..., Any],- *args: Any,- **kwargs: Any,-) -> Optional[Exception]:- try:- func(*args, **kwargs)- except Exception as e:- return e- return Nonediff --git a/libs/langchain/tests/unit_tests/output_parsers/test_retry.py b/libs/langchain/tests/unit_tests/output_parsers/test_retry.pyindex d10aa8b3f8..99dcccbf75 100644--- a/libs/langchain/tests/unit_tests/output_parsers/test_retry.py+++ b/libs/langchain/tests/unit_tests/output_parsers/test_retry.py@@ -1,6 +1,6 @@from datetime import datetime as dtfrom datetime import timezone-from typing import Any, Callable, Optional, TypeVar+from typing import Any, TypeVarimport pytestfrom langchain_core.exceptions import OutputParserException@@ -318,15 +318,3 @@ async def test_retry_with_error_output_parser_aparse_with_prompt_with_retry_chailegacy=False,)assert (await parser.aparse_with_prompt(completion, prompt)) == expected---def _extract_exception(- func: Callable[..., Any],- *args: Any,- **kwargs: Any,-) -> Optional[Exception]:- try:- func(*args, **kwargs)- except Exception as e:- return e- return None