Skip to content

Commit 017348b

Browse files
cbornetmdrxy
andauthored
chore(langchain): add ruff rule E501 in langchain_v1 (#32812)
Co-authored-by: Mason Daugherty <mason@langchain.dev>
1 parent 1e101ae commit 017348b

File tree

9 files changed

+148
-66
lines changed

9 files changed

+148
-66
lines changed

libs/langchain_v1/langchain/agents/interrupt.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,20 @@ class HumanInterrupt(TypedDict):
7474

7575

7676
class HumanResponse(TypedDict):
77-
"""The response provided by a human to an interrupt, which is returned when graph execution resumes.
77+
"""Human response.
78+
79+
The response provided by a human to an interrupt,
80+
which is returned when graph execution resumes.
7881
7982
Attributes:
8083
type: The type of response:
84+
8185
- "accept": Approves the current state without changes
8286
- "ignore": Skips/ignores the current step
8387
- "response": Provides text feedback or instructions
8488
- "edit": Modifies the current state/content
8589
args: The response payload:
90+
8691
- None: For ignore/accept actions
8792
- str: For text responses
8893
- ActionRequest: For edit actions with updated content

libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,10 @@ def after_model(self, state: AgentState) -> dict[str, Any] | None:
6565
# Right now, we do not support multiple tool calls with interrupts
6666
if len(interrupt_tool_calls) > 1:
6767
tool_names = [t["name"] for t in interrupt_tool_calls]
68-
msg = f"Called the following tools which require interrupts: {tool_names}\n\nYou may only call ONE tool that requires an interrupt at a time"
68+
msg = (
69+
f"Called the following tools which require interrupts: {tool_names}\n\n"
70+
"You may only call ONE tool that requires an interrupt at a time"
71+
)
6972
return {
7073
"messages": _generate_correction_tool_messages(msg, last_message.tool_calls),
7174
"jump_to": "model",
@@ -74,7 +77,11 @@ def after_model(self, state: AgentState) -> dict[str, Any] | None:
7477
# Right now, we do not support interrupting a tool call if other tool calls exist
7578
if auto_approved_tool_calls:
7679
tool_names = [t["name"] for t in interrupt_tool_calls]
77-
msg = f"Called the following tools which require interrupts: {tool_names}. You also called other tools that do not require interrupts. If you call a tool that requires and interrupt, you may ONLY call that tool."
80+
msg = (
81+
f"Called the following tools which require interrupts: {tool_names}. "
82+
"You also called other tools that do not require interrupts. "
83+
"If you call a tool that requires and interrupt, you may ONLY call that tool."
84+
)
7885
return {
7986
"messages": _generate_correction_tool_messages(msg, last_message.tool_calls),
8087
"jump_to": "model",

libs/langchain_v1/langchain/agents/middleware/prompt_caching.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66

77

88
class AnthropicPromptCachingMiddleware(AgentMiddleware):
9-
"""Prompt Caching Middleware - Optimizes API usage by caching conversation prefixes for Anthropic models.
9+
"""Prompt Caching Middleware.
1010
11-
Learn more about anthropic prompt caching [here](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching).
11+
Optimizes API usage by caching conversation prefixes for Anthropic models.
12+
13+
Learn more about Anthropic prompt caching
14+
`here <https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching>`__.
1215
"""
1316

1417
def __init__(
@@ -22,7 +25,8 @@ def __init__(
2225
Args:
2326
type: The type of cache to use, only "ephemeral" is supported.
2427
ttl: The time to live for the cache, only "5m" and "1h" are supported.
25-
min_messages_to_cache: The minimum number of messages until the cache is used, default is 0.
28+
min_messages_to_cache: The minimum number of messages until the cache is used,
29+
default is 0.
2630
"""
2731
self.type = type
2832
self.ttl = ttl
@@ -34,15 +38,16 @@ def modify_model_request(self, request: ModelRequest, state: AgentState) -> Mode
3438
from langchain_anthropic import ChatAnthropic
3539
except ImportError:
3640
msg = (
37-
"AnthropicPromptCachingMiddleware caching middleware only supports Anthropic models."
41+
"AnthropicPromptCachingMiddleware caching middleware only supports "
42+
"Anthropic models."
3843
"Please install langchain-anthropic."
3944
)
4045
raise ValueError(msg)
4146

4247
if not isinstance(request.model, ChatAnthropic):
4348
msg = (
44-
"AnthropicPromptCachingMiddleware caching middleware only supports Anthropic models, "
45-
f"not instances of {type(request.model)}"
49+
"AnthropicPromptCachingMiddleware caching middleware only supports "
50+
f"Anthropic models, not instances of {type(request.model)}"
4651
)
4752
raise ValueError(msg)
4853

libs/langchain_v1/langchain/agents/middleware/summarization.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
<messages>
4949
Messages to summarize:
5050
{messages}
51-
</messages>"""
51+
</messages>""" # noqa: E501
5252

5353
SUMMARY_PREFIX = "## Previous conversation summary:"
5454

libs/langchain_v1/langchain/agents/middleware/types.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ class PublicAgentState(TypedDict, Generic[ResponseT]):
5858
class AgentMiddleware(Generic[StateT]):
5959
"""Base middleware class for an agent.
6060
61-
Subclass this and implement any of the defined methods to customize agent behavior between steps in the main agent loop.
61+
Subclass this and implement any of the defined methods to customize agent behavior
62+
between steps in the main agent loop.
6263
"""
6364

6465
state_schema: type[StateT] = cast("type[StateT]", AgentState)

libs/langchain_v1/langchain/agents/react_agent.py

Lines changed: 64 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,9 @@ def _validate_chat_history(
176176
error_message = create_error_message(
177177
message="Found AIMessages with tool_calls that do not have a corresponding ToolMessage. "
178178
f"Here are the first few of those tool calls: {tool_calls_without_results[:3]}.\n\n"
179-
"Every tool call (LLM requesting to call a tool) in the message history MUST have a corresponding ToolMessage "
180-
"(result of a tool invocation to return to the LLM) - this is required by most LLM providers.",
179+
"Every tool call (LLM requesting to call a tool) in the message history "
180+
"MUST have a corresponding ToolMessage (result of a tool invocation to return to the LLM) -"
181+
" this is required by most LLM providers.",
181182
error_code=ErrorCode.INVALID_CHAT_HISTORY,
182183
)
183184
raise ValueError(error_message)
@@ -216,7 +217,8 @@ def __init__(
216217
if isinstance(model, Runnable) and not isinstance(model, BaseChatModel):
217218
msg = (
218219
"Expected `model` to be a BaseChatModel or a string, got {type(model)}."
219-
"The `model` parameter should not have pre-bound tools, simply pass the model and tools separately."
220+
"The `model` parameter should not have pre-bound tools, "
221+
"simply pass the model and tools separately."
220222
)
221223
raise ValueError(msg)
222224

@@ -308,7 +310,8 @@ def _handle_structured_response_tool_calls(self, response: AIMessage) -> Command
308310
Command with structured response update if found, None otherwise
309311
310312
Raises:
311-
MultipleStructuredOutputsError: If multiple structured responses are returned and error handling is disabled
313+
MultipleStructuredOutputsError: If multiple structured responses are returned
314+
and error handling is disabled
312315
StructuredOutputParsingError: If parsing fails and error handling is disabled
313316
"""
314317
if not isinstance(self.response_format, ToolStrategy) or not response.tool_calls:
@@ -452,7 +455,11 @@ def _apply_native_output_binding(self, model: LanguageModelLike) -> LanguageMode
452455
return model.bind(**kwargs)
453456

454457
def _handle_structured_response_native(self, response: AIMessage) -> Command | None:
455-
"""If native output is configured and there are no tool calls, parse using ProviderStrategyBinding."""
458+
"""Handle structured output using the native output.
459+
460+
If native output is configured and there are no tool calls,
461+
parse using ProviderStrategyBinding.
462+
"""
456463
if self.native_output_binding is None:
457464
return None
458465
if response.tool_calls:
@@ -922,7 +929,8 @@ def create_agent( # noqa: D417
922929
) -> CompiledStateGraph[StateT, ContextT]:
923930
"""Creates an agent graph that calls tools in a loop until a stopping condition is met.
924931
925-
For more details on using `create_agent`, visit [Agents](https://langchain-ai.github.io/langgraph/agents/overview/) documentation.
932+
For more details on using `create_agent`,
933+
visit [Agents](https://langchain-ai.github.io/langgraph/agents/overview/) documentation.
926934
927935
Args:
928936
model: The language model for the agent. Supports static and dynamic
@@ -969,25 +977,35 @@ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenA
969977
must be a subset of those specified in the `tools` parameter.
970978
971979
tools: A list of tools or a ToolNode instance.
972-
If an empty list is provided, the agent will consist of a single LLM node without tool calling.
980+
If an empty list is provided, the agent will consist of a single LLM node
981+
without tool calling.
973982
prompt: An optional prompt for the LLM. Can take a few different forms:
974983
975-
- str: This is converted to a SystemMessage and added to the beginning of the list of messages in state["messages"].
976-
- SystemMessage: this is added to the beginning of the list of messages in state["messages"].
977-
- Callable: This function should take in full graph state and the output is then passed to the language model.
978-
- Runnable: This runnable should take in full graph state and the output is then passed to the language model.
984+
- str: This is converted to a SystemMessage and added to the beginning
985+
of the list of messages in state["messages"].
986+
- SystemMessage: this is added to the beginning of the list of messages
987+
in state["messages"].
988+
- Callable: This function should take in full graph state and the output is then passed
989+
to the language model.
990+
- Runnable: This runnable should take in full graph state and the output is then passed
991+
to the language model.
979992
980993
response_format: An optional UsingToolStrategy configuration for structured responses.
981994
982-
If provided, the agent will handle structured output via tool calls during the normal conversation flow.
983-
When the model calls a structured output tool, the response will be captured and returned in the 'structured_response' state key.
995+
If provided, the agent will handle structured output via tool calls
996+
during the normal conversation flow.
997+
When the model calls a structured output tool, the response will be captured
998+
and returned in the 'structured_response' state key.
984999
If not provided, `structured_response` will not be present in the output state.
9851000
9861001
The UsingToolStrategy should contain:
987-
- schemas: A sequence of ResponseSchema objects that define the structured output format
1002+
1003+
- schemas: A sequence of ResponseSchema objects that define
1004+
the structured output format
9881005
- tool_choice: Either "required" or "auto" to control when structured output is used
9891006
9901007
Each ResponseSchema contains:
1008+
9911009
- schema: A Pydantic model that defines the structure
9921010
- name: Optional custom name for the tool (defaults to model name)
9931011
- description: Optional custom description (defaults to model docstring)
@@ -997,11 +1015,15 @@ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenA
9971015
`response_format` requires the model to support tool calling
9981016
9991017
!!! Note
1000-
Structured responses are handled directly in the model call node via tool calls, eliminating the need for separate structured response nodes.
1001-
1002-
pre_model_hook: An optional node to add before the `agent` node (i.e., the node that calls the LLM).
1003-
Useful for managing long message histories (e.g., message trimming, summarization, etc.).
1004-
Pre-model hook must be a callable or a runnable that takes in current graph state and returns a state update in the form of
1018+
Structured responses are handled directly in the model call node via tool calls,
1019+
eliminating the need for separate structured response nodes.
1020+
1021+
pre_model_hook: An optional node to add before the `agent` node
1022+
(i.e., the node that calls the LLM).
1023+
Useful for managing long message histories
1024+
(e.g., message trimming, summarization, etc.).
1025+
Pre-model hook must be a callable or a runnable that takes in current
1026+
graph state and returns a state update in the form of
10051027
```python
10061028
# At least one of `messages` or `llm_input_messages` MUST be provided
10071029
{
@@ -1016,21 +1038,26 @@ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenA
10161038
```
10171039
10181040
!!! Important
1019-
At least one of `messages` or `llm_input_messages` MUST be provided and will be used as an input to the `agent` node.
1041+
At least one of `messages` or `llm_input_messages` MUST be provided
1042+
and will be used as an input to the `agent` node.
10201043
The rest of the keys will be added to the graph state.
10211044
10221045
!!! Warning
1023-
If you are returning `messages` in the pre-model hook, you should OVERWRITE the `messages` key by doing the following:
1046+
If you are returning `messages` in the pre-model hook,
1047+
you should OVERWRITE the `messages` key by doing the following:
10241048
10251049
```python
10261050
{
10271051
"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *new_messages]
10281052
...
10291053
}
10301054
```
1031-
post_model_hook: An optional node to add after the `agent` node (i.e., the node that calls the LLM).
1032-
Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.
1033-
Post-model hook must be a callable or a runnable that takes in current graph state and returns a state update.
1055+
post_model_hook: An optional node to add after the `agent` node
1056+
(i.e., the node that calls the LLM).
1057+
Useful for implementing human-in-the-loop, guardrails, validation,
1058+
or other post-processing.
1059+
Post-model hook must be a callable or a runnable that takes in
1060+
current graph state and returns a state update.
10341061
10351062
!!! Note
10361063
Only available with `version="v2"`.
@@ -1039,12 +1066,14 @@ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenA
10391066
Defaults to `AgentState` that defines those two keys.
10401067
context_schema: An optional schema for runtime context.
10411068
checkpointer: An optional checkpoint saver object. This is used for persisting
1042-
the state of the graph (e.g., as chat memory) for a single thread (e.g., a single conversation).
1069+
the state of the graph (e.g., as chat memory) for a single thread
1070+
(e.g., a single conversation).
10431071
store: An optional store object. This is used for persisting data
10441072
across multiple threads (e.g., multiple conversations / users).
10451073
interrupt_before: An optional list of node names to interrupt before.
10461074
Should be one of the following: "agent", "tools".
1047-
This is useful if you want to add a user confirmation or other interrupt before taking an action.
1075+
This is useful if you want to add a user confirmation or other interrupt
1076+
before taking an action.
10481077
interrupt_after: An optional list of node names to interrupt after.
10491078
Should be one of the following: "agent", "tools".
10501079
This is useful if you want to return directly or run additional processing on an output.
@@ -1059,7 +1088,8 @@ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenA
10591088
node using the [Send](https://langchain-ai.github.io/langgraph/concepts/low_level/#send)
10601089
API.
10611090
name: An optional name for the CompiledStateGraph.
1062-
This name will be automatically used when adding ReAct agent graph to another graph as a subgraph node -
1091+
This name will be automatically used when adding ReAct agent graph to
1092+
another graph as a subgraph node -
10631093
particularly useful for building multi-agent systems.
10641094
10651095
!!! warning "`config_schema` Deprecated"
@@ -1071,9 +1101,11 @@ def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenA
10711101
A compiled LangChain runnable that can be used for chat interactions.
10721102
10731103
The "agent" node calls the language model with the messages list (after applying the prompt).
1074-
If the resulting AIMessage contains `tool_calls`, the graph will then call the ["tools"][langgraph.prebuilt.tool_node.ToolNode].
1075-
The "tools" node executes the tools (1 tool per `tool_call`) and adds the responses to the messages list
1076-
as `ToolMessage` objects. The agent node then calls the language model again.
1104+
If the resulting AIMessage contains `tool_calls`,
1105+
the graph will then call the ["tools"][langgraph.prebuilt.tool_node.ToolNode].
1106+
The "tools" node executes the tools (1 tool per `tool_call`)
1107+
and adds the responses to the messages list as `ToolMessage` objects.
1108+
The agent node then calls the language model again.
10771109
The process repeats until no more `tool_calls` are present in the response.
10781110
The agent then returns the full list of messages as a dictionary containing the key "messages".
10791111
@@ -1135,7 +1167,8 @@ def check_weather(location: str) -> str:
11351167
# Handle deprecated config_schema parameter
11361168
if (config_schema := deprecated_kwargs.pop("config_schema", MISSING)) is not MISSING:
11371169
warn(
1138-
"`config_schema` is deprecated and will be removed. Please use `context_schema` instead.",
1170+
"`config_schema` is deprecated and will be removed. "
1171+
"Please use `context_schema` instead.",
11391172
category=DeprecationWarning,
11401173
stacklevel=2,
11411174
)

0 commit comments

Comments
 (0)