Skip to content

chore(langchain): add ruff rules N #32098

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions libs/langchain/langchain/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,11 @@ def __getattr__(name: str) -> Any:
"""Get attr name."""
if name in DEPRECATED_CODE:
# Get directory of langchain package
HERE = Path(__file__).parents[1]
here = Path(__file__).parents[1]
relative_path = as_import_path(
Path(__file__).parent,
suffix=name,
relative_to=HERE,
relative_to=here,
)
old_path = "langchain." + relative_path
new_path = "langchain_experimental." + relative_path
Expand Down
13 changes: 3 additions & 10 deletions libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
from pathlib import Path
from typing import Any

from langchain_core._api.path import as_import_path


def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_csv_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think there was an edge case here which is why i did it this way rather

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change replaces the dynamic determination of the package names with a static one.
I don't see how it could be wrong.
It even fixes the target path as the dynamic way resolves to langchain_experimental.agents.agent_toolkits.csv. create_csv_agent which doesn't exist.

here = as_import_path(Path(__file__).parent, relative_to=HERE)

old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
"Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md "
"and https://github.com/langchain-ai/langchain/discussions/11680"
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
"update your import statement from:\n "
f"`langchain.agents.agent_toolkits.csv.{name}` to "
f"`langchain_experimental.agents.agent_toolkits.{name}`."
)
raise ImportError(msg)
msg = f"{name} does not exist"
Expand Down
13 changes: 3 additions & 10 deletions libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
from pathlib import Path
from typing import Any

from langchain_core._api.path import as_import_path


def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_pandas_dataframe_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(Path(__file__).parent, relative_to=HERE)

old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
"Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md "
"and https://github.com/langchain-ai/langchain/discussions/11680"
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
"update your import statement from:\n"
f"`langchain.agents.agent_toolkits.pandas.{name}` to "
f"`langchain_experimental.agents.agent_toolkits.{name}`."
)
raise ImportError(msg)
msg = f"{name} does not exist"
Expand Down
13 changes: 3 additions & 10 deletions libs/langchain/langchain/agents/agent_toolkits/python/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
from pathlib import Path
from typing import Any

from langchain_core._api.path import as_import_path


def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_python_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(Path(__file__).parent, relative_to=HERE)

old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
"Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md "
"and https://github.com/langchain-ai/langchain/discussions/11680"
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
"update your import statement from:\n"
f"`langchain.agents.agent_toolkits.python.{name}` to "
f"`langchain_experimental.agents.agent_toolkits.{name}`."
)
raise ImportError(msg)
msg = f"{name} does not exist"
Expand Down
13 changes: 3 additions & 10 deletions libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
from pathlib import Path
from typing import Any

from langchain_core._api.path import as_import_path


def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_spark_dataframe_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(Path(__file__).parent, relative_to=HERE)

old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
"Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md "
"and https://github.com/langchain-ai/langchain/discussions/11680"
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
"update your import statement from:\n"
f"`langchain.agents.agent_toolkits.spark.{name}` to "
f"`langchain_experimental.agents.agent_toolkits.{name}`."
)
raise ImportError(msg)
msg = f"{name} does not exist"
Expand Down
13 changes: 3 additions & 10 deletions libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
from pathlib import Path
from typing import Any

from langchain_core._api.path import as_import_path


def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_xorbits_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(Path(__file__).parent, relative_to=HERE)

old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
"Read https://github.com/langchain-ai/langchain/blob/master/SECURITY.md "
"and https://github.com/langchain-ai/langchain/discussions/11680"
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
"update your import statement from:\n"
f"`langchain.agents.agent_toolkits.xorbits.{name}` to "
f"`langchain_experimental.agents.agent_toolkits.{name}`."
)
raise ImportError(msg)
msg = f"{name} does not exist"
Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/callbacks/streamlit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from streamlit.delta_generator import DeltaGenerator


