From 6993330a26e3654d5fa7477d900144704d290047 Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Tue, 21 Jan 2025 12:00:14 +0100 Subject: [PATCH] core: Add ruff rules G, FA, INP, AIR and ISC --- libs/core/langchain_core/callbacks/manager.py | 30 ++++++++++++------- libs/core/langchain_core/tracers/core.py | 5 ++-- .../core/langchain_core/tracers/evaluation.py | 12 ++++---- libs/core/langchain_core/utils/html.py | 4 ++- libs/core/langchain_core/utils/mustache.py | 2 +- libs/core/langchain_core/vectorstores/base.py | 14 +++++---- libs/core/pyproject.toml | 6 ++-- libs/core/tests/unit_tests/caches/__init__.py | 0 .../unit_tests/runnables/test_history.py | 4 +-- .../unit_tests/utils/test_function_calling.py | 2 +- 10 files changed, 47 insertions(+), 32 deletions(-) create mode 100644 libs/core/tests/unit_tests/caches/__init__.py diff --git a/libs/core/langchain_core/callbacks/manager.py b/libs/core/langchain_core/callbacks/manager.py index f675b230c879b..a80a0b1dc79b7 100644 --- a/libs/core/langchain_core/callbacks/manager.py +++ b/libs/core/langchain_core/callbacks/manager.py @@ -280,13 +280,17 @@ def handle_event( else: handler_name = handler.__class__.__name__ logger.warning( - f"NotImplementedError in {handler_name}.{event_name}" - f" callback: {repr(e)}" + "NotImplementedError in %s.%s callback: %s", + handler_name, + event_name, + repr(e), ) except Exception as e: logger.warning( - f"Error in {handler.__class__.__name__}.{event_name} callback:" - f" {repr(e)}" + "Error in %s.%s callback: %s", + handler.__class__.__name__, + event_name, + repr(e), ) if handler.raise_error: raise @@ -326,7 +330,7 @@ def _run_coros(coros: list[Coroutine[Any, Any, Any]]) -> None: try: runner.run(coro) except Exception as e: - logger.warning(f"Error in callback coroutine: {repr(e)}") + logger.warning("Error in callback coroutine: %s", repr(e)) # Run pending tasks scheduled by coros until they are all done while pending := asyncio.all_tasks(runner.get_loop()): @@ -338,7 +342,7 @@ def _run_coros(coros: list[Coroutine[Any, Any, Any]]) -> None: try: asyncio.run(coro) except Exception as e: - logger.warning(f"Error in callback coroutine: {repr(e)}") + logger.warning("Error in callback coroutine: %s", repr(e)) async def _ahandle_event_for_handler( @@ -380,12 +384,17 @@ async def _ahandle_event_for_handler( ) else: logger.warning( - f"NotImplementedError in {handler.__class__.__name__}.{event_name}" - f" callback: {repr(e)}" + "NotImplementedError in %s.%s callback: %s", + handler.__class__.__name__, + event_name, + repr(e), ) except Exception as e: logger.warning( - f"Error in {handler.__class__.__name__}.{event_name} callback: {repr(e)}" + "Error in %s.%s callback: %s", + handler.__class__.__name__, + event_name, + repr(e), ) if handler.raise_error: raise @@ -2384,7 +2393,8 @@ def _configure( "Unable to load requested LangChainTracer." " To disable this warning," " unset the LANGCHAIN_TRACING_V2 environment variables.\n" - f"{repr(e)}", + "%s", + repr(e), ) if run_tree is not None: for handler in callback_manager.handlers: diff --git a/libs/core/langchain_core/tracers/core.py b/libs/core/langchain_core/tracers/core.py index d3544df04e3dc..73dd39fced816 100644 --- a/libs/core/langchain_core/tracers/core.py +++ b/libs/core/langchain_core/tracers/core.py @@ -118,8 +118,9 @@ def _start_trace(self, run: Run) -> Union[None, Coroutine[Any, Any, None]]: # t else: if self.log_missing_parent: logger.debug( - f"Parent run {run.parent_run_id} not found for run {run.id}." - " Treating as a root run." + "Parent run %s not found for run %s. Treating as a root run.", + run.parent_run_id, + run.id, ) run.parent_run_id = None run.trace_id = run.id diff --git a/libs/core/langchain_core/tracers/evaluation.py b/libs/core/langchain_core/tracers/evaluation.py index 425c1c0122213..0df87e05c1e11 100644 --- a/libs/core/langchain_core/tracers/evaluation.py +++ b/libs/core/langchain_core/tracers/evaluation.py @@ -133,11 +133,11 @@ def _evaluate_in_project(self, run: Run, evaluator: langsmith.RunEvaluator) -> N run, source_run_id=cb.latest_run.id if cb.latest_run else None, ) - except Exception as e: - logger.error( - f"Error evaluating run {run.id} with " - f"{evaluator.__class__.__name__}: {repr(e)}", - exc_info=True, + except Exception: + logger.exception( + "Error evaluating run %s with %s", + run.id, + evaluator.__class__.__name__, ) raise example_id = str(run.reference_example_id) @@ -201,7 +201,7 @@ def _persist_run(self, run: Run) -> None: """ if self.skip_unfinished and not run.outputs: - logger.debug(f"Skipping unfinished run {run.id}") + logger.debug("Skipping unfinished run %s", run.id) return run_ = run.copy() run_.reference_example_id = self.example_id diff --git a/libs/core/langchain_core/utils/html.py b/libs/core/langchain_core/utils/html.py index f54e52024ccb0..3b7a3b1896477 100644 --- a/libs/core/langchain_core/utils/html.py +++ b/libs/core/langchain_core/utils/html.py @@ -95,7 +95,9 @@ def extract_sub_links( absolute_paths.add(absolute_path) except Exception as e: if continue_on_failure: - logger.warning(f"Unable to load link {link}. Raised exception:\n\n{e}") + logger.warning( + "Unable to load link %s. Raised exception:\n\n%s", link, e + ) continue raise diff --git a/libs/core/langchain_core/utils/mustache.py b/libs/core/langchain_core/utils/mustache.py index ee2ed8f2528f8..92cdaf8351ae0 100644 --- a/libs/core/langchain_core/utils/mustache.py +++ b/libs/core/langchain_core/utils/mustache.py @@ -384,7 +384,7 @@ def _get_key( # We couldn't find the key in any of the scopes if warn: - logger.warn(f"Could not find key '{key}'") + logger.warning("Could not find key '%s'", key) if keep: return f"{def_ldel} {key} {def_rdel}" diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.py index b154a14b98191..535de22a75102 100644 --- a/libs/core/langchain_core/vectorstores/base.py +++ b/libs/core/langchain_core/vectorstores/base.py @@ -116,8 +116,8 @@ def add_texts( def embeddings(self) -> Optional[Embeddings]: """Access the query embedding object if available.""" logger.debug( - f"The embeddings property has not been " - f"implemented for {self.__class__.__name__}" + "The embeddings property has not been implemented for %s", + self.__class__.__name__, ) return None @@ -572,8 +572,9 @@ def similarity_search_with_relevance_scores( ] if len(docs_and_similarities) == 0: logger.warning( - "No relevant docs were retrieved using the relevance score" - f" threshold {score_threshold}" + "No relevant docs were retrieved using the " + "relevance score threshold %s", + score_threshold, ) return docs_and_similarities @@ -620,8 +621,9 @@ async def asimilarity_search_with_relevance_scores( ] if len(docs_and_similarities) == 0: logger.warning( - "No relevant docs were retrieved using the relevance score" - f" threshold {score_threshold}" + "No relevant docs were retrieved using the " + "relevance score threshold %s", + score_threshold, ) return docs_and_similarities diff --git a/libs/core/pyproject.toml b/libs/core/pyproject.toml index f9b731c730163..79630db83b06b 100644 --- a/libs/core/pyproject.toml +++ b/libs/core/pyproject.toml @@ -44,8 +44,8 @@ python = ">=3.12.4" [tool.poetry.extras] [tool.ruff.lint] -select = [ "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TID", "TRY", "UP", "W", "YTT",] -ignore = [ "COM812", "UP007", "S110", "S112",] +select = [ "AIR", "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FA", "FAST", "FLY", "FURB", "G", "I", "ICN", "INP","INT", "ISC", "LOG", "N", "NPY", "PD", "PIE", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T20", "TID", "UP", "TRY", "W", "YTT",] +ignore = [ "COM812", "FA100", "ISC001", "UP007", "S110", "S112",] [tool.coverage.run] omit = [ "tests/*",] @@ -79,7 +79,7 @@ classmethod-decorators = [ "classmethod", "langchain_core.utils.pydantic.pre_ini "tests/unit_tests/runnables/test_runnable.py" = [ "E501",] "tests/unit_tests/runnables/test_graph.py" = [ "E501",] "tests/**" = [ "S",] -"scripts/**" = [ "S",] +"scripts/**" = [ "INP", "S",] [tool.poetry.group.lint.dependencies] ruff = "^0.9.2" diff --git a/libs/core/tests/unit_tests/caches/__init__.py b/libs/core/tests/unit_tests/caches/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/libs/core/tests/unit_tests/runnables/test_history.py b/libs/core/tests/unit_tests/runnables/test_history.py index 06c63203f8974..de709a42a7c85 100644 --- a/libs/core/tests/unit_tests/runnables/test_history.py +++ b/libs/core/tests/unit_tests/runnables/test_history.py @@ -862,7 +862,7 @@ def test_get_output_messages_with_value_error() -> None: with_history.bound.invoke([HumanMessage(content="hello")], config) excepted = ( "Expected str, BaseMessage, List[BaseMessage], or Tuple[BaseMessage]." - + (f" Got {illegal_bool_message}.") + f" Got {illegal_bool_message}." ) assert excepted in str(excinfo.value) @@ -874,6 +874,6 @@ def test_get_output_messages_with_value_error() -> None: with_history.bound.invoke([HumanMessage(content="hello")], config) excepted = ( "Expected str, BaseMessage, List[BaseMessage], or Tuple[BaseMessage]." - + (f" Got {illegal_int_message}.") + f" Got {illegal_int_message}." ) assert excepted in str(excinfo.value) diff --git a/libs/core/tests/unit_tests/utils/test_function_calling.py b/libs/core/tests/unit_tests/utils/test_function_calling.py index d7a90635e3627..6e182297dc340 100644 --- a/libs/core/tests/unit_tests/utils/test_function_calling.py +++ b/libs/core/tests/unit_tests/utils/test_function_calling.py @@ -969,7 +969,7 @@ class Tool(typed_dict): ) def test_convert_union_type_py_39() -> None: @tool - def magic_function(input: int | float) -> str: + def magic_function(input: int | float) -> str: # noqa: FA102 """Compute a magic function.""" result = convert_to_openai_function(magic_function)