Skip to content

The agent engineering platform.

chore(langchain): cleanup ruff config (#32810)

Christophe Bornet3fb90666be43
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index 43f7c3aba0..ddc5a9d89a 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -20,9 +20,9 @@ from langgraph._internal._runnable import RunnableCallable
from langgraph.constants import END, START
from langgraph.graph.state import StateGraph
from langgraph.prebuilt.tool_node import ToolCallWithContext, ToolNode
-from langgraph.runtime import Runtime # noqa: TC002
+from langgraph.runtime import Runtime
from langgraph.types import Command, Send
-from langgraph.typing import ContextT # noqa: TC002
+from langgraph.typing import ContextT
from typing_extensions import NotRequired, Required, TypedDict
from langchain.agents.middleware.types import (
@@ -538,7 +538,7 @@ def _chain_async_tool_call_wrappers(
return result
-def create_agent( # noqa: PLR0915
+def create_agent(
model: str | BaseChatModel,
tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
*,
@@ -791,9 +791,9 @@ def create_agent( # noqa: PLR0915
default_tools = list(built_in_tools)
# validate middleware
- assert len({m.name for m in middleware}) == len(middleware), ( # noqa: S101
- "Please remove duplicate middleware instances."
- )
+ if len({m.name for m in middleware}) != len(middleware):
+ msg = "Please remove duplicate middleware instances."
+ raise AssertionError(msg)
middleware_w_before_agent = [
m
for m in middleware
@@ -886,12 +886,12 @@ def create_agent( # noqa: PLR0915
)
try:
structured_response = provider_strategy_binding.parse(output)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
schema_name = getattr(
effective_response_format.schema_spec.schema, "__name__", "response_format"
)
validation_error = StructuredOutputValidationError(schema_name, exc, output)
- raise validation_error
+ raise validation_error from exc
else:
return {"messages": [output], "structured_response": structured_response}
return {"messages": [output]}
@@ -952,13 +952,13 @@ def create_agent( # noqa: PLR0915
],
"structured_response": structured_response,
}
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
exception = StructuredOutputValidationError(tool_call["name"], exc, output)
should_retry, error_message = _handle_structured_output_error(
exception, effective_response_format
)
if not should_retry:
- raise exception
+ raise exception from exc
return {
"messages": [
diff --git a/libs/langchain_v1/langchain/agents/middleware/_redaction.py b/libs/langchain_v1/langchain/agents/middleware/_redaction.py
index ba4755b8ce..c2d2c95971 100644
--- a/libs/langchain_v1/langchain/agents/middleware/_redaction.py
+++ b/libs/langchain_v1/langchain/agents/middleware/_redaction.py
@@ -179,11 +179,14 @@ BUILTIN_DETECTORS: dict[str, Detector] = {
}
"""Registry of built-in detectors keyed by type name."""
+_CARD_NUMBER_MIN_DIGITS = 13
+_CARD_NUMBER_MAX_DIGITS = 19
+
def _passes_luhn(card_number: str) -> bool:
"""Validate credit card number using the Luhn checksum."""
digits = [int(d) for d in card_number if d.isdigit()]
- if not 13 <= len(digits) <= 19:
+ if not _CARD_NUMBER_MIN_DIGITS <= len(digits) <= _CARD_NUMBER_MAX_DIGITS:
return False
checksum = 0
@@ -191,7 +194,7 @@ def _passes_luhn(card_number: str) -> bool:
value = digit
if index % 2 == 1:
value *= 2
- if value > 9:
+ if value > 9: # noqa: PLR2004
value -= 9
checksum += value
return checksum % 10 == 0
@@ -205,6 +208,10 @@ def _apply_redact_strategy(content: str, matches: list[PIIMatch]) -> str:
return result
+_UNMASKED_CHAR_NUMBER = 4
+_IPV4_PARTS_NUMBER = 4
+
+
def _apply_mask_strategy(content: str, matches: list[PIIMatch]) -> str:
result = content
for match in sorted(matches, key=lambda item: item["start"], reverse=True):
@@ -212,11 +219,11 @@ def _apply_mask_strategy(content: str, matches: list[PIIMatch]) -> str:
pii_type = match["type"]
if pii_type == "email":
parts = value.split("@")
- if len(parts) == 2:
+ if len(parts) == 2: # noqa: PLR2004
domain_parts = parts[1].split(".")
masked = (
f"{parts[0]}@****.{domain_parts[-1]}"
- if len(domain_parts) >= 2
+ if len(domain_parts) > 1
else f"{parts[0]}@****"
)
else:
@@ -225,12 +232,15 @@ def _apply_mask_strategy(content: str, matches: list[PIIMatch]) -> str:
digits_only = "".join(c for c in value if c.isdigit())
separator = "-" if "-" in value else " " if " " in value else ""
if separator:
- masked = f"****{separator}****{separator}****{separator}{digits_only[-4:]}"
+ masked = (
+ f"****{separator}****{separator}****{separator}"
+ f"{digits_only[-_UNMASKED_CHAR_NUMBER:]}"
+ )
else:
- masked = f"************{digits_only[-4:]}"
+ masked = f"************{digits_only[-_UNMASKED_CHAR_NUMBER:]}"
elif pii_type == "ip":
octets = value.split(".")
- masked = f"*.*.*.{octets[-1]}" if len(octets) == 4 else "****"
+ masked = f"*.*.*.{octets[-1]}" if len(octets) == _IPV4_PARTS_NUMBER else "****"
elif pii_type == "mac_address":
separator = ":" if ":" in value else "-"
masked = (
@@ -239,7 +249,11 @@ def _apply_mask_strategy(content: str, matches: list[PIIMatch]) -> str:
elif pii_type == "url":
masked = "[MASKED_URL]"
else:
- masked = f"****{value[-4:]}" if len(value) > 4 else "****"
+ masked = (
+ f"****{value[-_UNMASKED_CHAR_NUMBER:]}"
+ if len(value) > _UNMASKED_CHAR_NUMBER
+ else "****"
+ )
result = result[: match["start"]] + masked + result[match["end"] :]
return result
diff --git a/libs/langchain_v1/langchain/agents/middleware/context_editing.py b/libs/langchain_v1/langchain/agents/middleware/context_editing.py
index 0f13221010..f24202b99d 100644
--- a/libs/langchain_v1/langchain/agents/middleware/context_editing.py
+++ b/libs/langchain_v1/langchain/agents/middleware/context_editing.py
@@ -228,6 +228,7 @@ class ContextEditingMiddleware(AgentMiddleware):
def count_tokens(messages: Sequence[BaseMessage]) -> int:
return count_tokens_approximately(messages)
+
else:
system_msg = [request.system_message] if request.system_message else []
@@ -255,6 +256,7 @@ class ContextEditingMiddleware(AgentMiddleware):
def count_tokens(messages: Sequence[BaseMessage]) -> int:
return count_tokens_approximately(messages)
+
else:
system_msg = [request.system_message] if request.system_message else []
diff --git a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py
index 663b90b081..cb7810e53f 100644
--- a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py
+++ b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Annotated, Any, Literal
from langchain_core.messages import AIMessage
from langgraph.channels.untracked_value import UntrackedValue
-from typing_extensions import NotRequired
+from typing_extensions import NotRequired, override
from langchain.agents.middleware.types import (
AgentMiddleware,
@@ -157,7 +157,8 @@ class ModelCallLimitMiddleware(AgentMiddleware[ModelCallLimitState, Any]):
self.exit_behavior = exit_behavior
@hook_config(can_jump_to=["end"])
- def before_model(self, state: ModelCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ @override
+ def before_model(self, state: ModelCallLimitState, runtime: Runtime) -> dict[str, Any] | None:
"""Check model call limits before making a model call.
Args:
@@ -222,7 +223,8 @@ class ModelCallLimitMiddleware(AgentMiddleware[ModelCallLimitState, Any]):
"""
return self.before_model(state, runtime)
- def after_model(self, state: ModelCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ @override
+ def after_model(self, state: ModelCallLimitState, runtime: Runtime) -> dict[str, Any] | None:
"""Increment model call counts after a model call.
Args:
diff --git a/libs/langchain_v1/langchain/agents/middleware/model_fallback.py b/libs/langchain_v1/langchain/agents/middleware/model_fallback.py
index 304d7f0ebb..7bae4ce6ea 100644
--- a/libs/langchain_v1/langchain/agents/middleware/model_fallback.py
+++ b/libs/langchain_v1/langchain/agents/middleware/model_fallback.py
@@ -87,14 +87,14 @@ class ModelFallbackMiddleware(AgentMiddleware):
last_exception: Exception
try:
return handler(request)
- except Exception as e: # noqa: BLE001
+ except Exception as e:
last_exception = e
# Try fallback models
for fallback_model in self.models:
try:
return handler(request.override(model=fallback_model))
- except Exception as e: # noqa: BLE001
+ except Exception as e:
last_exception = e
continue
@@ -121,14 +121,14 @@ class ModelFallbackMiddleware(AgentMiddleware):
last_exception: Exception
try:
return await handler(request)
- except Exception as e: # noqa: BLE001
+ except Exception as e:
last_exception = e
# Try fallback models
for fallback_model in self.models:
try:
return await handler(request.override(model=fallback_model))
- except Exception as e: # noqa: BLE001
+ except Exception as e:
last_exception = e
continue
diff --git a/libs/langchain_v1/langchain/agents/middleware/model_retry.py b/libs/langchain_v1/langchain/agents/middleware/model_retry.py
index 1299f869a7..4de836ed2d 100644
--- a/libs/langchain_v1/langchain/agents/middleware/model_retry.py
+++ b/libs/langchain_v1/langchain/agents/middleware/model_retry.py
@@ -223,7 +223,7 @@ class ModelRetryMiddleware(AgentMiddleware):
for attempt in range(self.max_retries + 1):
try:
return handler(request)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
attempts_made = attempt + 1 # attempt is 0-indexed
# Check if we should retry this exception
@@ -270,7 +270,7 @@ class ModelRetryMiddleware(AgentMiddleware):
for attempt in range(self.max_retries + 1):
try:
return await handler(request)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
attempts_made = attempt + 1 # attempt is 0-indexed
# Check if we should retry this exception
diff --git a/libs/langchain_v1/langchain/agents/middleware/pii.py b/libs/langchain_v1/langchain/agents/middleware/pii.py
index 4f11e709fb..9b827cb716 100644
--- a/libs/langchain_v1/langchain/agents/middleware/pii.py
+++ b/libs/langchain_v1/langchain/agents/middleware/pii.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal
from langchain_core.messages import AIMessage, AnyMessage, HumanMessage, ToolMessage
+from typing_extensions import override
from langchain.agents.middleware._redaction import (
PIIDetectionError,
@@ -92,6 +93,8 @@ class PIIMiddleware(AgentMiddleware):
def __init__(
self,
+ # From a typing point of view, the literals are covered by 'str'.
+ # Nonetheless, we escape PYI051 to keep hints and autocompletion for the caller.
pii_type: Literal["email", "credit_card", "ip", "mac_address", "url"] | str, # noqa: PYI051
*,
strategy: Literal["block", "redact", "mask", "hash"] = "redact",
@@ -158,10 +161,11 @@ class PIIMiddleware(AgentMiddleware):
return sanitized, matches
@hook_config(can_jump_to=["end"])
+ @override
def before_model(
self,
state: AgentState,
- runtime: Runtime, # noqa: ARG002
+ runtime: Runtime,
) -> dict[str, Any] | None:
"""Check user messages and tool results for PII before model invocation.
@@ -273,10 +277,11 @@ class PIIMiddleware(AgentMiddleware):
"""
return self.before_model(state, runtime)
+ @override
def after_model(
self,
state: AgentState,
- runtime: Runtime, # noqa: ARG002
+ runtime: Runtime,
) -> dict[str, Any] | None:
"""Check AI messages for PII after model invocation.
diff --git a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
index 17a23e90ce..a8b0737b2e 100644
--- a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
+++ b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
@@ -22,7 +22,7 @@ from langchain_core.tools.base import ToolException
from langgraph.channels.untracked_value import UntrackedValue
from pydantic import BaseModel, model_validator
from pydantic.json_schema import SkipJsonSchema
-from typing_extensions import NotRequired
+from typing_extensions import NotRequired, override
from langchain.agents.middleware._execution import (
SHELL_TEMP_PREFIX,
@@ -78,10 +78,10 @@ class _SessionResources:
session: ShellSession
tempdir: tempfile.TemporaryDirectory[str] | None
policy: BaseExecutionPolicy
- _finalizer: weakref.finalize = field(init=False, repr=False)
+ finalizer: weakref.finalize = field(init=False, repr=False)
def __post_init__(self) -> None:
- self._finalizer = weakref.finalize(
+ self.finalizer = weakref.finalize(
self,
_cleanup_resources,
self.session,
@@ -489,7 +489,8 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
normalized[key] = str(value)
return normalized
- def before_agent(self, state: ShellToolState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ @override
+ def before_agent(self, state: ShellToolState, runtime: Runtime) -> dict[str, Any] | None:
"""Start the shell session and run startup commands."""
resources = self._get_or_create_resources(state)
return {"shell_session_resources": resources}
@@ -498,7 +499,8 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
"""Async start the shell session and run startup commands."""
return self.before_agent(state, runtime)
- def after_agent(self, state: ShellToolState, runtime: Runtime) -> None: # noqa: ARG002
+ @override
+ def after_agent(self, state: ShellToolState, runtime: Runtime) -> None:
"""Run shutdown commands and release resources when an agent completes."""
resources = state.get("shell_session_resources")
if not isinstance(resources, _SessionResources):
@@ -507,7 +509,7 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
try:
self._run_shutdown_commands(resources.session)
finally:
- resources._finalizer()
+ resources.finalizer()
async def aafter_agent(self, state: ShellToolState, runtime: Runtime) -> None:
"""Async run shutdown commands and release resources when an agent completes."""
diff --git a/libs/langchain_v1/langchain/agents/middleware/summarization.py b/libs/langchain_v1/langchain/agents/middleware/summarization.py
index c25f1b2334..10baf72466 100644
--- a/libs/langchain_v1/langchain/agents/middleware/summarization.py
+++ b/libs/langchain_v1/langchain/agents/middleware/summarization.py
@@ -18,6 +18,7 @@ from langgraph.graph.message import (
REMOVE_ALL_MESSAGES,
)
from langgraph.runtime import Runtime
+from typing_extensions import override
from langchain.agents.middleware.types import AgentMiddleware, AgentState
from langchain.chat_models import BaseChatModel, init_chat_model
@@ -262,7 +263,8 @@ class SummarizationMiddleware(AgentMiddleware):
)
raise ValueError(msg)
- def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ @override
+ def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
"""Process messages before model invocation, potentially triggering summarization."""
messages = state["messages"]
self._ensure_message_ids(messages)
@@ -289,7 +291,8 @@ class SummarizationMiddleware(AgentMiddleware):
]
}
- async def abefore_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ @override
+ async def abefore_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
"""Process messages before model invocation, potentially triggering summarization."""
messages = state["messages"]
self._ensure_message_ids(messages)
@@ -491,7 +494,7 @@ class SummarizationMiddleware(AgentMiddleware):
try:
response = self.model.invoke(self.summary_prompt.format(messages=trimmed_messages))
return response.text.strip()
- except Exception as e: # noqa: BLE001
+ except Exception as e:
return f"Error generating summary: {e!s}"
async def _acreate_summary(self, messages_to_summarize: list[AnyMessage]) -> str:
@@ -508,7 +511,7 @@ class SummarizationMiddleware(AgentMiddleware):
self.summary_prompt.format(messages=trimmed_messages)
)
return response.text.strip()
- except Exception as e: # noqa: BLE001
+ except Exception as e:
return f"Error generating summary: {e!s}"
def _trim_messages_for_summary(self, messages: list[AnyMessage]) -> list[AnyMessage]:
@@ -528,5 +531,5 @@ class SummarizationMiddleware(AgentMiddleware):
include_system=True,
),
)
- except Exception: # noqa: BLE001
+ except Exception:
return messages[-_DEFAULT_FALLBACK_MESSAGE_COUNT:]
diff --git a/libs/langchain_v1/langchain/agents/middleware/todo.py b/libs/langchain_v1/langchain/agents/middleware/todo.py
index 32b3d280a0..f34bd42fa5 100644
--- a/libs/langchain_v1/langchain/agents/middleware/todo.py
+++ b/libs/langchain_v1/langchain/agents/middleware/todo.py
@@ -1,5 +1,4 @@
"""Planning and task management middleware for agents."""
-# ruff: noqa: E501
from __future__ import annotations
@@ -99,7 +98,7 @@ It is important to skip using this tool when:
- Use clear, descriptive task names
Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
-Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all."""
+Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.""" # noqa: E501
WRITE_TODOS_SYSTEM_PROMPT = """## `write_todos`
@@ -113,7 +112,7 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
## Important To-Do List Usage Notes to Remember
- The `write_todos` tool should never be called multiple times in parallel.
-- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant."""
+- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.""" # noqa: E501
@tool(description=WRITE_TODOS_TOOL_DESCRIPTION)
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
index 0cedb231cd..749d0e5eaf 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Annotated, Any, Generic, Literal
from langchain_core.messages import AIMessage, ToolCall, ToolMessage
from langgraph.channels.untracked_value import UntrackedValue
from langgraph.typing import ContextT
-from typing_extensions import NotRequired
+from typing_extensions import NotRequired, override
from langchain.agents.middleware.types import (
AgentMiddleware,
@@ -322,10 +322,11 @@ class ToolCallLimitMiddleware(
return allowed_calls, blocked_calls, temp_thread_count, temp_run_count
@hook_config(can_jump_to=["end"])
+ @override
def after_model(
self,
state: ToolCallLimitState[ResponseT],
- runtime: Runtime[ContextT], # noqa: ARG002
+ runtime: Runtime[ContextT],
) -> dict[str, Any] | None:
"""Increment tool call counts after a model call and check limits.
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py b/libs/langchain_v1/langchain/agents/middleware/tool_retry.py
index baf3a9ee61..ee91053a8f 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_retry.py
@@ -310,7 +310,7 @@ class ToolRetryMiddleware(AgentMiddleware):
for attempt in range(self.max_retries + 1):
try:
return handler(request)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
attempts_made = attempt + 1 # attempt is 0-indexed
# Check if we should retry this exception
@@ -366,7 +366,7 @@ class ToolRetryMiddleware(AgentMiddleware):
for attempt in range(self.max_retries + 1):
try:
return await handler(request)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
attempts_made = attempt + 1 # attempt is 0-indexed
# Check if we should retry this exception
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py b/libs/langchain_v1/langchain/agents/middleware/tool_selection.py
index 3978fa795a..12740ffc80 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_selection.py
@@ -57,7 +57,7 @@ def _create_tool_selection_response(tools: list[BaseTool]) -> TypeAdapter:
raise AssertionError(msg)
# Create a Union of Annotated Literal types for each tool name with description
- # Example: Union[Annotated[Literal["tool1"], Field(description="...")], ...] noqa: ERA001
+ # For instance: Union[Annotated[Literal["tool1"], Field(description="...")], ...]
literals = [
Annotated[Literal[tool.name], Field(description=tool.description)] for tool in tools
]
@@ -282,7 +282,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):
# Response should be a dict since we're passing a schema (not a Pydantic model class)
if not isinstance(response, dict):
msg = f"Expected dict response, got {type(response)}"
- raise AssertionError(msg)
+ raise AssertionError(msg) # noqa: TRY004
modified_request = self._process_selection_response(
response, selection_request.available_tools, selection_request.valid_tool_names, request
)
@@ -313,7 +313,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):
# Response should be a dict since we're passing a schema (not a Pydantic model class)
if not isinstance(response, dict):
msg = f"Expected dict response, got {type(response)}"
- raise AssertionError(msg)
+ raise AssertionError(msg) # noqa: TRY004
modified_request = self._process_selection_response(
response, selection_request.available_tools, selection_request.valid_tool_names, request
)
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index 5d7ab319d1..ebb1ad4ee7 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -33,7 +33,7 @@ from langchain_core.messages import (
from langgraph.channels.ephemeral_value import EphemeralValue
from langgraph.graph.message import add_messages
from langgraph.prebuilt.tool_node import ToolCallRequest, ToolCallWrapper
-from langgraph.types import Command # noqa: TC002
+from langgraph.types import Command
from langgraph.typing import ContextT
from typing_extensions import NotRequired, Required, TypedDict, TypeVar, Unpack
@@ -897,7 +897,7 @@ def before_model(
if is_async:
async def async_wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -922,7 +922,7 @@ def before_model(
)()
def wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1038,7 +1038,7 @@ def after_model(
if is_async:
async def async_wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1061,7 +1061,7 @@ def after_model(
)()
def wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1189,7 +1189,7 @@ def before_agent(
if is_async:
async def async_wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1214,7 +1214,7 @@ def before_agent(
)()
def wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1332,7 +1332,7 @@ def after_agent(
if is_async:
async def async_wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1355,7 +1355,7 @@ def after_agent(
)()
def wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
state: StateT,
runtime: Runtime[ContextT],
) -> dict[str, Any] | Command | None:
@@ -1463,7 +1463,7 @@ def dynamic_prompt(
if is_async:
async def async_wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
@@ -1487,7 +1487,7 @@ def dynamic_prompt(
)()
def wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
@@ -1499,7 +1499,7 @@ def dynamic_prompt(
return handler(request)
async def async_wrapped_from_sync(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
@@ -1644,7 +1644,7 @@ def wrap_model_call(
if is_async:
async def async_wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
@@ -1665,7 +1665,7 @@ def wrap_model_call(
)()
def wrapped(
- self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
+ _self: AgentMiddleware[StateT, ContextT],
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
@@ -1804,7 +1804,7 @@ def wrap_tool_call(
if is_async:
async def async_wrapped(
- self: AgentMiddleware, # noqa: ARG001
+ _self: AgentMiddleware,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
) -> ToolMessage | Command:
@@ -1825,7 +1825,7 @@ def wrap_tool_call(
)()
def wrapped(
- self: AgentMiddleware, # noqa: ARG001
+ _self: AgentMiddleware,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
) -> ToolMessage | Command:
diff --git a/libs/langchain_v1/langchain/agents/structured_output.py b/libs/langchain_v1/langchain/agents/structured_output.py
index 05bc3c88d5..fd50d45d0c 100644
--- a/libs/langchain_v1/langchain/agents/structured_output.py
+++ b/libs/langchain_v1/langchain/agents/structured_output.py
@@ -227,7 +227,7 @@ class ToolStrategy(Generic[SchemaT]):
def _iter_variants(schema: Any) -> Iterable[Any]:
"""Yield leaf variants from Union and JSON Schema oneOf."""
- if get_origin(schema) in (UnionType, Union):
+ if get_origin(schema) in {UnionType, Union}:
for arg in get_args(schema):
yield from _iter_variants(arg)
return
diff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.py
index c731c15f63..b7d425a396 100644
--- a/libs/langchain_v1/langchain/chat_models/base.py
+++ b/libs/langchain_v1/langchain/chat_models/base.py
@@ -513,8 +513,12 @@ def _attempt_infer_model_provider(model_name: str) -> str | None:
def _parse_model(model: str, model_provider: str | None) -> tuple[str, str]:
- if not model_provider and ":" in model and model.split(":")[0] in _SUPPORTED_PROVIDERS:
- model_provider = model.split(":")[0]
+ if (
+ not model_provider
+ and ":" in model
+ and model.split(":", maxsplit=1)[0] in _SUPPORTED_PROVIDERS
+ ):
+ model_provider = model.split(":", maxsplit=1)[0]
model = ":".join(model.split(":")[1:])
model_provider = model_provider or _attempt_infer_model_provider(model)
if not model_provider:
@@ -643,6 +647,7 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]):
)
@property
+ @override
def InputType(self) -> TypeAlias:
"""Get the input type for this `Runnable`."""
from langchain_core.prompt_values import ChatPromptValueConcrete, StringPromptValue
@@ -827,6 +832,7 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]):
yield x
@overload
+ @override
def astream_log(
self,
input: Any,
@@ -844,6 +850,7 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]):
) -> AsyncIterator[RunLogPatch]: ...
@overload
+ @override
def astream_log(
self,
input: Any,
diff --git a/libs/langchain_v1/pyproject.toml b/libs/langchain_v1/pyproject.toml
index c93d0a84fc..a40851e08e 100644
--- a/libs/langchain_v1/pyproject.toml
+++ b/libs/langchain_v1/pyproject.toml
@@ -60,7 +60,7 @@ test = [
"langchain-openai",
]
lint = [
- "ruff>=0.12.2,<0.13.0",
+ "ruff>=0.14.2,<0.15.0",
]
typing = [
"mypy>=1.18.1,<1.19.0",
@@ -71,7 +71,6 @@ test_integration = [
"vcrpy>=7.0.0,<8.0.0",
"wrapt>=1.15.0,<2.0.0",
"python-dotenv>=1.0.0,<2.0.0",
- "cassio>=0.1.0,<1.0.0",
"langchainhub>=0.1.16,<1.0.0",
"langchain-core",
"langchain-text-splitters",
@@ -87,7 +86,6 @@ langchain-text-splitters = { path = "../text-splitters", editable = true }
langchain-openai = { path = "../partners/openai", editable = true }
[tool.ruff]
-exclude = ["tests/integration_tests/examples/non-utf8-encoding.py"]
line-length = 100
[tool.mypy]
@@ -108,83 +106,58 @@ select = [
"ALL"
]
ignore = [
+ "C90", # McCabe complexity
"COM812", # Messes with the formatter
+ "CPY", # No copyright
+ "FIX002", # Line contains TODO
"ISC001", # Messes with the formatter
"PERF203", # Rarely useful
- "SLF001", # Private member access
+ "PLR09", # Too many something (arg, statements, etc)
+ "RUF012", # Doesn't play well with Pydantic
+ "TC001", # Doesn't play well with Pydantic
+ "TC002", # Doesn't play well with Pydantic
+ "TC003", # Doesn't play well with Pydantic
+ "TD002", # Missing author in TODO
+ "TD003", # Missing issue link in TODO
+
+ # TODO rules
+ "ANN401", # Any in type annotations
+ "BLE", # Blind exceptions
"PLC0415", # Imports should be at the top. Not always desirable
- "PLR0913", # Too many arguments in function definition
- "PLC0414", # Inconsistent with how type checkers expect to be notified of intentional re-exports
- "RUF002", # Em-dash in docstring
]
-unfixable = ["B028"] # People should intentionally tune the stacklevel
+unfixable = [
+ "B028", # People should intentionally tune the stacklevel
+ "PLW1510", # People should intentionally set the check argument
+]
-pyupgrade.keep-runtime-typing = true
flake8-annotations.allow-star-arg-any = true
+allowed-confusables = ["–"]
[tool.ruff.lint.pydocstyle]
convention = "google"
ignore-var-parameters = true # ignore missing documentation for *args and **kwargs parameters
-[tool.ruff.lint.per-file-ignores]
-"tests/*" = [
- "D1", # Documentation rules
- "PLC0415", # Imports should be at the top. Not always desirable for tests
-]
-"langchain/agents/*" = [
- "ANN401", # we use Any right now, need to narrow
- "A002", # input is shadowing builtin
- "A001", # input is shadowing builtin
- "B904", # use from for exceptions
- "PLR2004", # magic values are fine for this case
- "C901", # too complex
- "TRY004", # type error exception
- "PLR0912", # too many branches
- "PLR0911", # too many return statements
-]
-"tests/unit_tests/agents/*" = ["ALL"]
-"tests/integration_tests/agents/*" = ["ALL"]
-
[tool.ruff.lint.extend-per-file-ignores]
-"scripts/check_imports.py" = ["ALL"]
-
-"langchain/chat_models/base.py" = [
- "ANN",
- "C901",
- "FIX002",
- "N802",
- "PLR0911",
- "PLR0912",
- "PLR0915",
-]
-
-"langchain/embeddings/base.py" = [
- "PLR0911",
- "PLR0913",
+"tests/unit_tests/agents/*" = [
+ "ANN", # Annotations, needs to fix
+ "ARG", # Arguments, needs to fix
+ "PT", # pytest, needs to fix
]
+"tests/unit_tests/agents/test_return_direct_spec.py" = ["F821"]
+"tests/unit_tests/agents/test_responses_spec.py" = ["F821"]
+"tests/unit_tests/agents/test_responses.py" = ["F821"]
+"tests/unit_tests/agents/test_react_agent.py" = ["ALL"]
-"tests/**/*.py" = [
- "S101", # Tests need assertions
- "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes
- "SLF001", # Private member access in tests
+"tests/*" = [
+ "D1", # Documentation rules
+ "S101", # Tests need assertions
+ "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes
+ "SLF001", # Private member access in tests
"PLR2004", # Magic values are perfectly fine in unit tests (e.g. 0, 1, 2, etc.)
- "C901", # Too complex
- "ANN401", # Annotated type is not necessary
- "N802", # Function name should be lowercase
- "PLW1641", # Object does not implement __hash__ method
- "ARG002", # Unused argument
- "BLE001", # Do not catch blind exception
- "N801", # class name should use CapWords convention
]
-"langchain/tools/tool_node.py" = [
- "ANN401", # we use Any right now, need to narrow
- "A002", # input is shadowing builtin
- "A001", # input is shadowing builtin
- "B904", # use from for exceptions
- "PLR2004", # magic values are fine for this case
- "C901", # too complex
- "TRY004", # type error exception
+"scripts/*" = [
+ "INP", # Scripts are not in a package
]
[tool.coverage.run]
diff --git a/libs/langchain_v1/scripts/check_imports.py b/libs/langchain_v1/scripts/check_imports.py
index f02c82ef37..ebf66aa036 100644
--- a/libs/langchain_v1/scripts/check_imports.py
+++ b/libs/langchain_v1/scripts/check_imports.py
@@ -1,4 +1,6 @@
-"""Quickly verify that a list of Python files can be loaded by the Python interpreter
+"""Check imports script.
+
+Quickly verify that a list of Python files can be loaded by the Python interpreter
without raising any errors. Ran before running more expensive tests. Useful in
Makefiles.
diff --git a/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py b/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py
index 7e8389f6e6..6aed4959e3 100644
--- a/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py
+++ b/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py
@@ -7,9 +7,7 @@ from typing import Any
import pytest
from langchain_core.messages import HumanMessage
-from langgraph._internal._typing import StateLike
from langgraph.graph.state import CompiledStateGraph
-from typing_extensions import TypedDict
from langchain.agents import create_agent
from langchain.agents.middleware.shell_tool import ShellToolMiddleware
@@ -22,13 +20,12 @@ def _get_model(provider: str) -> Any:
from langchain_anthropic import ChatAnthropic
return ChatAnthropic(model="claude-sonnet-4-5-20250929")
- elif provider == "openai":
+ if provider == "openai":
from langchain_openai import ChatOpenAI
return ChatOpenAI(model="gpt-4o-mini")
- else:
- msg = f"Unknown provider: {provider}"
- raise ValueError(msg)
+ msg = f"Unknown provider: {provider}"
+ raise ValueError(msg)
@pytest.mark.parametrize("provider", ["anthropic", "openai"])
diff --git a/libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py b/libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py
index a07f3312a2..b9b0a80760 100644
--- a/libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py
+++ b/libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py
@@ -3,6 +3,7 @@
import math
from langchain_core.embeddings import Embeddings
+from typing_extensions import override
fake_texts = ["foo", "bar", "baz"]
@@ -10,6 +11,7 @@ fake_texts = ["foo", "bar", "baz"]
class FakeEmbeddings(Embeddings):
"""Fake embeddings functionality for testing."""
+ @override
def embed_documents(self, texts: list[str]) -> list[list[float]]:
"""Return simple embeddings.
@@ -20,6 +22,7 @@ class FakeEmbeddings(Embeddings):
async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
return self.embed_documents(texts)
+ @override
def embed_query(self, text: str) -> list[float]:
"""Return constant query embeddings.
@@ -72,6 +75,7 @@ class AngularTwoDimensionalEmbeddings(Embeddings):
"""Make a list of texts into a list of embedding vectors."""
return [self.embed_query(text) for text in texts]
+ @override
def embed_query(self, text: str) -> list[float]:
"""Convert input text to a 'vector' (list of floats).
diff --git a/libs/langchain_v1/tests/integration_tests/chat_models/test_base.py b/libs/langchain_v1/tests/integration_tests/chat_models/test_base.py
index ad0a90fa1d..ee47dde3bc 100644
--- a/libs/langchain_v1/tests/integration_tests/chat_models/test_base.py
+++ b/libs/langchain_v1/tests/integration_tests/chat_models/test_base.py
@@ -11,7 +11,7 @@ from pydantic import BaseModel
from langchain.chat_models import init_chat_model
-class multiply(BaseModel):
+class Multiply(BaseModel):
"""Product of two ints."""
x: int
@@ -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"]),
diff --git a/libs/langchain_v1/tests/unit_tests/agents/any_str.py b/libs/langchain_v1/tests/unit_tests/agents/any_str.py
index 790324322d..da0dea1a50 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/any_str.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/any_str.py
@@ -1,9 +1,10 @@
import re
-from typing import Union
class AnyStr(str):
- def __init__(self, prefix: Union[str, re.Pattern] = "") -> None:
+ __slots__ = ("prefix",)
+
+ def __init__(self, prefix: str | re.Pattern = "") -> None:
super().__init__()
self.prefix = prefix
diff --git a/libs/langchain_v1/tests/unit_tests/agents/conftest.py b/libs/langchain_v1/tests/unit_tests/agents/conftest.py
index 7e134f6827..14aad66092 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/conftest.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/conftest.py
@@ -29,7 +29,7 @@ from .conftest_store import (
)
# Global variables for checkpointer and store configurations
-FAST_MODE = os.getenv("LANGGRAPH_TEST_FAST", "true").lower() in ("true", "1", "yes")
+FAST_MODE = os.getenv("LANGGRAPH_TEST_FAST", "true").lower() in {"true", "1", "yes"}
SYNC_CHECKPOINTER_PARAMS = (
["memory"]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/messages.py b/libs/langchain_v1/tests/unit_tests/agents/messages.py
index 285c2941fe..b344b45805 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/messages.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/messages.py
@@ -14,14 +14,14 @@ from langchain_core.messages import HumanMessage, ToolMessage
from .any_str import AnyStr
-def _AnyIdHumanMessage(**kwargs: Any) -> HumanMessage:
+def _AnyIdHumanMessage(**kwargs: Any) -> HumanMessage: # noqa: N802
"""Create a human message with an any id field."""
message = HumanMessage(**kwargs)
message.id = AnyStr()
return message
-def _AnyIdToolMessage(**kwargs: Any) -> ToolMessage:
+def _AnyIdToolMessage(**kwargs: Any) -> ToolMessage: # noqa: N802
"""Create a tool message with an any id field."""
message = ToolMessage(**kwargs)
message.id = AnyStr()
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_composition.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_composition.py
index 5d3d360518..6d7c0889b5 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_composition.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_composition.py
@@ -1,18 +1,16 @@
"""Unit tests for _chain_model_call_handlers handler composition."""
-import pytest
+from typing import cast
+
from langchain_core.messages import AIMessage
+from langgraph.runtime import Runtime
from langchain.agents.factory import _chain_model_call_handlers
from langchain.agents.middleware.types import ModelRequest, ModelResponse
-from typing import cast
-from langgraph.runtime import Runtime
-
def create_test_request(**kwargs):
"""Helper to create a `ModelRequest` with sensible defaults."""
-
defaults = {
"messages": [],
"model": None,
@@ -21,7 +19,7 @@ def create_test_request(**kwargs):
"tools": [],
"response_format": None,
"state": {},
- "runtime": cast(Runtime, object()),
+ "runtime": cast("Runtime", object()),
}
defaults.update(kwargs)
return ModelRequest(**defaults)
@@ -150,7 +148,8 @@ class TestChainModelCallHandlers:
def mock_base_handler(req):
call_count["value"] += 1
if call_count["value"] < 3:
- raise ValueError("fail")
+ msg = "fail"
+ raise ValueError(msg)
return ModelResponse(result=[AIMessage(content="success")], structured_response=None)
result = composed(create_test_request(), mock_base_handler)
@@ -176,7 +175,8 @@ class TestChainModelCallHandlers:
assert composed is not None
def mock_base_handler(req):
- raise ValueError("Model failed")
+ msg = "Model failed"
+ raise ValueError(msg)
result = composed(create_test_request(), mock_base_handler)
@@ -262,7 +262,8 @@ class TestChainModelCallHandlers:
def mock_base_handler(req):
attempt["value"] += 1
if attempt["value"] == 1:
- raise ValueError("fail")
+ msg = "fail"
+ raise ValueError(msg)
return ModelResponse(result=[AIMessage(content="ok")], structured_response=None)
result = composed(create_test_request(), mock_base_handler)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py
index cb3ccd1757..22901d5848 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py
@@ -1,28 +1,27 @@
"""Consolidated tests for middleware decorators: before_model, after_model, and wrap_model_call."""
-import pytest
from typing import Any
-from typing_extensions import NotRequired
-from syrupy.assertion import SnapshotAssertion
-from langchain_core.messages import HumanMessage, AIMessage
+import pytest
+from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.tools import tool
from langgraph.runtime import Runtime
-from langgraph.types import Command
+from syrupy.assertion import SnapshotAssertion
+from typing_extensions import NotRequired
+from langchain.agents.factory import _get_can_jump_to, create_agent
from langchain.agents.middleware.types import (
AgentMiddleware,
AgentState,
ModelRequest,
- before_model,
after_model,
+ before_model,
dynamic_prompt,
+ hook_config,
wrap_model_call,
wrap_tool_call,
- hook_config,
)
-from langchain.agents.factory import create_agent, _get_can_jump_to
-from ...model import FakeToolCallingModel
+from tests.unit_tests.agents.model import FakeToolCallingModel
class CustomState(AgentState):
@@ -32,9 +31,9 @@ class CustomState(AgentState):
@tool
-def test_tool(input: str) -> str:
+def test_tool(value: str) -> str:
"""A test tool for middleware testing."""
- return f"Tool result: {input}"
+ return f"Tool result: {value}"
def test_before_model_decorator() -> None:
@@ -124,7 +123,6 @@ def test_all_decorators_integration() -> None:
@before_model
def track_before(state: AgentState, runtime: Runtime) -> None:
call_order.append("before")
- return None
@wrap_model_call
def track_on_call(request, handler):
@@ -134,7 +132,6 @@ def test_all_decorators_integration() -> None:
@after_model
def track_after(state: AgentState, runtime: Runtime) -> None:
call_order.append("after")
- return None
agent = create_agent(
model=FakeToolCallingModel(), middleware=[track_before, track_on_call, track_after]
@@ -310,7 +307,6 @@ def test_mixed_sync_async_decorators() -> None:
assert isinstance(async_on_call, AgentMiddleware)
async def test_async_decorators_integration() -> None:
"""Test async decorators working together in an agent."""
call_order = []
@@ -318,7 +314,6 @@ async def test_async_decorators_integration() -> None:
@before_model
async def track_async_before(state: AgentState, runtime: Runtime) -> None:
call_order.append("async_before")
- return None
@wrap_model_call
async def track_async_on_call(request, handler):
@@ -328,7 +323,6 @@ async def test_async_decorators_integration() -> None:
@after_model
async def track_async_after(state: AgentState, runtime: Runtime) -> None:
call_order.append("async_after")
- return None
agent = create_agent(
model=FakeToolCallingModel(),
@@ -340,7 +334,6 @@ async def test_async_decorators_integration() -> None:
assert call_order == ["async_before", "async_on_call", "async_after"]
async def test_mixed_sync_async_decorators_integration() -> None:
"""Test mixed sync/async decorators working together in an agent."""
call_order = []
@@ -348,12 +341,10 @@ async def test_mixed_sync_async_decorators_integration() -> None:
@before_model
def track_sync_before(state: AgentState, runtime: Runtime) -> None:
call_order.append("sync_before")
- return None
@before_model
async def track_async_before(state: AgentState, runtime: Runtime) -> None:
call_order.append("async_before")
- return None
@wrap_model_call
async def track_async_on_call(request, handler):
@@ -368,12 +359,10 @@ async def test_mixed_sync_async_decorators_integration() -> None:
@after_model
async def track_async_after(state: AgentState, runtime: Runtime) -> None:
call_order.append("async_after")
- return None
@after_model
def track_sync_after(state: AgentState, runtime: Runtime) -> None:
call_order.append("sync_after")
- return None
agent = create_agent(
model=FakeToolCallingModel(),
@@ -436,7 +425,6 @@ def test_async_after_model_preserves_can_jump_to() -> None:
]
async def test_async_can_jump_to_integration() -> None:
"""Test can_jump_to parameter in a full agent with async middleware."""
calls = []
@@ -507,7 +495,11 @@ def test_get_can_jump_to_only_overridden_methods() -> None:
def test_async_middleware_with_can_jump_to_graph_snapshot(snapshot: SnapshotAssertion) -> None:
- """Test that async middleware with can_jump_to creates correct graph structure with conditional edges."""
+ """Test async middleware with can_jump_to graph snapshot.
+
+ Test that async middleware with `can_jump_to` creates correct graph structure with
+ conditional edges.
+ """
# Test 1: Async before_model with can_jump_to
@before_model(can_jump_to=["end"])
@@ -628,14 +620,13 @@ def test_dynamic_prompt_uses_state() -> None:
def test_dynamic_prompt_integration() -> None:
"""Test dynamic_prompt decorator in a full agent."""
-
prompt_calls = 0
@dynamic_prompt
def context_aware_prompt(request: ModelRequest) -> str:
nonlocal prompt_calls
prompt_calls += 1
- return f"you are a helpful assistant."
+ return "you are a helpful assistant."
agent = create_agent(model=FakeToolCallingModel(), middleware=[context_aware_prompt])
# Agent is already compiled
@@ -661,14 +652,13 @@ async def test_async_dynamic_prompt_decorator() -> None:
async def test_async_dynamic_prompt_integration() -> None:
"""Test async dynamic_prompt decorator in a full agent."""
-
prompt_calls = 0
@dynamic_prompt
async def async_context_prompt(request: ModelRequest) -> str:
nonlocal prompt_calls
prompt_calls += 1
- return f"Async assistant."
+ return "Async assistant."
agent = create_agent(model=FakeToolCallingModel(), middleware=[async_context_prompt])
# Agent is already compiled
@@ -717,7 +707,10 @@ def test_dynamic_prompt_multiple_in_sequence() -> None:
def test_async_dynamic_prompt_skipped_on_sync_invoke() -> None:
- """Test that async dynamic_prompt raises NotImplementedError when invoked via sync path (.invoke).
+ """Test async dynamic_prompt skipped on sync invoke.
+
+ Test that async `dynamic_prompt` raises `NotImplementedError` when invoked via sync
+ path (.invoke).
When an async-only middleware is defined, it cannot be called from the sync path.
The framework will raise NotImplementedError when trying to invoke the sync method.
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_diagram.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_diagram.py
index f2cc289dda..6c15500699 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_diagram.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_diagram.py
@@ -1,12 +1,11 @@
from collections.abc import Callable
+from langchain_core.messages import AIMessage
from syrupy.assertion import SnapshotAssertion
from langchain.agents.factory import create_agent
from langchain.agents.middleware.types import AgentMiddleware, ModelRequest
-from langchain_core.messages import AIMessage
-
-from ...model import FakeToolCallingModel
+from tests.unit_tests.agents.model import FakeToolCallingModel
def test_create_agent_diagram(
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py
index 5a4d27ca6f..3ca5c52bbc 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py
@@ -1,6 +1,6 @@
import sys
from collections.abc import Callable
-from typing import Any
+from typing import Annotated, Any
import pytest
from langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
@@ -9,23 +9,21 @@ from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph.checkpoint.memory import InMemorySaver
from pydantic import BaseModel, Field
from syrupy.assertion import SnapshotAssertion
-from typing_extensions import Annotated
from langchain.agents.factory import create_agent
from langchain.agents.middleware.types import (
AgentMiddleware,
AgentState,
- hook_config,
ModelRequest,
OmitFromInput,
OmitFromOutput,
PrivateStateAttr,
+ hook_config,
)
from langchain.agents.structured_output import ToolStrategy
from langchain.tools import InjectedState
-
-from ...messages import _AnyIdHumanMessage, _AnyIdToolMessage
-from ...model import FakeToolCallingModel
+from tests.unit_tests.agents.messages import _AnyIdHumanMessage, _AnyIdToolMessage
+from tests.unit_tests.agents.model import FakeToolCallingModel
def test_create_agent_invoke(
@@ -65,16 +63,16 @@ def test_create_agent_invoke(
calls.append("NoopEight.after_model")
@tool
- def my_tool(input: str) -> str:
- """A great tool"""
+ def my_tool(value: str) -> str:
+ """A great tool."""
calls.append("my_tool")
- return input.upper()
+ return value.upper()
agent_one = create_agent(
model=FakeToolCallingModel(
tool_calls=[
[
- {"args": {"input": "yo"}, "id": "1", "name": "my_tool"},
+ {"args": {"value": "yo"}, "id": "1", "name": "my_tool"},
],
[],
]
@@ -97,7 +95,7 @@ def test_create_agent_invoke(
tool_calls=[
{
"name": "my_tool",
- "args": {"input": "yo"},
+ "args": {"value": "yo"},
"id": "1",
"type": "tool_call",
}
@@ -168,14 +166,14 @@ def test_create_agent_jump(
calls.append("NoopEight.after_model")
@tool
- def my_tool(input: str) -> str:
- """A great tool"""
+ def my_tool(value: str) -> str:
+ """A great tool."""
calls.append("my_tool")
- return input.upper()
+ return value.upper()
agent_one = create_agent(
model=FakeToolCallingModel(
- tool_calls=[[ToolCall(id="1", name="my_tool", args={"input": "yo"})]],
+ tool_calls=[[ToolCall(id="1", name="my_tool", args={"value": "yo"})]],
),
tools=[my_tool],
system_prompt="You are a helpful assistant.",
@@ -265,7 +263,11 @@ def test_on_model_call() -> None:
def test_tools_to_model_edge_with_structured_and_regular_tool_calls():
- """Test that when there are both structured and regular tool calls, we execute regular and jump to END."""
+ """Test tools to model edge with structured and regular tool calls.
+
+ Test that when there are both structured and regular tool calls, we execute regular
+ and jump to END.
+ """
class WeatherResponse(BaseModel):
"""Weather response."""
@@ -376,7 +378,6 @@ def test_runtime_injected_into_middleware() -> None:
class CustomMiddleware(AgentMiddleware):
def before_model(self, state: AgentState, runtime: Runtime) -> None:
assert runtime is not None
- return None
def wrap_model_call(
self,
@@ -388,9 +389,6 @@ def test_runtime_injected_into_middleware() -> None:
def after_model(self, state: AgentState, runtime: Runtime) -> None:
assert runtime is not None
- return None
-
- middleware = CustomMiddleware()
agent = create_agent(model=FakeToolCallingModel(), middleware=[CustomMiddleware()])
agent.invoke({"messages": [HumanMessage("Hello")]})
@@ -435,7 +433,6 @@ agent = create_agent(
)
def test_injected_state_in_middleware_agent() -> None:
"""Test that custom state is properly injected into tools when using middleware."""
-
result = agent.invoke(
{"custom_state": "I love pizza", "messages": [HumanMessage("Call the test state tool")]}
)
@@ -527,7 +524,7 @@ def test_create_agent_sync_invoke_with_mixed_middleware() -> None:
middleware=[MixedMiddleware()],
)
- result = agent.invoke({"messages": [HumanMessage("hello")]})
+ agent.invoke({"messages": [HumanMessage("hello")]})
# In sync mode, only sync methods should be called
assert calls == [
@@ -564,15 +561,15 @@ async def test_create_agent_async_invoke() -> None:
calls.append("AsyncMiddleware.aafter_model")
@tool
- def my_tool_async(input: str) -> str:
- """A great tool"""
+ def my_tool_async(value: str) -> str:
+ """A great tool."""
calls.append("my_tool_async")
- return input.upper()
+ return value.upper()
agent = create_agent(
model=FakeToolCallingModel(
tool_calls=[
- [{"args": {"input": "yo"}, "id": "1", "name": "my_tool_async"}],
+ [{"args": {"value": "yo"}, "id": "1", "name": "my_tool_async"}],
[],
]
),
@@ -647,7 +644,7 @@ async def test_create_agent_async_invoke_multiple_middleware() -> None:
middleware=[AsyncMiddlewareOne(), AsyncMiddlewareTwo()],
)
- result = await agent.ainvoke({"messages": [HumanMessage("hello")]})
+ await agent.ainvoke({"messages": [HumanMessage("hello")]})
assert calls == [
"AsyncMiddlewareOne.abefore_model",
@@ -676,14 +673,14 @@ async def test_create_agent_async_jump() -> None:
return {"jump_to": "end"}
@tool
- def my_tool_jump(input: str) -> str:
- """A great tool"""
+ def my_tool_jump(value: str) -> str:
+ """A great tool."""
calls.append("my_tool_jump")
- return input.upper()
+ return value.upper()
agent = create_agent(
model=FakeToolCallingModel(
- tool_calls=[[ToolCall(id="1", name="my_tool_jump", args={"input": "yo"})]],
+ tool_calls=[[ToolCall(id="1", name="my_tool_jump", args={"value": "yo"})]],
),
tools=[my_tool_jump],
system_prompt="You are a helpful assistant.",
@@ -774,7 +771,7 @@ class TestAgentMiddlewareHooks:
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("hook_type", ["before", "after"])
- async def test_hook_execution(self, is_async: bool, hook_type: str) -> None:
+ async def test_hook_execution(self, *, is_async: bool, hook_type: str) -> None:
"""Test that agent hooks are called in both sync and async modes."""
from langchain.agents.middleware import after_agent, before_agent
@@ -795,21 +792,20 @@ class TestAgentMiddlewareHooks:
execution_log.append(f"{hook_type}_agent_called")
execution_log.append(f"message_count: {len(state['messages'])}")
return None
- else:
- if hook_type == "before":
+ elif hook_type == "before":
- @before_agent
- def log_hook(state: AgentState, runtime) -> dict[str, Any] | None:
- execution_log.append(f"{hook_type}_agent_called")
- execution_log.append(f"message_count: {len(state['messages'])}")
- return None
- else:
+ @before_agent
+ def log_hook(state: AgentState, runtime) -> dict[str, Any] | None:
+ execution_log.append(f"{hook_type}_agent_called")
+ execution_log.append(f"message_count: {len(state['messages'])}")
+ return None
+ else:
- @after_agent
- def log_hook(state: AgentState, runtime) -> dict[str, Any] | None:
- execution_log.append(f"{hook_type}_agent_called")
- execution_log.append(f"message_count: {len(state['messages'])}")
- return None
+ @after_agent
+ def log_hook(state: AgentState, runtime) -> dict[str, Any] | None:
+ execution_log.append(f"{hook_type}_agent_called")
+ execution_log.append(f"message_count: {len(state['messages'])}")
+ return None
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
@@ -826,7 +822,7 @@ class TestAgentMiddlewareHooks:
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("hook_type", ["before", "after"])
- async def test_hook_with_class_inheritance(self, is_async: bool, hook_type: str) -> None:
+ async def test_hook_with_class_inheritance(self, *, is_async: bool, hook_type: str) -> None:
"""Test agent hooks using class inheritance in both sync and async modes."""
execution_log: list[str] = []
@@ -873,7 +869,7 @@ class TestAgentHooksCombined:
"""Test before_agent and after_agent hooks working together."""
@pytest.mark.parametrize("is_async", [False, True])
- async def test_execution_order(self, is_async: bool) -> None:
+ async def test_execution_order(self, *, is_async: bool) -> None:
"""Test that before_agent executes before after_agent in both sync and async modes."""
from langchain.agents.middleware import after_agent, before_agent
@@ -912,9 +908,10 @@ class TestAgentHooksCombined:
def test_state_passthrough(self) -> None:
"""Test that state modifications in before_agent are visible to after_agent."""
- from langchain.agents.middleware import before_agent
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
+ from langchain.agents.middleware import before_agent
+
@before_agent
def modify_in_before(state: AgentState, runtime) -> dict[str, Any]:
return {"messages": [HumanMessage("Added by before_agent")]}
@@ -928,9 +925,10 @@ class TestAgentHooksCombined:
def test_multiple_middleware_instances(self) -> None:
"""Test multiple before_agent and after_agent middleware instances."""
- from langchain.agents.middleware import after_agent, before_agent
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
+ from langchain.agents.middleware import after_agent, before_agent
+
execution_log = []
@before_agent
@@ -971,7 +969,6 @@ class TestAgentHooksCombined:
before_agent,
before_model,
)
- from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
execution_log = []
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_overrides.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_overrides.py
index 8005b40fdb..a8d65d70e8 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_overrides.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_overrides.py
@@ -1,12 +1,9 @@
"""Unit tests for override() methods on ModelRequest and ToolCallRequest."""
-import pytest
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage
-from langchain_core.tools import BaseTool
-from langchain.agents.middleware.types import ModelRequest
-from langchain.agents.middleware.types import ToolCallRequest
+from langchain.agents.middleware.types import ModelRequest, ToolCallRequest
class TestModelRequestOverride:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_sync_async_wrappers.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_sync_async_wrappers.py
index 24a3218cb5..d68e88976b 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_sync_async_wrappers.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_sync_async_wrappers.py
@@ -12,8 +12,7 @@ from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents.factory import create_agent
-from langchain.agents.middleware.types import AgentMiddleware, wrap_tool_call
-from langchain.agents.middleware.types import ToolCallRequest
+from langchain.agents.middleware.types import AgentMiddleware, ToolCallRequest, wrap_tool_call
from tests.unit_tests.agents.model import FakeToolCallingModel
@@ -182,7 +181,7 @@ class TestSyncAsyncMiddlewareComposition:
# Sync path
call_log.clear()
- result_sync = agent.invoke(
+ agent.invoke(
{"messages": [HumanMessage("Search")]},
{"configurable": {"thread_id": "test1"}},
)
@@ -220,7 +219,7 @@ class TestSyncAsyncMiddlewareComposition:
# Async path
call_log.clear()
- result_async = await agent.ainvoke(
+ await agent.ainvoke(
{"messages": [HumanMessage("Search")]},
{"configurable": {"thread_id": "test2"}},
)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_tools.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_tools.py
index 074af94706..08486d04d9 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_tools.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_tools.py
@@ -3,12 +3,12 @@
from collections.abc import Callable
import pytest
+from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
+from langchain_core.tools import tool
+from langgraph.prebuilt.tool_node import ToolNode
from langchain.agents.factory import create_agent
from langchain.agents.middleware.types import AgentMiddleware, AgentState, ModelRequest
-from langgraph.prebuilt.tool_node import ToolNode
-from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
-from langchain_core.tools import tool
from tests.unit_tests.agents.model import FakeToolCallingModel
@@ -58,17 +58,17 @@ def test_middleware_can_modify_tools() -> None:
"""Test that middleware can modify the list of tools in ModelRequest."""
@tool
- def tool_a(input: str) -> str:
+ def tool_a(value: str) -> str:
"""Tool A."""
return "A"
@tool
- def tool_b(input: str) -> str:
+ def tool_b(value: str) -> str:
"""Tool B."""
return "B"
@tool
- def tool_c(input: str) -> str:
+ def tool_c(value: str) -> str:
"""Tool C."""
return "C"
@@ -107,12 +107,12 @@ def test_unknown_tool_raises_error() -> None:
"""Test that using an unknown tool in ModelRequest raises a clear error."""
@tool
- def known_tool(input: str) -> str:
+ def known_tool(value: str) -> str:
"""A known tool."""
return "result"
@tool
- def unknown_tool(input: str) -> str:
+ def unknown_tool(value: str) -> str:
"""An unknown tool not passed to create_agent."""
return "unknown"
@@ -123,7 +123,7 @@ def test_unknown_tool_raises_error() -> None:
handler: Callable[[ModelRequest], AIMessage],
) -> AIMessage:
# Add an unknown tool
- return handler(request.override(tools=request.tools + [unknown_tool]))
+ return handler(request.override(tools=[*request.tools, unknown_tool]))
agent = create_agent(
model=FakeToolCallingModel(),
@@ -189,7 +189,7 @@ def test_empty_tools_list_is_valid() -> None:
"""Test that middleware can set tools to an empty list."""
@tool
- def some_tool(input: str) -> str:
+ def some_tool(value: str) -> str:
"""Some tool."""
return "result"
@@ -222,17 +222,17 @@ def test_tools_preserved_across_multiple_middleware() -> None:
modification_order: list[list[str]] = []
@tool
- def tool_a(input: str) -> str:
+ def tool_a(value: str) -> str:
"""Tool A."""
return "A"
@tool
- def tool_b(input: str) -> str:
+ def tool_b(value: str) -> str:
"""Tool B."""
return "B"
@tool
- def tool_c(input: str) -> str:
+ def tool_c(value: str) -> str:
"""Tool C."""
return "C"
@@ -283,12 +283,12 @@ def test_middleware_with_additional_tools() -> None:
"""Test middleware that provides additional tools via tools attribute."""
@tool
- def base_tool(input: str) -> str:
+ def base_tool(value: str) -> str:
"""Base tool."""
return "base"
@tool
- def middleware_tool(input: str) -> str:
+ def middleware_tool(value: str) -> str:
"""Tool provided by middleware."""
return "middleware"
@@ -298,7 +298,7 @@ def test_middleware_with_additional_tools() -> None:
# Model calls the middleware-provided tool
model = FakeToolCallingModel(
tool_calls=[
- [{"args": {"input": "test"}, "id": "1", "name": "middleware_tool"}],
+ [{"args": {"value": "test"}, "id": "1", "name": "middleware_tool"}],
[],
]
)
@@ -324,7 +324,7 @@ def test_tool_node_not_accepted() -> None:
"""Test that passing a ToolNode instance to create_agent raises an error."""
@tool
- def some_tool(input: str) -> str:
+ def some_tool(value: str) -> str:
"""Some tool."""
return "result"
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
index 93e1ba0707..e28120ef00 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
@@ -12,7 +12,6 @@ import pytest
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage
-from langchain_core.outputs import ChatGeneration, ChatResult
from langchain.agents import create_agent
from langchain.agents.middleware.types import (
@@ -20,8 +19,7 @@ from langchain.agents.middleware.types import (
ModelRequest,
wrap_model_call,
)
-
-from ...model import FakeToolCallingModel
+from tests.unit_tests.agents.model import FakeToolCallingModel
class TestBasicWrapModelCall:
@@ -93,7 +91,8 @@ class TestRetryLogic:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First call fails")
+ msg = "First call fails"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
class RetryOnceMiddleware(AgentMiddleware):
@@ -122,7 +121,8 @@ class TestRetryLogic:
class AlwaysFailModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Always fails")
+ msg = "Always fails"
+ raise ValueError(msg)
class MaxRetriesMiddleware(AgentMiddleware):
def __init__(self, max_retries=3):
@@ -142,6 +142,7 @@ class TestRetryLogic:
# Re-raise the last exception
if last_exception:
raise last_exception
+ pytest.fail("Should have raised an exception")
retry_middleware = MaxRetriesMiddleware(max_retries=3)
model = AlwaysFailModel(messages=iter([]))
@@ -159,7 +160,8 @@ class TestRetryLogic:
"""Model that always fails."""
def _generate(self, messages, **kwargs):
- raise ValueError("Model error")
+ msg = "Model error"
+ raise ValueError(msg)
@property
def _llm_type(self):
@@ -181,7 +183,8 @@ class TestRetryLogic:
"""Model that always fails."""
def _generate(self, messages, **kwargs):
- raise ValueError("Always fails")
+ msg = "Always fails"
+ raise ValueError(msg)
@property
def _llm_type(self):
@@ -197,7 +200,7 @@ class TestRetryLogic:
def wrap_model_call(self, request, handler):
last_exception = None
- for attempt in range(self.max_retries):
+ for _attempt in range(self.max_retries):
self.attempt_count += 1
try:
return handler(request)
@@ -208,6 +211,7 @@ class TestRetryLogic:
# All retries exhausted, re-raise the last error
if last_exception:
raise last_exception
+ pytest.fail("Should have raised an exception")
model = AlwaysFailingModel()
middleware = LimitedRetryMiddleware(max_retries=10)
@@ -294,7 +298,8 @@ class TestErrorHandling:
class AlwaysFailModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Model error")
+ msg = "Model error"
+ raise ValueError(msg)
class ErrorToSuccessMiddleware(AgentMiddleware):
def wrap_model_call(self, request, handler):
@@ -317,7 +322,8 @@ class TestErrorHandling:
class SpecificErrorModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ConnectionError("Network error")
+ msg = "Network error"
+ raise ConnectionError(msg)
class SelectiveErrorMiddleware(AgentMiddleware):
def wrap_model_call(self, request, handler):
@@ -343,10 +349,10 @@ class TestErrorHandling:
call_log.append("before-yield")
result = handler(request)
call_log.append("after-yield-success")
- return result
except Exception:
call_log.append("caught-error")
return AIMessage(content="Recovered from error")
+ return result
# Test 1: Success path
call_log.clear()
@@ -362,7 +368,8 @@ class TestErrorHandling:
class AlwaysFailModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Model error")
+ msg = "Model error"
+ raise ValueError(msg)
model2 = AlwaysFailModel(messages=iter([]))
agent2 = create_agent(model=model2, middleware=[ErrorRecoveryMiddleware()])
@@ -388,11 +395,10 @@ class TestShortCircuit:
if cache_key in cache:
# Short-circuit with cached result
return cache[cache_key]
- else:
- # Execute and cache
- result = handler(request)
- cache[cache_key] = result
- return result
+ # Execute and cache
+ result = handler(request)
+ cache[cache_key] = result
+ return result
class TrackingModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
@@ -504,6 +510,7 @@ class TestStateAndRuntime:
except Exception:
if attempt == max_retries - 1:
raise
+ pytest.fail("Should have raised an exception")
call_count = {"value": 0}
@@ -511,7 +518,8 @@ class TestStateAndRuntime:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First fails")
+ msg = "First fails"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
model = FailOnceThenSucceed(messages=iter([AIMessage(content="Success")]))
@@ -590,7 +598,8 @@ class TestMiddlewareComposition:
agent.invoke({"messages": [HumanMessage("Test")]})
- # First wraps Second wraps Third: 1-before, 2-before, 3-before, model, 3-after, 2-after, 1-after
+ # First wraps Second wraps Third:
+ # 1-before, 2-before, 3-before, model, 3-after, 2-after, 1-after
assert execution_order == [
"first-before",
"second-before",
@@ -609,7 +618,8 @@ class TestMiddlewareComposition:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First call fails")
+ msg = "First call fails"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
class LoggingMiddleware(AgentMiddleware):
@@ -625,12 +635,12 @@ class TestMiddlewareComposition:
try:
result = handler(request)
log.append("retry-after")
- return result
except Exception:
log.append("retry-retrying")
result = handler(request)
log.append("retry-after")
- return result
+
+ return result
model = FailOnceThenSucceed(messages=iter([AIMessage(content="Success")]))
# Logging is outer, Retry is inner
@@ -683,7 +693,8 @@ class TestMiddlewareComposition:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First call fails")
+ msg = "First call fails"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
class RetryMiddleware(AgentMiddleware):
@@ -808,7 +819,8 @@ class TestWrapModelCallDecorator:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First call fails")
+ msg = "First call fails"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
@wrap_model_call
@@ -849,7 +861,8 @@ class TestWrapModelCallDecorator:
class AlwaysFailModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Model error")
+ msg = "Model error"
+ raise ValueError(msg)
@wrap_model_call
def error_to_fallback(request, handler):
@@ -1015,7 +1028,8 @@ class TestWrapModelCallDecorator:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] <= 2:
- raise ValueError(f"Attempt {call_count['value']} failed")
+ msg = f"Attempt {call_count['value']} failed"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
@wrap_model_call
@@ -1029,8 +1043,8 @@ class TestWrapModelCallDecorator:
# On error, continue to next attempt
if attempt < max_retries - 1:
continue # Retry
- else:
- raise # All retries failed
+ raise # All retries failed
+ pytest.fail("Should have raised an exception")
model = UnreliableModel(messages=iter([AIMessage(content="Finally worked")]))
agent = create_agent(model=model, middleware=[retry_with_tracking])
@@ -1098,7 +1112,8 @@ class TestAsyncWrapModelCall:
async def _agenerate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First async call fails")
+ msg = "First async call fails"
+ raise ValueError(msg)
return await super()._agenerate(messages, **kwargs)
class RetryMiddleware(AgentMiddleware):
@@ -1194,7 +1209,7 @@ class TestSyncAsyncInterop:
middleware=[MixedMiddleware()],
)
- result = agent.invoke({"messages": [HumanMessage("hello")]})
+ agent.invoke({"messages": [HumanMessage("hello")]})
# In sync mode, only sync methods should be called
assert calls == [
@@ -1243,7 +1258,8 @@ class TestEdgeCases:
def _generate(self, messages, **kwargs):
call_count["value"] += 1
if call_count["value"] == 1:
- raise ValueError("First fails")
+ msg = "First fails"
+ raise ValueError(msg)
return super()._generate(messages, **kwargs)
model = FailFirstSucceedSecond(messages=iter([AIMessage(content="Success")]))
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_tool_call.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_tool_call.py
index 89c10ee0c3..5c27c0b695 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_tool_call.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_tool_call.py
@@ -12,8 +12,7 @@ from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
from langchain.agents.factory import create_agent
-from langchain.agents.middleware.types import wrap_tool_call
-from langchain.agents.middleware.types import ToolCallRequest
+from langchain.agents.middleware.types import ToolCallRequest, wrap_tool_call
from tests.unit_tests.agents.model import FakeToolCallingModel
@@ -30,9 +29,9 @@ def calculator(expression: str) -> str:
@tool
-def failing_tool(input: str) -> str:
+def failing_tool(value: str) -> str:
"""Tool that always fails."""
- msg = f"Failed: {input}"
+ msg = f"Failed: {value}"
raise ValueError(msg)
@@ -229,7 +228,7 @@ def test_wrap_tool_call_retry_on_error() -> None:
if attempt == max_retries - 1:
# Return error message instead of raising
return ToolMessage(
- content=f"Error after {max_retries} attempts: {str(last_error)}",
+ content=f"Error after {max_retries} attempts: {last_error}",
tool_call_id=request.tool_call["id"],
name=request.tool_call["name"],
status="error",
@@ -237,7 +236,7 @@ def test_wrap_tool_call_retry_on_error() -> None:
# Continue to retry
# This line should never be reached due to return above
return ToolMessage(
- content=f"Unexpected error: {str(last_error)}",
+ content=f"Unexpected error: {last_error}",
tool_call_id=request.tool_call["id"],
name=request.tool_call["name"],
status="error",
@@ -245,7 +244,7 @@ def test_wrap_tool_call_retry_on_error() -> None:
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -319,12 +318,11 @@ def test_wrap_tool_call_response_modification() -> None:
# Modify the response
if isinstance(response, ToolMessage):
- modified = ToolMessage(
+ return ToolMessage(
content=f"MODIFIED: {response.content}",
tool_call_id=response.tool_call_id,
name=response.name,
)
- return modified
return response
model = FakeToolCallingModel(
@@ -450,9 +448,9 @@ def test_wrap_tool_call_with_tools_parameter() -> None:
"""Test wrap_tool_call decorator with tools parameter."""
@tool
- def extra_tool(input: str) -> str:
+ def extra_tool(value: str) -> str:
"""Extra tool registered with middleware."""
- return f"Extra: {input}"
+ return f"Extra: {value}"
@wrap_tool_call(tools=[extra_tool])
def wrapper_with_tools(request: ToolCallRequest, handler: Callable) -> ToolMessage | Command:
@@ -527,7 +525,7 @@ def test_wrap_tool_call_outer_intercepts_inner() -> None:
@wrap_tool_call(name="InterceptingOuter")
def intercepting_outer(request: ToolCallRequest, handler: Callable) -> ToolMessage | Command:
call_log.append("outer_before")
- response = handler(request)
+ handler(request)
call_log.append("outer_after")
# Return modified message
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_context_editing.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_context_editing.py
index e8197cb06a..900cf6978b 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_context_editing.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_context_editing.py
@@ -2,13 +2,9 @@
from __future__ import annotations
-from typing import Iterable, cast
+from collections.abc import Iterable
+from typing import cast
-from langchain.agents.middleware.context_editing import (
- ClearToolUsesEdit,
- ContextEditingMiddleware,
-)
-from langchain.agents.middleware.types import AgentState, ModelRequest
from langchain_core.language_models.fake_chat_models import FakeChatModel
from langchain_core.messages import (
AIMessage,
@@ -17,6 +13,12 @@ from langchain_core.messages import (
)
from langgraph.runtime import Runtime
+from langchain.agents.middleware.context_editing import (
+ ClearToolUsesEdit,
+ ContextEditingMiddleware,
+)
+from langchain.agents.middleware.types import AgentState, ModelRequest
+
class _TokenCountingChatModel(FakeChatModel):
"""Fake chat model that counts tokens deterministically for tests."""
@@ -24,7 +26,7 @@ class _TokenCountingChatModel(FakeChatModel):
def get_num_tokens_from_messages(
self,
messages: list[MessageLikeRepresentation],
- tools: Iterable | None = None, # noqa: ARG002
+ tools: Iterable | None = None,
) -> int:
return sum(_count_message_tokens(message) for message in messages)
@@ -54,7 +56,7 @@ def _make_state_and_request(
) -> tuple[AgentState, ModelRequest]:
model = _TokenCountingChatModel()
conversation = list(messages)
- state = cast(AgentState, {"messages": conversation})
+ state = cast("AgentState", {"messages": conversation})
request = ModelRequest(
model=model,
system_prompt=system_prompt,
@@ -77,7 +79,7 @@ def test_no_edit_when_below_trigger() -> None:
)
tool_message = ToolMessage(content="12345", tool_call_id=tool_call_id)
- state, request = _make_state_and_request([ai_message, tool_message])
+ _state, request = _make_state_and_request([ai_message, tool_message])
middleware = ContextEditingMiddleware(
edits=[ClearToolUsesEdit(trigger=50)],
)
@@ -111,7 +113,7 @@ def test_clear_tool_outputs_and_inputs() -> None:
)
tool_message = ToolMessage(content="x" * 200, tool_call_id=tool_call_id)
- state, request = _make_state_and_request([ai_message, tool_message])
+ _state, request = _make_state_and_request([ai_message, tool_message])
edit = ClearToolUsesEdit(
trigger=50,
@@ -168,7 +170,7 @@ def test_respects_keep_last_tool_results() -> None:
)
conversation.append(ToolMessage(content=text, tool_call_id=call_id))
- state, request = _make_state_and_request(conversation)
+ _state, request = _make_state_and_request(conversation)
middleware = ContextEditingMiddleware(
edits=[
@@ -178,7 +180,7 @@ def test_respects_keep_last_tool_results() -> None:
placeholder="[cleared]",
)
],
- token_count_method="model",
+ token_count_method="model", # noqa: S106
)
modified_request = None
@@ -207,7 +209,7 @@ def test_exclude_tools_prevents_clearing() -> None:
search_call = "call-search"
calc_call = "call-calc"
- state, request = _make_state_and_request(
+ _state, request = _make_state_and_request(
[
AIMessage(
content="",
@@ -256,7 +258,7 @@ def test_exclude_tools_prevents_clearing() -> None:
def _fake_runtime() -> Runtime:
- return cast(Runtime, object())
+ return cast("Runtime", object())
async def test_no_edit_when_below_trigger_async() -> None:
@@ -268,7 +270,7 @@ async def test_no_edit_when_below_trigger_async() -> None:
)
tool_message = ToolMessage(content="12345", tool_call_id=tool_call_id)
- state, request = _make_state_and_request([ai_message, tool_message])
+ _state, request = _make_state_and_request([ai_message, tool_message])
middleware = ContextEditingMiddleware(
edits=[ClearToolUsesEdit(trigger=50)],
)
@@ -303,7 +305,7 @@ async def test_clear_tool_outputs_and_inputs_async() -> None:
)
tool_message = ToolMessage(content="x" * 200, tool_call_id=tool_call_id)
- state, request = _make_state_and_request([ai_message, tool_message])
+ _state, request = _make_state_and_request([ai_message, tool_message])
edit = ClearToolUsesEdit(
trigger=50,
@@ -361,7 +363,7 @@ async def test_respects_keep_last_tool_results_async() -> None:
)
conversation.append(ToolMessage(content=text, tool_call_id=call_id))
- state, request = _make_state_and_request(conversation)
+ _state, request = _make_state_and_request(conversation)
middleware = ContextEditingMiddleware(
edits=[
@@ -371,7 +373,7 @@ async def test_respects_keep_last_tool_results_async() -> None:
placeholder="[cleared]",
)
],
- token_count_method="model",
+ token_count_method="model", # noqa: S106
)
modified_request = None
@@ -401,7 +403,7 @@ async def test_exclude_tools_prevents_clearing_async() -> None:
search_call = "call-search"
calc_call = "call-calc"
- state, request = _make_state_and_request(
+ _state, request = _make_state_and_request(
[
AIMessage(
content="",
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_file_search.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_file_search.py
index bb3340d981..3e6a90573a 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_file_search.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_file_search.py
@@ -18,7 +18,6 @@ class TestFilesystemGrepSearch:
def test_grep_invalid_include_pattern(self, tmp_path: Path) -> None:
"""Return error when include glob cannot be parsed."""
-
(tmp_path / "example.py").write_text("print('hello')\n", encoding="utf-8")
middleware = FilesystemFileSearchMiddleware(root_path=str(tmp_path), use_ripgrep=False)
@@ -31,7 +30,6 @@ class TestFilesystemGrepSearch:
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Ensure ripgrep receives pattern after ``--`` to avoid option parsing."""
-
(tmp_path / "example.py").write_text("print('hello')\n", encoding="utf-8")
middleware = FilesystemFileSearchMiddleware(root_path=str(tmp_path), use_ripgrep=True)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py
index ca823cd4f4..18e549d078 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py
@@ -1,3 +1,4 @@
+import re
from typing import Any
from unittest.mock import patch
@@ -14,7 +15,6 @@ from langchain.agents.middleware.types import AgentState
def test_human_in_the_loop_middleware_initialization() -> None:
"""Test HumanInTheLoopMiddleware initialization."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "edit", "reject"]}},
description_prefix="Custom prefix",
@@ -28,7 +28,6 @@ def test_human_in_the_loop_middleware_initialization() -> None:
def test_human_in_the_loop_middleware_no_interrupts_needed() -> None:
"""Test HumanInTheLoopMiddleware when no interrupts are needed."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "edit", "reject"]}}
)
@@ -55,7 +54,6 @@ def test_human_in_the_loop_middleware_no_interrupts_needed() -> None:
def test_human_in_the_loop_middleware_single_tool_accept() -> None:
"""Test HumanInTheLoopMiddleware with single tool accept response."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "edit", "reject"]}}
)
@@ -123,7 +121,6 @@ def test_human_in_the_loop_middleware_single_tool_edit() -> None:
def test_human_in_the_loop_middleware_single_tool_response() -> None:
"""Test HumanInTheLoopMiddleware with single tool response with custom message."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "edit", "reject"]}}
)
@@ -153,7 +150,6 @@ def test_human_in_the_loop_middleware_single_tool_response() -> None:
def test_human_in_the_loop_middleware_multiple_tools_mixed_responses() -> None:
"""Test HumanInTheLoopMiddleware with multiple tools and mixed response types."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={
"get_forecast": {"allowed_decisions": ["approve", "edit", "reject"]},
@@ -203,7 +199,6 @@ def test_human_in_the_loop_middleware_multiple_tools_mixed_responses() -> None:
def test_human_in_the_loop_middleware_multiple_tools_edit_responses() -> None:
"""Test HumanInTheLoopMiddleware with multiple tools and edit responses."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={
"get_forecast": {"allowed_decisions": ["approve", "edit", "reject"]},
@@ -257,7 +252,6 @@ def test_human_in_the_loop_middleware_multiple_tools_edit_responses() -> None:
def test_human_in_the_loop_middleware_edit_with_modified_args() -> None:
"""Test HumanInTheLoopMiddleware with edit action that includes modified args."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "edit", "reject"]}}
)
@@ -311,17 +305,23 @@ def test_human_in_the_loop_middleware_unknown_response_type() -> None:
def mock_unknown(requests):
return {"decisions": [{"type": "unknown"}]}
- with patch("langchain.agents.middleware.human_in_the_loop.interrupt", side_effect=mock_unknown):
- with pytest.raises(
+ with (
+ patch("langchain.agents.middleware.human_in_the_loop.interrupt", side_effect=mock_unknown),
+ pytest.raises(
ValueError,
- match=r"Unexpected human decision: {'type': 'unknown'}. Decision type 'unknown' is not allowed for tool 'test_tool'. Expected one of \['approve', 'edit', 'reject'\] based on the tool's configuration.",
- ):
- middleware.after_model(state, None)
+ match=re.escape(
+ "Unexpected human decision: {'type': 'unknown'}. "
+ "Decision type 'unknown' is not allowed for tool 'test_tool'. "
+ "Expected one of ['approve', 'edit', 'reject'] based on the tool's "
+ "configuration."
+ ),
+ ),
+ ):
+ middleware.after_model(state, None)
def test_human_in_the_loop_middleware_disallowed_action() -> None:
"""Test HumanInTheLoopMiddleware with action not allowed by tool config."""
-
# edit is not allowed by tool config
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "reject"]}}
@@ -346,20 +346,27 @@ def test_human_in_the_loop_middleware_disallowed_action() -> None:
]
}
- with patch(
- "langchain.agents.middleware.human_in_the_loop.interrupt",
- side_effect=mock_disallowed_action,
- ):
- with pytest.raises(
+ with (
+ patch(
+ "langchain.agents.middleware.human_in_the_loop.interrupt",
+ side_effect=mock_disallowed_action,
+ ),
+ pytest.raises(
ValueError,
- match=r"Unexpected human decision: {'type': 'edit', 'edited_action': {'name': 'test_tool', 'args': {'input': 'modified'}}}. Decision type 'edit' is not allowed for tool 'test_tool'. Expected one of \['approve', 'reject'\] based on the tool's configuration.",
- ):
- middleware.after_model(state, None)
+ match=re.escape(
+ "Unexpected human decision: {'type': 'edit', 'edited_action': "
+ "{'name': 'test_tool', 'args': {'input': 'modified'}}}. "
+ "Decision type 'edit' is not allowed for tool 'test_tool'. "
+ "Expected one of ['approve', 'reject'] based on the tool's "
+ "configuration."
+ ),
+ ),
+ ):
+ middleware.after_model(state, None)
def test_human_in_the_loop_middleware_mixed_auto_approved_and_interrupt() -> None:
"""Test HumanInTheLoopMiddleware with mix of auto-approved and interrupt tools."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"interrupt_tool": {"allowed_decisions": ["approve", "edit", "reject"]}}
)
@@ -391,7 +398,6 @@ def test_human_in_the_loop_middleware_mixed_auto_approved_and_interrupt() -> Non
def test_human_in_the_loop_middleware_interrupt_request_structure() -> None:
"""Test that interrupt requests are structured correctly."""
-
middleware = HumanInTheLoopMiddleware(
interrupt_on={"test_tool": {"allowed_decisions": ["approve", "edit", "reject"]}},
description_prefix="Custom prefix",
@@ -493,31 +499,39 @@ def test_human_in_the_loop_middleware_sequence_mismatch() -> None:
state = {"messages": [HumanMessage(content="Hello"), ai_message]}
# Test with too few responses
- with patch(
- "langchain.agents.middleware.human_in_the_loop.interrupt",
- return_value={"decisions": []}, # No responses for 1 tool call
- ):
- with pytest.raises(
+ with (
+ patch(
+ "langchain.agents.middleware.human_in_the_loop.interrupt",
+ return_value={"decisions": []}, # No responses for 1 tool call
+ ),
+ pytest.raises(
ValueError,
- match=r"Number of human decisions \(0\) does not match number of hanging tool calls \(1\)\.",
- ):
- middleware.after_model(state, None)
+ match=re.escape(
+ "Number of human decisions (0) does not match number of hanging tool calls (1)."
+ ),
+ ),
+ ):
+ middleware.after_model(state, None)
# Test with too many responses
- with patch(
- "langchain.agents.middleware.human_in_the_loop.interrupt",
- return_value={
- "decisions": [
- {"type": "approve"},
- {"type": "approve"},
- ]
- }, # 2 responses for 1 tool call
- ):
- with pytest.raises(
+ with (
+ patch(
+ "langchain.agents.middleware.human_in_the_loop.interrupt",
+ return_value={
+ "decisions": [
+ {"type": "approve"},
+ {"type": "approve"},
+ ]
+ }, # 2 responses for 1 tool call
+ ),
+ pytest.raises(
ValueError,
- match=r"Number of human decisions \(2\) does not match number of hanging tool calls \(1\)\.",
- ):
- middleware.after_model(state, None)
+ match=re.escape(
+ "Number of human decisions (2) does not match number of hanging tool calls (1)."
+ ),
+ ),
+ ):
+ middleware.after_model(state, None)
def test_human_in_the_loop_middleware_description_as_callable() -> None:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_call_limit.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_call_limit.py
index 0ad2f6e8fd..5c264ed094 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_call_limit.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_call_limit.py
@@ -5,17 +5,16 @@ from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents.factory import create_agent
from langchain.agents.middleware.model_call_limit import (
- ModelCallLimitMiddleware,
ModelCallLimitExceededError,
+ ModelCallLimitMiddleware,
)
-
-from ...model import FakeToolCallingModel
+from tests.unit_tests.agents.model import FakeToolCallingModel
@tool
-def simple_tool(input: str) -> str:
- """A simple tool"""
- return input
+def simple_tool(value: str) -> str:
+ """A simple tool."""
+ return value
def test_middleware_unit_functionality():
@@ -202,8 +201,11 @@ def test_exception_error_message():
def test_run_limit_resets_between_invocations() -> None:
- """Test that run_model_call_count resets between invocations, but thread_model_call_count accumulates."""
+ """Test run limit resets between invocations.
+ Test that run_model_call_count resets between invocations, but
+ thread_model_call_count accumulates.
+ """
# First: No tool calls per invocation, so model does not increment call counts internally
middleware = ModelCallLimitMiddleware(thread_limit=3, run_limit=1, exit_behavior="error")
model = FakeToolCallingModel(
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_fallback.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_fallback.py
index b1e5d5a470..ce7b0e23d6 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_fallback.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_fallback.py
@@ -10,17 +10,16 @@ from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.outputs import ChatGeneration, ChatResult
+from langgraph.runtime import Runtime
from langchain.agents.factory import create_agent
from langchain.agents.middleware.model_fallback import ModelFallbackMiddleware
-from langchain.agents.middleware.types import ModelRequest, ModelResponse
-from langgraph.runtime import Runtime
-
-from ...model import FakeToolCallingModel
+from langchain.agents.middleware.types import AgentState, ModelRequest, ModelResponse
+from tests.unit_tests.agents.model import FakeToolCallingModel
def _fake_runtime() -> Runtime:
- return cast(Runtime, object())
+ return cast("Runtime", object())
def _make_request() -> ModelRequest:
@@ -33,7 +32,7 @@ def _make_request() -> ModelRequest:
tool_choice=None,
tools=[],
response_format=None,
- state=cast("AgentState", {}), # type: ignore[name-defined]
+ state=cast("AgentState", {}),
runtime=_fake_runtime(),
model_settings={},
)
@@ -64,7 +63,8 @@ def test_fallback_on_primary_failure() -> None:
class FailingPrimaryModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Primary model failed")
+ msg = "Primary model failed"
+ raise ValueError(msg)
primary_model = FailingPrimaryModel(messages=iter([AIMessage(content="should not see")]))
fallback_model = GenericFakeChatModel(messages=iter([AIMessage(content="fallback response")]))
@@ -88,7 +88,8 @@ def test_multiple_fallbacks() -> None:
class FailingModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Model failed")
+ msg = "Model failed"
+ raise ValueError(msg)
primary_model = FailingModel(messages=iter([AIMessage(content="should not see")]))
fallback1 = FailingModel(messages=iter([AIMessage(content="fallback1")]))
@@ -113,7 +114,8 @@ def test_all_models_fail() -> None:
class AlwaysFailingModel(GenericFakeChatModel):
def _generate(self, messages, **kwargs):
- raise ValueError("Model failed")
+ msg = "Model failed"
+ raise ValueError(msg)
primary_model = AlwaysFailingModel(messages=iter([]))
fallback_model = AlwaysFailingModel(messages=iter([]))
@@ -155,7 +157,8 @@ async def test_fallback_on_primary_failure_async() -> None:
class AsyncFailingPrimaryModel(GenericFakeChatModel):
async def _agenerate(self, messages, **kwargs):
- raise ValueError("Primary model failed")
+ msg = "Primary model failed"
+ raise ValueError(msg)
primary_model = AsyncFailingPrimaryModel(messages=iter([AIMessage(content="should not see")]))
fallback_model = GenericFakeChatModel(messages=iter([AIMessage(content="fallback response")]))
@@ -179,7 +182,8 @@ async def test_multiple_fallbacks_async() -> None:
class AsyncFailingModel(GenericFakeChatModel):
async def _agenerate(self, messages, **kwargs):
- raise ValueError("Model failed")
+ msg = "Model failed"
+ raise ValueError(msg)
primary_model = AsyncFailingModel(messages=iter([AIMessage(content="should not see")]))
fallback1 = AsyncFailingModel(messages=iter([AIMessage(content="fallback1")]))
@@ -204,7 +208,8 @@ async def test_all_models_fail_async() -> None:
class AsyncAlwaysFailingModel(GenericFakeChatModel):
async def _agenerate(self, messages, **kwargs):
- raise ValueError("Model failed")
+ msg = "Model failed"
+ raise ValueError(msg)
primary_model = AsyncAlwaysFailingModel(messages=iter([]))
fallback_model = AsyncAlwaysFailingModel(messages=iter([]))
@@ -228,7 +233,8 @@ def test_model_fallback_middleware_with_agent() -> None:
"""Model that always fails."""
def _generate(self, messages, **kwargs):
- raise ValueError("Primary model failed")
+ msg = "Primary model failed"
+ raise ValueError(msg)
@property
def _llm_type(self):
@@ -272,7 +278,8 @@ def test_model_fallback_middleware_exhausted_with_agent() -> None:
self.name = name
def _generate(self, messages, **kwargs):
- raise ValueError(f"{self.name} failed")
+ msg = f"{self.name} failed"
+ raise ValueError(msg)
@property
def _llm_type(self):
@@ -294,7 +301,6 @@ def test_model_fallback_middleware_exhausted_with_agent() -> None:
def test_model_fallback_middleware_initialization() -> None:
"""Test ModelFallbackMiddleware initialization."""
-
# Test with no models - now a TypeError (missing required argument)
with pytest.raises(TypeError):
ModelFallbackMiddleware() # type: ignore[call-arg]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_retry.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_retry.py
index 0ce3261362..1b6257c3ce 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_retry.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_retry.py
@@ -1,6 +1,5 @@
"""Tests for ModelRetryMiddleware functionality."""
-import asyncio
import time
from typing import Any
@@ -319,7 +318,7 @@ def test_model_retry_custom_exception_filter() -> None:
class CustomError(Exception):
"""Custom exception with retry_me attribute."""
- def __init__(self, message: str, retry_me: bool):
+ def __init__(self, message: str, *, retry_me: bool):
"""Initialize custom error.
Args:
@@ -354,8 +353,10 @@ def test_model_retry_custom_exception_filter() -> None:
"""
attempt_count["value"] += 1
if attempt_count["value"] == 1:
- raise CustomError("Retryable error", retry_me=True)
- raise CustomError("Non-retryable error", retry_me=False)
+ msg = "Retryable error"
+ raise CustomError(msg, retry_me=True)
+ msg = "Non-retryable error"
+ raise CustomError(msg, retry_me=False)
def should_retry(exc: Exception) -> bool:
return isinstance(exc, CustomError) and exc.retry_me
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
index 3fbd04b118..7ade5cec53 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
@@ -3,6 +3,7 @@
import pytest
from langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
+from langchain.agents.factory import create_agent
from langchain.agents.middleware.pii import (
PIIDetectionError,
PIIMiddleware,
@@ -12,11 +13,8 @@ from langchain.agents.middleware.pii import (
detect_mac_address,
detect_url,
)
-from langchain.agents.factory import create_agent
-
from tests.unit_tests.agents.model import FakeToolCallingModel
-
# ============================================================================
# Detection Function Tests
# ============================================================================
@@ -69,7 +67,6 @@ class TestCreditCardDetection:
def test_detect_credit_card_with_spaces(self):
# Valid Mastercard test number
- content = "Card: 5425233430109903"
# Add spaces
spaced_content = "Card: 5425 2334 3010 9903"
matches = detect_credit_card(spaced_content)
@@ -216,7 +213,7 @@ class TestURLDetection:
def test_bare_domain_without_path_not_detected(self):
# To reduce false positives, bare domains without paths are not detected
content = "The word example.com in prose"
- matches = detect_url(content)
+ detect_url(content)
# May or may not detect depending on implementation
# This is acceptable
@@ -354,7 +351,7 @@ class TestPIIMiddlewareIntegration:
"""Test that middleware only processes input when configured."""
middleware = PIIMiddleware(
"email", strategy="redact", apply_to_input=True, apply_to_output=False
- ) # noqa: E501
+ )
# Should process HumanMessage
state = {"messages": [HumanMessage("Email: [email protected]")]}
@@ -371,7 +368,7 @@ class TestPIIMiddlewareIntegration:
"""Test that middleware only processes output when configured."""
middleware = PIIMiddleware(
"email", strategy="redact", apply_to_input=False, apply_to_output=True
- ) # noqa: E501
+ )
# Should not process HumanMessage
state = {"messages": [HumanMessage("Email: [email protected]")]}
@@ -388,7 +385,7 @@ class TestPIIMiddlewareIntegration:
"""Test that middleware processes both input and output."""
middleware = PIIMiddleware(
"email", strategy="redact", apply_to_input=True, apply_to_output=True
- ) # noqa: E501
+ )
# Should process HumanMessage
state = {"messages": [HumanMessage("Email: [email protected]")]}
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_execution_policies.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_execution_policies.py
index 237e69f5fe..4425d99db3 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_execution_policies.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_execution_policies.py
@@ -7,14 +7,13 @@ from typing import Any
import pytest
+from langchain.agents.middleware import _execution
from langchain.agents.middleware.shell_tool import (
- HostExecutionPolicy,
CodexSandboxExecutionPolicy,
DockerExecutionPolicy,
+ HostExecutionPolicy,
)
-from langchain.agents.middleware import _execution
-
def _make_resource(
*,
@@ -78,7 +77,7 @@ def test_host_policy_applies_prlimit(monkeypatch: pytest.MonkeyPatch, tmp_path:
class DummyProcess:
pid = 1234
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
recorded["command"] = list(command)
recorded["env"] = dict(env)
recorded["cwd"] = cwd
@@ -112,7 +111,7 @@ def test_host_policy_uses_preexec_on_macos(monkeypatch: pytest.MonkeyPatch, tmp_
class DummyProcess:
pid = 4321
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
captured["preexec_fn"] = preexec_fn
captured["start_new_session"] = start_new_session
return DummyProcess()
@@ -147,7 +146,7 @@ def test_host_policy_respects_process_group_flag(
class DummyProcess:
pid = 1111
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
recorded["start_new_session"] = start_new_session
return DummyProcess()
@@ -170,7 +169,7 @@ def test_host_policy_falls_back_to_rlimit_data(
class DummyProcess:
pid = 2222
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
return DummyProcess()
monkeypatch.setattr(_execution, "_launch_subprocess", fake_launch)
@@ -195,7 +194,7 @@ def test_codex_policy_spawns_codex_cli(monkeypatch, tmp_path: Path) -> None:
class DummyProcess:
pass
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
recorded["command"] = list(command)
assert cwd == tmp_path
assert env["TEST_VAR"] == "1"
@@ -286,7 +285,7 @@ def test_docker_policy_spawns_docker_run(monkeypatch, tmp_path: Path) -> None:
class DummyProcess:
pass
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
recorded["command"] = list(command)
assert cwd == tmp_path
assert "PATH" in env # host environment should retain system PATH
@@ -339,7 +338,7 @@ def test_docker_policy_skips_mount_for_temp_workspace(
class DummyProcess:
pass
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
recorded["command"] = list(command)
assert cwd == workspace
return DummyProcess()
@@ -380,7 +379,7 @@ def test_docker_policy_read_only_and_user(monkeypatch: pytest.MonkeyPatch, tmp_p
class DummyProcess:
pass
- def fake_launch(command, *, env, cwd, preexec_fn, start_new_session): # noqa: ANN001
+ def fake_launch(command, *, env, cwd, preexec_fn, start_new_session):
recorded["command"] = list(command)
return DummyProcess()
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_tool.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_tool.py
index 187e614abd..5125b471de 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_tool.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_shell_tool.py
@@ -7,7 +7,7 @@ import time
from pathlib import Path
import pytest
-from langchain_core.messages import AIMessage, ToolMessage
+from langchain_core.messages import ToolMessage
from langchain_core.tools.base import ToolException
from langchain.agents.middleware.shell_tool import (
@@ -161,14 +161,14 @@ def test_session_resources_finalizer_cleans_up(tmp_path: Path) -> None:
def __init__(self) -> None:
self.stopped: bool = False
- def stop(self, timeout: float) -> None: # noqa: ARG002
+ def stop(self, timeout: float) -> None:
self.stopped = True
session = DummySession()
tempdir = tempfile.TemporaryDirectory(dir=tmp_path)
tempdir_path = Path(tempdir.name)
resources = _SessionResources(session=session, tempdir=tempdir, policy=policy) # type: ignore[arg-type]
- finalizer = resources._finalizer
+ finalizer = resources.finalizer
# Drop our last strong reference and force collection.
del resources
@@ -339,7 +339,7 @@ def test_startup_command_failure(tmp_path: Path) -> None:
workspace_root=tmp_path / "workspace", startup_commands=("exit 1",), execution_policy=policy
)
state: AgentState = _empty_state()
- with pytest.raises(RuntimeError, match="Startup command.*failed"):
+ with pytest.raises(RuntimeError, match=r"Startup command.*failed"):
middleware.before_agent(state, None)
@@ -533,7 +533,7 @@ def test_get_or_create_resources_creates_when_missing(tmp_path: Path) -> None:
assert state.get("shell_session_resources") is resources
# Clean up
- resources._finalizer()
+ resources.finalizer()
def test_get_or_create_resources_reuses_existing(tmp_path: Path) -> None:
@@ -553,4 +553,4 @@ def test_get_or_create_resources_reuses_existing(tmp_path: Path) -> None:
assert resources1.session is resources2.session
# Clean up
- resources1._finalizer()
+ resources1.finalizer()
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
index f811c1b4d0..5e8c007d14 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
@@ -1,4 +1,3 @@
-from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
@@ -9,8 +8,7 @@ from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langchain.agents.middleware.summarization import SummarizationMiddleware
-
-from ...model import FakeToolCallingModel
+from tests.unit_tests.agents.model import FakeToolCallingModel
class MockChatModel(BaseChatModel):
@@ -138,7 +136,8 @@ def test_summarization_middleware_summary_creation() -> None:
# Test error handling
class ErrorModel(BaseChatModel):
def invoke(self, prompt):
- raise Exception("Model error")
+ msg = "Model error"
+ raise ValueError(msg)
def _generate(self, messages, **kwargs):
return ChatResult(generations=[ChatGeneration(message=AIMessage(content="Summary"))])
@@ -173,7 +172,9 @@ def test_summarization_middleware_trim_limit_none_keeps_all_messages() -> None:
def test_summarization_middleware_profile_inference_triggers_summary() -> None:
"""Ensure automatic profile inference triggers summarization when limits are exceeded."""
- token_counter = lambda messages: len(messages) * 200
+
+ def token_counter(messages):
+ return len(messages) * 200
middleware = SummarizationMiddleware(
model=ProfileChatModel(),
@@ -192,14 +193,14 @@ def test_summarization_middleware_profile_inference_triggers_summary() -> None:
}
# Test we don't engage summarization
- # total_tokens = 4 * 200 = 800
- # max_input_tokens = 1000
- # 0.81 * 1000 == 810 > 800 -> summarization not triggered
+ # we have total_tokens = 4 * 200 = 800
+ # and max_input_tokens = 1000
+ # since 0.81 * 1000 == 810 > 800 -> summarization not triggered
result = middleware.before_model(state, None)
assert result is None
# Engage summarization
- # 0.80 * 1000 == 800 <= 800
+ # since 0.80 * 1000 == 800 <= 800
middleware = SummarizationMiddleware(
model=ProfileChatModel(),
trigger=("fraction", 0.80),
@@ -331,7 +332,8 @@ def test_summarization_middleware_missing_profile() -> None:
@property
def profile(self):
- raise ImportError("Profile not available")
+ msg = "Profile not available"
+ raise ImportError(msg)
with pytest.raises(
ValueError,
@@ -470,7 +472,7 @@ def test_summarization_middleware_keep_messages() -> None:
assert [message.content for message in result["messages"][2:]] == ["4", "5"]
# Above threshold - should also trigger summarization
- messages_above = messages_at_threshold + [HumanMessage(content="6")]
+ messages_above = [*messages_at_threshold, HumanMessage(content="6")]
state_above = {"messages": messages_above}
result = middleware.before_model(state_above, None)
assert result is not None
@@ -616,7 +618,8 @@ def test_summarization_middleware_trim_messages_error_fallback() -> None:
# Create a mock token counter that raises an exception
def failing_token_counter(messages):
- raise Exception("Token counting failed")
+ msg = "Token counting failed"
+ raise ValueError(msg)
middleware.token_counter = failing_token_counter
@@ -700,7 +703,6 @@ def test_summarization_middleware_zero_and_negative_target_tokens() -> None:
# Should set threshold to 1 when calculated value is <= 0
messages = [HumanMessage(content="test")]
- state = {"messages": messages}
# The trigger fraction calculation: int(1000 * 0.0001) = 0, but should be set to 1
# Token count of 1 message should exceed threshold of 1
@@ -719,7 +721,8 @@ async def test_summarization_middleware_async_error_handling() -> None:
return ChatResult(generations=[ChatGeneration(message=AIMessage(content="Summary"))])
async def _agenerate(self, messages, **kwargs):
- raise Exception("Async model error")
+ msg = "Async model error"
+ raise ValueError(msg)
@property
def _llm_type(self):
@@ -836,7 +839,7 @@ def test_summarization_middleware_find_safe_cutoff_advances_past_tools() -> None
model=MockChatModel(), trigger=("messages", 10), keep=("messages", 3)
)
- # Messages: [Human, AI, Tool, Tool, Tool, Human]
+ # Messages list: [Human, AI, Tool, Tool, Tool, Human]
messages: list[AnyMessage] = [
HumanMessage(content="msg1"),
AIMessage(
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py
index 5b11a30aa7..aa0d71e706 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py
@@ -11,19 +11,18 @@ from langgraph.runtime import Runtime
from langchain.agents.factory import create_agent
from langchain.agents.middleware.todo import (
- PlanningState,
- TodoListMiddleware,
WRITE_TODOS_SYSTEM_PROMPT,
WRITE_TODOS_TOOL_DESCRIPTION,
+ PlanningState,
+ TodoListMiddleware,
write_todos,
)
-from langchain.agents.middleware.types import ModelRequest, ModelResponse
-
-from ...model import FakeToolCallingModel
+from langchain.agents.middleware.types import AgentState, ModelRequest, ModelResponse
+from tests.unit_tests.agents.model import FakeToolCallingModel
def _fake_runtime() -> Runtime:
- return cast(Runtime, object())
+ return cast("Runtime", object())
def _make_request(system_prompt: str | None = None) -> ModelRequest:
@@ -36,7 +35,7 @@ def _make_request(system_prompt: str | None = None) -> ModelRequest:
tool_choice=None,
tools=[],
response_format=None,
- state=cast("AgentState", {}), # type: ignore[name-defined]
+ state=AgentState(messages=[]),
runtime=_fake_runtime(),
model_settings={},
)
@@ -147,7 +146,7 @@ def test_todo_middleware_on_model_call(original_prompt, expected_prompt_prefix)
tools=[],
response_format=None,
state=state,
- runtime=cast(Runtime, object()),
+ runtime=cast("Runtime", object()),
model_settings={},
)
@@ -206,7 +205,7 @@ def test_todo_middleware_custom_system_prompt() -> None:
response_format=None,
model_settings={},
state=state,
- runtime=cast(Runtime, object()),
+ runtime=cast("Runtime", object()),
)
captured_request = None
@@ -266,7 +265,7 @@ def test_todo_middleware_custom_system_prompt_and_tool_description() -> None:
tools=[],
response_format=None,
state=state,
- runtime=cast(Runtime, object()),
+ runtime=cast("Runtime", object()),
model_settings={},
)
@@ -304,7 +303,9 @@ def test_todo_middleware_custom_system_prompt_and_tool_description() -> None:
{"content": "Task 1", "status": "pending"},
{"content": "Task 2", "status": "in_progress"},
],
- "Updated todo list to [{'content': 'Task 1', 'status': 'pending'}, {'content': 'Task 2', 'status': 'in_progress'}]",
+ "Updated todo list to ["
+ "{'content': 'Task 1', 'status': 'pending'}, "
+ "{'content': 'Task 2', 'status': 'in_progress'}]",
),
(
[
@@ -312,7 +313,10 @@ def test_todo_middleware_custom_system_prompt_and_tool_description() -> None:
{"content": "Task 2", "status": "in_progress"},
{"content": "Task 3", "status": "completed"},
],
- "Updated todo list to [{'content': 'Task 1', 'status': 'pending'}, {'content': 'Task 2', 'status': 'in_progress'}, {'content': 'Task 3', 'status': 'completed'}]",
+ "Updated todo list to ["
+ "{'content': 'Task 1', 'status': 'pending'}, "
+ "{'content': 'Task 2', 'status': 'in_progress'}, "
+ "{'content': 'Task 3', 'status': 'completed'}]",
),
],
)
@@ -344,7 +348,7 @@ def test_todo_middleware_write_todos_tool_validation_errors(invalid_todos) -> No
"type": "tool_call",
"id": "test_call",
}
- with pytest.raises(Exception):
+ with pytest.raises(ValueError, match="1 validation error for write_todos"):
write_todos.invoke(tool_call)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_call_limit.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_call_limit.py
index 961b0e6225..ec82265a61 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_call_limit.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_call_limit.py
@@ -44,7 +44,7 @@ def test_middleware_initialization_validation():
# Test run_limit exceeding thread_limit
with pytest.raises(
ValueError,
- match="run_limit .* cannot exceed thread_limit",
+ match=r"run_limit .* cannot exceed thread_limit",
):
ToolCallLimitMiddleware(thread_limit=3, run_limit=5)
@@ -157,7 +157,10 @@ def test_middleware_unit_functionality():
def test_middleware_end_behavior_with_unrelated_parallel_tool_calls():
- """Test that 'end' behavior raises NotImplementedError when there are parallel calls to unrelated tools.
+ """Test middleware 'end' behavior with unrelated parallel tool calls.
+
+ Test that 'end' behavior raises NotImplementedError when there are parallel calls
+ to unrelated tools.
When limiting a specific tool with "end" behavior and the model proposes parallel calls
to BOTH the limited tool AND other tools, we can't handle this scenario (we'd be stopping
@@ -221,7 +224,11 @@ def test_middleware_with_specific_tool():
def test_middleware_error_behavior():
- """Test that middleware raises ToolCallLimitExceededError when configured with exit_behavior='error'."""
+ """Test middleware error behavior.
+
+ Test that middleware raises ToolCallLimitExceededError when configured with
+ exit_behavior='error'.
+ """
middleware = ToolCallLimitMiddleware(thread_limit=2, exit_behavior="error")
runtime = None
@@ -716,7 +723,8 @@ def test_parallel_tool_calls_with_limit_end_mode():
assert "Tool call limit exceeded" in error_msg.content
assert "Do not" in error_msg.content
- # Verify AI message explaining why execution stopped (displayed to user - includes thread/run details)
+ # Verify AI message explaining why execution stopped
+ # (displayed to user - includes thread/run details)
ai_limit_messages = [
msg
for msg in messages
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py
index f522ca1648..9aef96f0e0 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py
@@ -3,38 +3,40 @@
import typing
from collections.abc import Callable
from itertools import cycle
-from typing import Any, Literal, Union
+from typing import Any, Literal
-from pydantic import BaseModel
-
-from langchain.agents import create_agent
-from langchain.agents.middleware import LLMToolEmulator
-from langchain.messages import AIMessage
from langchain_core.language_models import LanguageModelInput
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_core.runnables import Runnable
from langchain_core.tools import BaseTool, tool
+from pydantic import BaseModel
+
+from langchain.agents import create_agent
+from langchain.agents.middleware import LLMToolEmulator
+from langchain.messages import AIMessage
@tool
def get_weather(location: str) -> str:
"""Get current weather for a location."""
- raise NotImplementedError("This tool should be emulated")
+ msg = "This tool should be emulated"
+ raise NotImplementedError(msg)
@tool
def search_web(query: str) -> str:
"""Search the web for information."""
- raise NotImplementedError("This tool should be emulated")
+ msg = "This tool should be emulated"
+ raise NotImplementedError(msg)
@tool
def calculator(expression: str) -> str:
"""Perform mathematical calculations."""
# This tool executes normally (not emulated)
- return f"Result: {eval(expression)}"
+ return f"Result: {eval(expression)}" # noqa: S307
class FakeModel(GenericFakeChatModel):
@@ -44,7 +46,7 @@ class FakeModel(GenericFakeChatModel):
def bind_tools(
self,
- tools: typing.Sequence[Union[dict[str, Any], type[BaseModel], Callable, BaseTool]],
+ tools: typing.Sequence[dict[str, Any] | type[BaseModel] | Callable | BaseTool],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
if len(tools) == 0:
@@ -52,11 +54,11 @@ class FakeModel(GenericFakeChatModel):
raise ValueError(msg)
tool_dicts = []
- for tool in tools:
- if isinstance(tool, dict):
- tool_dicts.append(tool)
+ for tool_ in tools:
+ if isinstance(tool_, dict):
+ tool_dicts.append(tool_)
continue
- if not isinstance(tool, BaseTool):
+ if not isinstance(tool_, BaseTool):
msg = "Only BaseTool and dict is supported by FakeModel.bind_tools"
raise TypeError(msg)
@@ -66,14 +68,14 @@ class FakeModel(GenericFakeChatModel):
{
"type": "function",
"function": {
- "name": tool.name,
+ "name": tool_.name,
},
}
)
elif self.tool_style == "anthropic":
tool_dicts.append(
{
- "name": tool.name,
+ "name": tool_.name,
}
)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_retry.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_retry.py
index 2f81e3af17..a31cfe811d 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_retry.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_retry.py
@@ -1,6 +1,5 @@
"""Tests for ToolRetryMiddleware functionality."""
-import asyncio
import time
from collections.abc import Callable
@@ -8,6 +7,8 @@ import pytest
from langchain_core.messages import HumanMessage, ToolCall, ToolMessage
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
+from langgraph.prebuilt.tool_node import ToolCallRequest
+from langgraph.types import Command
from langchain.agents.factory import create_agent
from langchain.agents.middleware._retry import calculate_delay
@@ -16,15 +17,15 @@ from tests.unit_tests.agents.model import FakeToolCallingModel
@tool
-def working_tool(input: str) -> str:
+def working_tool(value: str) -> str:
"""Tool that always succeeds."""
- return f"Success: {input}"
+ return f"Success: {value}"
@tool
-def failing_tool(input: str) -> str:
+def failing_tool(value: str) -> str:
"""Tool that always fails."""
- msg = f"Failed: {input}"
+ msg = f"Failed: {value}"
raise ValueError(msg)
@@ -40,11 +41,11 @@ class TemporaryFailureTool:
self.fail_count = fail_count
self.attempt = 0
- def __call__(self, input: str) -> str:
+ def __call__(self, value: str) -> str:
"""Execute the tool.
Args:
- input: Input string.
+ value: Input string.
Returns:
Success message if attempt >= fail_count.
@@ -56,7 +57,7 @@ class TemporaryFailureTool:
if self.attempt <= self.fail_count:
msg = f"Temporary failure {self.attempt}"
raise ValueError(msg)
- return f"Success after {self.attempt} attempts: {input}"
+ return f"Success after {self.attempt} attempts: {value}"
def test_tool_retry_initialization_defaults() -> None:
@@ -151,7 +152,7 @@ def test_tool_retry_working_tool_no_retry_needed() -> None:
"""Test ToolRetryMiddlewarewith a working tool (no retry needed)."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="working_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="working_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -180,7 +181,7 @@ def test_tool_retry_failing_tool_returns_message() -> None:
"""Test ToolRetryMiddlewarewith failing tool returns error message."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -217,7 +218,7 @@ def test_tool_retry_failing_tool_raises() -> None:
"""Test ToolRetryMiddlewarewith on_failure='error' re-raises exception."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -252,7 +253,7 @@ def test_tool_retry_custom_failure_formatter() -> None:
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -286,13 +287,13 @@ def test_tool_retry_succeeds_after_retries() -> None:
temp_fail = TemporaryFailureTool(fail_count=2)
@tool
- def temp_failing_tool(input: str) -> str:
+ def temp_failing_tool(value: str) -> str:
"""Tool that fails temporarily."""
- return temp_fail(input)
+ return temp_fail(value)
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="temp_failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -327,8 +328,8 @@ def test_tool_retry_specific_tools_only() -> None:
model = FakeToolCallingModel(
tool_calls=[
[
- ToolCall(name="failing_tool", args={"input": "test1"}, id="1"),
- ToolCall(name="working_tool", args={"input": "test2"}, id="2"),
+ ToolCall(name="failing_tool", args={"value": "test1"}, id="1"),
+ ToolCall(name="working_tool", args={"value": "test2"}, id="2"),
],
[],
]
@@ -374,8 +375,8 @@ def test_tool_retry_specific_tools_with_base_tool() -> None:
model = FakeToolCallingModel(
tool_calls=[
[
- ToolCall(name="failing_tool", args={"input": "test1"}, id="1"),
- ToolCall(name="working_tool", args={"input": "test2"}, id="2"),
+ ToolCall(name="failing_tool", args={"value": "test1"}, id="1"),
+ ToolCall(name="working_tool", args={"value": "test2"}, id="2"),
],
[],
]
@@ -420,22 +421,22 @@ def test_tool_retry_specific_exceptions() -> None:
"""Test ToolRetryMiddlewareonly retries specific exception types."""
@tool
- def value_error_tool(input: str) -> str:
+ def value_error_tool(value: str) -> str:
"""Tool that raises ValueError."""
- msg = f"ValueError: {input}"
+ msg = f"ValueError: {value}"
raise ValueError(msg)
@tool
- def runtime_error_tool(input: str) -> str:
+ def runtime_error_tool(value: str) -> str:
"""Tool that raises RuntimeError."""
- msg = f"RuntimeError: {input}"
+ msg = f"RuntimeError: {value}"
raise RuntimeError(msg)
model = FakeToolCallingModel(
tool_calls=[
[
- ToolCall(name="value_error_tool", args={"input": "test1"}, id="1"),
- ToolCall(name="runtime_error_tool", args={"input": "test2"}, id="2"),
+ ToolCall(name="value_error_tool", args={"value": "test1"}, id="1"),
+ ToolCall(name="runtime_error_tool", args={"value": "test2"}, id="2"),
],
[],
]
@@ -480,7 +481,7 @@ def test_tool_retry_custom_exception_filter() -> None:
class CustomError(Exception):
"""Custom exception with retry_me attribute."""
- def __init__(self, message: str, retry_me: bool):
+ def __init__(self, message: str, *, retry_me: bool):
"""Initialize custom error.
Args:
@@ -493,19 +494,21 @@ def test_tool_retry_custom_exception_filter() -> None:
attempt_count = {"value": 0}
@tool
- def custom_error_tool(input: str) -> str:
+ def custom_error_tool(val: str) -> str:
"""Tool that raises CustomError."""
attempt_count["value"] += 1
if attempt_count["value"] == 1:
- raise CustomError("Retryable error", retry_me=True)
- raise CustomError("Non-retryable error", retry_me=False)
+ msg = "Retryable error"
+ raise CustomError(msg, retry_me=True)
+ msg = "Non-retryable error"
+ raise CustomError(msg, retry_me=False)
def should_retry(exc: Exception) -> bool:
return isinstance(exc, CustomError) and exc.retry_me
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="custom_error_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="custom_error_tool", args={"val": "test"}, id="1")],
[],
]
)
@@ -543,13 +546,13 @@ def test_tool_retry_backoff_timing() -> None:
temp_fail = TemporaryFailureTool(fail_count=3)
@tool
- def temp_failing_tool(input: str) -> str:
+ def temp_failing_tool(value: str) -> str:
"""Tool that fails temporarily."""
- return temp_fail(input)
+ return temp_fail(value)
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="temp_failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -588,13 +591,13 @@ def test_tool_retry_constant_backoff() -> None:
temp_fail = TemporaryFailureTool(fail_count=2)
@tool
- def temp_failing_tool(input: str) -> str:
+ def temp_failing_tool(value: str) -> str:
"""Tool that fails temporarily."""
- return temp_fail(input)
+ return temp_fail(value)
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="temp_failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -680,12 +683,11 @@ def test_tool_retry_jitter_variation() -> None:
assert len(set(delays)) > 1
async def test_tool_retry_async_working_tool() -> None:
"""Test ToolRetryMiddlewarewith async execution and working tool."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="working_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="working_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -709,12 +711,11 @@ async def test_tool_retry_async_working_tool() -> None:
assert "Success: test" in tool_messages[0].content
async def test_tool_retry_async_failing_tool() -> None:
"""Test ToolRetryMiddlewarewith async execution and failing tool."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -745,19 +746,18 @@ async def test_tool_retry_async_failing_tool() -> None:
assert tool_messages[0].status == "error"
async def test_tool_retry_async_succeeds_after_retries() -> None:
"""Test ToolRetryMiddlewareasync execution succeeds after temporary failures."""
temp_fail = TemporaryFailureTool(fail_count=2)
@tool
- def temp_failing_tool(input: str) -> str:
+ def temp_failing_tool(value: str) -> str:
"""Tool that fails temporarily."""
- return temp_fail(input)
+ return temp_fail(value)
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="temp_failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -785,19 +785,18 @@ async def test_tool_retry_async_succeeds_after_retries() -> None:
assert "Success after 3 attempts" in tool_messages[0].content
async def test_tool_retry_async_backoff_timing() -> None:
"""Test ToolRetryMiddlewareasync applies correct backoff delays."""
temp_fail = TemporaryFailureTool(fail_count=3)
@tool
- def temp_failing_tool(input: str) -> str:
+ def temp_failing_tool(value: str) -> str:
"""Tool that fails temporarily."""
- return temp_fail(input)
+ return temp_fail(value)
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="temp_failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -834,7 +833,7 @@ def test_tool_retry_zero_retries() -> None:
"""Test ToolRetryMiddlewarewith max_retries=0 (no retries)."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -871,9 +870,7 @@ def test_tool_retry_multiple_middleware_composition() -> None:
from langchain.agents.middleware.types import wrap_tool_call
@wrap_tool_call
- def logging_middleware(
- request: "ToolCallRequest", handler: Callable
- ) -> "ToolMessage | Command":
+ def logging_middleware(request: ToolCallRequest, handler: Callable) -> ToolMessage | Command:
call_log.append(f"before_{request.tool.name}")
response = handler(request)
call_log.append(f"after_{request.tool.name}")
@@ -881,7 +878,7 @@ def test_tool_retry_multiple_middleware_composition() -> None:
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="working_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="working_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -921,7 +918,11 @@ def test_tool_retry_deprecated_raise_keyword() -> None:
def test_tool_retry_deprecated_return_message_keyword() -> None:
- """Test ToolRetryMiddleware with deprecated 'return_message' keyword shows deprecation warning."""
+ """Test tool retry with deprecated 'return_message' keyword.
+
+ Test ToolRetryMiddleware with deprecated 'return_message' keyword shows deprecation
+ warning.
+ """
# Use string concatenation to avoid batch replace affecting test code
deprecated_value = "return" + "_message"
with pytest.warns(DeprecationWarning, match="on_failure='return_message' is deprecated"):
@@ -938,7 +939,7 @@ def test_tool_retry_deprecated_raise_behavior() -> None:
"""Test ToolRetryMiddleware with deprecated 'raise' forwards to 'error' behavior."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
@@ -970,7 +971,7 @@ def test_tool_retry_deprecated_return_message_behavior() -> None:
"""Test ToolRetryMiddleware with deprecated 'return_message' forwards to 'continue' behavior."""
model = FakeToolCallingModel(
tool_calls=[
- [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
+ [ToolCall(name="failing_tool", args={"value": "test"}, id="1")],
[],
]
)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py
index 1a8c642245..abc2484a9d 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py
@@ -2,21 +2,20 @@
import typing
from itertools import cycle
-from typing import Any, Literal, Union
+from typing import Any, Literal
import pytest
-from pydantic import BaseModel
-
-from langchain.agents import create_agent
-from langchain.agents.middleware import LLMToolSelectorMiddleware, ModelRequest, wrap_model_call
-from langchain.agents.middleware.tool_selection import _create_tool_selection_response
-from langchain.agents.middleware.types import AgentState
-from langchain.messages import AIMessage
from langchain_core.language_models import LanguageModelInput
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_core.runnables import Runnable
from langchain_core.tools import BaseTool, tool
+from pydantic import BaseModel
+
+from langchain.agents import create_agent
+from langchain.agents.middleware import LLMToolSelectorMiddleware, wrap_model_call
+from langchain.agents.middleware.tool_selection import _create_tool_selection_response
+from langchain.messages import AIMessage
@tool
@@ -54,7 +53,7 @@ class FakeModel(GenericFakeChatModel):
def bind_tools(
self,
- tools: typing.Sequence[Union[dict[str, Any], type[BaseModel], typing.Callable, BaseTool]],
+ tools: typing.Sequence[dict[str, Any] | type[BaseModel] | typing.Callable | BaseTool],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
if len(tools) == 0:
@@ -62,11 +61,11 @@ class FakeModel(GenericFakeChatModel):
raise ValueError(msg)
tool_dicts = []
- for tool in tools:
- if isinstance(tool, dict):
- tool_dicts.append(tool)
+ for tool_ in tools:
+ if isinstance(tool_, dict):
+ tool_dicts.append(tool_)
continue
- if not isinstance(tool, BaseTool):
+ if not isinstance(tool_, BaseTool):
msg = "Only BaseTool and dict is supported by FakeToolCallingModel.bind_tools"
raise TypeError(msg)
@@ -76,14 +75,14 @@ class FakeModel(GenericFakeChatModel):
{
"type": "function",
"function": {
- "name": tool.name,
+ "name": tool_.name,
},
}
)
elif self.tool_style == "anthropic":
tool_dicts.append(
{
- "name": tool.name,
+ "name": tool_.name,
}
)
@@ -97,16 +96,6 @@ class TestLLMToolSelectorBasic:
"""Test synchronous tool selection."""
# First call: selector picks tools
# Second call: agent uses selected tools
- tool_calls = [
- [
- {
- "name": "ToolSelectionResponse",
- "id": "1",
- "args": {"tools": ["get_weather", "calculate"]},
- }
- ],
- [{"name": "get_weather", "id": "2", "args": {"location": "Paris"}}],
- ]
model_requests = []
diff --git a/libs/langchain_v1/tests/unit_tests/agents/model.py b/libs/langchain_v1/tests/unit_tests/agents/model.py
index 247c64c80f..16e4ca52cf 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/model.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/model.py
@@ -6,7 +6,6 @@ from typing import (
Generic,
Literal,
TypeVar,
- Union,
)
from langchain_core.callbacks import CallbackManagerForLLMRun
@@ -25,7 +24,7 @@ StructuredResponseT = TypeVar("StructuredResponseT")
class FakeToolCallingModel(BaseChatModel, Generic[StructuredResponseT]):
- tool_calls: Union[list[list[ToolCall]], list[list[dict]]] | None = None
+ tool_calls: list[list[ToolCall]] | list[list[dict]] | None = None
structured_response: StructuredResponseT | None = None
index: int = 0
tool_style: Literal["openai", "anthropic"] = "openai"
@@ -37,7 +36,7 @@ class FakeToolCallingModel(BaseChatModel, Generic[StructuredResponseT]):
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
- """Top Level call"""
+ """Top Level call."""
is_native = kwargs.get("response_format")
if self.tool_calls:
@@ -74,7 +73,7 @@ class FakeToolCallingModel(BaseChatModel, Generic[StructuredResponseT]):
def bind_tools(
self,
- tools: Sequence[Union[dict[str, Any], type[BaseModel], Callable, BaseTool]],
+ tools: Sequence[dict[str, Any] | type[BaseModel] | Callable | BaseTool],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
if len(tools) == 0:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_create_agent_tool_validation.py b/libs/langchain_v1/tests/unit_tests/agents/test_create_agent_tool_validation.py
index 537dd9e954..d903b22c9b 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_create_agent_tool_validation.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_create_agent_tool_validation.py
@@ -1,21 +1,25 @@
import sys
-import pytest
from typing import Annotated
-from langchain.agents import AgentState, create_agent
-from langchain.tools import InjectedState, tool as dec_tool
-from .model import FakeToolCallingModel
+import pytest
from langchain_core.messages import HumanMessage
from langgraph.prebuilt import InjectedStore, ToolRuntime
from langgraph.store.base import BaseStore
from langgraph.store.memory import InMemoryStore
+from langchain.agents import AgentState, create_agent
+from langchain.tools import InjectedState
+from langchain.tools import tool as dec_tool
+
+from .model import FakeToolCallingModel
+
@pytest.mark.skipif(
sys.version_info >= (3, 14), reason="Pydantic model rebuild issue in Python 3.14"
)
def test_tool_invocation_error_excludes_injected_state() -> None:
"""Test that tool invocation errors only include LLM-controllable arguments.
+
When a tool has InjectedState parameters and the LLM makes an incorrect
invocation (e.g., missing required arguments), the error message should only
contain the arguments from the tool call that the LLM controls. This ensures
@@ -84,6 +88,7 @@ def test_tool_invocation_error_excludes_injected_state() -> None:
)
async def test_tool_invocation_error_excludes_injected_state_async() -> None:
"""Test that async tool invocation errors only include LLM-controllable arguments.
+
This test verifies that the async execution path (_execute_tool_async and _arun_one)
properly filters validation errors to exclude system-injected arguments, ensuring
the LLM receives only relevant context for correction.
@@ -169,7 +174,7 @@ async def test_tool_invocation_error_excludes_injected_state_async() -> None:
and len(line.split()) <= 2
]
# Verify system-injected 'state' is not in the field error list
- assert not any("state" == field.lower() for field in field_errors), (
+ assert not any(field.lower() == "state" for field in field_errors), (
"The field 'state' (system-injected) should not appear in validation errors"
)
@@ -179,6 +184,7 @@ async def test_tool_invocation_error_excludes_injected_state_async() -> None:
)
async def test_create_agent_error_content_with_multiple_params() -> None:
"""Test that error messages only include LLM-controlled parameter errors.
+
Uses create_agent to verify that when a tool with both LLM-controlled
and system-injected parameters receives invalid arguments, the error message:
1. Contains details about LLM-controlled parameter errors (query, limit)
@@ -202,6 +208,7 @@ async def test_create_agent_error_content_with_multiple_params() -> None:
runtime: ToolRuntime,
) -> str:
"""A complex tool with multiple injected and non-injected parameters.
+
Args:
query: The search query string.
limit: Maximum number of results to return.
@@ -297,6 +304,7 @@ async def test_create_agent_error_content_with_multiple_params() -> None:
)
async def test_create_agent_error_only_model_controllable_params() -> None:
"""Test that errors only include LLM-controllable parameter issues.
+
Focused test ensuring that validation errors for LLM-controlled parameters
are clearly reported, while system-injected parameters remain completely
absent from error messages. This provides focused feedback to the LLM.
@@ -312,6 +320,7 @@ async def test_create_agent_error_only_model_controllable_params() -> None:
state: Annotated[StateWithSecrets, InjectedState],
) -> str:
"""Tool that validates user credentials.
+
Args:
username: The username (3-20 chars).
email: The email address.
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py b/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py
index 65808eb70a..184745b8a9 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py
@@ -16,15 +16,12 @@ configurations.
from __future__ import annotations
-from typing import Any
+from typing import Annotated, Any
-import pytest
-from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
+from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langgraph.prebuilt import InjectedStore
-from langgraph.store.base import BaseStore
from langgraph.store.memory import InMemoryStore
-from typing_extensions import Annotated
from langchain.agents import create_agent
from langchain.agents.middleware.types import AgentState
@@ -283,8 +280,6 @@ def test_tool_runtime_config_access() -> None:
def test_tool_runtime_with_custom_state() -> None:
"""Test ToolRuntime works with custom state schemas."""
- from typing_extensions import Annotated, TypedDict
-
from langchain.agents.middleware.types import AgentMiddleware
class CustomState(AgentState):
@@ -314,7 +309,10 @@ def test_tool_runtime_with_custom_state() -> None:
)
result = agent.invoke(
- {"messages": [HumanMessage("Test custom state")], "custom_field": "custom_value"}
+ {
+ "messages": [HumanMessage("Test custom state")],
+ "custom_field": "custom_value",
+ }
)
# Verify custom field was accessible
@@ -431,9 +429,9 @@ def test_tool_runtime_error_handling() -> None:
try:
if x == 0:
return "Error: Cannot process zero"
- return f"Processed: {x}"
except Exception as e:
return f"Error: {e}"
+ return f"Processed: {x}"
agent = create_agent(
model=FakeToolCallingModel(
@@ -462,8 +460,6 @@ def test_tool_runtime_error_handling() -> None:
def test_tool_runtime_with_middleware() -> None:
"""Test ToolRuntime injection works with agent middleware."""
- from typing import Any
-
from langchain.agents.middleware.types import AgentMiddleware
middleware_calls = []
@@ -541,7 +537,8 @@ def test_tool_runtime_type_hints() -> None:
result = agent.invoke({"messages": [HumanMessage("Test")]})
- # Verify typed runtime worked - should see 2 messages (HumanMessage + AIMessage) before tool executes
+ # Verify typed runtime worked -
+ # should see 2 messages (HumanMessage + AIMessage) before tool executes
assert typed_runtime["message_count"] == 2
tool_message = result["messages"][2]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py b/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py
index 0290cbffa9..76e221a264 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py
@@ -1,14 +1,18 @@
"""Test suite for create_agent with structured output response_format permutations."""
import json
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
+from typing import Any
import pytest
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.messages import AIMessage as CoreAIMessage
+from langchain_core.messages import BaseMessage, HumanMessage
+from langchain_core.runnables import Runnable
+from pydantic import BaseModel, Field
+from typing_extensions import TypedDict
-from dataclasses import dataclass
-from typing import Union, Sequence, Any, Callable
-from collections.abc import Awaitable
-
-from langchain_core.messages import HumanMessage, AIMessage as CoreAIMessage
from langchain.agents import create_agent
from langchain.agents.structured_output import (
MultipleStructuredOutputsError,
@@ -16,16 +20,9 @@ from langchain.agents.structured_output import (
StructuredOutputValidationError,
ToolStrategy,
)
-from langchain.tools import tool
-from pydantic import BaseModel, Field
-from typing_extensions import TypedDict
-
from langchain.messages import AIMessage
-from langchain_core.messages import BaseMessage
-from langchain_core.language_models import LanguageModelInput
-from langchain_core.runnables import Runnable
+from langchain.tools import BaseTool, tool
from tests.unit_tests.agents.model import FakeToolCallingModel
-from langchain.tools import BaseTool
# Test data models
@@ -86,14 +83,12 @@ location_json_schema = {
@tool
def get_weather() -> str:
"""Get the weather."""
-
return "The weather is sunny and 75°F."
@tool
def get_location() -> str:
"""Get the current location."""
-
return "You are in New York, USA."
@@ -345,14 +340,12 @@ class TestResponseFormatAsToolStrategy:
],
]
- model = FakeToolCallingModel[Union[WeatherBaseModel, LocationResponse]](
- tool_calls=tool_calls
- )
+ model = FakeToolCallingModel[WeatherBaseModel | LocationResponse](tool_calls=tool_calls)
agent = create_agent(
model,
[get_weather, get_location],
- response_format=ToolStrategy(Union[WeatherBaseModel, LocationResponse]),
+ response_format=ToolStrategy(WeatherBaseModel | LocationResponse),
)
response = agent.invoke({"messages": [HumanMessage("What's the weather?")]})
@@ -376,7 +369,7 @@ class TestResponseFormatAsToolStrategy:
agent_location = create_agent(
model_location,
[get_weather, get_location],
- response_format=ToolStrategy(Union[WeatherBaseModel, LocationResponse]),
+ response_format=ToolStrategy(WeatherBaseModel | LocationResponse),
)
response_location = agent_location.invoke({"messages": [HumanMessage("Where am I?")]})
@@ -384,7 +377,11 @@ class TestResponseFormatAsToolStrategy:
assert len(response_location["messages"]) == 5
def test_multiple_structured_outputs_error_without_retry(self) -> None:
- """Test that MultipleStructuredOutputsError is raised when model returns multiple structured tool calls without retry."""
+ """Test multiple structured outputs error without retry.
+
+ Test that MultipleStructuredOutputsError is raised when model returns multiple
+ structured tool calls without retry.
+ """
tool_calls = [
[
{
@@ -406,14 +403,14 @@ class TestResponseFormatAsToolStrategy:
model,
[],
response_format=ToolStrategy(
- Union[WeatherBaseModel, LocationResponse],
+ WeatherBaseModel | LocationResponse,
handle_errors=False,
),
)
with pytest.raises(
MultipleStructuredOutputsError,
- match=".*WeatherBaseModel.*LocationResponse.*",
+ match=r".*WeatherBaseModel.*LocationResponse.*",
):
agent.invoke({"messages": [HumanMessage("Give me weather and location")]})
@@ -447,7 +444,7 @@ class TestResponseFormatAsToolStrategy:
model,
[],
response_format=ToolStrategy(
- Union[WeatherBaseModel, LocationResponse],
+ WeatherBaseModel | LocationResponse,
handle_errors=True,
),
)
@@ -459,7 +456,11 @@ class TestResponseFormatAsToolStrategy:
assert response["structured_response"] == EXPECTED_WEATHER_PYDANTIC
def test_structured_output_parsing_error_without_retry(self) -> None:
- """Test that StructuredOutputParsingError is raised when tool args fail to parse without retry."""
+ """Test structured output parsing error without retry.
+
+ Test that StructuredOutputParsingError is raised when tool args fail to parse
+ without retry.
+ """
tool_calls = [
[
{
@@ -483,7 +484,7 @@ class TestResponseFormatAsToolStrategy:
with pytest.raises(
StructuredOutputValidationError,
- match=".*WeatherBaseModel.*",
+ match=r".*WeatherBaseModel.*",
):
agent.invoke({"messages": [HumanMessage("What's the weather?")]})
@@ -558,7 +559,7 @@ class TestResponseFormatAsToolStrategy:
model,
[],
response_format=ToolStrategy(
- Union[WeatherBaseModel, LocationResponse],
+ WeatherBaseModel | LocationResponse,
handle_errors=custom_message,
),
)
@@ -611,7 +612,11 @@ class TestResponseFormatAsToolStrategy:
assert response["structured_response"] == EXPECTED_WEATHER_PYDANTIC
def test_validation_error_with_invalid_response(self) -> None:
- """Test that StructuredOutputValidationError is raised when tool strategy receives invalid response."""
+ """Test validation error with invalid response.
+
+ Test that StructuredOutputValidationError is raised when tool strategy receives
+ invalid response.
+ """
tool_calls = [
[
{
@@ -635,7 +640,7 @@ class TestResponseFormatAsToolStrategy:
with pytest.raises(
StructuredOutputValidationError,
- match=".*WeatherBaseModel.*",
+ match=r".*WeatherBaseModel.*",
):
agent.invoke({"messages": [HumanMessage("What's the weather?")]})
@@ -660,7 +665,11 @@ class TestResponseFormatAsProviderStrategy:
assert len(response["messages"]) == 4
def test_validation_error_with_invalid_response(self) -> None:
- """Test that StructuredOutputValidationError is raised when provider strategy receives invalid response."""
+ """Test validation error with invalid response.
+
+ Test that StructuredOutputValidationError is raised when provider strategy
+ receives invalid response.
+ """
tool_calls = [
[{"args": {}, "id": "1", "name": "get_weather"}],
]
@@ -677,7 +686,7 @@ class TestResponseFormatAsProviderStrategy:
with pytest.raises(
StructuredOutputValidationError,
- match=".*WeatherBaseModel.*",
+ match=r".*WeatherBaseModel.*",
):
agent.invoke({"messages": [HumanMessage("What's the weather?")]})
@@ -761,9 +770,11 @@ class TestDynamicModelWithResponseFormat:
selected based on the final model's capabilities.
"""
from unittest.mock import patch
- from langchain.agents.middleware.types import AgentMiddleware, ModelRequest
+
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
+ from langchain.agents.middleware.types import AgentMiddleware, ModelRequest
+
# Custom model that we'll use to test whether the tool strategy is applied
# correctly at runtime.
class CustomModel(GenericFakeChatModel):
@@ -771,7 +782,7 @@ class TestDynamicModelWithResponseFormat:
def bind_tools(
self,
- tools: Sequence[Union[dict[str, Any], type[BaseModel], Callable, BaseTool]],
+ tools: Sequence[dict[str, Any] | type[BaseModel] | Callable | BaseTool],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
# Record every tool binding event.
@@ -849,14 +860,14 @@ def test_union_of_types() -> None:
],
]
- model = FakeToolCallingModel[Union[WeatherBaseModel, LocationResponse]](
+ model = FakeToolCallingModel[WeatherBaseModel | LocationResponse](
tool_calls=tool_calls, structured_response=EXPECTED_WEATHER_PYDANTIC
)
agent = create_agent(
model,
[get_weather, get_location],
- response_format=ToolStrategy(Union[WeatherBaseModel, LocationResponse]),
+ response_format=ToolStrategy(WeatherBaseModel | LocationResponse),
)
response = agent.invoke({"messages": [HumanMessage("What's the weather?")]})
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_response_format_integration.py b/libs/langchain_v1/tests/unit_tests/agents/test_response_format_integration.py
index c1a26401be..aadc7a1992 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_response_format_integration.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_response_format_integration.py
@@ -1,4 +1,4 @@
-"""Test response_format for langchain-openai.
+r"""Test response_format for langchain-openai.
If tests fail, cassettes may need to be re-recorded.
@@ -41,7 +41,7 @@ for request, response in list(zip(requests, responses)):
print(json.dumps(resp, indent=2, default=bytes_encoder))
print("\n\n")
```
-"""
+""" # noqa: E501
import os
from typing import Any
@@ -62,7 +62,7 @@ class WeatherBaseModel(BaseModel):
condition: str = Field(description="Weather condition")
-def get_weather(city: str) -> str: # noqa: ARG001
+def get_weather(city: str) -> str:
"""Get the weather for a city."""
return f"The weather in {city} is sunny and 75°F."
@@ -70,7 +70,7 @@ def get_weather(city: str) -> str: # noqa: ARG001
@pytest.mark.requires("langchain_openai")
@pytest.mark.vcr
@pytest.mark.parametrize("use_responses_api", [False, True])
-def test_inference_to_native_output(use_responses_api: bool) -> None:
+def test_inference_to_native_output(*, use_responses_api: bool) -> None:
"""Test that native output is inferred when a model supports it."""
from langchain_openai import ChatOpenAI
@@ -108,7 +108,7 @@ def test_inference_to_native_output(use_responses_api: bool) -> None:
@pytest.mark.requires("langchain_openai")
@pytest.mark.vcr
@pytest.mark.parametrize("use_responses_api", [False, True])
-def test_inference_to_tool_output(use_responses_api: bool) -> None:
+def test_inference_to_tool_output(*, use_responses_api: bool) -> None:
"""Test that tool output is inferred when a model supports it."""
from langchain_openai import ChatOpenAI
@@ -147,7 +147,7 @@ def test_inference_to_tool_output(use_responses_api: bool) -> None:
@pytest.mark.requires("langchain_openai")
@pytest.mark.vcr
@pytest.mark.parametrize("use_responses_api", [False, True])
-def test_strict_mode(use_responses_api: bool) -> None:
+def test_strict_mode(*, use_responses_api: bool) -> None:
from langchain_openai import ChatOpenAI
model_kwargs = {"model": "gpt-5", "use_responses_api": use_responses_api}
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_responses.py b/libs/langchain_v1/tests/unit_tests/agents/test_responses.py
index 6f21e4b21c..476a195848 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_responses.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_responses.py
@@ -97,7 +97,7 @@ class TestOutputToolBinding:
tool_binding = OutputToolBinding.from_schema_spec(schema_spec)
# Should use empty description when model has default BaseModel docstring
- assert tool_binding.tool.description == ""
+ assert not tool_binding.tool.description
def test_parse_payload_pydantic_success(self) -> None:
"""Test successful parsing for Pydantic model."""
@@ -137,4 +137,4 @@ class TestEdgeCases:
"""Test that BASE_MODEL_DOC constant is set correctly."""
binding = OutputToolBinding.from_schema_spec(_SchemaSpec(EmptyDocModel))
assert binding.tool.name == "EmptyDocModel"
- assert binding.tool.description[:5] == "" # Should be empty for default docstring
+ assert not binding.tool.description[:5] # Should be empty for default docstring
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py b/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py
index 7d9d97ca64..38d3da9f3a 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py
@@ -51,9 +51,9 @@ TEST_CASES = load_spec("responses", as_model=TestCase)
def _make_tool(fn, *, name: str, description: str):
mock = MagicMock(side_effect=lambda *, name: fn(name=name))
- InputModel = create_model(f"{name}_input", name=(str, ...))
+ input_model = create_model(f"{name}_input", name=(str, ...))
- @tool(name, description=description, args_schema=InputModel)
+ @tool(name, description=description, args_schema=input_model)
def _wrapped(name: str):
return mock(name=name)
@@ -65,7 +65,8 @@ def _make_tool(fn, *, name: str, description: str):
def test_responses_integration_matrix(case: TestCase) -> None:
if case.name == "asking for information that does not fit into the response format":
pytest.xfail(
- "currently failing due to undefined behavior when model cannot conform to any of the structured response formats."
+ "currently failing due to undefined behavior when model cannot conform to "
+ "any of the structured response formats."
)
def get_employee_role(*, name: str) -> str | None:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py b/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py
index 4bdd2e8fd8..ca1ba39f2a 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_return_direct_spec.py
@@ -33,7 +33,7 @@ class TestCase(BaseSchema):
TEST_CASES = load_spec("return_direct", as_model=TestCase)
-def _make_tool(return_direct: bool):
+def _make_tool(*, return_direct: bool):
attempts = 0
def _side_effect():
@@ -63,7 +63,7 @@ def _make_tool(return_direct: bool):
@pytest.mark.skipif(skip_openai_integration_tests, reason="OpenAI integration tests are disabled.")
@pytest.mark.parametrize("case", TEST_CASES, ids=[c.name for c in TEST_CASES])
def test_return_direct_integration_matrix(case: TestCase) -> None:
- poll_tool = _make_tool(case.return_direct)
+ poll_tool = _make_tool(return_direct=case.return_direct)
model = ChatOpenAI(
model="gpt-4o",
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py b/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py
index d3962c2174..d7bb9e57f5 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py
@@ -8,8 +8,6 @@ from __future__ import annotations
from typing import Any
-import pytest
-
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
@@ -181,7 +179,10 @@ async def test_state_schema_async() -> None:
)
result = await agent.ainvoke(
- {"messages": [HumanMessage("Test async")], "async_field": "async_value"}
+ {
+ "messages": [HumanMessage("Test async")],
+ "async_field": "async_value",
+ }
)
assert result["async_field"] == "async_value"
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_system_message.py b/libs/langchain_v1/tests/unit_tests/agents/test_system_message.py
index e75b150db5..532f465b18 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_system_message.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_system_message.py
@@ -21,9 +21,7 @@ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langgraph.runtime import Runtime
from langchain.agents.factory import create_agent
-from langchain.agents.middleware.types import ModelRequest, ModelResponse
-
-from .model import FakeToolCallingModel
+from langchain.agents.middleware.types import AgentState, ModelRequest, ModelResponse
def _fake_runtime(context: dict | None = None) -> Runtime:
@@ -34,8 +32,8 @@ def _fake_runtime(context: dict | None = None) -> Runtime:
def __init__(self):
self.context = type("Context", (), context)()
- return cast(Runtime, FakeRuntime())
- return cast(Runtime, object())
+ return cast("Runtime", FakeRuntime())
+ return cast("Runtime", object())
def _make_request(
@@ -439,7 +437,7 @@ class TestSystemMessageUpdateViaMiddleware:
append_with_metadata_middleware(request, mock_handler)
assert captured_request is not None
- assert "Base prompt Additional instructions." == captured_request.system_message.text
+ assert captured_request.system_message.text == "Base prompt Additional instructions."
assert captured_request.system_message.additional_kwargs["base"] == "value"
assert captured_request.system_message.additional_kwargs["middleware"] == "applied"
@@ -544,7 +542,7 @@ class TestMultipleMiddlewareChaining:
)
def final_handler(req: ModelRequest) -> ModelResponse:
- assert "String prompt + SystemMessage" == req.system_message.text
+ assert req.system_message.text == "String prompt + SystemMessage"
assert req.system_message.additional_kwargs["metadata"] == "added"
return ModelResponse(result=[AIMessage(content="response")])
@@ -619,7 +617,7 @@ class TestCacheControlPreservation:
def second_middleware_appends(request: ModelRequest, handler) -> ModelResponse:
"""Append to system message while preserving cache control."""
existing_content = request.system_message.content_blocks
- new_content = existing_content + [{"type": "text", "text": "Additional text"}]
+ new_content = [*existing_content, {"type": "text", "text": "Additional text"}]
new_message = SystemMessage(content=new_content)
new_request = request.override(system_message=new_message)
@@ -923,9 +921,8 @@ class TestSystemMessageMiddlewareIntegration:
if request.system_message:
new_message = SystemMessage(content=request.system_message.text + " [modified]")
return request.override(system_message=new_message)
- else:
- new_message = SystemMessage(content="[created]")
- return request.override(system_message=new_message)
+ new_message = SystemMessage(content="[created]")
+ return request.override(system_message=new_message)
if isinstance(initial_value, SystemMessage):
request = _make_request(system_message=initial_value)
diff --git a/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py b/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py
index c4a95c73d4..822503b6df 100644
--- a/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py
+++ b/libs/langchain_v1/tests/unit_tests/chat_models/test_chat_models.py
@@ -57,7 +57,7 @@ def test_init_missing_dep() -> None:
def test_init_unknown_provider() -> None:
- with pytest.raises(ValueError, match="Unsupported model_provider='bar'."):
+ with pytest.raises(ValueError, match="Unsupported model_provider='bar'"):
init_chat_model("foo", model_provider="bar")
diff --git a/libs/langchain_v1/tests/unit_tests/conftest.py b/libs/langchain_v1/tests/unit_tests/conftest.py
index da92150720..e846f9432f 100644
--- a/libs/langchain_v1/tests/unit_tests/conftest.py
+++ b/libs/langchain_v1/tests/unit_tests/conftest.py
@@ -7,7 +7,7 @@ from typing import Any
import pytest
from langchain_tests.conftest import CustomPersister, CustomSerializer
from langchain_tests.conftest import (
- _base_vcr_config as _base_vcr_config,
+ _base_vcr_config as _base_vcr_config, # noqa: PLC0414
)
from vcr import VCR
diff --git a/libs/langchain_v1/tests/unit_tests/embeddings/test_base.py b/libs/langchain_v1/tests/unit_tests/embeddings/test_base.py
index 30bfaeb677..24460855ce 100644
--- a/libs/langchain_v1/tests/unit_tests/embeddings/test_base.py
+++ b/libs/langchain_v1/tests/unit_tests/embeddings/test_base.py
@@ -88,7 +88,7 @@ def test_infer_model_and_provider_errors() -> None:
_infer_model_and_provider("model", provider="")
# Test invalid provider
- with pytest.raises(ValueError, match="Provider 'invalid' is not supported.") as exc:
+ with pytest.raises(ValueError, match="Provider 'invalid' is not supported") as exc:
_infer_model_and_provider("model", provider="invalid")
# Test provider list is in error
for provider in _SUPPORTED_PROVIDERS:
diff --git a/libs/langchain_v1/tests/unit_tests/stubs.py b/libs/langchain_v1/tests/unit_tests/stubs.py
deleted file mode 100644
index 44450d946b..0000000000
--- a/libs/langchain_v1/tests/unit_tests/stubs.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from typing import Any
-
-from langchain_core.documents import Document
-from langchain_core.messages import AIMessage, AIMessageChunk, HumanMessage
-
-
-class AnyStr(str):
- __slots__ = ()
-
- def __eq__(self, other: object) -> bool:
- return isinstance(other, str)
-
-
-# The code below creates version of pydantic models
-# that will work in unit tests with AnyStr as id field
-# Please note that the `id` field is assigned AFTER the model is created
-# to workaround an issue with pydantic ignoring the __eq__ method on
-# subclassed strings.
-
-
-def _AnyIdDocument(**kwargs: Any) -> Document:
- """Create a document with an id field."""
- message = Document(**kwargs)
- message.id = AnyStr()
- return message
-
-
-def _AnyIdAIMessage(**kwargs: Any) -> AIMessage:
- """Create ai message with an any id field."""
- message = AIMessage(**kwargs)
- message.id = AnyStr()
- return message
-
-
-def _AnyIdAIMessageChunk(**kwargs: Any) -> AIMessageChunk:
- """Create ai message with an any id field."""
- message = AIMessageChunk(**kwargs)
- message.id = AnyStr()
- return message
-
-
-def _AnyIdHumanMessage(**kwargs: Any) -> HumanMessage:
- """Create a human with an any id field."""
- message = HumanMessage(**kwargs)
- message.id = AnyStr()
- return message
diff --git a/libs/langchain_v1/tests/unit_tests/test_dependencies.py b/libs/langchain_v1/tests/unit_tests/test_dependencies.py
index 5150332e69..e061f31c03 100644
--- a/libs/langchain_v1/tests/unit_tests/test_dependencies.py
+++ b/libs/langchain_v1/tests/unit_tests/test_dependencies.py
@@ -30,4 +30,10 @@ def test_required_dependencies(uv_conf: Mapping[str, Any]) -> None:
dependencies = uv_conf["project"]["dependencies"]
required_dependencies = {Requirement(dep).name for dep in dependencies}
- assert sorted(required_dependencies) == sorted(["langchain-core", "langgraph", "pydantic"])
+ assert sorted(required_dependencies) == sorted(
+ [
+ "langchain-core",
+ "langgraph",
+ "pydantic",
+ ]
+ )
diff --git a/libs/langchain_v1/tests/unit_tests/test_pytest_config.py b/libs/langchain_v1/tests/unit_tests/test_pytest_config.py
index c2b0af645f..ce4e8662c4 100644
--- a/libs/langchain_v1/tests/unit_tests/test_pytest_config.py
+++ b/libs/langchain_v1/tests/unit_tests/test_pytest_config.py
@@ -6,6 +6,4 @@ import requests
def test_socket_disabled() -> None:
"""This test should fail."""
with pytest.raises(pytest_socket.SocketBlockedError):
- # Ignore S113 since we don't need a timeout here as the request
- # should fail immediately
- requests.get("https://www.example.com") # noqa: S113
+ requests.get("https://www.example.com", timeout=1)
diff --git a/libs/langchain_v1/uv.lock b/libs/langchain_v1/uv.lock
index bbb7f4388e..42fd5ec20c 100644
--- a/libs/langchain_v1/uv.lock
+++ b/libs/langchain_v1/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 2
+revision = 3
requires-python = ">=3.10.0, <4.0.0"
resolution-markers = [
"python_full_version >= '3.14' and platform_python_implementation == 'PyPy'",
@@ -539,56 +539,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e6/46/eb6eca305c77a4489affe1c5d8f4cae82f285d9addd8de4ec084a7184221/cachetools-6.2.2-py3-none-any.whl", hash = "sha256:6c09c98183bf58560c97b2abfcedcbaf6a896a490f534b031b661d3723b45ace", size = 11503, upload-time = "2025-11-13T17:42:50.232Z" },
]
-[[package]]
-name = "cassandra-driver"
-version = "3.29.3"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "geomet" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/06/47/4e0fbdf02a7a418997f16f59feba26937d9973b979d3f23d79fbd8f6186f/cassandra_driver-3.29.3.tar.gz", hash = "sha256:ff6b82ee4533f6fd4474d833e693b44b984f58337173ee98ed76bce08721a636", size = 294612, upload-time = "2025-10-22T15:15:01.335Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/70/04/ddc400299c2279c9f83c952268b312e36ef40e68049923b84c290e1fbb02/cassandra_driver-3.29.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:96ad742f5cbfb771df512959ab5de36e248ce9aa2c487fd81c37d5c0a627c094", size = 364299, upload-time = "2025-10-22T15:14:19.908Z" },
- { url = "https://files.pythonhosted.org/packages/36/3b/8a02505dec925b8336cc06c6bcaa41272d884ea6262a0344c44c6d66ff8f/cassandra_driver-3.29.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c935431682557ffcd3efc1c7bcb01b0f6769a1c90751a7154d5e3c905a6a2042", size = 364911, upload-time = "2025-10-22T15:14:21.805Z" },
- { url = "https://files.pythonhosted.org/packages/73/32/fecd1245df5ef95cf2c8fbaaf37f2714b685eaf913c6894ef52cf6469a09/cassandra_driver-3.29.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:54afde4aaa5b55fbc2c075e1c55fb14a5739459428f3bb81f849ad020f7d5bcf", size = 374313, upload-time = "2025-10-22T15:14:23.246Z" },
- { url = "https://files.pythonhosted.org/packages/8e/47/b238acf157920745252f580bf121cf1ff8b1584acc88ce0e4df5355bf67d/cassandra_driver-3.29.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7552fb7189acd06161f8feac7045a387dc9e03b3b9f7dcb5675178906cee792e", size = 374250, upload-time = "2025-10-22T15:14:24.728Z" },
- { url = "https://files.pythonhosted.org/packages/14/af/6c6097804c91deb3f20ab5741e642a5624e7b13e4be9adfd5914d6b0634d/cassandra_driver-3.29.3-cp310-cp310-win32.whl", hash = "sha256:891a1b6a111a591ad9f1c9e088846848dc9e6be030a6086c8c3aa5d2d837f266", size = 341529, upload-time = "2025-10-22T15:14:26.219Z" },
- { url = "https://files.pythonhosted.org/packages/95/7a/2c2262184bd671f71e2cbbd9a2ec9254e79c5f0730bdaf6ed919b280f907/cassandra_driver-3.29.3-cp310-cp310-win_amd64.whl", hash = "sha256:29fc241475801872dc27c3dd1a3976373536223dd4fd1c01868ff86bdbbfd48b", size = 349178, upload-time = "2025-10-22T15:14:27.686Z" },
- { url = "https://files.pythonhosted.org/packages/69/5d/03af94c5f0da81c6d5e476b781151c3895e7734b30e819e1934601dda7f7/cassandra_driver-3.29.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0785f6e0986089e922378ae3b64b5f696440aeb595fb84c2cf3ccef220c6ae91", size = 364328, upload-time = "2025-10-22T15:14:28.962Z" },
- { url = "https://files.pythonhosted.org/packages/bb/27/01bff47c47a4e3553f00399f21630916258ed84e0b22f249f6dcc538ad20/cassandra_driver-3.29.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1c241ba08473baf31a333feb59793190d01625541c2368d3bbb0f43a586f1d6a", size = 364948, upload-time = "2025-10-22T15:14:30.439Z" },
- { url = "https://files.pythonhosted.org/packages/e5/c8/60b8dde74270c15a77b417462344cbee827a752439434a50f6ecd0aceca4/cassandra_driver-3.29.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:064bf45d3ca87239e11168c0110676fc64f7fdbddb4bcba9be787b8ad5f6d734", size = 374346, upload-time = "2025-10-22T15:14:31.628Z" },
- { url = "https://files.pythonhosted.org/packages/47/f6/19828944af2333a1740f22eac9496e760c16df9aa04922ee472c35cdcc9d/cassandra_driver-3.29.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f9858b5ccdf75dd89c20d74474b59dd3a2e2f86c7251b310011c46acdef3874", size = 374276, upload-time = "2025-10-22T15:14:33.135Z" },
- { url = "https://files.pythonhosted.org/packages/2a/e3/09d9f33a35d69523991c4c487c2d0bb62882a9a31253d504fa8edb198521/cassandra_driver-3.29.3-cp311-cp311-win32.whl", hash = "sha256:84b24f69a7bbe76302330d47422a7fcc1998a6a96ffd414a795d7d95992b49cb", size = 341532, upload-time = "2025-10-22T15:14:34.795Z" },
- { url = "https://files.pythonhosted.org/packages/be/0f/ec3dc7942a50c8e3e874059b893c429c59dd0e3dfa68065295cf5814a890/cassandra_driver-3.29.3-cp311-cp311-win_amd64.whl", hash = "sha256:26013d768b2ea4728c09144b08c0eb86ad692e85cb15f4e52e3107abca83683c", size = 349183, upload-time = "2025-10-22T15:14:36.214Z" },
- { url = "https://files.pythonhosted.org/packages/30/cd/c94b06c8a63792aee3858fded79ec7c7a48df6967ca01ba53522fd6b54ad/cassandra_driver-3.29.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7a2f371af54cd1d153ef373a733889ebfbcc9c30e00429fc12a2569bad9239e1", size = 364459, upload-time = "2025-10-22T15:14:37.424Z" },
- { url = "https://files.pythonhosted.org/packages/be/9a/13a207f7b5e39720e8a0a7080dcf7d0eea97a8644527b4983a299a1a6b88/cassandra_driver-3.29.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3f654b01d8d49f68deedfaff1edcff314e3103d29130b2a034df6c490c522351", size = 365067, upload-time = "2025-10-22T15:14:38.643Z" },
- { url = "https://files.pythonhosted.org/packages/ef/31/1c03cf0f08d48cf5d3184d5e8383870153baaf7770a6c0e5f5e88f755f4d/cassandra_driver-3.29.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:facd488c2b9be8bffcad5903566581e96d2863d2ec4bcad7f114d1b2b2f39ad0", size = 374565, upload-time = "2025-10-22T15:14:40.394Z" },
- { url = "https://files.pythonhosted.org/packages/43/44/8b0edc9ee39b40d42e6eb612059965019be3c9271717e0575e43db9a6e9c/cassandra_driver-3.29.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:572bd5a01089ab92da12f4f52b32b878547bbc544a798d8cfd042e7fc2601c75", size = 374427, upload-time = "2025-10-22T15:14:41.547Z" },
- { url = "https://files.pythonhosted.org/packages/f2/0a/001f8c9243a4d8fb609b27c8f95af251ef7d3bf4b156c93839fe66b7d1b2/cassandra_driver-3.29.3-cp312-cp312-win32.whl", hash = "sha256:63adca0f9219be3fe8789f4aa7b77c5f6a7bf65d6442959db52c653140ca4185", size = 341534, upload-time = "2025-10-22T15:14:42.994Z" },
- { url = "https://files.pythonhosted.org/packages/0d/49/775b7be48193510e2855703e6b050f733a51b3d65b29869f946011f7323d/cassandra_driver-3.29.3-cp312-cp312-win_amd64.whl", hash = "sha256:9b7032b44769c454e96aa11483bfd167a87ea341268f1075b0ff84f780c910a9", size = 349257, upload-time = "2025-10-22T15:14:44.199Z" },
- { url = "https://files.pythonhosted.org/packages/d1/9f/5933f1f964e4e4f98b3743f0b548ce4a6f3d9d76baf0f064911f4ee871e5/cassandra_driver-3.29.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5a0113020d86e8f61c7a2ae3d508720cd036df7462a55926b85dd97ada27e143", size = 364457, upload-time = "2025-10-22T15:14:45.453Z" },
- { url = "https://files.pythonhosted.org/packages/73/7e/3b36461b3f2a7444e0183dcabfd8fe1fb5f700a260812fb0f6b751c3e9ba/cassandra_driver-3.29.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2b72312a8b62a905da6133effbba9b0731c8e30af96e10ca77fc5c34532c6827", size = 365062, upload-time = "2025-10-22T15:14:46.707Z" },
- { url = "https://files.pythonhosted.org/packages/b3/f5/ae49f30eb59c55fb226467129f02fed3ac042f87990b647a7e9021ffb3db/cassandra_driver-3.29.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:38216e13d6f2e0d4513a5b8806e70ce4a8f28a82962793a67371582fc2c7141b", size = 374573, upload-time = "2025-10-22T15:14:48.116Z" },
- { url = "https://files.pythonhosted.org/packages/ea/42/a4f10ef8274a2bd05e859b7d2141c2c0cc13a8ef4ea6e825a660960b17d7/cassandra_driver-3.29.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51d6a5390e2454b599500049f0a5c72aa701db155c1e542f9a1157c1c45814b1", size = 374432, upload-time = "2025-10-22T15:14:49.44Z" },
- { url = "https://files.pythonhosted.org/packages/ea/55/611982779ddeb4b98658d87ab3b150506b2121d8d16a843459c7aacc7884/cassandra_driver-3.29.3-cp313-cp313-win32.whl", hash = "sha256:638047c1f70fb14c9d8f743931d4f4f42aff6793b47afded3097c002ef8c1165", size = 341529, upload-time = "2025-10-22T15:14:50.896Z" },
- { url = "https://files.pythonhosted.org/packages/b2/13/aaa6c7559bfb11c58a1978dfa46732f4d477230641259f13a14907cb4546/cassandra_driver-3.29.3-cp313-cp313-win_amd64.whl", hash = "sha256:27adf8869937461ad08c5fefb47857532e467b408db496db4dbf8b132a4bd623", size = 349242, upload-time = "2025-10-22T15:14:52.472Z" },
-]
-
-[[package]]
-name = "cassio"
-version = "0.1.10"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "cassandra-driver" },
- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
- { name = "numpy", version = "2.3.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
- { name = "requests" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/88/00/a9a3a958169677f5f713bb3ed5a4afc1baf7abd1e08f37acad718aa923db/cassio-0.1.10.tar.gz", hash = "sha256:577f0a2ce5898a57c83195bf74811dec8794282477eb6fa4debd4ccec6cfab98", size = 35854, upload-time = "2024-10-03T16:53:57.549Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/73/ae/25347dca6ca4032d421cd674fdb35bb02985baf5dcb8cbfac0cc95dfae49/cassio-0.1.10-py3-none-any.whl", hash = "sha256:9eebe5f18b627d0f328de4dbbf22c68cc76dbeecf46d846c0277e410de5cb1dc", size = 45726, upload-time = "2024-10-03T16:53:54.79Z" },
-]
-
[[package]]
name = "certifi"
version = "2025.11.12"
@@ -1180,18 +1130,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/eb/02/a6b21098b1d5d6249b7c5ab69dde30108a71e4e819d4a9778f1de1d5b70d/fsspec-2025.10.0-py3-none-any.whl", hash = "sha256:7c7712353ae7d875407f97715f0e1ffcc21e33d5b24556cb1e090ae9409ec61d", size = 200966, upload-time = "2025-10-30T14:58:42.53Z" },
]
-[[package]]
-name = "geomet"
-version = "1.1.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "click" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/2a/8c/dde022aa6747b114f6b14a7392871275dea8867e2bd26cddb80cc6d66620/geomet-1.1.0.tar.gz", hash = "sha256:51e92231a0ef6aaa63ac20c443377ba78a303fd2ecd179dc3567de79f3c11605", size = 28732, upload-time = "2023-11-14T15:43:36.764Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/af/90/3bc780df088d439714af8295196a4332a26559ae66fd99865e36f92efa9e/geomet-1.1.0-py3-none-any.whl", hash = "sha256:4372fe4e286a34acc6f2e9308284850bd8c4aa5bc12065e2abbd4995900db12f", size = 31522, upload-time = "2023-11-14T15:43:35.305Z" },
-]
-
[[package]]
name = "google-ai-generativelanguage"
version = "0.9.0"
@@ -2001,7 +1939,6 @@ test = [
{ name = "toml" },
]
test-integration = [
- { name = "cassio" },
{ name = "langchain-core" },
{ name = "langchain-text-splitters" },
{ name = "langchainhub" },
@@ -2039,7 +1976,7 @@ requires-dist = [
provides-extras = ["community", "anthropic", "openai", "azure-ai", "google-vertexai", "google-genai", "fireworks", "ollama", "together", "mistralai", "huggingface", "groq", "aws", "deepseek", "xai", "perplexity"]
[package.metadata.requires-dev]
-lint = [{ name = "ruff", specifier = ">=0.12.2,<0.13.0" }]
+lint = [{ name = "ruff", specifier = ">=0.14.2,<0.15.0" }]
test = [
{ name = "langchain-openai", editable = "../partners/openai" },
{ name = "langchain-tests", editable = "../standard-tests" },
@@ -2054,7 +1991,6 @@ test = [
{ name = "toml", specifier = ">=0.10.2,<1.0.0" },
]
test-integration = [
- { name = "cassio", specifier = ">=0.1.0,<1.0.0" },
{ name = "langchain-core", editable = "../core" },
{ name = "langchain-text-splitters", editable = "../text-splitters" },
{ name = "langchainhub", specifier = ">=0.1.16,<1.0.0" },
@@ -2166,7 +2102,7 @@ wheels = [
[[package]]
name = "langchain-core"
-version = "1.1.2"
+version = "1.1.3"
source = { editable = "../core" }
dependencies = [
{ name = "jsonpatch" },
@@ -2347,7 +2283,7 @@ wheels = [
[[package]]
name = "langchain-openai"
-version = "1.1.1"
+version = "1.1.2"
source = { editable = "../partners/openai" }
dependencies = [
{ name = "langchain-core" },
@@ -4404,28 +4340,28 @@ wheels = [
[[package]]
name = "ruff"
-version = "0.12.12"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/a8/f0/e0965dd709b8cabe6356811c0ee8c096806bb57d20b5019eb4e48a117410/ruff-0.12.12.tar.gz", hash = "sha256:b86cd3415dbe31b3b46a71c598f4c4b2f550346d1ccf6326b347cc0c8fd063d6", size = 5359915, upload-time = "2025-09-04T16:50:18.273Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/09/79/8d3d687224d88367b51c7974cec1040c4b015772bfbeffac95face14c04a/ruff-0.12.12-py3-none-linux_armv6l.whl", hash = "sha256:de1c4b916d98ab289818e55ce481e2cacfaad7710b01d1f990c497edf217dafc", size = 12116602, upload-time = "2025-09-04T16:49:18.892Z" },
- { url = "https://files.pythonhosted.org/packages/c3/c3/6e599657fe192462f94861a09aae935b869aea8a1da07f47d6eae471397c/ruff-0.12.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:7acd6045e87fac75a0b0cdedacf9ab3e1ad9d929d149785903cff9bb69ad9727", size = 12868393, upload-time = "2025-09-04T16:49:23.043Z" },
- { url = "https://files.pythonhosted.org/packages/e8/d2/9e3e40d399abc95336b1843f52fc0daaceb672d0e3c9290a28ff1a96f79d/ruff-0.12.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:abf4073688d7d6da16611f2f126be86523a8ec4343d15d276c614bda8ec44edb", size = 12036967, upload-time = "2025-09-04T16:49:26.04Z" },
- { url = "https://files.pythonhosted.org/packages/e9/03/6816b2ed08836be272e87107d905f0908be5b4a40c14bfc91043e76631b8/ruff-0.12.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:968e77094b1d7a576992ac078557d1439df678a34c6fe02fd979f973af167577", size = 12276038, upload-time = "2025-09-04T16:49:29.056Z" },
- { url = "https://files.pythonhosted.org/packages/9f/d5/707b92a61310edf358a389477eabd8af68f375c0ef858194be97ca5b6069/ruff-0.12.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:42a67d16e5b1ffc6d21c5f67851e0e769517fb57a8ebad1d0781b30888aa704e", size = 11901110, upload-time = "2025-09-04T16:49:32.07Z" },
- { url = "https://files.pythonhosted.org/packages/9d/3d/f8b1038f4b9822e26ec3d5b49cf2bc313e3c1564cceb4c1a42820bf74853/ruff-0.12.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b216ec0a0674e4b1214dcc998a5088e54eaf39417327b19ffefba1c4a1e4971e", size = 13668352, upload-time = "2025-09-04T16:49:35.148Z" },
- { url = "https://files.pythonhosted.org/packages/98/0e/91421368ae6c4f3765dd41a150f760c5f725516028a6be30e58255e3c668/ruff-0.12.12-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:59f909c0fdd8f1dcdbfed0b9569b8bf428cf144bec87d9de298dcd4723f5bee8", size = 14638365, upload-time = "2025-09-04T16:49:38.892Z" },
- { url = "https://files.pythonhosted.org/packages/74/5d/88f3f06a142f58ecc8ecb0c2fe0b82343e2a2b04dcd098809f717cf74b6c/ruff-0.12.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9ac93d87047e765336f0c18eacad51dad0c1c33c9df7484c40f98e1d773876f5", size = 14060812, upload-time = "2025-09-04T16:49:42.732Z" },
- { url = "https://files.pythonhosted.org/packages/13/fc/8962e7ddd2e81863d5c92400820f650b86f97ff919c59836fbc4c1a6d84c/ruff-0.12.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:01543c137fd3650d322922e8b14cc133b8ea734617c4891c5a9fccf4bfc9aa92", size = 13050208, upload-time = "2025-09-04T16:49:46.434Z" },
- { url = "https://files.pythonhosted.org/packages/53/06/8deb52d48a9a624fd37390555d9589e719eac568c020b27e96eed671f25f/ruff-0.12.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2afc2fa864197634e549d87fb1e7b6feb01df0a80fd510d6489e1ce8c0b1cc45", size = 13311444, upload-time = "2025-09-04T16:49:49.931Z" },
- { url = "https://files.pythonhosted.org/packages/2a/81/de5a29af7eb8f341f8140867ffb93f82e4fde7256dadee79016ac87c2716/ruff-0.12.12-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0c0945246f5ad776cb8925e36af2438e66188d2b57d9cf2eed2c382c58b371e5", size = 13279474, upload-time = "2025-09-04T16:49:53.465Z" },
- { url = "https://files.pythonhosted.org/packages/7f/14/d9577fdeaf791737ada1b4f5c6b59c21c3326f3f683229096cccd7674e0c/ruff-0.12.12-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:a0fbafe8c58e37aae28b84a80ba1817f2ea552e9450156018a478bf1fa80f4e4", size = 12070204, upload-time = "2025-09-04T16:49:56.882Z" },
- { url = "https://files.pythonhosted.org/packages/77/04/a910078284b47fad54506dc0af13839c418ff704e341c176f64e1127e461/ruff-0.12.12-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:b9c456fb2fc8e1282affa932c9e40f5ec31ec9cbb66751a316bd131273b57c23", size = 11880347, upload-time = "2025-09-04T16:49:59.729Z" },
- { url = "https://files.pythonhosted.org/packages/df/58/30185fcb0e89f05e7ea82e5817b47798f7fa7179863f9d9ba6fd4fe1b098/ruff-0.12.12-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5f12856123b0ad0147d90b3961f5c90e7427f9acd4b40050705499c98983f489", size = 12891844, upload-time = "2025-09-04T16:50:02.591Z" },
- { url = "https://files.pythonhosted.org/packages/21/9c/28a8dacce4855e6703dcb8cdf6c1705d0b23dd01d60150786cd55aa93b16/ruff-0.12.12-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:26a1b5a2bf7dd2c47e3b46d077cd9c0fc3b93e6c6cc9ed750bd312ae9dc302ee", size = 13360687, upload-time = "2025-09-04T16:50:05.8Z" },
- { url = "https://files.pythonhosted.org/packages/c8/fa/05b6428a008e60f79546c943e54068316f32ec8ab5c4f73e4563934fbdc7/ruff-0.12.12-py3-none-win32.whl", hash = "sha256:173be2bfc142af07a01e3a759aba6f7791aa47acf3604f610b1c36db888df7b1", size = 12052870, upload-time = "2025-09-04T16:50:09.121Z" },
- { url = "https://files.pythonhosted.org/packages/85/60/d1e335417804df452589271818749d061b22772b87efda88354cf35cdb7a/ruff-0.12.12-py3-none-win_amd64.whl", hash = "sha256:e99620bf01884e5f38611934c09dd194eb665b0109104acae3ba6102b600fd0d", size = 13178016, upload-time = "2025-09-04T16:50:12.559Z" },
- { url = "https://files.pythonhosted.org/packages/28/7e/61c42657f6e4614a4258f1c3b0c5b93adc4d1f8575f5229d1906b483099b/ruff-0.12.12-py3-none-win_arm64.whl", hash = "sha256:2a8199cab4ce4d72d158319b63370abf60991495fb733db96cd923a34c52d093", size = 12256762, upload-time = "2025-09-04T16:50:15.737Z" },
+version = "0.14.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/82/fa/fbb67a5780ae0f704876cb8ac92d6d76da41da4dc72b7ed3565ab18f2f52/ruff-0.14.5.tar.gz", hash = "sha256:8d3b48d7d8aad423d3137af7ab6c8b1e38e4de104800f0d596990f6ada1a9fc1", size = 5615944, upload-time = "2025-11-13T19:58:51.155Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/68/31/c07e9c535248d10836a94e4f4e8c5a31a1beed6f169b31405b227872d4f4/ruff-0.14.5-py3-none-linux_armv6l.whl", hash = "sha256:f3b8248123b586de44a8018bcc9fefe31d23dda57a34e6f0e1e53bd51fd63594", size = 13171630, upload-time = "2025-11-13T19:57:54.894Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/5c/283c62516dca697cd604c2796d1487396b7a436b2f0ecc3fd412aca470e0/ruff-0.14.5-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:f7a75236570318c7a30edd7f5491945f0169de738d945ca8784500b517163a72", size = 13413925, upload-time = "2025-11-13T19:57:59.181Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/f3/aa319f4afc22cb6fcba2b9cdfc0f03bbf747e59ab7a8c5e90173857a1361/ruff-0.14.5-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6d146132d1ee115f8802356a2dc9a634dbf58184c51bff21f313e8cd1c74899a", size = 12574040, upload-time = "2025-11-13T19:58:02.056Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/7f/cb5845fcc7c7e88ed57f58670189fc2ff517fe2134c3821e77e29fd3b0c8/ruff-0.14.5-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e2380596653dcd20b057794d55681571a257a42327da8894b93bbd6111aa801f", size = 13009755, upload-time = "2025-11-13T19:58:05.172Z" },
+ { url = "https://files.pythonhosted.org/packages/21/d2/bcbedbb6bcb9253085981730687ddc0cc7b2e18e8dc13cf4453de905d7a0/ruff-0.14.5-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2d1fa985a42b1f075a098fa1ab9d472b712bdb17ad87a8ec86e45e7fa6273e68", size = 12937641, upload-time = "2025-11-13T19:58:08.345Z" },
+ { url = "https://files.pythonhosted.org/packages/a4/58/e25de28a572bdd60ffc6bb71fc7fd25a94ec6a076942e372437649cbb02a/ruff-0.14.5-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88f0770d42b7fa02bbefddde15d235ca3aa24e2f0137388cc15b2dcbb1f7c7a7", size = 13610854, upload-time = "2025-11-13T19:58:11.419Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/24/43bb3fd23ecee9861970978ea1a7a63e12a204d319248a7e8af539984280/ruff-0.14.5-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:3676cb02b9061fee7294661071c4709fa21419ea9176087cb77e64410926eb78", size = 15061088, upload-time = "2025-11-13T19:58:14.551Z" },
+ { url = "https://files.pythonhosted.org/packages/23/44/a022f288d61c2f8c8645b24c364b719aee293ffc7d633a2ca4d116b9c716/ruff-0.14.5-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b595bedf6bc9cab647c4a173a61acf4f1ac5f2b545203ba82f30fcb10b0318fb", size = 14734717, upload-time = "2025-11-13T19:58:17.518Z" },
+ { url = "https://files.pythonhosted.org/packages/58/81/5c6ba44de7e44c91f68073e0658109d8373b0590940efe5bd7753a2585a3/ruff-0.14.5-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f55382725ad0bdb2e8ee2babcbbfb16f124f5a59496a2f6a46f1d9d99d93e6e2", size = 14028812, upload-time = "2025-11-13T19:58:20.533Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/ef/41a8b60f8462cb320f68615b00299ebb12660097c952c600c762078420f8/ruff-0.14.5-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7497d19dce23976bdaca24345ae131a1d38dcfe1b0850ad8e9e6e4fa321a6e19", size = 13825656, upload-time = "2025-11-13T19:58:23.345Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/00/207e5de737fdb59b39eb1fac806904fe05681981b46d6a6db9468501062e/ruff-0.14.5-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:410e781f1122d6be4f446981dd479470af86537fb0b8857f27a6e872f65a38e4", size = 13959922, upload-time = "2025-11-13T19:58:26.537Z" },
+ { url = "https://files.pythonhosted.org/packages/bc/7e/fa1f5c2776db4be405040293618846a2dece5c70b050874c2d1f10f24776/ruff-0.14.5-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:c01be527ef4c91a6d55e53b337bfe2c0f82af024cc1a33c44792d6844e2331e1", size = 12932501, upload-time = "2025-11-13T19:58:29.822Z" },
+ { url = "https://files.pythonhosted.org/packages/67/d8/d86bf784d693a764b59479a6bbdc9515ae42c340a5dc5ab1dabef847bfaa/ruff-0.14.5-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:f66e9bb762e68d66e48550b59c74314168ebb46199886c5c5aa0b0fbcc81b151", size = 12927319, upload-time = "2025-11-13T19:58:32.923Z" },
+ { url = "https://files.pythonhosted.org/packages/ac/de/ee0b304d450ae007ce0cb3e455fe24fbcaaedae4ebaad6c23831c6663651/ruff-0.14.5-py3-none-musllinux_1_2_i686.whl", hash = "sha256:d93be8f1fa01022337f1f8f3bcaa7ffee2d0b03f00922c45c2207954f351f465", size = 13206209, upload-time = "2025-11-13T19:58:35.952Z" },
+ { url = "https://files.pythonhosted.org/packages/33/aa/193ca7e3a92d74f17d9d5771a765965d2cf42c86e6f0fd95b13969115723/ruff-0.14.5-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:c135d4b681f7401fe0e7312017e41aba9b3160861105726b76cfa14bc25aa367", size = 13953709, upload-time = "2025-11-13T19:58:39.002Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/f1/7119e42aa1d3bf036ffc9478885c2e248812b7de9abea4eae89163d2929d/ruff-0.14.5-py3-none-win32.whl", hash = "sha256:c83642e6fccfb6dea8b785eb9f456800dcd6a63f362238af5fc0c83d027dd08b", size = 12925808, upload-time = "2025-11-13T19:58:42.779Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/9d/7c0a255d21e0912114784e4a96bf62af0618e2190cae468cd82b13625ad2/ruff-0.14.5-py3-none-win_amd64.whl", hash = "sha256:9d55d7af7166f143c94eae1db3312f9ea8f95a4defef1979ed516dbb38c27621", size = 14331546, upload-time = "2025-11-13T19:58:45.691Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/80/69756670caedcf3b9be597a6e12276a6cf6197076eb62aad0c608f8efce0/ruff-0.14.5-py3-none-win_arm64.whl", hash = "sha256:4b700459d4649e2594b31f20a9de33bc7c19976d4746d8d0798ad959621d64a4", size = 13433331, upload-time = "2025-11-13T19:58:48.434Z" },
]
[[package]]