Skip to content

Commit d64fe41

Browse files
committed
chore(langchain): cleanup ruff config
1 parent aa63de9 commit d64fe41

File tree

10 files changed

+64
-132
lines changed

10 files changed

+64
-132
lines changed

libs/langchain_v1/langchain/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
__version__ = "1.0.0a3"
66

77

8-
def __getattr__(name: str) -> Any: # noqa: ANN401
8+
def __getattr__(name: str) -> Any:
99
"""Get an attribute from the package.
1010
1111
TODO: will be removed in a future alpha version.

libs/langchain_v1/langchain/agents/react_agent.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def __init__(
221221
"Expected `model` to be a BaseChatModel or a string, got {type(model)}."
222222
"The `model` parameter should not have pre-bound tools, simply pass the model and tools separately."
223223
)
224-
raise ValueError(msg)
224+
raise TypeError(msg)
225225

226226
self._setup_tools()
227227
self._setup_state_schema()
@@ -397,13 +397,13 @@ def _handle_single_structured_output(
397397
"structured_response": structured_response,
398398
}
399399
)
400-
except Exception as exc: # noqa: BLE001
400+
except Exception as exc:
401401
exception = StructuredOutputValidationError(tool_call["name"], exc)
402402

403403
should_retry, error_message = self._handle_structured_output_error(exception)
404404

405405
if not should_retry:
406-
raise exception
406+
raise exception from exc
407407

408408
return Command(
409409
update={

libs/langchain_v1/langchain/agents/tool_node.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def msg_content_output(output: Any) -> Union[str, list[dict]]:
119119
# any existing ToolNode usage.
120120
try:
121121
return json.dumps(output, ensure_ascii=False)
122-
except Exception: # noqa: BLE001
122+
except Exception:
123123
return str(output)
124124

125125

@@ -202,7 +202,7 @@ def _handle_tool_error(
202202
f"Got unexpected type of `handle_tool_error`. Expected bool, str "
203203
f"or callable. Received: {flag}"
204204
)
205-
raise ValueError(msg)
205+
raise TypeError(msg)
206206
return content
207207

208208

@@ -417,7 +417,7 @@ def tools_by_name(self) -> dict[str, BaseTool]:
417417

418418
def _func(
419419
self,
420-
input: Union[
420+
input_: Union[
421421
list[AnyMessage],
422422
dict[str, Any],
423423
BaseModel,
@@ -426,7 +426,7 @@ def _func(
426426
*,
427427
store: Optional[BaseStore], # noqa: UP045
428428
) -> Any:
429-
tool_calls, input_type = self._parse_input(input, store)
429+
tool_calls, input_type = self._parse_input(input_, store)
430430
config_list = get_config_list(config, len(tool_calls))
431431
input_types = [input_type] * len(tool_calls)
432432
with get_executor_for_config(config) as executor:
@@ -436,7 +436,7 @@ def _func(
436436

437437
async def _afunc(
438438
self,
439-
input: Union[
439+
input_: Union[
440440
list[AnyMessage],
441441
dict[str, Any],
442442
BaseModel,
@@ -445,7 +445,7 @@ async def _afunc(
445445
*,
446446
store: Optional[BaseStore], # noqa: UP045
447447
) -> Any:
448-
tool_calls, input_type = self._parse_input(input, store)
448+
tool_calls, input_type = self._parse_input(input_, store)
449449
outputs = await asyncio.gather(
450450
*(self._arun_one(call, input_type, config) for call in tool_calls)
451451
)
@@ -625,24 +625,24 @@ async def _arun_one(
625625

626626
def _parse_input(
627627
self,
628-
input: Union[
628+
input_: Union[
629629
list[AnyMessage],
630630
dict[str, Any],
631631
BaseModel,
632632
],
633633
store: BaseStore | None,
634634
) -> tuple[list[ToolCall], Literal["list", "dict", "tool_calls"]]:
635635
input_type: Literal["list", "dict", "tool_calls"]
636-
if isinstance(input, list):
637-
if isinstance(input[-1], dict) and input[-1].get("type") == "tool_call":
636+
if isinstance(input_, list):
637+
if isinstance(input_[-1], dict) and input_[-1].get("type") == "tool_call":
638638
input_type = "tool_calls"
639-
tool_calls = cast("list[ToolCall]", input)
639+
tool_calls = cast("list[ToolCall]", input_)
640640
return tool_calls, input_type
641641
input_type = "list"
642-
messages = input
643-
elif isinstance(input, dict) and (messages := input.get(self._messages_key, [])):
642+
messages = input_
643+
elif isinstance(input_, dict) and (messages := input_.get(self._messages_key, [])):
644644
input_type = "dict"
645-
elif messages := getattr(input, self._messages_key, []):
645+
elif messages := getattr(input_, self._messages_key, []):
646646
# Assume dataclass-like state that can coerce from dict
647647
input_type = "dict"
648648
else:
@@ -651,12 +651,12 @@ def _parse_input(
651651

652652
try:
653653
latest_ai_message = next(m for m in reversed(messages) if isinstance(m, AIMessage))
654-
except StopIteration:
654+
except StopIteration as e:
655655
msg = "No AIMessage found in input"
656-
raise ValueError(msg)
656+
raise ValueError(msg) from e
657657

658658
tool_calls = [
659-
self.inject_tool_args(call, input, store) for call in latest_ai_message.tool_calls
659+
self.inject_tool_args(call, input_, store) for call in latest_ai_message.tool_calls
660660
]
661661
return tool_calls, input_type
662662

@@ -676,19 +676,19 @@ def _validate_tool_call(self, call: ToolCall) -> ToolMessage | None:
676676
def _inject_state(
677677
self,
678678
tool_call: ToolCall,
679-
input: Union[
679+
input_: Union[
680680
list[AnyMessage],
681681
dict[str, Any],
682682
BaseModel,
683683
],
684684
) -> ToolCall:
685685
state_args = self._tool_to_state_args[tool_call["name"]]
686-
if state_args and isinstance(input, list):
686+
if state_args and isinstance(input_, list):
687687
required_fields = list(state_args.values())
688688
if (
689689
len(required_fields) == 1 and required_fields[0] == self._messages_key
690690
) or required_fields[0] is None:
691-
input = {self._messages_key: input}
691+
input_ = {self._messages_key: input_}
692692
else:
693693
err_msg = (
694694
f"Invalid input to ToolNode. Tool {tool_call['name']} requires "
@@ -699,14 +699,14 @@ def _inject_state(
699699
err_msg += f" State should contain fields {required_fields_str}."
700700
raise ValueError(err_msg)
701701

702-
if isinstance(input, dict):
702+
if isinstance(input_, dict):
703703
tool_state_args = {
704-
tool_arg: input[state_field] if state_field else input
704+
tool_arg: input_[state_field] if state_field else input_
705705
for tool_arg, state_field in state_args.items()
706706
}
707707
else:
708708
tool_state_args = {
709-
tool_arg: getattr(input, state_field) if state_field else input
709+
tool_arg: getattr(input_, state_field) if state_field else input_
710710
for tool_arg, state_field in state_args.items()
711711
}
712712

@@ -737,7 +737,7 @@ def _inject_store(self, tool_call: ToolCall, store: BaseStore | None) -> ToolCal
737737
def inject_tool_args(
738738
self,
739739
tool_call: ToolCall,
740-
input: Union[
740+
input_: Union[
741741
list[AnyMessage],
742742
dict[str, Any],
743743
BaseModel,
@@ -758,7 +758,7 @@ def inject_tool_args(
758758
Args:
759759
tool_call: The tool call dictionary to augment with injected arguments.
760760
Must contain 'name', 'args', 'id', and 'type' fields.
761-
input: The current graph state to inject into tools requiring state access.
761+
input_: The current graph state to inject into tools requiring state access.
762762
Can be a message list, state dictionary, or BaseModel instance.
763763
store: The persistent store instance to inject into tools requiring storage.
764764
Will be None if no store is configured for the graph.
@@ -781,7 +781,7 @@ def inject_tool_args(
781781
return tool_call
782782

783783
tool_call_copy: ToolCall = copy(tool_call)
784-
tool_call_with_state = self._inject_state(tool_call_copy, input)
784+
tool_call_with_state = self._inject_state(tool_call_copy, input_)
785785
return self._inject_store(tool_call_with_state, store)
786786

787787
def _validate_tool_command(

libs/langchain_v1/langchain/chat_models/base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ def with_config(
628628
)
629629

630630
@property
631+
@override
631632
def InputType(self) -> TypeAlias:
632633
"""Get the input type for this runnable."""
633634
from langchain_core.prompt_values import (
@@ -819,6 +820,7 @@ async def atransform(
819820
yield x
820821

821822
@overload
823+
@override
822824
def astream_log(
823825
self,
824826
input: Any,
@@ -836,6 +838,7 @@ def astream_log(
836838
) -> AsyncIterator[RunLogPatch]: ...
837839

838840
@overload
841+
@override
839842
def astream_log(
840843
self,
841844
input: Any,

libs/langchain_v1/pyproject.toml

Lines changed: 25 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ test = [
5959
]
6060
codespell = ["codespell<3.0.0,>=2.2.0"]
6161
lint = [
62-
"ruff>=0.12.2",
62+
"ruff<0.13,>=0.12.11",
6363
]
6464
typing = [
6565
"mypy<0.18,>=1.17.1",
@@ -70,7 +70,6 @@ test_integration = [
7070
"vcrpy>=7.0",
7171
"wrapt>=1.15.0",
7272
"python-dotenv>=1.0.0",
73-
"cassio>=0.1.0",
7473
"langchainhub>=0.1.16",
7574
"langchain-core",
7675
"langchain-text-splitters",
@@ -107,71 +106,43 @@ select = [
107106
"ALL"
108107
]
109108
ignore = [
110-
"COM812", # Messes with the formatter
111-
"ISC001", # Messes with the formatter
112-
"PERF203", # Rarely useful
113-
"SLF001", # Private member access
114-
"UP007", # pyupgrade: non-pep604-annotation-union
115-
"PLC0415", # Imports should be at the top. Not always desirable
116-
"PLR0913", # Too many arguments in function definition
117-
"PLC0414", # Inconsistent with how type checkers expect to be notified of intentional re-exports
109+
"C90", # McCabe complexity
110+
"COM812", # Messes with the formatter
111+
"ISC001", # Messes with the formatter
112+
"PERF203", # Rarely useful
113+
"PLR09", # Too many something (arg, statements, etc)
114+
"UP007", # pyupgrade: non-pep604-annotation-union
115+
"PLC0415", # Imports should be at the top. Not always desirable
116+
117+
# TODO rules
118+
"ANN401",
119+
"BLE",
120+
]
121+
unfixable = [
122+
"B028", # People should intentionally tune the stacklevel
123+
"PLW1510", # People should intentionally set the check argument
118124
]
119-
unfixable = ["B028"] # People should intentionally tune the stacklevel
120125

121126
pydocstyle.convention = "google"
122127
pyupgrade.keep-runtime-typing = true
123128
flake8-annotations.allow-star-arg-any = true
124129

125-
[tool.ruff.lint.per-file-ignores]
126-
"tests/*" = [
127-
"D1", # Documentation rules
128-
"PLC0415", # Imports should be at the top. Not always desirable for tests
129-
]
130-
"langchain/agents/*" = [
131-
"ANN401", # we use Any right now, need to narrow
132-
"E501", # line too long, needs to fix
133-
"A002", # input is shadowing builtin
134-
"A001", # input is shadowing builtin
135-
"B904", # use from for exceptions
136-
"PLR2004", # magic values are fine for this case
137-
"C901", # too complex
138-
"TRY004", # type error exception
139-
"PLR0912", # too many branches
140-
"PLR0911", # too many return statements
141-
]
130+
[tool.ruff.lint.extend-per-file-ignores]
142131
"tests/unit_tests/agents/*" = ["ALL"]
143132
"tests/integration_tests/agents/*" = ["ALL"]
144-
145-
[tool.ruff.lint.extend-per-file-ignores]
146133
"scripts/check_imports.py" = ["ALL"]
147134

148-
"langchain/chat_models/base.py" = [
149-
"ANN",
150-
"C901",
151-
"FIX002",
152-
"N802",
153-
"PLR0911",
154-
"PLR0912",
155-
"PLR0915",
156-
]
157-
158-
"langchain/embeddings/base.py" = [
159-
"PLR0911",
160-
"PLR0913",
135+
"langchain/agents/*" = [
136+
"E501", # line too long, needs to fix
137+
"PLR2004", # magic values are fine for this case
161138
]
162139

163-
"tests/**/*.py" = [
164-
"S101", # Tests need assertions
165-
"S311", # Standard pseudo-random generators are not suitable for cryptographic purposes
166-
"SLF001", # Private member access in tests
140+
"tests/*" = [
141+
"D1", # Documentation rules
142+
"S101", # Tests need assertions
143+
"S311", # Standard pseudo-random generators are not suitable for cryptographic purposes
144+
"SLF001", # Private member access in tests
167145
"PLR2004", # Magic values are perfectly fine in unit tests (e.g. 0, 1, 2, etc.)
168-
"C901", # Too complex
169-
"ANN401", # Annotated type is not necessary
170-
"N802", # Function name should be lowercase
171-
"PLW1641", # Object does not implement __hash__ method
172-
"ARG002", # Unused argument
173-
"BLE001", # Do not catch blind exception
174-
"N801", # class name should use CapWords convention
175146
]
176147

177148
[tool.coverage.run]

libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import math
44

55
from langchain_core.embeddings import Embeddings
6+
from typing_extensions import override
67

78
fake_texts = ["foo", "bar", "baz"]
89

@@ -20,6 +21,7 @@ def embed_documents(self, texts: list[str]) -> list[list[float]]:
2021
async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
2122
return self.embed_documents(texts)
2223

24+
@override
2325
def embed_query(self, text: str) -> list[float]:
2426
"""Return constant query embeddings.
2527