def StreamlitCallbackHandler(
def StreamlitCallbackHandler( # noqa: N802
parent_container: DeltaGenerator,
*,
max_thought_containers: int = 4,
Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/chains/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class LLMChain(Chain):

@classmethod
@override
def is_lc_serializable(self) -> bool:
def is_lc_serializable(cls) -> bool:
return True

prompt: BasePromptTemplate
Expand Down
1 change: 1 addition & 0 deletions libs/langchain/langchain/chat_models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,7 @@ def with_config(
)

@property
@override
def InputType(self) -> TypeAlias:
"""Get the input type for this runnable."""
from langchain_core.prompt_values import (
Expand Down
6 changes: 3 additions & 3 deletions libs/langchain/langchain/retrievers/self_query/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
Pinecone as CommunityPinecone,
)

BUILTIN_TRANSLATORS: dict[type[VectorStore], type[Visitor]] = {
builtin_translators: dict[type[VectorStore], type[Visitor]] = {
AstraDB: AstraDBTranslator,
PGVector: PGVectorTranslator,
CommunityPinecone: PineconeTranslator,
Expand Down Expand Up @@ -128,8 +128,8 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
field.name for field in (vectorstore.meta_fields or []) if field.index
]
return TencentVectorDBTranslator(fields)
if vectorstore.__class__ in BUILTIN_TRANSLATORS:
return BUILTIN_TRANSLATORS[vectorstore.__class__]()
if vectorstore.__class__ in builtin_translators:
return builtin_translators[vectorstore.__class__]()
try:
from langchain_astradb.vectorstores import AstraDBVectorStore
except ImportError:
Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/smith/evaluation/runner_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def to_dataframe(self) -> pd.DataFrame:
class EvalError(dict):
"""Your architecture raised an error."""

def __init__(self, Error: BaseException, **kwargs: Any) -> None:
def __init__(self, Error: BaseException, **kwargs: Any) -> None: # noqa: N803
"""Initialize the EvalError with an error and additional attributes.

Args:
Expand Down
8 changes: 4 additions & 4 deletions libs/langchain/langchain/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
_DEPRECATED_TOOLS = {"PythonAstREPLTool", "PythonREPLTool"}


def _import_python_tool_PythonAstREPLTool() -> Any:
def _import_python_tool_python_ast_repl_tool() -> Any:
msg = (
"This tool has been moved to langchain experiment. "
"This tool has access to a python REPL. "
Expand All @@ -50,7 +50,7 @@ def _import_python_tool_PythonAstREPLTool() -> Any:
raise ImportError(msg)


def _import_python_tool_PythonREPLTool() -> Any:
def _import_python_tool_python_repl_tool() -> Any:
msg = (
"This tool has been moved to langchain experiment. "
"This tool has access to a python REPL. "
Expand All @@ -64,9 +64,9 @@ def _import_python_tool_PythonREPLTool() -> Any:

def __getattr__(name: str) -> Any:
if name == "PythonAstREPLTool":
return _import_python_tool_PythonAstREPLTool()
return _import_python_tool_python_ast_repl_tool()
if name == "PythonREPLTool":
return _import_python_tool_PythonREPLTool()
return _import_python_tool_python_repl_tool()
from langchain_community import tools

# If not in interactive env, raise warning.
Expand Down
2 changes: 2 additions & 0 deletions libs/langchain/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ select = [
"ICN", # flake8-import-conventions
"INT", # flake8-gettext
"ISC", # isort-comprehensions
"N", # pep8-naming
"PERF", # flake8-perf
"PGH", # pygrep-hooks
"PIE", # flake8-pie
Expand Down Expand Up @@ -207,6 +208,7 @@ ignore = [
]
unfixable = ["B028"] # People should intentionally tune the stacklevel

pep8-naming.classmethod-decorators = [ "classmethod", "langchain_core.utils.pre_init", "pydantic.field_validator", "pydantic.v1.root_validator",]
pydocstyle.convention = "google"
pyupgrade.keep-runtime-typing = true

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from langchain.chat_models import init_chat_model


class multiply(BaseModel):
class Multiply(BaseModel):
"""Product of two ints."""

x: int
Expand All @@ -21,7 +21,7 @@ class multiply(BaseModel):
@pytest.mark.requires("langchain_openai", "langchain_anthropic")
async def test_init_chat_model_chain() -> None:
model = init_chat_model("gpt-4o", configurable_fields="any", config_prefix="bar")
model_with_tools = model.bind_tools([multiply])
model_with_tools = model.bind_tools([Multiply])

model_with_config = model_with_tools.with_config(
RunnableConfig(tags=["foo"]),
Expand Down
8 changes: 5 additions & 3 deletions libs/langchain/tests/unit_tests/chains/test_sequential.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,10 @@ def test_simple_sequential_functionality() -> None:
assert output == expected_output


@pytest.mark.parametrize("isAsync", [False, True])
async def test_simple_sequential_functionality_with_callbacks(*, isAsync: bool) -> None:
@pytest.mark.parametrize("is_async", [False, True])
async def test_simple_sequential_functionality_with_callbacks(
*, is_async: bool
) -> None:
"""Test simple sequential functionality."""
handler_1 = FakeCallbackHandler()
handler_2 = FakeCallbackHandler()
Expand All @@ -225,7 +227,7 @@ async def test_simple_sequential_functionality_with_callbacks(*, isAsync: bool)
callbacks=[handler_3],
)
chain = SimpleSequentialChain(chains=[chain_1, chain_2, chain_3])
if isAsync:
if is_async:
output = await chain.ainvoke({"input": "123"})
else:
output = chain({"input": "123"})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_resolve_criteria_list_enum() -> None:
assert set(val.keys()) == {c.value for c in list(Criteria)}


def test_PairwiseStringResultOutputParser_parse() -> None:
def test_pairwise_string_result_output_parser_parse() -> None:
output_parser = PairwiseStringResultOutputParser()
text = """I like pie better than cake.
[[A]]"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def test_resolve_criteria_str() -> None:
),
],
)
def test_CriteriaResultOutputParser_parse(text: str, want: dict) -> None:
def test_criteria_result_output_parser_parse(text: str, want: dict) -> None:
output_parser = CriteriaResultOutputParser()
got = output_parser.parse(text)
assert got.get("reasoning") == want["reasoning"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from tests.unit_tests.llms.fake_llm import FakeLLM


def test_PairwiseStringResultOutputParser_parse() -> None:
def test_pairwise_string_result_output_parser_parse() -> None:
output_parser = ScoreStringResultOutputParser()
text = """This answer is really good.
Rating: [[10]]"""
Expand Down
Loading