Skip to content

Commit

Permalink
core: Add ruff rules RUF
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet committed Jan 25, 2025
1 parent dbb6b7b commit bc47278
Show file tree
Hide file tree
Showing 49 changed files with 152 additions and 164 deletions.
6 changes: 3 additions & 3 deletions libs/core/langchain_core/_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@
from .path import as_import_path, get_relative_path

__all__ = [
"LangChainBetaWarning",
"LangChainDeprecationWarning",
"as_import_path",
"beta",
"deprecated",
"get_relative_path",
"LangChainBetaWarning",
"LangChainDeprecationWarning",
"suppress_langchain_beta_warning",
"surface_langchain_beta_warnings",
"suppress_langchain_deprecation_warning",
"surface_langchain_beta_warnings",
"surface_langchain_deprecation_warnings",
"warn_deprecated",
]
50 changes: 25 additions & 25 deletions libs/core/langchain_core/callbacks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,36 +45,36 @@
from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler

__all__ = [
"dispatch_custom_event",
"adispatch_custom_event",
"RetrieverManagerMixin",
"LLMManagerMixin",
"ChainManagerMixin",
"ToolManagerMixin",
"Callbacks",
"CallbackManagerMixin",
"RunManagerMixin",
"BaseCallbackHandler",
"AsyncCallbackHandler",
"BaseCallbackManager",
"BaseRunManager",
"RunManager",
"ParentRunManager",
"AsyncRunManager",
"AsyncParentRunManager",
"CallbackManagerForLLMRun",
"AsyncCallbackManagerForLLMRun",
"CallbackManagerForChainRun",
"AsyncCallbackManager",
"AsyncCallbackManagerForChainGroup",
"AsyncCallbackManagerForChainRun",
"CallbackManagerForToolRun",
"AsyncCallbackManagerForToolRun",
"CallbackManagerForRetrieverRun",
"AsyncCallbackManagerForLLMRun",
"AsyncCallbackManagerForRetrieverRun",
"AsyncCallbackManagerForToolRun",
"AsyncParentRunManager",
"AsyncRunManager",
"BaseCallbackHandler",
"BaseCallbackManager",
"BaseRunManager",
"CallbackManager",
"CallbackManagerForChainGroup",
"AsyncCallbackManager",
"AsyncCallbackManagerForChainGroup",
"CallbackManagerForChainRun",
"CallbackManagerForLLMRun",
"CallbackManagerForRetrieverRun",
"CallbackManagerForToolRun",
"CallbackManagerMixin",
"Callbacks",
"ChainManagerMixin",
"FileCallbackHandler",
"LLMManagerMixin",
"ParentRunManager",
"RetrieverManagerMixin",
"RunManager",
"RunManagerMixin",
"StdOutCallbackHandler",
"StreamingStdOutCallbackHandler",
"FileCallbackHandler",
"ToolManagerMixin",
"adispatch_custom_event",
"dispatch_custom_event",
]
2 changes: 1 addition & 1 deletion libs/core/langchain_core/document_loaders/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
"BaseLoader",
"Blob",
"BlobLoader",
"PathLike",
"LangSmithLoader",
"PathLike",
]
2 changes: 1 addition & 1 deletion libs/core/langchain_core/documents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
from langchain_core.documents.compressor import BaseDocumentCompressor
from langchain_core.documents.transformers import BaseDocumentTransformer

__all__ = ["Document", "BaseDocumentTransformer", "BaseDocumentCompressor"]
__all__ = ["BaseDocumentCompressor", "BaseDocumentTransformer", "Document"]
6 changes: 3 additions & 3 deletions libs/core/langchain_core/indexing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
)

__all__ = [
"aindex",
"DeleteResponse",
"DocumentIndex",
"index",
"IndexingResult",
"InMemoryRecordManager",
"IndexingResult",
"RecordManager",
"UpsertResponse",
"aindex",
"index",
]
20 changes: 10 additions & 10 deletions libs/core/langchain_core/language_models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,20 @@
from langchain_core.language_models.llms import LLM, BaseLLM