libs/langchain_v1/tests/integration_tests/chat_models/test_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from langchain.chat_models import init_chat_model
1212

1313

14-
class multiply(BaseModel):
14+
class Multiply(BaseModel):
1515
"""Product of two ints."""
1616

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

2626
model_with_config = model_with_tools.with_config(
2727
RunnableConfig(tags=["foo"]),

libs/langchain_v1/tests/unit_tests/agents/test_react_agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ def tool2(some_val: int) -> str:
266266
}
267267
)
268268
# check valid agent constructor
269-
with pytest.raises(ValueError):
269+
with pytest.raises(TypeError):
270270
create_agent(
271271
model.bind_tools(tools),
272272
tools,

libs/langchain_v1/tests/unit_tests/embeddings/test_caching.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import pytest
99
from langchain_core.embeddings import Embeddings
10+
from typing_extensions import override
1011

1112
from langchain.embeddings import CacheBackedEmbeddings
1213
from langchain.storage.in_memory import InMemoryStore
@@ -23,6 +24,7 @@ def embed_documents(self, texts: list[str]) -> list[list[float]]:
2324
embeddings.append([len(text), len(text) + 1])
2425
return embeddings
2526

27+
@override
2628
def embed_query(self, text: str) -> list[float]:
2729
# Simulate embedding a query
2830
return [5.0, 6.0]

0 commit comments

Comments
 (0)