The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(langchain): pass on reference docstrings (middleware) (#33904)
Mason Daugherty1996d81d72f7
diff --git a/libs/langchain/langchain_classic/chat_models/base.py b/libs/langchain/langchain_classic/chat_models/base.pyindex 098304ce50..03be5b2718 100644--- a/libs/langchain/langchain_classic/chat_models/base.py+++ b/libs/langchain/langchain_classic/chat_models/base.py@@ -100,6 +100,21 @@ def init_chat_model(You can also specify model and model provider in a single argument using`'{model_provider}:{model}'` format, e.g. `'openai:o1'`.++ Will attempt to infer `model_provider` from model if not specified.++ The following providers will be inferred based on these model prefixes:++ - `gpt-...` | `o1...` | `o3...` -> `openai`+ - `claude...` -> `anthropic`+ - `amazon...` -> `bedrock`+ - `gemini...` -> `google_vertexai`+ - `command...` -> `cohere`+ - `accounts/fireworks...` -> `fireworks`+ - `mistral...` -> `mistralai`+ - `deepseek...` -> `deepseek`+ - `grok...` -> `xai`+ - `sonar...` -> `perplexity`model_provider: The model provider if not specified as part of the model arg(see above).@@ -127,20 +142,6 @@ def init_chat_model(- `nvidia` -> [`langchain-nvidia-ai-endpoints`](https://docs.langchain.com/oss/python/integrations/providers/nvidia)- `xai` -> [`langchain-xai`](https://docs.langchain.com/oss/python/integrations/providers/xai)- `perplexity` -> [`langchain-perplexity`](https://docs.langchain.com/oss/python/integrations/providers/perplexity)-- Will attempt to infer `model_provider` from model if not specified. The- following providers will be inferred based on these model prefixes:-- - `gpt-...` | `o1...` | `o3...` -> `openai`- - `claude...` -> `anthropic`- - `amazon...` -> `bedrock`- - `gemini...` -> `google_vertexai`- - `command...` -> `cohere`- - `accounts/fireworks...` -> `fireworks`- - `mistral...` -> `mistralai`- - `deepseek...` -> `deepseek`- - `grok...` -> `xai`- - `sonar...` -> `perplexity`configurable_fields: Which model parameters are configurable at runtime:- `None`: No configurable fields (i.e., a fixed model).@@ -155,6 +156,7 @@ def init_chat_model(If `model` is not specified, then defaults to `("model", "model_provider")`.!!! warning "Security note"+Setting `configurable_fields="any"` means fields like `api_key`,`base_url`, etc., can be altered at runtime, potentially redirectingmodel requests to a different service/user.diff --git a/libs/langchain_v1/langchain/agents/__init__.py b/libs/langchain_v1/langchain/agents/__init__.pyindex 67ac01b1ac..5e5c545fe2 100644--- a/libs/langchain_v1/langchain/agents/__init__.py+++ b/libs/langchain_v1/langchain/agents/__init__.py@@ -1,10 +1,4 @@-"""Entrypoint to building [Agents](https://docs.langchain.com/oss/python/langchain/agents) with LangChain.--!!! warning "Reference docs"- This page contains **reference documentation** for Agents. See- [the docs](https://docs.langchain.com/oss/python/langchain/agents) for conceptual- guides, tutorials, and examples on using Agents.-""" # noqa: E501+"""Entrypoint to building [Agents](https://docs.langchain.com/oss/python/langchain/agents) with LangChain.""" # noqa: E501from langchain.agents.factory import create_agentfrom langchain.agents.middleware.types import AgentStatediff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.pyindex f2229b0902..af02e587d6 100644--- a/libs/langchain_v1/langchain/agents/factory.py+++ b/libs/langchain_v1/langchain/agents/factory.py@@ -537,17 +537,29 @@ def create_agent( # noqa: PLR0915visit the [Agents](https://docs.langchain.com/oss/python/langchain/agents) docs.Args:- model: The language model for the agent. Can be a string identifier- (e.g., `"openai:gpt-4"`) or a direct chat model instance (e.g.,- [`ChatOpenAI`][langchain_openai.ChatOpenAI] or other another- [chat model](https://docs.langchain.com/oss/python/integrations/chat)).+ model: The language model for the agent.++ Can be a string identifier (e.g., `"openai:gpt-4"`) or a direct chat model+ instance (e.g., [`ChatOpenAI`][langchain_openai.ChatOpenAI] or other another+ [LangChain chat model](https://docs.langchain.com/oss/python/integrations/chat)).For a full list of supported model strings, see[`init_chat_model`][langchain.chat_models.init_chat_model(model_provider)].- tools: A list of tools, `dicts`, or `Callable`.++ !!! tip ""++ See the [Models](https://docs.langchain.com/oss/python/langchain/models)+ docs for more information.+ tools: A list of tools, `dict`, or `Callable`.If `None` or an empty list, the agent will consist of a model node without atool calling loop.+++ !!! tip ""++ See the [Tools](https://docs.langchain.com/oss/python/langchain/tools)+ docs for more information.system_prompt: An optional system prompt for the LLM.Prompts are converted to a@@ -555,24 +567,34 @@ def create_agent( # noqa: PLR0915beginning of the message list.middleware: A sequence of middleware instances to apply to the agent.- Middleware can intercept and modify agent behavior at various stages. See- the [full guide](https://docs.langchain.com/oss/python/langchain/middleware).+ Middleware can intercept and modify agent behavior at various stages.++ !!! tip ""++ See the [Middleware](https://docs.langchain.com/oss/python/langchain/middleware)+ docs for more information.response_format: An optional configuration for structured responses.Can be a `ToolStrategy`, `ProviderStrategy`, or a Pydantic model class.If provided, the agent will handle structured output during the- conversation flow. Raw schemas will be wrapped in an appropriate strategy- based on model capabilities.+ conversation flow.++ Raw schemas will be wrapped in an appropriate strategy based on model+ capabilities.++ !!! tip ""++ See the [Structured output](https://docs.langchain.com/oss/python/langchain/structured-output)+ docs for more information.state_schema: An optional `TypedDict` schema that extends `AgentState`.When provided, this schema is used instead of `AgentState` as the baseschema for merging with middleware state schemas. This allows users toadd custom state fields without needing to create custom middleware.+Generally, it's recommended to use `state_schema` extensions via middlewareto keep relevant extensions scoped to corresponding hooks / tools.-- The schema must be a subclass of `AgentState[ResponseT]`.context_schema: An optional schema for runtime context.checkpointer: An optional checkpoint saver object.diff --git a/libs/langchain_v1/langchain/agents/middleware/__init__.py b/libs/langchain_v1/langchain/agents/middleware/__init__.pyindex 8ed35aafcd..2399db7c22 100644--- a/libs/langchain_v1/langchain/agents/middleware/__init__.py+++ b/libs/langchain_v1/langchain/agents/middleware/__init__.py@@ -1,10 +1,4 @@-"""Entrypoint to using [Middleware](https://docs.langchain.com/oss/python/langchain/middleware) plugins with [Agents](https://docs.langchain.com/oss/python/langchain/agents).--!!! warning "Reference docs"- This page contains **reference documentation** for Middleware. See- [the docs](https://docs.langchain.com/oss/python/langchain/middleware) for conceptual- guides, tutorials, and examples on using Middleware.-""" # noqa: E501+"""Entrypoint to using [middleware](https://docs.langchain.com/oss/python/langchain/middleware) plugins with [Agents](https://docs.langchain.com/oss/python/langchain/agents).""" # noqa: E501from .context_editing import (ClearToolUsesEdit,diff --git a/libs/langchain_v1/langchain/agents/middleware/_execution.py b/libs/langchain_v1/langchain/agents/middleware/_execution.pyindex f14235bf62..e01f7acc45 100644--- a/libs/langchain_v1/langchain/agents/middleware/_execution.py+++ b/libs/langchain_v1/langchain/agents/middleware/_execution.py@@ -56,11 +56,12 @@ class BaseExecutionPolicy(abc.ABC):"""Configuration contract for persistent shell sessions.Concrete subclasses encapsulate how a shell process is launched and constrained.+Each policy documents its security guarantees and the operating environments in- which it is appropriate. Use :class:`HostExecutionPolicy` for trusted, same-host- execution; :class:`CodexSandboxExecutionPolicy` when the Codex CLI sandbox is- available and you want additional syscall restrictions; and- :class:`DockerExecutionPolicy` for container-level isolation using Docker.+ which it is appropriate. Use `HostExecutionPolicy` for trusted, same-host execution;+ `CodexSandboxExecutionPolicy` when the Codex CLI sandbox is available and you want+ additional syscall restrictions; and `DockerExecutionPolicy` for container-level+ isolation using Docker."""command_timeout: float = 30.0@@ -91,13 +92,13 @@ class HostExecutionPolicy(BaseExecutionPolicy):This policy is best suited for trusted or single-tenant environments (CI jobs,developer workstations, pre-sandboxed containers) where the agent must access the- host filesystem and tooling without additional isolation. It enforces optional CPU- and memory limits to prevent runaway commands but offers **no** filesystem or network+ host filesystem and tooling without additional isolation. Enforces optional CPU and+ memory limits to prevent runaway commands but offers **no** filesystem or networksandboxing; commands can modify anything the process user can reach.- On Linux platforms resource limits are applied with ``resource.prlimit`` after the- shell starts. On macOS, where ``prlimit`` is unavailable, limits are set in a- ``preexec_fn`` before ``exec``. In both cases the shell runs in its own process group+ On Linux platforms resource limits are applied with `resource.prlimit` after the+ shell starts. On macOS, where `prlimit` is unavailable, limits are set in a+ `preexec_fn` before `exec`. In both cases the shell runs in its own process groupso timeouts can terminate the full subtree."""@@ -199,9 +200,9 @@ class CodexSandboxExecutionPolicy(BaseExecutionPolicy):(Linux) profiles. Commands still run on the host, but within the sandbox requested bythe CLI. If the Codex binary is unavailable or the runtime lacks the requiredkernel features (e.g., Landlock inside some containers), process startup fails with a- :class:`RuntimeError`.+ `RuntimeError`.- Configure sandbox behaviour via ``config_overrides`` to align with your Codex CLI+ Configure sandbox behavior via `config_overrides` to align with your Codex CLIprofile. This policy does not add its own resource limits; combine it withhost-level guards (cgroups, container resource limits) as needed."""@@ -271,17 +272,17 @@ class DockerExecutionPolicy(BaseExecutionPolicy):"""Run the shell inside a dedicated Docker container.Choose this policy when commands originate from untrusted users or you require- strong isolation between sessions. By default the workspace is bind-mounted only when- it refers to an existing non-temporary directory; ephemeral sessions run without a- mount to minimise host exposure. The container's network namespace is disabled by- default (``--network none``) and you can enable further hardening via- ``read_only_rootfs`` and ``user``.+ strong isolation between sessions. By default the workspace is bind-mounted only+ when it refers to an existing non-temporary directory; ephemeral sessions run+ without a mount to minimise host exposure. The container's network namespace is+ disabled by default (`--network none`) and you can enable further hardening via+ `read_only_rootfs` and `user`.The security guarantees depend on your Docker daemon configuration. Run the agent on- a host where Docker is locked down (rootless mode, AppArmor/SELinux, etc.) and review- any additional volumes or capabilities passed through ``extra_run_args``. The default- image is ``python:3.12-alpine3.19``; supply a custom image if you need preinstalled- tooling.+ a host where Docker is locked down (rootless mode, AppArmor/SELinux, etc.) and+ review any additional volumes or capabilities passed through ``extra_run_args``. The+ default image is `python:3.12-alpine3.19`; supply a custom image if you need+ preinstalled tooling."""binary: str = "docker"diff --git a/libs/langchain_v1/langchain/agents/middleware/context_editing.py b/libs/langchain_v1/langchain/agents/middleware/context_editing.pyindex 3623d1872c..29fcd99154 100644--- a/libs/langchain_v1/langchain/agents/middleware/context_editing.py+++ b/libs/langchain_v1/langchain/agents/middleware/context_editing.py@@ -1,9 +1,10 @@"""Context editing middleware.-This middleware mirrors Anthropic's context editing capabilities by clearing-older tool results once the conversation grows beyond a configurable token-threshold. The implementation is intentionally model-agnostic so it can be used-with any LangChain chat model.+Mirrors Anthropic's context editing capabilities by clearing older tool results once the+conversation grows beyond a configurable token threshold.++The implementation is intentionally model-agnostic so it can be used with any LangChain+chat model."""from __future__ import annotations@@ -182,11 +183,13 @@ class ClearToolUsesEdit(ContextEdit):class ContextEditingMiddleware(AgentMiddleware):- """Automatically prunes tool results to manage context size.+ """Automatically prune tool results to manage context size.++ The middleware applies a sequence of edits when the total input token count exceeds+ configured thresholds.- The middleware applies a sequence of edits when the total input token count- exceeds configured thresholds. Currently the `ClearToolUsesEdit` strategy is- supported, aligning with Anthropic's `clear_tool_uses_20250919` behaviour.+ Currently the `ClearToolUsesEdit` strategy is supported, aligning with Anthropic's+ `clear_tool_uses_20250919` behavior [(read more)](https://docs.claude.com/en/docs/agents-and-tools/tool-use/memory-tool)."""edits: list[ContextEdit]@@ -198,11 +201,12 @@ class ContextEditingMiddleware(AgentMiddleware):edits: Iterable[ContextEdit] | None = None,token_count_method: Literal["approximate", "model"] = "approximate", # noqa: S107) -> None:- """Initializes a context editing middleware instance.+ """Initialize an instance of context editing middleware.Args:- edits: Sequence of edit strategies to apply. Defaults to a single- `ClearToolUsesEdit` mirroring Anthropic defaults.+ edits: Sequence of edit strategies to apply.++ Defaults to a single `ClearToolUsesEdit` mirroring Anthropic defaults.token_count_method: Whether to use approximate token counting(faster, less accurate) or exact counting implemented by thechat model (potentially slower, more accurate).diff --git a/libs/langchain_v1/langchain/agents/middleware/file_search.py b/libs/langchain_v1/langchain/agents/middleware/file_search.pyindex fe9efc60b0..2c099f780a 100644--- a/libs/langchain_v1/langchain/agents/middleware/file_search.py+++ b/libs/langchain_v1/langchain/agents/middleware/file_search.py@@ -21,7 +21,7 @@ from langchain.agents.middleware.types import AgentMiddlewaredef _expand_include_patterns(pattern: str) -> list[str] | None:- """Expand brace patterns like ``*.{py,pyi}`` into a list of globs."""+ """Expand brace patterns like `*.{py,pyi}` into a list of globs."""if "}" in pattern and "{" not in pattern:return None@@ -88,6 +88,7 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):"""Provides Glob and Grep search over filesystem files.This middleware adds two tools that search through local filesystem:+- Glob: Fast file pattern matching by file path- Grep: Fast content search using ripgrep or Python fallback@@ -100,7 +101,7 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):agent = create_agent(model=model,- tools=[],+ tools=[], # Add tools as neededmiddleware=[FilesystemFileSearchMiddleware(root_path="/workspace"),],@@ -119,9 +120,10 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):Args:root_path: Root directory to search.- use_ripgrep: Whether to use ripgrep for search (default: True).+ use_ripgrep: Whether to use ripgrep for search.+Falls back to Python if ripgrep unavailable.- max_file_size_mb: Maximum file size to search in MB (default: 10).+ max_file_size_mb: Maximum file size to search in MB."""self.root_path = Path(root_path).resolve()self.use_ripgrep = use_ripgrep@@ -132,8 +134,10 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):def glob_search(pattern: str, path: str = "/") -> str:"""Fast file pattern matching tool that works with any codebase size.- Supports glob patterns like **/*.js or src/**/*.ts.+ Supports glob patterns like `**/*.js` or `src/**/*.ts`.+Returns matching file paths sorted by modification time.+Use this tool when you need to find files by name patterns.Args:@@ -142,7 +146,7 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):Returns:Newline-separated list of matching file paths, sorted by modification- time (most recently modified first). Returns "No files found" if no+ time (most recently modified first). Returns `'No files found'` if nomatches."""try:@@ -184,15 +188,16 @@ class FilesystemFileSearchMiddleware(AgentMiddleware):Args:pattern: The regular expression pattern to search for in file contents.path: The directory to search in. If not specified, searches from root.- include: File pattern to filter (e.g., "*.js", "*.{ts,tsx}").+ include: File pattern to filter (e.g., `'*.js'`, `'*.{ts,tsx}'`).output_mode: Output format:- - "files_with_matches": Only file paths containing matches (default)- - "content": Matching lines with file:line:content format- - "count": Count of matches per file++ - `'files_with_matches'`: Only file paths containing matches+ - `'content'`: Matching lines with `file:line:content` format+ - `'count'`: Count of matches per fileReturns:- Search results formatted according to output_mode. Returns "No matches- found" if no results.+ Search results formatted according to `output_mode`.+ Returns `'No matches found'` if no results."""# Compile regex pattern (for validation)try: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.pyindex cc1a4f2df3..a7c21b0c8e 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@@ -14,10 +14,10 @@ class Action(TypedDict):"""Represents an action with a name and args."""name: str- """The type or name of action being requested (e.g., "add_numbers")."""+ """The type or name of action being requested (e.g., `'add_numbers'`)."""args: dict[str, Any]- """Key-value pairs of args needed for the action (e.g., {"a": 1, "b": 2})."""+ """Key-value pairs of args needed for the action (e.g., `{"a": 1, "b": 2}`)."""class ActionRequest(TypedDict):@@ -27,7 +27,7 @@ class ActionRequest(TypedDict):"""The name of the action being requested."""args: dict[str, Any]- """Key-value pairs of args needed for the action (e.g., {"a": 1, "b": 2})."""+ """Key-value pairs of args needed for the action (e.g., `{"a": 1, "b": 2}`)."""description: NotRequired[str]"""The description of the action to be reviewed."""@@ -169,18 +169,22 @@ class HumanInTheLoopMiddleware(AgentMiddleware):Args:interrupt_on: Mapping of tool name to allowed actions.+If a tool doesn't have an entry, it's auto-approved by default.* `True` indicates all decisions are allowed: approve, edit, and reject.* `False` indicates that the tool is auto-approved.* `InterruptOnConfig` indicates the specific decisions allowed for thistool.- The InterruptOnConfig can include a `description` field (`str` or++ The `InterruptOnConfig` can include a `description` field (`str` or`Callable`) for custom formatting of the interrupt description.description_prefix: The prefix to use when constructing action requests.+This is used to provide context about the tool call and the action being- requested. Not used if a tool has a `description` in its- `InterruptOnConfig`.+ requested.++ Not used if a tool has a `description` in its `InterruptOnConfig`."""super().__init__()resolved_configs: dict[str, InterruptOnConfig] = {}diff --git a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.pyindex 90dba99dfa..d44c26bad3 100644--- a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py+++ b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py@@ -20,9 +20,9 @@ if TYPE_CHECKING:class ModelCallLimitState(AgentState):- """State schema for ModelCallLimitMiddleware.+ """State schema for `ModelCallLimitMiddleware`.- Extends AgentState with model call tracking fields.+ Extends `AgentState` with model call tracking fields."""thread_model_call_count: NotRequired[Annotated[int, PrivateStateAttr]]@@ -58,8 +58,8 @@ def _build_limit_exceeded_message(class ModelCallLimitExceededError(Exception):"""Exception raised when model call limits are exceeded.- This exception is raised when the configured exit behavior is 'error'- and either the thread or run model call limit has been exceeded.+ This exception is raised when the configured exit behavior is `'error'` and either+ the thread or run model call limit has been exceeded."""def __init__(@@ -127,13 +127,16 @@ class ModelCallLimitMiddleware(AgentMiddleware[ModelCallLimitState, Any]):Args:thread_limit: Maximum number of model calls allowed per thread.- None means no limit.++ `None` means no limit.run_limit: Maximum number of model calls allowed per run.- None means no limit.++ `None` means no limit.exit_behavior: What to do when limits are exceeded.- - "end": Jump to the end of the agent execution and- inject an artificial AI message indicating that the limit was exceeded.- - "error": Raise a `ModelCallLimitExceededError`+ - `'end'`: Jump to the end of the agent execution and+ inject an artificial AI message indicating that the limit was+ exceeded.+ - `'error'`: Raise a `ModelCallLimitExceededError`Raises:ValueError: If both limits are `None` or if `exit_behavior` is invalid.@@ -161,12 +164,13 @@ class ModelCallLimitMiddleware(AgentMiddleware[ModelCallLimitState, Any]):runtime: The langgraph runtime.Returns:- If limits are exceeded and exit_behavior is "end", returns- a Command to jump to the end with a limit exceeded message. Otherwise returns None.+ If limits are exceeded and exit_behavior is `'end'`, returns+ a `Command` to jump to the end with a limit exceeded message. Otherwise+ returns `None`.Raises:- ModelCallLimitExceededError: If limits are exceeded and exit_behavior- is "error".+ ModelCallLimitExceededError: If limits are exceeded and `exit_behavior`+ is `'error'`."""thread_count = state.get("thread_model_call_count", 0)run_count = state.get("run_model_call_count", 0)diff --git a/libs/langchain_v1/langchain/agents/middleware/model_fallback.py b/libs/langchain_v1/langchain/agents/middleware/model_fallback.pyindex 6ac85e5775..b14ae8025c 100644--- a/libs/langchain_v1/langchain/agents/middleware/model_fallback.py+++ b/libs/langchain_v1/langchain/agents/middleware/model_fallback.py@@ -22,7 +22,7 @@ class ModelFallbackMiddleware(AgentMiddleware):"""Automatic fallback to alternative models on errors.Retries failed model calls with alternative models in sequence until- success or all models exhausted. Primary model specified in create_agent().+ success or all models exhausted. Primary model specified in `create_agent`.Example:```pythondiff --git a/libs/langchain_v1/langchain/agents/middleware/pii.py b/libs/langchain_v1/langchain/agents/middleware/pii.pyindex 4ca139174a..5a7eb581a6 100644--- a/libs/langchain_v1/langchain/agents/middleware/pii.py+++ b/libs/langchain_v1/langchain/agents/middleware/pii.py@@ -27,24 +27,26 @@ if TYPE_CHECKING:class PIIMiddleware(AgentMiddleware):- """Detect and handle Personally Identifiable Information (PII) in agent conversations.+ """Detect and handle Personally Identifiable Information (PII) in conversations.This middleware detects common PII types and applies configurable strategies- to handle them. It can detect emails, credit cards, IP addresses,- MAC addresses, and URLs in both user input and agent output.+ to handle them. It can detect emails, credit cards, IP addresses, MAC addresses, and+ URLs in both user input and agent output.Built-in PII types:- - `email`: Email addresses- - `credit_card`: Credit card numbers (validated with Luhn algorithm)- - `ip`: IP addresses (validated with stdlib)- - `mac_address`: MAC addresses- - `url`: URLs (both `http`/`https` and bare URLs)++ - `email`: Email addresses+ - `credit_card`: Credit card numbers (validated with Luhn algorithm)+ - `ip`: IP addresses (validated with stdlib)+ - `mac_address`: MAC addresses+ - `url`: URLs (both `http`/`https` and bare URLs)Strategies:- - `block`: Raise an exception when PII is detected- - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders- - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)- - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)++ - `block`: Raise an exception when PII is detected+ - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders+ - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)+ - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)Strategy Selection Guide:@@ -101,12 +103,15 @@ class PIIMiddleware(AgentMiddleware):"""Initialize the PII detection middleware.Args:- pii_type: Type of PII to detect. Can be a built-in type- (`email`, `credit_card`, `ip`, `mac_address`, `url`)- or a custom type name.- strategy: How to handle detected PII:+ pii_type: Type of PII to detect.++ Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`,+ `url`) or a custom type name.+ strategy: How to handle detected PII.- * `block`: Raise PIIDetectionError when PII is detected+ Options:++ * `block`: Raise `PIIDetectionError` when PII is detected* `redact`: Replace with `[REDACTED_TYPE]` placeholders* `mask`: Partially mask PII (show last few characters)* `hash`: Replace with deterministic hash (format: `<type_hash:digest>`)@@ -114,16 +119,15 @@ class PIIMiddleware(AgentMiddleware):detector: Custom detector function or regex pattern.* If `Callable`: Function that takes content string and returns- list of PIIMatch objects+ list of `PIIMatch` objects* If `str`: Regex pattern to match PII- * If `None`: Uses built-in detector for the pii_type-+ * If `None`: Uses built-in detector for the `pii_type`apply_to_input: Whether to check user messages before model call.apply_to_output: Whether to check AI messages after model call.apply_to_tool_results: Whether to check tool result messages after tool execution.Raises:- ValueError: If pii_type is not built-in and no detector is provided.+ ValueError: If `pii_type` is not built-in and no detector is provided."""super().__init__()@@ -166,10 +170,11 @@ class PIIMiddleware(AgentMiddleware):runtime: The langgraph runtime.Returns:- Updated state with PII handled according to strategy, or None if no PII detected.+ Updated state with PII handled according to strategy, or `None` if no PII+ detected.Raises:- PIIDetectionError: If PII is detected and strategy is "block".+ PIIDetectionError: If PII is detected and strategy is `'block'`."""if not self.apply_to_input and not self.apply_to_tool_results:return None@@ -259,10 +264,11 @@ class PIIMiddleware(AgentMiddleware):runtime: The langgraph runtime.Returns:- Updated state with PII handled according to strategy, or None if no PII detected.+ Updated state with PII handled according to strategy, or None if no PII+ detected.Raises:- PIIDetectionError: If PII is detected and strategy is "block".+ PIIDetectionError: If PII is detected and strategy is `'block'`."""if not self.apply_to_output:return Nonediff --git a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py b/libs/langchain_v1/langchain/agents/middleware/shell_tool.pyindex 563ef2a2c3..8c03cfe28a 100644--- a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py+++ b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py@@ -368,17 +368,18 @@ class _PersistentShellTool(BaseTool):class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):"""Middleware that registers a persistent shell tool for agents.- The middleware exposes a single long-lived shell session. Use the execution policy to- match your deployment's security posture:-- * ``HostExecutionPolicy`` - full host access; best for trusted environments where the- agent already runs inside a container or VM that provides isolation.- * ``CodexSandboxExecutionPolicy`` - reuses the Codex CLI sandbox for additional- syscall/filesystem restrictions when the CLI is available.- * ``DockerExecutionPolicy`` - launches a separate Docker container for each agent run,- providing harder isolation, optional read-only root filesystems, and user remapping.-- When no policy is provided the middleware defaults to ``HostExecutionPolicy``.+ The middleware exposes a single long-lived shell session. Use the execution policy+ to match your deployment's security posture:++ * `HostExecutionPolicy` – full host access; best for trusted environments where the+ agent already runs inside a container or VM that provides isolation.+ * `CodexSandboxExecutionPolicy` – reuses the Codex CLI sandbox for additional+ syscall/filesystem restrictions when the CLI is available.+ * `DockerExecutionPolicy` – launches a separate Docker container for each agent run,+ providing harder isolation, optional read-only root filesystems, and user+ remapping.++ When no policy is provided the middleware defaults to `HostExecutionPolicy`."""state_schema = ShellToolState@@ -398,20 +399,29 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):"""Initialize the middleware.Args:- workspace_root: Base directory for the shell session. If omitted, a temporary- directory is created when the agent starts and removed when it ends.- startup_commands: Optional commands executed sequentially after the session starts.+ workspace_root: Base directory for the shell session.++ If omitted, a temporary directory is created when the agent starts and+ removed when it ends.+ startup_commands: Optional commands executed sequentially after the session+ starts.shutdown_commands: Optional commands executed before the session shuts down.- execution_policy: Execution policy controlling timeouts, output limits, and resource- configuration. Defaults to :class:`HostExecutionPolicy` for native execution.+ execution_policy: Execution policy controlling timeouts, output limits, and+ resource configuration.++ Defaults to `HostExecutionPolicy` for native execution.redaction_rules: Optional redaction rules to sanitize command output beforereturning it to the model.- tool_description: Optional override for the registered shell tool description.- shell_command: Optional shell executable (string) or argument sequence used to- launch the persistent session. Defaults to an implementation-defined bash command.- env: Optional environment variables to supply to the shell session. Values are- coerced to strings before command execution. If omitted, the session inherits the- parent process environment.+ tool_description: Optional override for the registered shell tool+ description.+ shell_command: Optional shell executable (string) or argument sequence used+ to launch the persistent session.++ Defaults to an implementation-defined bash command.+ env: Optional environment variables to supply to the shell session.++ Values are coerced to strings before command execution. If omitted, the+ session inherits the parent process environment."""super().__init__()self._workspace_root = Path(workspace_root) if workspace_root else Nonediff --git a/libs/langchain_v1/langchain/agents/middleware/summarization.py b/libs/langchain_v1/langchain/agents/middleware/summarization.pyindex 6ba6221206..96adb87179 100644--- a/libs/langchain_v1/langchain/agents/middleware/summarization.py+++ b/libs/langchain_v1/langchain/agents/middleware/summarization.py@@ -76,7 +76,7 @@ class SummarizationMiddleware(AgentMiddleware):summary_prompt: str = DEFAULT_SUMMARY_PROMPT,summary_prefix: str = SUMMARY_PREFIX,) -> None:- """Initialize the summarization middleware.+ """Initialize summarization middleware.Args:model: The language model to use for generating summaries.diff --git a/libs/langchain_v1/langchain/agents/middleware/todo.py b/libs/langchain_v1/langchain/agents/middleware/todo.pyindex 5ec0215efc..c2c0b61721 100644--- a/libs/langchain_v1/langchain/agents/middleware/todo.py+++ b/libs/langchain_v1/langchain/agents/middleware/todo.py@@ -153,9 +153,7 @@ class TodoListMiddleware(AgentMiddleware):Args:system_prompt: Custom system prompt to guide the agent on using the todo tool.- If not provided, uses the default `WRITE_TODOS_SYSTEM_PROMPT`.tool_description: Custom description for the write_todos tool.- If not provided, uses the default `WRITE_TODOS_TOOL_DESCRIPTION`."""state_schema = PlanningState@@ -166,11 +164,12 @@ class TodoListMiddleware(AgentMiddleware):system_prompt: str = WRITE_TODOS_SYSTEM_PROMPT,tool_description: str = WRITE_TODOS_TOOL_DESCRIPTION,) -> None:- """Initialize the TodoListMiddleware with optional custom prompts.+ """Initialize the `TodoListMiddleware` with optional custom prompts.Args:- system_prompt: Custom system prompt to guide the agent on using the todo tool.- tool_description: Custom description for the write_todos tool.+ system_prompt: Custom system prompt to guide the agent on using the todo+ tool.+ tool_description: Custom description for the `write_todos` tool."""super().__init__()self.system_prompt = system_promptdiff --git a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.pyindex 686ca06ab8..c01cf53631 100644--- a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py+++ b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py@@ -23,22 +23,23 @@ if TYPE_CHECKING:ExitBehavior = Literal["continue", "error", "end"]"""How to handle execution when tool call limits are exceeded.-- `"continue"`: Block exceeded tools with error messages, let other tools continue (default)-- `"error"`: Raise a `ToolCallLimitExceededError` exception-- `"end"`: Stop execution immediately, injecting a ToolMessage and an AI message- for the single tool call that exceeded the limit. Raises `NotImplementedError`- if there are other pending tool calls (due to parallel tool calling).+- `'continue'`: Block exceeded tools with error messages, let other tools continue+ (default)+- `'error'`: Raise a `ToolCallLimitExceededError` exception+- `'end'`: Stop execution immediately, injecting a `ToolMessage` and an `AIMessage` for+ the single tool call that exceeded the limit. Raises `NotImplementedError` if there+ are other pending tool calls (due to parallel tool calling)."""class ToolCallLimitState(AgentState[ResponseT], Generic[ResponseT]):- """State schema for ToolCallLimitMiddleware.+ """State schema for `ToolCallLimitMiddleware`.- Extends AgentState with tool call tracking fields.+ Extends `AgentState` with tool call tracking fields.- The count fields are dictionaries mapping tool names to execution counts.- This allows multiple middleware instances to track different tools independently.- The special key "__all__" is used for tracking all tool calls globally.+ The count fields are dictionaries mapping tool names to execution counts. This+ allows multiple middleware instances to track different tools independently. The+ special key `'__all__'` is used for tracking all tool calls globally."""thread_tool_call_count: NotRequired[Annotated[dict[str, int], PrivateStateAttr]]@@ -46,13 +47,13 @@ class ToolCallLimitState(AgentState[ResponseT], Generic[ResponseT]):def _build_tool_message_content(tool_name: str | None) -> str:- """Build the error message content for ToolMessage when limit is exceeded.+ """Build the error message content for `ToolMessage` when limit is exceeded.This message is sent to the model, so it should not reference thread/run conceptsthat the model has no notion of.Args:- tool_name: Tool name being limited (if specific tool), or None for all tools.+ tool_name: Tool name being limited (if specific tool), or `None` for all tools.Returns:A concise message instructing the model not to call the tool again.@@ -70,7 +71,7 @@ def _build_final_ai_message_content(run_limit: int | None,tool_name: str | None,) -> str:- """Build the final AI message content for 'end' behavior.+ """Build the final AI message content for `'end'` behavior.This message is displayed to the user, so it should include detailed informationabout which limits were exceeded.@@ -80,7 +81,7 @@ def _build_final_ai_message_content(run_count: Current run tool call count.thread_limit: Thread tool call limit (if set).run_limit: Run tool call limit (if set).- tool_name: Tool name being limited (if specific tool), or None for all tools.+ tool_name: Tool name being limited (if specific tool), or `None` for all tools.Returns:A formatted message describing which limits were exceeded.@@ -100,8 +101,8 @@ def _build_final_ai_message_content(class ToolCallLimitExceededError(Exception):"""Exception raised when tool call limits are exceeded.- This exception is raised when the configured exit behavior is 'error'- and either the thread or run tool call limit has been exceeded.+ This exception is raised when the configured exit behavior is `'error'` and either+ the thread or run tool call limit has been exceeded."""def __init__(@@ -145,15 +146,14 @@ class ToolCallLimitMiddleware(Configuration:- `exit_behavior`: How to handle when limits are exceeded- - `"continue"`: Block exceeded tools, let execution continue (default)- - `"error"`: Raise an exception- - `"end"`: Stop immediately with a ToolMessage + AI message for the single- tool call that exceeded the limit (raises `NotImplementedError` if there- are other pending tool calls (due to parallel tool calling).+ - `'continue'`: Block exceeded tools, let execution continue (default)+ - `'error'`: Raise an exception+ - `'end'`: Stop immediately with a `ToolMessage` + AI message for the single+ tool call that exceeded the limit (raises `NotImplementedError` if there+ are other pending tool calls (due to parallel tool calling).Examples:- Continue execution with blocked tools (default):- ```python+ ```python title="Continue execution with blocked tools (default)"from langchain.agents.middleware.tool_call_limit import ToolCallLimitMiddlewarefrom langchain.agents import create_agent@@ -167,16 +167,14 @@ class ToolCallLimitMiddleware(agent = create_agent("openai:gpt-4o", middleware=[limiter])```- Stop immediately when limit exceeded:- ```python+ ```python title="Stop immediately when limit exceeded"# End execution immediately with an AI messagelimiter = ToolCallLimitMiddleware(run_limit=5, exit_behavior="end")agent = create_agent("openai:gpt-4o", middleware=[limiter])```- Raise exception on limit:- ```python+ ```python title="Raise exception on limit"# Strict limit with exception handlinglimiter = ToolCallLimitMiddleware(tool_name="search", thread_limit=5, exit_behavior="error")@@ -204,23 +202,23 @@ class ToolCallLimitMiddleware(Args:tool_name: Name of the specific tool to limit. If `None`, limits apply- to all tools. Defaults to `None`.+ to all tools.thread_limit: Maximum number of tool calls allowed per thread.- `None` means no limit. Defaults to `None`.+ `None` means no limit.run_limit: Maximum number of tool calls allowed per run.- `None` means no limit. Defaults to `None`.+ `None` means no limit.exit_behavior: How to handle when limits are exceeded.- - `"continue"`: Block exceeded tools with error messages, let other- tools continue. Model decides when to end. (default)- - `"error"`: Raise a `ToolCallLimitExceededError` exception- - `"end"`: Stop execution immediately with a ToolMessage + AI message- for the single tool call that exceeded the limit. Raises- `NotImplementedError` if there are multiple parallel tool- calls to other tools or multiple pending tool calls.+ - `'continue'`: Block exceeded tools with error messages, let other+ tools continue. Model decides when to end.+ - `'error'`: Raise a `ToolCallLimitExceededError` exception+ - `'end'`: Stop execution immediately with a `ToolMessage` + AI message+ for the single tool call that exceeded the limit. Raises+ `NotImplementedError` if there are multiple parallel tool+ calls to other tools or multiple pending tool calls.Raises:- ValueError: If both limits are `None`, if exit_behavior is invalid,- or if run_limit exceeds thread_limit.+ ValueError: If both limits are `None`, if `exit_behavior` is invalid,+ or if `run_limit` exceeds thread_limit."""super().__init__()@@ -293,7 +291,8 @@ class ToolCallLimitMiddleware(run_count: Current run call count.Returns:- Tuple of (allowed_calls, blocked_calls, final_thread_count, final_run_count).+ Tuple of `(allowed_calls, blocked_calls, final_thread_count,+ final_run_count)`."""allowed_calls: list[ToolCall] = []blocked_calls: list[ToolCall] = []@@ -327,13 +326,13 @@ class ToolCallLimitMiddleware(Returns:State updates with incremented tool call counts. If limits are exceeded- and exit_behavior is "end", also includes a jump to end with a ToolMessage- and AI message for the single exceeded tool call.+ and exit_behavior is `'end'`, also includes a jump to end with a+ `ToolMessage` and AI message for the single exceeded tool call.Raises:- ToolCallLimitExceededError: If limits are exceeded and exit_behavior- is "error".- NotImplementedError: If limits are exceeded, exit_behavior is "end",+ ToolCallLimitExceededError: If limits are exceeded and `exit_behavior`+ is `'error'`.+ NotImplementedError: If limits are exceeded, `exit_behavior` is `'end'`,and there are multiple tool calls."""# Get the last AIMessage to check for tool callsdiff --git a/libs/langchain_v1/langchain/agents/middleware/tool_emulator.py b/libs/langchain_v1/langchain/agents/middleware/tool_emulator.pyindex 90018150e4..45bb0ad5a9 100644--- a/libs/langchain_v1/langchain/agents/middleware/tool_emulator.py+++ b/libs/langchain_v1/langchain/agents/middleware/tool_emulator.py@@ -23,12 +23,12 @@ class LLMToolEmulator(AgentMiddleware):"""Emulates specified tools using an LLM instead of executing them.This middleware allows selective emulation of tools for testing purposes.- By default (when tools=None), all tools are emulated. You can specify which++ By default (when `tools=None`), all tools are emulated. You can specify whichtools to emulate by passing a list of tool names or BaseTool instances.Examples:- Emulate all tools (default behavior):- ```python+ ```python title="Emulate all tools (default behavior)"from langchain.agents.middleware import LLMToolEmulatormiddleware = LLMToolEmulator()@@ -40,20 +40,17 @@ class LLMToolEmulator(AgentMiddleware):)```- Emulate specific tools by name:- ```python+ ```python title="Emulate specific tools by name"middleware = LLMToolEmulator(tools=["get_weather", "get_user_location"])```- Use a custom model for emulation:- ```python+ ```python title="Use a custom model for emulation"middleware = LLMToolEmulator(tools=["get_weather"], model="anthropic:claude-sonnet-4-5-20250929")```- Emulate specific tools by passing tool instances:- ```python+ ```python title="Emulate specific tools by passing tool instances"middleware = LLMToolEmulator(tools=[get_weather, get_user_location])```"""@@ -67,12 +64,16 @@ class LLMToolEmulator(AgentMiddleware):"""Initialize the tool emulator.Args:- tools: List of tool names (str) or BaseTool instances to emulate.- If None (default), ALL tools will be emulated.+ tools: List of tool names (`str`) or `BaseTool` instances to emulate.++ If `None`, ALL tools will be emulated.+If empty list, no tools will be emulated.model: Model to use for emulation.- Defaults to "anthropic:claude-sonnet-4-5-20250929".- Can be a model identifier string or BaseChatModel instance.++ Defaults to `'anthropic:claude-sonnet-4-5-20250929'`.++ Can be a model identifier string or `BaseChatModel` instance."""super().__init__()@@ -110,7 +111,7 @@ class LLMToolEmulator(AgentMiddleware):Returns:ToolMessage with emulated response if tool should be emulated,- otherwise calls handler for normal execution.+ otherwise calls handler for normal execution."""tool_name = request.tool_call["name"]@@ -152,7 +153,7 @@ class LLMToolEmulator(AgentMiddleware):request: ToolCallRequest,handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],) -> ToolMessage | Command:- """Async version of wrap_tool_call.+ """Async version of `wrap_tool_call`.Emulate tool execution using LLM if tool should be emulated.@@ -162,7 +163,7 @@ class LLMToolEmulator(AgentMiddleware):Returns:ToolMessage with emulated response if tool should be emulated,- otherwise calls handler for normal execution.+ otherwise calls handler for normal execution."""tool_name = request.tool_call["name"]diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py b/libs/langchain_v1/langchain/agents/middleware/tool_retry.pyindex 361158b0c6..7f9cde39d4 100644--- a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py+++ b/libs/langchain_v1/langchain/agents/middleware/tool_retry.py@@ -27,6 +27,7 @@ class ToolRetryMiddleware(AgentMiddleware):Examples:Basic usage with default settings (2 retries, exponential backoff):+```pythonfrom langchain.agents import create_agentfrom langchain.agents.middleware import ToolRetryMiddleware@@ -35,6 +36,7 @@ class ToolRetryMiddleware(AgentMiddleware):```Retry specific exceptions only:+```pythonfrom requests.exceptions import RequestException, Timeout@@ -46,6 +48,7 @@ class ToolRetryMiddleware(AgentMiddleware):```Custom exception filtering:+```pythonfrom requests.exceptions import HTTPError@@ -64,6 +67,7 @@ class ToolRetryMiddleware(AgentMiddleware):```Apply to specific tools with custom error handling:+```pythondef format_error(exc: Exception) -> str:return "Database temporarily unavailable. Please try again later."@@ -77,6 +81,7 @@ class ToolRetryMiddleware(AgentMiddleware):```Apply to specific tools using BaseTool instances:+```pythonfrom langchain_core.tools import tool@@ -94,6 +99,7 @@ class ToolRetryMiddleware(AgentMiddleware):```Constant backoff (no exponential growth):+```pythonretry = ToolRetryMiddleware(max_retries=5,@@ -103,6 +109,7 @@ class ToolRetryMiddleware(AgentMiddleware):```Raise exception on failure:+```pythonretry = ToolRetryMiddleware(max_retries=2,@@ -125,34 +132,42 @@ class ToolRetryMiddleware(AgentMiddleware):max_delay: float = 60.0,jitter: bool = True,) -> None:- """Initialize ToolRetryMiddleware.+ """Initialize `ToolRetryMiddleware`.Args:max_retries: Maximum number of retry attempts after the initial call.- Default is 2 retries (3 total attempts). Must be >= 0.+ Default is `2` retries (`3` total attempts). Must be `>= 0`.tools: Optional list of tools or tool names to apply retry logic to.+Can be a list of `BaseTool` instances or tool name strings.- If `None`, applies to all tools. Default is `None`.++ If `None`, applies to all tools.retry_on: Either a tuple of exception types to retry on, or a callablethat takes an exception and returns `True` if it should be retried.+Default is to retry on all exceptions.on_failure: Behavior when all retries are exhausted. Options:- - `"return_message"` (default): Return a ToolMessage with error details,- allowing the LLM to handle the failure and potentially recover.- - `"raise"`: Re-raise the exception, stopping agent execution.- - Custom callable: Function that takes the exception and returns a string- for the ToolMessage content, allowing custom error formatting.- backoff_factor: Multiplier for exponential backoff. Each retry waits- `initial_delay * (backoff_factor ** retry_number)` seconds.- Set to 0.0 for constant delay. Default is 2.0.- initial_delay: Initial delay in seconds before first retry. Default is 1.0.- max_delay: Maximum delay in seconds between retries. Caps exponential- backoff growth. Default is 60.0.- jitter: Whether to add random jitter (±25%) to delay to avoid thundering herd.- Default is `True`.++ - `'return_message'`: Return a `ToolMessage` with error details,+ allowing the LLM to handle the failure and potentially recover.+ - `'raise'`: Re-raise the exception, stopping agent execution.+ - Custom callable: Function that takes the exception and returns a+ string for the `ToolMessage` content, allowing custom error+ formatting.+ backoff_factor: Multiplier for exponential backoff.++ Each retry waits `initial_delay * (backoff_factor ** retry_number)`+ seconds.++ Set to `0.0` for constant delay.+ initial_delay: Initial delay in seconds before first retry.+ max_delay: Maximum delay in seconds between retries.++ Caps exponential backoff growth.+ jitter: Whether to add random jitter (`±25%`) to delay to avoid thundering herd.Raises:- ValueError: If max_retries < 0 or delays are negative.+ ValueError: If `max_retries < 0` or delays are negative."""super().__init__()@@ -260,15 +275,15 @@ class ToolRetryMiddleware(AgentMiddleware):Args:tool_name: Name of the tool that failed.- tool_call_id: ID of the tool call (may be None).+ tool_call_id: ID of the tool call (may be `None`).exc: The exception that caused the failure.attempts_made: Number of attempts actually made.Returns:- ToolMessage with error details.+ `ToolMessage` with error details.Raises:- Exception: If on_failure is "raise", re-raises the exception.+ Exception: If `on_failure` is `'raise'`, re-raises the exception."""if self.on_failure == "raise":raise exc@@ -293,11 +308,11 @@ class ToolRetryMiddleware(AgentMiddleware):"""Intercept tool execution and retry on failure.Args:- request: Tool call request with call dict, BaseTool, state, and runtime.+ request: Tool call request with call dict, `BaseTool`, state, and runtime.handler: Callable to execute the tool (can be called multiple times).Returns:- ToolMessage or Command (the final result).+ `ToolMessage` or `Command` (the final result)."""tool_name = request.tool.name if request.tool else request.tool_call["name"]@@ -342,11 +357,12 @@ class ToolRetryMiddleware(AgentMiddleware):"""Intercept and control async tool execution with retry logic.Args:- request: Tool call request with call dict, BaseTool, state, and runtime.- handler: Async callable to execute the tool and returns ToolMessage or Command.+ request: Tool call request with call `dict`, `BaseTool`, state, and runtime.+ handler: Async callable to execute the tool and returns `ToolMessage` or+ `Command`.Returns:- ToolMessage or Command (the final result).+ `ToolMessage` or `Command` (the final result)."""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.pyindex b674673815..34fa8a0f04 100644--- a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py+++ b/libs/langchain_v1/langchain/agents/middleware/tool_selection.py@@ -49,7 +49,8 @@ def _create_tool_selection_response(tools: list[BaseTool]) -> TypeAdapter:tools: Available tools to include in the schema.Returns:- TypeAdapter for a schema where each tool name is a Literal with its description.+ `TypeAdapter` for a schema where each tool name is a `Literal` with its+ description."""if not tools:msg = "Invalid usage: tools must be non-empty"@@ -92,8 +93,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):and helps the main model focus on the right tools.Examples:- Limit to 3 tools:- ```python+ ```python title="Limit to 3 tools"from langchain.agents.middleware import LLMToolSelectorMiddlewaremiddleware = LLMToolSelectorMiddleware(max_tools=3)@@ -105,8 +105,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):)```- Use a smaller model for selection:- ```python+ ```python title="Use a smaller model for selection"middleware = LLMToolSelectorMiddleware(model="openai:gpt-4o-mini", max_tools=2)```"""@@ -122,13 +121,20 @@ class LLMToolSelectorMiddleware(AgentMiddleware):"""Initialize the tool selector.Args:- model: Model to use for selection. If not provided, uses the agent's main model.- Can be a model identifier string or BaseChatModel instance.+ model: Model to use for selection.++ If not provided, uses the agent's main model.++ Can be a model identifier string or `BaseChatModel` instance.system_prompt: Instructions for the selection model.- max_tools: Maximum number of tools to select. If the model selects more,- only the first max_tools will be used. No limit if not specified.+ max_tools: Maximum number of tools to select.++ If the model selects more, only the first `max_tools` will be used.++ No limit if not specified.always_include: Tool names to always include regardless of selection.- These do not count against the max_tools limit.++ These do not count against the `max_tools` limit."""super().__init__()self.system_prompt = system_prompt@@ -144,7 +150,8 @@ class LLMToolSelectorMiddleware(AgentMiddleware):"""Prepare inputs for tool selection.Returns:- SelectionRequest with prepared inputs, or None if no selection is needed.+ `SelectionRequest` with prepared inputs, or `None` if no selection is+ needed."""# If no tools available, return Noneif not request.tools or len(request.tools) == 0:@@ -211,7 +218,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):valid_tool_names: list[str],request: ModelRequest,) -> ModelRequest:- """Process the selection response and return filtered ModelRequest."""+ """Process the selection response and return filtered `ModelRequest`."""selected_tool_names: list[str] = []invalid_tool_selections = []diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.pyindex cedcc28502..fc93043094 100644--- a/libs/langchain_v1/langchain/agents/middleware/types.py+++ b/libs/langchain_v1/langchain/agents/middleware/types.py@@ -69,7 +69,7 @@ ResponseT = TypeVar("ResponseT")class _ModelRequestOverrides(TypedDict, total=False):- """Possible overrides for ModelRequest.override() method."""+ """Possible overrides for `ModelRequest.override()` method."""model: BaseChatModelsystem_prompt: str | None@@ -98,27 +98,31 @@ class ModelRequest:"""Replace the request with a new request with the given overrides.Returns a new `ModelRequest` instance with the specified attributes replaced.+This follows an immutable pattern, leaving the original request unchanged.Args:- **overrides: Keyword arguments for attributes to override. Supported keys:- - model: BaseChatModel instance- - system_prompt: Optional system prompt string- - messages: List of messages- - tool_choice: Tool choice configuration- - tools: List of available tools- - response_format: Response format specification- - model_settings: Additional model settings+ **overrides: Keyword arguments for attributes to override.++ Supported keys:++ - `model`: `BaseChatModel` instance+ - `system_prompt`: Optional system prompt string+ - `messages`: `list` of messages+ - `tool_choice`: Tool choice configuration+ - `tools`: `list` of available tools+ - `response_format`: Response format specification+ - `model_settings`: Additional model settingsReturns:- New ModelRequest instance with specified overrides applied.+ New `ModelRequest` instance with specified overrides applied.Examples:- ```python- # Create a new request with different model+ ```python title="Create a new request with different model"new_request = request.override(model=different_model)+ ```- # Override multiple attributes+ ```python title="Override multiple attributes"new_request = request.override(system_prompt="New instructions", tool_choice="auto")```"""@@ -129,24 +133,25 @@ class ModelRequest:class ModelResponse:"""Response from model execution including messages and optional structured output.- The result will usually contain a single AIMessage, but may include- an additional ToolMessage if the model used a tool for structured output.+ The result will usually contain a single `AIMessage`, but may include an additional+ `ToolMessage` if the model used a tool for structured output."""result: list[BaseMessage]"""List of messages from model execution."""structured_response: Any = None- """Parsed structured output if response_format was specified, None otherwise."""+ """Parsed structured output if `response_format` was specified, `None` otherwise."""# Type alias for middleware return type - allows returning either full response or just AIMessageModelCallResult: TypeAlias = "ModelResponse | AIMessage"-"""Type alias for model call handler return value.+"""`TypeAlias` for model call handler return value.Middleware can return either:-- ModelResponse: Full response with messages and optional structured output-- AIMessage: Simplified return for simple use cases++- `ModelResponse`: Full response with messages and optional structured output+- `AIMessage`: Simplified return for simple use cases"""@@ -257,15 +262,19 @@ class AgentMiddleware(Generic[StateT, ContextT]):Args:request: Model request to execute (includes state and runtime).handler: Callback that executes the model request and returns- `ModelResponse`. Call this to execute the model. Can be called multiple- times for retry logic. Can skip calling it to short-circuit.+ `ModelResponse`.++ Call this to execute the model.++ Can be called multiple times for retry logic.++ Can skip calling it to short-circuit.Returns:`ModelCallResult`Examples:- Retry on error:- ```python+ ```python title="Retry on error"def wrap_model_call(self, request, handler):for attempt in range(3):try:@@ -275,8 +284,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):raise```- Rewrite response:- ```python+ ```python title="Rewrite response"def wrap_model_call(self, request, handler):response = handler(request)ai_msg = response.result[0]@@ -286,8 +294,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):)```- Error to fallback:- ```python+ ```python title="Error to fallback"def wrap_model_call(self, request, handler):try:return handler(request)@@ -295,8 +302,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):return ModelResponse(result=[AIMessage(content="Service unavailable")])```- Cache/short-circuit:- ```python+ ```python title="Cache/short-circuit"def wrap_model_call(self, request, handler):if cached := get_cache(request):return cached # Short-circuit with cached result@@ -305,8 +311,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):return response```- Simple AIMessage return (converted automatically):- ```python+ ```python title="Simple `AIMessage` return (converted automatically)"def wrap_model_call(self, request, handler):response = handler(request)# Can return AIMessage directly for simple cases@@ -333,6 +338,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):"""Intercept and control async model execution via handler callback.The handler callback executes the model request and returns a `ModelResponse`.+Middleware can call the handler multiple times for retry logic, skip callingit to short-circuit, or modify the request/response. Multiple middlewarecompose with first in list as outermost layer.@@ -340,15 +346,19 @@ class AgentMiddleware(Generic[StateT, ContextT]):Args:request: Model request to execute (includes state and runtime).handler: Async callback that executes the model request and returns- `ModelResponse`. Call this to execute the model. Can be called multiple- times for retry logic. Can skip calling it to short-circuit.+ `ModelResponse`.++ Call this to execute the model.++ Can be called multiple times for retry logic.++ Can skip calling it to short-circuit.Returns:- ModelCallResult+ `ModelCallResult`Examples:- Retry on error:- ```python+ ```python title="Retry on error"async def awrap_model_call(self, request, handler):for attempt in range(3):try:@@ -386,31 +396,30 @@ class AgentMiddleware(Generic[StateT, ContextT]):"""Intercept tool execution for retries, monitoring, or modification.Multiple middleware compose automatically (first defined = outermost).+Exceptions propagate unless `handle_tool_errors` is configured on `ToolNode`.Args:request: Tool call request with call `dict`, `BaseTool`, state, and runtime.+Access state via `request.state` and runtime via `request.runtime`.- handler: Callable to execute the tool (can be called multiple times).+ handler: `Callable` to execute the tool (can be called multiple times).Returns:`ToolMessage` or `Command` (the final result).- The handler callable can be invoked multiple times for retry logic.+ The handler `Callable` can be invoked multiple times for retry logic.+Each call to handler is independent and stateless.Examples:- Modify request before execution:-- ```python+ ```python title="Modify request before execution"def wrap_tool_call(self, request, handler):request.tool_call["args"]["value"] *= 2return handler(request)```- Retry on error (call handler multiple times):-- ```python+ ```python title="Retry on error (call handler multiple times)"def wrap_tool_call(self, request, handler):for attempt in range(3):try:@@ -423,9 +432,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):return result```- Conditional retry based on response:-- ```python+ ```python title="Conditional retry based on response"def wrap_tool_call(self, request, handler):for attempt in range(3):result = handler(request)@@ -462,20 +469,26 @@ class AgentMiddleware(Generic[StateT, ContextT]):Args:request: Tool call request with call `dict`, `BaseTool`, state, and runtime.+Access state via `request.state` and runtime via `request.runtime`.handler: Async callable to execute the tool and returns `ToolMessage` or- `Command`. Call this to execute the tool. Can be called multiple times- for retry logic. Can skip calling it to short-circuit.+ `Command`.++ Call this to execute the tool.++ Can be called multiple times for retry logic.++ Can skip calling it to short-circuit.Returns:`ToolMessage` or `Command` (the final result).- The handler callable can be invoked multiple times for retry logic.+ The handler `Callable` can be invoked multiple times for retry logic.+Each call to handler is independent and stateless.Examples:- Async retry on error:- ```python+ ```python title="Async retry on error"async def awrap_tool_call(self, request, handler):for attempt in range(3):try:@@ -574,16 +587,20 @@ def hook_config(can jump to, which establishes conditional edges in the agent graph.Args:- can_jump_to: Optional list of valid jump destinations. Can be:- - "tools": Jump to the tools node- - "model": Jump back to the model node- - "end": Jump to the end of the graph+ can_jump_to: Optional list of valid jump destinations.++ Can be:++ - `'tools'`: Jump to the tools node+ - `'model'`: Jump back to the model node+ - `'end'`: Jump to the end of the graphReturns:Decorator function that marks the method with configuration metadata.Examples:Using decorator on a class method:+```pythonclass MyMiddleware(AgentMiddleware):@hook_config(can_jump_to=["end", "model"])@@ -593,7 +610,9 @@ def hook_config(return None```- Alternative: Use the `can_jump_to` parameter in `before_model`/`after_model` decorators:+ Alternative: Use the `can_jump_to` parameter in `before_model`/`after_model`+ decorators:+```python@before_model(can_jump_to=["end"])def conditional_middleware(state: AgentState) -> dict[str, Any] | None:@@ -644,35 +663,39 @@ def before_model("""Decorator used to dynamically create a middleware with the `before_model` hook.Args:- func: The function to be decorated. Must accept:- `state: StateT, runtime: Runtime[ContextT]` - State and runtime context- state_schema: Optional custom state schema type. If not provided, uses the default- `AgentState` schema.+ func: The function to be decorated.++ Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime+ context+ state_schema: Optional custom state schema type.++ If not provided, uses the default `AgentState` schema.tools: Optional list of additional tools to register with this middleware.can_jump_to: Optional list of valid jump destinations for conditional edges.- Valid values are: `"tools"`, `"model"`, `"end"`- name: Optional name for the generated middleware class. If not provided,- uses the decorated function's name.++ Valid values are: `'tools'`, `'model'`, `'end'`+ name: Optional name for the generated middleware class.++ If not provided, uses the decorated function's name.Returns:Either an `AgentMiddleware` instance (if func is provided directly) or a- decorator function that can be applied to a function it is wrapping.+ decorator function that can be applied to a function it is wrapping.The decorated function should return:- - `dict[str, Any]` - State updates to merge into the agent state- - `Command` - A command to control flow (e.g., jump to different node)- - `None` - No state updates or flow control++ - `dict[str, Any]` - State updates to merge into the agent state+ - `Command` - A command to control flow (e.g., jump to different node)+ - `None` - No state updates or flow controlExamples:- Basic usage:- ```python+ ```python title="Basic usage"@before_modeldef log_before_model(state: AgentState, runtime: Runtime) -> None:print(f"About to call model with {len(state['messages'])} messages")```- With conditional jumping:- ```python+ ```python title="With conditional jumping"@before_model(can_jump_to=["end"])def conditional_before_model(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:if some_condition(state):@@ -680,8 +703,7 @@ def before_model(return None```- With custom state schema:- ```python+ ```python title="With custom state schema"@before_model(state_schema=MyCustomState)def custom_before_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:return {"custom_field": "updated_value"}@@ -786,35 +808,39 @@ def after_model("""Decorator used to dynamically create a middleware with the `after_model` hook.Args:- func: The function to be decorated. Must accept:- `state: StateT, runtime: Runtime[ContextT]` - State and runtime context- state_schema: Optional custom state schema type. If not provided, uses the- default `AgentState` schema.+ func: The function to be decorated.++ Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime+ context+ state_schema: Optional custom state schema type.++ If not provided, uses the default `AgentState` schema.tools: Optional list of additional tools to register with this middleware.can_jump_to: Optional list of valid jump destinations for conditional edges.- Valid values are: `"tools"`, `"model"`, `"end"`- name: Optional name for the generated middleware class. If not provided,- uses the decorated function's name.++ Valid values are: `'tools'`, `'model'`, `'end'`+ name: Optional name for the generated middleware class.++ If not provided, uses the decorated function's name.Returns:Either an `AgentMiddleware` instance (if func is provided) or a decorator- function that can be applied to a function.+ function that can be applied to a function.The decorated function should return:- - `dict[str, Any]` - State updates to merge into the agent state- - `Command` - A command to control flow (e.g., jump to different node)- - `None` - No state updates or flow control++ - `dict[str, Any]` - State updates to merge into the agent state+ - `Command` - A command to control flow (e.g., jump to different node)+ - `None` - No state updates or flow controlExamples:- Basic usage for logging model responses:- ```python+ ```python title="Basic usage for logging model responses"@after_modeldef log_latest_message(state: AgentState, runtime: Runtime) -> None:print(state["messages"][-1].content)```- With custom state schema:- ```python+ ```python title="With custom state schema"@after_model(state_schema=MyCustomState, name="MyAfterModelMiddleware")def custom_after_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:return {"custom_field": "updated_after_model"}@@ -917,35 +943,39 @@ def before_agent("""Decorator used to dynamically create a middleware with the `before_agent` hook.Args:- func: The function to be decorated. Must accept:- `state: StateT, runtime: Runtime[ContextT]` - State and runtime context- state_schema: Optional custom state schema type. If not provided, uses the- default `AgentState` schema.+ func: The function to be decorated.++ Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime+ context+ state_schema: Optional custom state schema type.++ If not provided, uses the default `AgentState` schema.tools: Optional list of additional tools to register with this middleware.can_jump_to: Optional list of valid jump destinations for conditional edges.- Valid values are: `"tools"`, `"model"`, `"end"`- name: Optional name for the generated middleware class. If not provided,- uses the decorated function's name.++ Valid values are: `'tools'`, `'model'`, `'end'`+ name: Optional name for the generated middleware class.++ If not provided, uses the decorated function's name.Returns:Either an `AgentMiddleware` instance (if func is provided directly) or a- decorator function that can be applied to a function it is wrapping.+ decorator function that can be applied to a function it is wrapping.The decorated function should return:- - `dict[str, Any]` - State updates to merge into the agent state- - `Command` - A command to control flow (e.g., jump to different node)- - `None` - No state updates or flow control++ - `dict[str, Any]` - State updates to merge into the agent state+ - `Command` - A command to control flow (e.g., jump to different node)+ - `None` - No state updates or flow controlExamples:- Basic usage:- ```python+ ```python title="Basic usage"@before_agentdef log_before_agent(state: AgentState, runtime: Runtime) -> None:print(f"Starting agent with {len(state['messages'])} messages")```- With conditional jumping:- ```python+ ```python title="With conditional jumping"@before_agent(can_jump_to=["end"])def conditional_before_agent(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:if some_condition(state):@@ -953,8 +983,7 @@ def before_agent(return None```- With custom state schema:- ```python+ ```python title="With custom state schema"@before_agent(state_schema=MyCustomState)def custom_before_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:return {"custom_field": "initialized_value"}@@ -1059,35 +1088,39 @@ def after_agent("""Decorator used to dynamically create a middleware with the `after_agent` hook.Args:- func: The function to be decorated. Must accept:- `state: StateT, runtime: Runtime[ContextT]` - State and runtime context- state_schema: Optional custom state schema type. If not provided, uses the- default `AgentState` schema.+ func: The function to be decorated.++ Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime+ context+ state_schema: Optional custom state schema type.++ If not provided, uses the default `AgentState` schema.tools: Optional list of additional tools to register with this middleware.can_jump_to: Optional list of valid jump destinations for conditional edges.- Valid values are: `"tools"`, `"model"`, `"end"`- name: Optional name for the generated middleware class. If not provided,- uses the decorated function's name.++ Valid values are: `'tools'`, `'model'`, `'end'`+ name: Optional name for the generated middleware class.++ If not provided, uses the decorated function's name.Returns:Either an `AgentMiddleware` instance (if func is provided) or a decorator- function that can be applied to a function.+ function that can be applied to a function.The decorated function should return:- - `dict[str, Any]` - State updates to merge into the agent state- - `Command` - A command to control flow (e.g., jump to different node)- - `None` - No state updates or flow control++ - `dict[str, Any]` - State updates to merge into the agent state+ - `Command` - A command to control flow (e.g., jump to different node)+ - `None` - No state updates or flow controlExamples:- Basic usage for logging agent completion:- ```python+ ```python title="Basic usage for logging agent completion"@after_agentdef log_completion(state: AgentState, runtime: Runtime) -> None:print(f"Agent completed with {len(state['messages'])} messages")```- With custom state schema:- ```python+ ```python title="With custom state schema"@after_agent(state_schema=MyCustomState, name="MyAfterAgentMiddleware")def custom_after_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:return {"custom_field": "finalized_value"}@@ -1188,18 +1221,21 @@ def dynamic_prompt(a string that will be set as the system prompt for the model request.Args:- func: The function to be decorated. Must accept:- `request: ModelRequest` - Model request (contains state and runtime)+ func: The function to be decorated.++ Must accept: `request: ModelRequest` - Model request (contains state and+ runtime)Returns:- Either an AgentMiddleware instance (if func is provided) or a decorator function- that can be applied to a function.+ Either an `AgentMiddleware` instance (if func is provided) or a decorator+ function that can be applied to a function.The decorated function should return:- - `str` - The system prompt to use for the model request+ - `str` – The system prompt to use for the model requestExamples:Basic usage with dynamic content:+```python@dynamic_promptdef my_prompt(request: ModelRequest) -> str:@@ -1208,6 +1244,7 @@ def dynamic_prompt(```Using state to customize the prompt:+```python@dynamic_promptdef context_aware_prompt(request: ModelRequest) -> str:@@ -1218,6 +1255,7 @@ def dynamic_prompt(```Using with agent:+```pythonagent = create_agent(model, middleware=[my_prompt])```@@ -1322,23 +1360,27 @@ def wrap_model_call():"""Create middleware with `wrap_model_call` hook from a function.- Converts a function with handler callback into middleware that can intercept- model calls, implement retry logic, handle errors, and rewrite responses.+ Converts a function with handler callback into middleware that can intercept model+ calls, implement retry logic, handle errors, and rewrite responses.Args:func: Function accepting (request, handler) that calls handler(request)to execute the model and returns `ModelResponse` or `AIMessage`.+Request contains state and runtime.- state_schema: Custom state schema. Defaults to `AgentState`.+ state_schema: Custom state schema.++ Defaults to `AgentState`.tools: Additional tools to register with this middleware.- name: Middleware class name. Defaults to function name.+ name: Middleware class name.++ Defaults to function name.Returns:`AgentMiddleware` instance if func provided, otherwise a decorator.Examples:- Basic retry logic:- ```python+ ```python title="Basic retry logic"@wrap_model_calldef retry_on_error(request, handler):max_retries = 3@@ -1350,8 +1392,7 @@ def wrap_model_call(raise```- Model fallback:- ```python+ ```python title="Model fallback"@wrap_model_calldef fallback_model(request, handler):# Try primary model@@ -1365,8 +1406,7 @@ def wrap_model_call(return handler(request)```- Rewrite response content (full ModelResponse):- ```python+ ```python title="Rewrite response content (full `ModelResponse`)"@wrap_model_calldef uppercase_responses(request, handler):response = handler(request)@@ -1377,8 +1417,7 @@ def wrap_model_call()```- Simple AIMessage return (converted automatically):- ```python+ ```python title="Simple `AIMessage` return (converted automatically)"@wrap_model_calldef simple_response(request, handler):# AIMessage is automatically converted to ModelResponse@@ -1476,16 +1515,19 @@ def wrap_tool_call(Args:func: Function accepting (request, handler) that callshandler(request) to execute the tool and returns final `ToolMessage` or- `Command`. Can be sync or async.+ `Command`.++ Can be sync or async.tools: Additional tools to register with this middleware.- name: Middleware class name. Defaults to function name.+ name: Middleware class name.++ Defaults to function name.Returns:`AgentMiddleware` instance if func provided, otherwise a decorator.Examples:- Retry logic:- ```python+ ```python title="Retry logic"@wrap_tool_calldef retry_on_error(request, handler):max_retries = 3@@ -1497,8 +1539,7 @@ def wrap_tool_call(raise```- Async retry logic:- ```python+ ```python title="Async retry logic"@wrap_tool_callasync def async_retry(request, handler):for attempt in range(3):@@ -1509,16 +1550,14 @@ def wrap_tool_call(raise```- Modify request:- ```python+ ```python title="Modify request"@wrap_tool_calldef modify_args(request, handler):request.tool_call["args"]["value"] *= 2return handler(request)```- Short-circuit with cached result:- ```python+ ```python title="Short-circuit with cached result"@wrap_tool_calldef with_cache(request, handler):if cached := get_cache(request):diff --git a/libs/langchain_v1/langchain/chat_models/__init__.py b/libs/langchain_v1/langchain/chat_models/__init__.pyindex f52b04c4e0..c6900dea8b 100644--- a/libs/langchain_v1/langchain/chat_models/__init__.py+++ b/libs/langchain_v1/langchain/chat_models/__init__.py@@ -1,10 +1,4 @@-"""Entrypoint to using [chat models](https://docs.langchain.com/oss/python/langchain/models) in LangChain.--!!! warning "Reference docs"- This page contains **reference documentation** for chat models. See- [the docs](https://docs.langchain.com/oss/python/langchain/models) for conceptual- guides, tutorials, and examples on using chat models.-""" # noqa: E501+"""Entrypoint to using [chat models](https://docs.langchain.com/oss/python/langchain/models) in LangChain.""" # noqa: E501from langchain_core.language_models import BaseChatModeldiff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.pyindex d481eda62a..8856fb6d44 100644--- a/libs/langchain_v1/langchain/chat_models/base.py+++ b/libs/langchain_v1/langchain/chat_models/base.py@@ -87,6 +87,21 @@ def init_chat_model(You can also specify model and model provider in a single argument using`'{model_provider}:{model}'` format, e.g. `'openai:o1'`.++ Will attempt to infer `model_provider` from model if not specified.++ The following providers will be inferred based on these model prefixes:++ - `gpt-...` | `o1...` | `o3...` -> `openai`+ - `claude...` -> `anthropic`+ - `amazon...` -> `bedrock`+ - `gemini...` -> `google_vertexai`+ - `command...` -> `cohere`+ - `accounts/fireworks...` -> `fireworks`+ - `mistral...` -> `mistralai`+ - `deepseek...` -> `deepseek`+ - `grok...` -> `xai`+ - `sonar...` -> `perplexity`model_provider: The model provider if not specified as part of the model arg(see above).@@ -115,19 +130,6 @@ def init_chat_model(- `xai` -> [`langchain-xai`](https://docs.langchain.com/oss/python/integrations/providers/xai)- `perplexity` -> [`langchain-perplexity`](https://docs.langchain.com/oss/python/integrations/providers/perplexity)- Will attempt to infer `model_provider` from model if not specified. The- following providers will be inferred based on these model prefixes:-- - `gpt-...` | `o1...` | `o3...` -> `openai`- - `claude...` -> `anthropic`- - `amazon...` -> `bedrock`- - `gemini...` -> `google_vertexai`- - `command...` -> `cohere`- - `accounts/fireworks...` -> `fireworks`- - `mistral...` -> `mistralai`- - `deepseek...` -> `deepseek`- - `grok...` -> `xai`- - `sonar...` -> `perplexity`configurable_fields: Which model parameters are configurable at runtime:- `None`: No configurable fields (i.e., a fixed model).@@ -142,6 +144,7 @@ def init_chat_model(If `model` is not specified, then defaults to `("model", "model_provider")`.!!! warning "Security note"+Setting `configurable_fields="any"` means fields like `api_key`,`base_url`, etc., can be altered at runtime, potentially redirectingmodel requests to a different service/user.diff --git a/libs/langchain_v1/langchain/embeddings/__init__.py b/libs/langchain_v1/langchain/embeddings/__init__.pyindex 6943b1cd7c..fd87dabbf9 100644--- a/libs/langchain_v1/langchain/embeddings/__init__.py+++ b/libs/langchain_v1/langchain/embeddings/__init__.py@@ -1,10 +1,5 @@"""Embeddings models.-!!! warning "Reference docs"- This page contains **reference documentation** for Embeddings. See- [the docs](https://docs.langchain.com/oss/python/langchain/retrieval#embedding-models)- for conceptual guides, tutorials, and examples on using Embeddings.-!!! warning "Modules moved"With the release of `langchain 1.0.0`, several embeddings modules were moved to`langchain-classic`, such as `CacheBackedEmbeddings` and all communitydiff --git a/libs/langchain_v1/langchain/messages/__init__.py b/libs/langchain_v1/langchain/messages/__init__.pyindex b757afd1f4..35c779ac12 100644--- a/libs/langchain_v1/langchain/messages/__init__.py+++ b/libs/langchain_v1/langchain/messages/__init__.py@@ -2,11 +2,6 @@Includes message types for different roles (e.g., human, AI, system), as well as typesfor message content blocks (e.g., text, image, audio) and tool calls.--!!! warning "Reference docs"- This page contains **reference documentation** for Messages. See- [the docs](https://docs.langchain.com/oss/python/langchain/messages) for conceptual- guides, tutorials, and examples on using Messages."""from langchain_core.messages import (diff --git a/libs/langchain_v1/langchain/tools/__init__.py b/libs/langchain_v1/langchain/tools/__init__.pyindex 92aca31aec..903ed78a86 100644--- a/libs/langchain_v1/langchain/tools/__init__.py+++ b/libs/langchain_v1/langchain/tools/__init__.py@@ -1,10 +1,4 @@-"""Tools.--!!! warning "Reference docs"- This page contains **reference documentation** for Tools. See- [the docs](https://docs.langchain.com/oss/python/langchain/tools) for conceptual- guides, tutorials, and examples on using Tools.-"""+"""Tools."""from langchain_core.tools import (BaseTool,