__all__ = [
"BaseLanguageModel",
"LLM",
"BaseChatModel",
"SimpleChatModel",
"BaseLLM",
"LLM",
"LanguageModelInput",
"get_tokenizer",
"LangSmithParams",
"LanguageModelOutput",
"LanguageModelLike",
"FakeListLLM",
"FakeStreamingListLLM",
"BaseLanguageModel",
"FakeListChatModel",
"FakeListLLM",
"FakeMessagesListChatModel",
"FakeStreamingListLLM",
"GenericFakeChatModel",
"LangSmithParams",
"LanguageModelInput",
"LanguageModelLike",
"LanguageModelOutput",
"ParrotFakeChatModel",
"SimpleChatModel",
"get_tokenizer",
]
4 changes: 3 additions & 1 deletion libs/core/langchain_core/language_models/llms.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ def _before_sleep(retry_state: RetryCallState) -> None:
try:
loop = asyncio.get_event_loop()
if loop.is_running():
loop.create_task(coro)
# TODO: Fix RUF006 - this task should have a reference
# and be awaited somewhere
loop.create_task(coro) # noqa: RUF006
else:
asyncio.run(coro)
except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion libs/core/langchain_core/load/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
from langchain_core.load.load import load, loads
from langchain_core.load.serializable import Serializable

__all__ = ["dumpd", "dumps", "load", "loads", "Serializable"]
__all__ = ["Serializable", "dumpd", "dumps", "load", "loads"]
2 changes: 1 addition & 1 deletion libs/core/langchain_core/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This module contains memory abstractions from LangChain v0.0.x.
These abstractions are now deprecated and will be removed in LangChain v1.0.0.
""" # noqa: E501
"""

from __future__ import annotations

Expand Down
8 changes: 4 additions & 4 deletions libs/core/langchain_core/messages/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,23 +66,23 @@
"HumanMessageChunk",
"InvalidToolCall",
"MessageLikeRepresentation",
"RemoveMessage",
"SystemMessage",
"SystemMessageChunk",
"ToolCall",
"ToolCallChunk",
"ToolMessage",
"ToolMessageChunk",
"RemoveMessage",
"_message_from_dict",
"convert_to_messages",
"convert_to_openai_messages",
"filter_messages",
"get_buffer_string",
"merge_content",
"merge_message_runs",
"message_chunk_to_message",
"message_to_dict",
"messages_from_dict",
"messages_to_dict",
"filter_messages",
"merge_message_runs",
"trim_messages",
"convert_to_openai_messages",
]
2 changes: 1 addition & 1 deletion libs/core/langchain_core/messages/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def merge_content(
merged = cast(str, merged) + content
# If the next chunk is a list, add the current to the start of the list
else:
merged = [merged] + content # type: ignore
merged = [merged, *content]
elif isinstance(content, list):
# If both are lists
merged = merge_lists(cast(list, merged), content) # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion libs/core/langchain_core/messages/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,7 @@ def dummy_token_counter(messages: list[BaseMessage]) -> int:
list_token_counter = token_counter.get_num_tokens_from_messages
elif callable(token_counter):
if (
list(inspect.signature(token_counter).parameters.values())[0].annotation
next(iter(inspect.signature(token_counter).parameters.values())).annotation
is BaseMessage
):

Expand Down
22 changes: 11 additions & 11 deletions libs/core/langchain_core/output_parsers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,21 @@
from langchain_core.output_parsers.xml import XMLOutputParser

__all__ = [
"BaseLLMOutputParser",
"BaseCumulativeTransformOutputParser",
"BaseGenerationOutputParser",
"BaseLLMOutputParser",
"BaseOutputParser",
"ListOutputParser",
"CommaSeparatedListOutputParser",
"NumberedListOutputParser",
"MarkdownListOutputParser",
"StrOutputParser",
"BaseTransformOutputParser",
"BaseCumulativeTransformOutputParser",
"SimpleJsonOutputParser",
"XMLOutputParser",
"CommaSeparatedListOutputParser",
"JsonOutputKeyToolsParser",
"JsonOutputParser",
"PydanticOutputParser",
"JsonOutputToolsParser",
"JsonOutputKeyToolsParser",
"ListOutputParser",
"MarkdownListOutputParser",
"NumberedListOutputParser",
"PydanticOutputParser",
"PydanticToolsParser",
"SimpleJsonOutputParser",
"StrOutputParser",
"XMLOutputParser",
]
2 changes: 1 addition & 1 deletion libs/core/langchain_core/output_parsers/xml.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import contextlib
import re
import xml
import xml.etree.ElementTree as ET # noqa: N817
import xml.etree.ElementTree as ET
from collections.abc import AsyncIterator, Iterator
from typing import Any, Literal, Optional, Union
from xml.etree.ElementTree import TreeBuilder
Expand Down
6 changes: 3 additions & 3 deletions libs/core/langchain_core/prompts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,20 @@
"BasePromptTemplate",
"ChatMessagePromptTemplate",
"ChatPromptTemplate",
"FewShotChatMessagePromptTemplate",
"FewShotPromptTemplate",
"FewShotPromptWithTemplates",
"FewShotChatMessagePromptTemplate",
"HumanMessagePromptTemplate",
"MessagesPlaceholder",
"PipelinePromptTemplate",
"PromptTemplate",
"StringPromptTemplate",
"SystemMessagePromptTemplate",
"load_prompt",
"format_document",
"aformat_document",
"check_valid_template",
"format_document",
"get_template_variables",
"jinja2_formatter",
"load_prompt",
"validate_jinja2",
]
6 changes: 3 additions & 3 deletions libs/core/langchain_core/prompts/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ def from_template(
raise ValueError(msg)
prompt = []
for tmpl in template:
if isinstance(tmpl, str) or isinstance(tmpl, dict) and "text" in tmpl:
if isinstance(tmpl, str) or (isinstance(tmpl, dict) and "text" in tmpl):
if isinstance(tmpl, str):
text: str = tmpl
else:
Expand Down Expand Up @@ -1043,13 +1043,13 @@ def __add__(self, other: Any) -> ChatPromptTemplate:
elif isinstance(
other, (BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate)
):
return ChatPromptTemplate(messages=self.messages + [other]) # type: ignore[call-arg]
return ChatPromptTemplate(messages=[*self.messages, other]) # type: ignore[call-arg]
elif isinstance(other, (list, tuple)):
_other = ChatPromptTemplate.from_messages(other)
return ChatPromptTemplate(messages=self.messages + _other.messages) # type: ignore[call-arg]
elif isinstance(other, str):
prompt = HumanMessagePromptTemplate.from_template(other)
return ChatPromptTemplate(messages=self.messages + [prompt]) # type: ignore[call-arg]
return ChatPromptTemplate(messages=[*self.messages, prompt]) # type: ignore[call-arg]
else:
msg = f"Unsupported operand type for +: {type(other)}"
raise NotImplementedError(msg)
Expand Down
10 changes: 3 additions & 7 deletions libs/core/langchain_core/prompts/loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,11 @@ def _load_examples(config: dict) -> dict:

def _load_output_parser(config: dict) -> dict:
"""Load output parser."""
if "output_parser" in config and config["output_parser"]:
_config = config.pop("output_parser")
output_parser_type = _config.pop("_type")
if output_parser_type == "default":
output_parser = StrOutputParser(**_config)
else:
if _config := config.get("output_parser"):
if output_parser_type := _config.get("_type") != "default":
msg = f"Unsupported output parser {output_parser_type}"
raise ValueError(msg)
config["output_parser"] = output_parser
config["output_parser"] = StrOutputParser(**_config)
return config


Expand Down
2 changes: 1 addition & 1 deletion libs/core/langchain_core/prompts/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _get_jinja2_variables_from_template(template: str) -> set[str]:
"Please install it with `pip install jinja2`."
)
raise ImportError(msg) from e
# noqa for insecure warning elsewhere

