Skip to content

The agent engineering platform.

style(langchain): fix some ruff preview rules (#34663)

Christophe Bornetb4cd67ac1520
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index dc25f35ce1..0f1e55c28c 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -288,6 +288,9 @@ def _resolve_schema(schemas: set[type], schema_name: str, omit_flag: str | None
schema_name: Name for the generated `TypedDict`
omit_flag: If specified, omit fields with this flag set (`'input'` or
`'output'`)
+
+ Returns:
+ Merged schema as `TypedDict`
"""
all_annotations = {}
@@ -653,6 +656,9 @@ def create_agent(
Returns:
A compiled `StateGraph` that can be used for chat interactions.
+ Raises:
+ AssertionError: If duplicate middleware instances are provided.
+
The agent node calls the language model with the messages list (after applying
the system prompt). If the resulting [`AIMessage`][langchain.messages.AIMessage]
contains `tool_calls`, the graph will then call the tools. The tools node executes
@@ -984,6 +990,10 @@ def create_agent(
Tuple of `(bound_model, effective_response_format)` where
`effective_response_format` is the actual strategy used (may differ from
initial if auto-detected).
+
+ Raises:
+ ValueError: If middleware returned unknown client-side tool names.
+ ValueError: If `ToolStrategy` specifies tools not declared upfront.
"""
# Validate ONLY client-side tools that need to exist in tool_node
# Build map of available client-side tools from the ToolNode
diff --git a/libs/langchain_v1/langchain/agents/middleware/_redaction.py b/libs/langchain_v1/langchain/agents/middleware/_redaction.py
index 50a0b5e35d..e70fcba333 100644
--- a/libs/langchain_v1/langchain/agents/middleware/_redaction.py
+++ b/libs/langchain_v1/langchain/agents/middleware/_redaction.py
@@ -48,7 +48,14 @@ Detector = Callable[[str], list[PIIMatch]]
def detect_email(content: str) -> list[PIIMatch]:
- """Detect email addresses in content."""
+ """Detect email addresses in content.
+
+ Args:
+ content: The text content to scan for email addresses.
+
+ Returns:
+ A list of detected email matches.
+ """
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
return [
PIIMatch(
@@ -62,7 +69,14 @@ def detect_email(content: str) -> list[PIIMatch]:
def detect_credit_card(content: str) -> list[PIIMatch]:
- """Detect credit card numbers in content using Luhn validation."""
+ """Detect credit card numbers in content using Luhn validation.
+
+ Args:
+ content: The text content to scan for credit card numbers.
+
+ Returns:
+ A list of detected credit card matches.
+ """
pattern = r"\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b"
matches = []
@@ -82,7 +96,14 @@ def detect_credit_card(content: str) -> list[PIIMatch]:
def detect_ip(content: str) -> list[PIIMatch]:
- """Detect IPv4 or IPv6 addresses in content."""
+ """Detect IPv4 or IPv6 addresses in content.
+
+ Args:
+ content: The text content to scan for IP addresses.
+
+ Returns:
+ A list of detected IP address matches.
+ """
matches: list[PIIMatch] = []
ipv4_pattern = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"
@@ -105,7 +126,14 @@ def detect_ip(content: str) -> list[PIIMatch]:
def detect_mac_address(content: str) -> list[PIIMatch]:
- """Detect MAC addresses in content."""
+ """Detect MAC addresses in content.
+
+ Args:
+ content: The text content to scan for MAC addresses.
+
+ Returns:
+ A list of detected MAC address matches.
+ """
pattern = r"\b([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b"
return [
PIIMatch(
@@ -119,7 +147,14 @@ def detect_mac_address(content: str) -> list[PIIMatch]:
def detect_url(content: str) -> list[PIIMatch]:
- """Detect URLs in content using regex and stdlib validation."""
+ """Detect URLs in content using regex and stdlib validation.
+
+ Args:
+ content: The text content to scan for URLs.
+
+ Returns:
+ A list of detected URL matches.
+ """
matches: list[PIIMatch] = []
# Pattern 1: URLs with scheme (http:// or https://)
@@ -273,7 +308,20 @@ def apply_strategy(
matches: list[PIIMatch],
strategy: RedactionStrategy,
) -> str:
- """Apply the configured strategy to matches within content."""
+ """Apply the configured strategy to matches within content.
+
+ Args:
+ content: The content to apply strategy to.
+ matches: List of detected PII matches.
+ strategy: The redaction strategy to apply.
+
+ Returns:
+ The content with the strategy applied.
+
+ Raises:
+ PIIDetectionError: If the strategy is `'block'` and matches are found.
+ ValueError: If the strategy is unknown.
+ """
if not matches:
return content
if strategy == "redact":
@@ -289,7 +337,19 @@ def apply_strategy(
def resolve_detector(pii_type: str, detector: Detector | str | None) -> Detector:
- """Return a callable detector for the given configuration."""
+ """Return a callable detector for the given configuration.
+
+ Args:
+ pii_type: The PII type name.
+ detector: Optional custom detector or regex pattern. If `None`, a built-in detector
+ for the given PII type will be used.
+
+ Returns:
+ The resolved detector.
+
+ Raises:
+ ValueError: If an unknown PII type is specified without a custom detector or regex.
+ """
if detector is None:
if pii_type not in BUILTIN_DETECTORS:
msg = (
@@ -325,7 +385,11 @@ class RedactionRule:
detector: Detector | str | None = None
def resolve(self) -> ResolvedRedactionRule:
- """Resolve runtime detector and return an immutable rule."""
+ """Resolve runtime detector and return an immutable rule.
+
+ Returns:
+ The resolved redaction rule.
+ """
resolved_detector = resolve_detector(self.pii_type, self.detector)
return ResolvedRedactionRule(
pii_type=self.pii_type,
@@ -343,7 +407,14 @@ class ResolvedRedactionRule:
detector: Detector
def apply(self, content: str) -> tuple[str, list[PIIMatch]]:
- """Apply this rule to content, returning new content and matches."""
+ """Apply this rule to content, returning new content and matches.
+
+ Args:
+ content: The text content to scan and redact.
+
+ Returns:
+ A tuple of (updated content, list of detected matches).
+ """
matches = self.detector(content)
if not matches:
return content, []
diff --git a/libs/langchain_v1/langchain/agents/middleware/context_editing.py b/libs/langchain_v1/langchain/agents/middleware/context_editing.py
index f24202b99d..a7a0a8e603 100644
--- a/libs/langchain_v1/langchain/agents/middleware/context_editing.py
+++ b/libs/langchain_v1/langchain/agents/middleware/context_editing.py
@@ -152,8 +152,8 @@ class ClearToolUsesEdit(ContextEdit):
return
+ @staticmethod
def _build_cleared_tool_input_message(
- self,
message: AIMessage,
tool_call_id: str,
) -> AIMessage:
@@ -220,7 +220,16 @@ class ContextEditingMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
- """Apply context edits before invoking the model via handler."""
+ """Apply context edits before invoking the model via handler.
+
+ Args:
+ request: Model request to execute (includes state and runtime).
+ handler: Async callback that executes the model request and returns
+ `ModelResponse`.
+
+ Returns:
+ The result of invoking the handler with potentially edited messages.
+ """
if not request.messages:
return handler(request)
@@ -248,7 +257,16 @@ class ContextEditingMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
- """Apply context edits before invoking the model via handler (async version)."""
+ """Apply context edits before invoking the model via handler.
+
+ Args:
+ request: Model request to execute (includes state and runtime).
+ handler: Async callback that executes the model request and returns
+ `ModelResponse`.
+
+ Returns:
+ The result of invoking the handler with potentially edited messages.
+ """
if not request.messages:
return await handler(request)
diff --git a/libs/langchain_v1/langchain/agents/middleware/file_search.py b/libs/langchain_v1/langchain/agents/middleware/file_search.py
index 021a64bcf5..b6dcb77541 100644
--- a/libs/langchain_v1/langchain/agents/middleware/file_search.py
+++ b/libs/langchain_v1/langchain/agents/middleware/file_search.py
@@ -352,8 +352,8 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):
return results
+ @staticmethod
def _format_grep_results(
- self,
results: dict[str, list[tuple[int, str]]],
output_mode: str,
) -> str:
diff --git a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py
index 82f5f0e449..3547bc83f2 100644
--- a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py
+++ b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py
@@ -235,8 +235,8 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT]):
return action_request, review_config
+ @staticmethod
def _process_decision(
- self,
decision: Decision,
tool_call: ToolCall,
config: InterruptOnConfig,
@@ -278,7 +278,19 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT]):
raise ValueError(msg)
def after_model(self, state: AgentState, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
- """Trigger interrupt flows for relevant tool calls after an `AIMessage`."""
+ """Trigger interrupt flows for relevant tool calls after an `AIMessage`.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Updated message with the revised tool calls.
+
+ Raises:
+ ValueError: If the number of human decisions does not match the number of
+ interrupted tool calls.
+ """
messages = state["messages"]
if not messages:
return None
@@ -353,5 +365,13 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT]):
async def aafter_model(
self, state: AgentState, runtime: Runtime[ContextT]
) -> dict[str, Any] | None:
- """Async trigger interrupt flows for relevant tool calls after an `AIMessage`."""
+ """Async trigger interrupt flows for relevant tool calls after an `AIMessage`.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Updated message with the revised tool calls.
+ """
return self.after_model(state, runtime)
diff --git a/libs/langchain_v1/langchain/agents/middleware/model_retry.py b/libs/langchain_v1/langchain/agents/middleware/model_retry.py
index 4de836ed2d..86e971544e 100644
--- a/libs/langchain_v1/langchain/agents/middleware/model_retry.py
+++ b/libs/langchain_v1/langchain/agents/middleware/model_retry.py
@@ -163,7 +163,8 @@ class ModelRetryMiddleware(AgentMiddleware):
self.max_delay = max_delay
self.jitter = jitter
- def _format_failure_message(self, exc: Exception, attempts_made: int) -> AIMessage:
+ @staticmethod
+ def _format_failure_message(exc: Exception, attempts_made: int) -> AIMessage:
"""Format the failure message when retries are exhausted.
Args:
@@ -218,6 +219,9 @@ class ModelRetryMiddleware(AgentMiddleware):
Returns:
`ModelResponse` or `AIMessage` (the final result).
+
+ Raises:
+ RuntimeError: If the retry loop completes without returning. (This should not happen.)
"""
# Initial attempt + retries
for attempt in range(self.max_retries + 1):
@@ -265,6 +269,9 @@ class ModelRetryMiddleware(AgentMiddleware):
Returns:
`ModelResponse` or `AIMessage` (the final result).
+
+ Raises:
+ RuntimeError: If the retry loop completes without returning. (This should not happen.)
"""
# Initial attempt + retries
for attempt in range(self.max_retries + 1):
diff --git a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
index 3bb2133148..9b7b756fa7 100644
--- a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
+++ b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
@@ -134,7 +134,11 @@ class ShellSession:
self._terminated = False
def start(self) -> None:
- """Start the shell subprocess and reader threads."""
+ """Start the shell subprocess and reader threads.
+
+ Raises:
+ RuntimeError: If the shell session pipes cannot be initialized.
+ """
if self._process and self._process.poll() is None:
return
@@ -611,12 +615,28 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
@override
def before_agent(self, state: ShellToolState, runtime: Runtime) -> dict[str, Any] | None:
- """Start the shell session and run startup commands."""
+ """Start the shell session and run startup commands.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Shell session resources to be stored in the agent state.
+ """
resources = self._get_or_create_resources(state)
return {"shell_session_resources": resources}
async def abefore_agent(self, state: ShellToolState, runtime: Runtime) -> dict[str, Any] | None:
- """Async start the shell session and run startup commands."""
+ """Async start the shell session and run startup commands.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Shell session resources to be stored in the agent state.
+ """
return self.before_agent(state, runtime)
@override
diff --git a/libs/langchain_v1/langchain/agents/middleware/summarization.py b/libs/langchain_v1/langchain/agents/middleware/summarization.py
index b3533c2eb6..d3546c65bb 100644
--- a/libs/langchain_v1/langchain/agents/middleware/summarization.py
+++ b/libs/langchain_v1/langchain/agents/middleware/summarization.py
@@ -270,7 +270,15 @@ class SummarizationMiddleware(AgentMiddleware):
@override
def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
- """Process messages before model invocation, potentially triggering summarization."""
+ """Process messages before model invocation, potentially triggering summarization.
+
+ Args:
+ state: The agent state.
+ runtime: The runtime environment.
+
+ Returns:
+ An updated state with summarized messages if summarization was performed.
+ """
messages = state["messages"]
self._ensure_message_ids(messages)
@@ -298,7 +306,15 @@ class SummarizationMiddleware(AgentMiddleware):
@override
async def abefore_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
- """Process messages before model invocation, potentially triggering summarization."""
+ """Process messages before model invocation, potentially triggering summarization.
+
+ Args:
+ state: The agent state.
+ runtime: The runtime environment.
+
+ Returns:
+ An updated state with summarized messages if summarization was performed.
+ """
messages = state["messages"]
self._ensure_message_ids(messages)
@@ -449,7 +465,8 @@ class SummarizationMiddleware(AgentMiddleware):
return max_input_tokens
- def _validate_context_size(self, context: ContextSize, parameter_name: str) -> ContextSize:
+ @staticmethod
+ def _validate_context_size(context: ContextSize, parameter_name: str) -> ContextSize:
"""Validate context configuration tuples."""
kind, value = context
if kind == "fraction":
@@ -465,19 +482,21 @@ class SummarizationMiddleware(AgentMiddleware):
raise ValueError(msg)
return context
- def _build_new_messages(self, summary: str) -> list[HumanMessage]:
+ @staticmethod
+ def _build_new_messages(summary: str) -> list[HumanMessage]:
return [
HumanMessage(content=f"Here is a summary of the conversation to date:\n\n{summary}")
]
- def _ensure_message_ids(self, messages: list[AnyMessage]) -> None:
+ @staticmethod
+ def _ensure_message_ids(messages: list[AnyMessage]) -> None:
"""Ensure all messages have unique IDs for the add_messages reducer."""
for msg in messages:
if msg.id is None:
msg.id = str(uuid.uuid4())
+ @staticmethod
def _partition_messages(
- self,
conversation_messages: list[AnyMessage],
cutoff_index: int,
) -> tuple[list[AnyMessage], list[AnyMessage]]:
@@ -502,7 +521,8 @@ class SummarizationMiddleware(AgentMiddleware):
target_cutoff = len(messages) - messages_to_keep
return self._find_safe_cutoff_point(messages, target_cutoff)
- def _find_safe_cutoff_point(self, messages: list[AnyMessage], cutoff_index: int) -> int:
+ @staticmethod
+ def _find_safe_cutoff_point(messages: list[AnyMessage], cutoff_index: int) -> int:
"""Find a safe cutoff point that doesn't split AI/Tool message pairs.
If the message at `cutoff_index` is a `ToolMessage`, search backward for the
diff --git a/libs/langchain_v1/langchain/agents/middleware/todo.py b/libs/langchain_v1/langchain/agents/middleware/todo.py
index f3df233021..564622d6fe 100644
--- a/libs/langchain_v1/langchain/agents/middleware/todo.py
+++ b/libs/langchain_v1/langchain/agents/middleware/todo.py
@@ -12,7 +12,7 @@ if TYPE_CHECKING:
from langchain_core.messages import AIMessage, SystemMessage, ToolMessage
from langchain_core.tools import tool
from langgraph.types import Command
-from typing_extensions import NotRequired, TypedDict
+from typing_extensions import NotRequired, TypedDict, override
from langchain.agents.middleware.types import (
AgentMiddleware,
@@ -196,7 +196,16 @@ class TodoListMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
- """Update the system message to include the todo system prompt."""
+ """Update the system message to include the todo system prompt.
+
+ Args:
+ request: Model request to execute (includes state and runtime).
+ handler: Async callback that executes the model request and returns
+ `ModelResponse`.
+
+ Returns:
+ The model call result.
+ """
if request.system_message is not None:
new_system_content = [
*request.system_message.content_blocks,
@@ -214,7 +223,16 @@ class TodoListMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
- """Update the system message to include the todo system prompt (async version)."""
+ """Update the system message to include the todo system prompt.
+
+ Args:
+ request: Model request to execute (includes state and runtime).
+ handler: Async callback that executes the model request and returns
+ `ModelResponse`.
+
+ Returns:
+ The model call result.
+ """
if request.system_message is not None:
new_system_content = [
*request.system_message.content_blocks,
@@ -227,10 +245,11 @@ class TodoListMiddleware(AgentMiddleware):
)
return await handler(request.override(system_message=new_system_message))
+ @override
def after_model(
self,
state: AgentState,
- runtime: Runtime, # noqa: ARG002
+ runtime: Runtime,
) -> dict[str, Any] | None:
"""Check for parallel write_todos tool calls and return errors if detected.
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py b/libs/langchain_v1/langchain/agents/middleware/tool_retry.py
index ee91053a8f..cf60ff9785 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_retry.py
@@ -233,7 +233,8 @@ class ToolRetryMiddleware(AgentMiddleware):
return True
return tool_name in self._tool_filter
- def _format_failure_message(self, tool_name: str, exc: Exception, attempts_made: int) -> str:
+ @staticmethod
+ def _format_failure_message(tool_name: str, exc: Exception, attempts_made: int) -> str:
"""Format the failure message when retries are exhausted.
Args:
@@ -297,6 +298,9 @@ class ToolRetryMiddleware(AgentMiddleware):
Returns:
`ToolMessage` or `Command` (the final result).
+
+ Raises:
+ RuntimeError: If the retry loop completes without returning. This should not happen.
"""
tool_name = request.tool.name if request.tool else request.tool_call["name"]
@@ -353,6 +357,9 @@ class ToolRetryMiddleware(AgentMiddleware):
Returns:
`ToolMessage` or `Command` (the final result).
+
+ Raises:
+ RuntimeError: If the retry loop completes without returning. This should not happen.
"""
tool_name = request.tool.name if request.tool else request.tool_call["name"]
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py b/libs/langchain_v1/langchain/agents/middleware/tool_selection.py
index 12740ffc80..24a2c79bde 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_selection.py
@@ -51,6 +51,9 @@ def _create_tool_selection_response(tools: list[BaseTool]) -> TypeAdapter:
Returns:
`TypeAdapter` for a schema where each tool name is a `Literal` with its
description.
+
+ Raises:
+ AssertionError: If `tools` is empty.
"""
if not tools:
msg = "Invalid usage: tools must be non-empty"
@@ -153,9 +156,16 @@ class LLMToolSelectorMiddleware(AgentMiddleware):
def _prepare_selection_request(self, request: ModelRequest) -> _SelectionRequest | None:
"""Prepare inputs for tool selection.
+ Args:
+ request: the model request.
+
Returns:
`SelectionRequest` with prepared inputs, or `None` if no selection is
- needed.
+ needed.
+
+ Raises:
+ ValueError: If tools in `always_include` are not found in the request.
+ AssertionError: If no user message is found in the request messages.
"""
# If no tools available, return None
if not request.tools or len(request.tools) == 0:
@@ -262,7 +272,19 @@ class LLMToolSelectorMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
- """Filter tools based on LLM selection before invoking the model via handler."""
+ """Filter tools based on LLM selection before invoking the model via handler.
+
+ Args:
+ request: Model request to execute (includes state and runtime).
+ handler: Async callback that executes the model request and returns
+ `ModelResponse`.
+
+ Returns:
+ The model call result.
+
+ Raises:
+ AssertionError: If the selection model response is not a dict.
+ """
selection_request = self._prepare_selection_request(request)
if selection_request is None:
return handler(request)
@@ -293,7 +315,19 @@ class LLMToolSelectorMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
- """Filter tools based on LLM selection before invoking the model via handler."""
+ """Filter tools based on LLM selection before invoking the model via handler.
+
+ Args:
+ request: Model request to execute (includes state and runtime).
+ handler: Async callback that executes the model request and returns
+ `ModelResponse`.
+
+ Returns:
+ The model call result.
+
+ Raises:
+ AssertionError: If the selection model response is not a dict.
+ """
selection_request = self._prepare_selection_request(request)
if selection_request is None:
return await handler(request)
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index 0a953ad276..07bda3b306 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -124,6 +124,9 @@ class ModelRequest:
model_settings: Additional model settings.
system_message: System message instance (preferred).
system_prompt: System prompt string (deprecated, converted to SystemMessage).
+
+ Raises:
+ ValueError: If both `system_prompt` and `system_message` are provided.
"""
# Handle system_prompt/system_message conversion and validation
if system_prompt is not None and system_message is not None:
@@ -239,6 +242,9 @@ class ModelRequest:
system_message=SystemMessage(content="New instructions"),
)
```
+
+ Raises:
+ ValueError: If both `system_prompt` and `system_message` are provided.
"""
# Handle system_prompt/system_message conversion
if "system_prompt" in overrides and "system_message" in overrides:
@@ -352,35 +358,74 @@ class AgentMiddleware(Generic[StateT, ContextT]):
def before_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
"""Logic to run before the agent execution starts.
- Async version is `abefore_agent`
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply before agent execution.
"""
async def abefore_agent(
self, state: StateT, runtime: Runtime[ContextT]
) -> dict[str, Any] | None:
- """Async logic to run before the agent execution starts."""
+ """Async logic to run before the agent execution starts.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply before agent execution.
+ """
def before_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
"""Logic to run before the model is called.
- Async version is `abefore_model`
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply before model call.
"""
async def abefore_model(
self, state: StateT, runtime: Runtime[ContextT]
) -> dict[str, Any] | None:
- """Async logic to run before the model is called."""
+ """Async logic to run before the model is called.
+
+ Args:
+ state: The agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply before model call.
+ """
def after_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
"""Logic to run after the model is called.
- Async version is `aafter_model`
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply after model call.
"""
async def aafter_model(
self, state: StateT, runtime: Runtime[ContextT]
) -> dict[str, Any] | None:
- """Async logic to run after the model is called."""
+ """Async logic to run after the model is called.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply after model call.
+ """
def wrap_model_call(
self,
@@ -408,7 +453,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
Can skip calling it to short-circuit.
Returns:
- `ModelCallResult`
+ The model call result.
Examples:
!!! example "Retry on error"
@@ -502,7 +547,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
Can skip calling it to short-circuit.
Returns:
- `ModelCallResult`
+ The model call result.
Examples:
!!! example "Retry on error"
@@ -530,12 +575,28 @@ class AgentMiddleware(Generic[StateT, ContextT]):
raise NotImplementedError(msg)
def after_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
- """Logic to run after the agent execution completes."""
+ """Logic to run after the agent execution completes.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply after agent execution.
+ """
async def aafter_agent(
self, state: StateT, runtime: Runtime[ContextT]
) -> dict[str, Any] | None:
- """Async logic to run after the agent execution completes."""
+ """Async logic to run after the agent execution completes.
+
+ Args:
+ state: The current agent state.
+ runtime: The runtime context.
+
+ Returns:
+ Agent state updates to apply after agent execution.
+ """
def wrap_tool_call(
self,
diff --git a/libs/langchain_v1/langchain/agents/structured_output.py b/libs/langchain_v1/langchain/agents/structured_output.py
index ed9751942a..d3c73cdb5a 100644
--- a/libs/langchain_v1/langchain/agents/structured_output.py
+++ b/libs/langchain_v1/langchain/agents/structured_output.py
@@ -140,7 +140,17 @@ class _SchemaSpec(Generic[SchemaT]):
description: str | None = None,
strict: bool | None = None,
) -> None:
- """Initialize SchemaSpec with schema and optional parameters."""
+ """Initialize `SchemaSpec` with schema and optional parameters.
+
+ Args:
+ schema: Schema to describe.
+ name: Optional name for the schema.
+ description: Optional description for the schema.
+ strict: Whether to enforce strict validation of the schema.
+
+ Raises:
+ ValueError: If the schema type is unsupported.
+ """
self.schema = schema
if name:
@@ -269,7 +279,11 @@ class ProviderStrategy(Generic[SchemaT]):
self.schema_spec = _SchemaSpec(schema, strict=strict)
def to_model_kwargs(self) -> dict[str, Any]:
- """Convert to kwargs to bind to a model to force structured output."""
+ """Convert to kwargs to bind to a model to force structured output.
+
+ Returns:
+ The kwargs to bind to a model.
+ """
# OpenAI:
# - see https://platform.openai.com/docs/guides/structured-outputs
json_schema: dict[str, Any] = {
@@ -399,7 +413,8 @@ class ProviderStrategyBinding(Generic[SchemaT]):
# Parse according to schema
return _parse_with_schema(self.schema, self.schema_kind, data)
- def _extract_text_content_from_message(self, message: AIMessage) -> str:
+ @staticmethod
+ def _extract_text_content_from_message(message: AIMessage) -> str:
"""Extract text content from an AIMessage.
Args:
diff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.py
index 7bd12911c6..940023caaf 100644
--- a/libs/langchain_v1/langchain/chat_models/base.py
+++ b/libs/langchain_v1/langchain/chat_models/base.py
@@ -652,7 +652,6 @@ class _ConfigurableModel(Runnable[LanguageModelInput, Any]):
config: RunnableConfig | None = None,
**kwargs: Any,
) -> _ConfigurableModel:
- """Bind config to a `Runnable`, returning a new `Runnable`."""
config = RunnableConfig(**(config or {}), **cast("RunnableConfig", kwargs))
# Ensure config is not None after creation
config = ensure_config(config)
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 a68f9b44d7..b6fe29e793 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
@@ -702,7 +702,7 @@ def test_dynamic_prompt_integration() -> None:
assert result["messages"][-1].content == "you are a helpful assistant.-Hello"
-async def test_async_dynamic_prompt_decorator() -> None:
+def test_async_dynamic_prompt_decorator() -> None:
"""Test dynamic_prompt decorator with async function."""
@dynamic_prompt
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 ff44c45022..382ce12026 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
@@ -305,9 +305,11 @@ 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'}]"
+ ),
),
(
[
@@ -315,10 +317,12 @@ 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'}]"
+ ),
),
],
)
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 bfc5a21519..2103f107d6 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
@@ -181,7 +181,7 @@ async def test_tool_invocation_error_excludes_injected_state_async() -> None:
@pytest.mark.skipif(
sys.version_info >= (3, 14), reason="Pydantic model rebuild issue in Python 3.14"
)
-async def test_create_agent_error_content_with_multiple_params() -> None:
+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
@@ -301,7 +301,7 @@ async def test_create_agent_error_content_with_multiple_params() -> None:
@pytest.mark.skipif(
sys.version_info >= (3, 14), reason="Pydantic model rebuild issue in Python 3.14"
)
-async def test_create_agent_error_only_model_controllable_params() -> None:
+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