env = Environment() # noqa: S701
ast = env.parse(template)
variables = meta.find_undeclared_variables(ast)
Expand Down
6 changes: 2 additions & 4 deletions libs/core/langchain_core/prompts/structured.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,8 @@ def pipe(
NotImplementedError: If the first element of `others`
is not a language model.
"""
if (
others
and isinstance(others[0], BaseLanguageModel)
or hasattr(others[0], "with_structured_output")
if (others and isinstance(others[0], BaseLanguageModel)) or hasattr(
others[0], "with_structured_output"
):
return RunnableSequence(
self,
Expand Down
16 changes: 8 additions & 8 deletions libs/core/langchain_core/runnables/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,15 @@
)

__all__ = [
"chain",
"AddableDict",
"ConfigurableField",
"ConfigurableFieldSingleOption",
"ConfigurableFieldMultiOption",
"ConfigurableFieldSingleOption",
"ConfigurableFieldSpec",
"ensure_config",
"run_in_executor",
"patch_config",
"RouterInput",
"RouterRunnable",
"Runnable",
"RunnableSerializable",
"RunnableAssign",
"RunnableBinding",
"RunnableBranch",
"RunnableConfig",
Expand All @@ -76,12 +72,16 @@
"RunnableMap",
"RunnableParallel",
"RunnablePassthrough",
"RunnableAssign",
"RunnablePick",
"RunnableSequence",
"RunnableSerializable",
"RunnableWithFallbacks",
"RunnableWithMessageHistory",
"get_config_list",
"aadd",
"add",
"chain",
"ensure_config",
"get_config_list",
"patch_config",
"run_in_executor",
]
Loading

0 comments on commit bc47278

Please sign in to comment.