Title: langchain | LangChain Reference
Open Graph Title: langchain
X Title: langchain
Description: Python API reference for langchain. Part of the LangChain ecosystem.
Open Graph Description: Python API reference for langchain. Part of the LangChain ecosystem.
X Description: Python API reference for langchain. Part of the LangChain ecosystem.
Opengraph URL: https://reference.langchain.com/python/langchain
Domain: reference.langchain.com
| og:image | https://reference.langchain.com/og/python/langchain |
| og:image:width | 1200 |
| og:image:height | 630 |
| og:image:alt | langchain |
| og:type | article |
| twitter:card | summary_large_image |
| twitter:image | https://reference.langchain.com/og/python/langchain |
Links:
| LangChain Reference home page | https://reference.langchain.com/ |
| GitHub | https://github.com/langchain-ai |
| Main Docs | https://docs.langchain.com/oss/python/langchain |
| Deep Agents | https://reference.langchain.com/python/deepagents |
| LangChain | https://reference.langchain.com/python/langchain/overview |
| LangGraph | https://reference.langchain.com/python/langgraph/overview |
| Integrations | https://reference.langchain.com/python/integrations/overview |
| LangSmith | https://reference.langchain.com/python/langsmith |
| Overview | https://reference.langchain.com/python/langchain/overview |
| Overview | https://reference.langchain.com/python/langchain |
| Agents | https://reference.langchain.com/python/langchain/agents |
| Middleware | https://reference.langchain.com/python/langchain/middleware |
| Models | https://reference.langchain.com/python/langchain/models |
| Messages | https://reference.langchain.com/python/langchain/messages |
| Tools | https://reference.langchain.com/python/langchain/tools |
| Embeddings | https://reference.langchain.com/python/langchain/embeddings |
| MCP Adapters | https://reference.langchain.com/python/langchain-mcp-adapters |
| Standard Tests | https://reference.langchain.com/python/langchain-tests |
| Text Splitters | https://reference.langchain.com/python/langchain-text-splitters |
| https://chat.langchain.com/ | |
| Overview | https://reference.langchain.com/python/langchain |
| Agents | https://reference.langchain.com/python/langchain/agents |
| Middleware | https://reference.langchain.com/python/langchain/middleware |
| Models | https://reference.langchain.com/python/langchain/models |
| Messages | https://reference.langchain.com/python/langchain/messages |
| Tools | https://reference.langchain.com/python/langchain/tools |
| Embeddings | https://reference.langchain.com/python/langchain/embeddings |
| MCP Adapters | https://reference.langchain.com/python/langchain-mcp-adapters |
| Standard Tests | https://reference.langchain.com/python/langchain-tests |
| Text Splitters | https://reference.langchain.com/python/langchain-text-splitters |
| https://pypi.org/project/langchain/#history | |
| https://opensource.org/licenses/MIT | |
| https://pypistats.org/packages/langchain | |
| https://x.com/langchain_oss | |
| LangChain.js | https://github.com/langchain-ai/langchainjs |
| LangSmith | https://www.langchain.com/langsmith |
| LangSmith | https://www.langchain.com/langsmith |
| more | https://docs.langchain.com/oss/python/integrations/providers/overview |
| LangGraph | https://docs.langchain.com/oss/python/langgraph/overview |
| agents | https://docs.langchain.com/oss/python/langchain/agents |
| API reference | https://reference.langchain.com/python/langchain/langchain/ |
| LangChain Docs | https://docs.langchain.com/oss/python/langchain/overview |
| Chat LangChain | https://chat.langchain.com |
| Releases | https://docs.langchain.com/oss/python/release-policy |
| Versioning | https://docs.langchain.com/oss/python/versioning |
| Contributing Guide | https://docs.langchain.com/oss/python/contributing/overview |
| LangChain Academy | https://academy.langchain.com/ |
| Code of Conduct | https://github.com/langchain-ai/langchain/?tab=coc-ov-file |
| ClassStructuredOutputErrorBase class for structured output errors. | https://reference.langchain.com/python/langchain/agents/structured_output/StructuredOutputError |
| ClassMultipleStructuredOutputsErrorRaised when model returns multiple structured output tool calls when only one is expected. | https://reference.langchain.com/python/langchain/agents/structured_output/MultipleStructuredOutputsError |
| ClassStructuredOutputValidationErrorRaised when structured output tool call arguments fail to parse according to the schema. | https://reference.langchain.com/python/langchain/agents/structured_output/StructuredOutputValidationError |
| ClassToolStrategyUse a tool calling strategy for model responses. | https://reference.langchain.com/python/langchain/agents/structured_output/ToolStrategy |
| ClassProviderStrategyUse the model provider's native structured output method. | https://reference.langchain.com/python/langchain/agents/structured_output/ProviderStrategy |
| ClassOutputToolBindingInformation for tracking structured output tool metadata. This contains all necessary information to handle structured responses generated via tool calls, including the original schema, its type clas | https://reference.langchain.com/python/langchain/agents/structured_output/OutputToolBinding |
| ClassProviderStrategyBindingInformation for tracking native structured output metadata. This contains all necessary information to handle structured responses generated via native provider output, including the original schema, | https://reference.langchain.com/python/langchain/agents/structured_output/ProviderStrategyBinding |
| ClassAutoStrategyAutomatically select the best strategy for structured output. | https://reference.langchain.com/python/langchain/agents/structured_output/AutoStrategy |
| ClassSubagentRunStreamTyped sync handle for a nested named-agent execution. Surfaces on run.subagents when a nested run's lc_agent_name differs from its parent's (i.e., a create_agent(name=...) dispatched from a too | https://reference.langchain.com/python/langchain/agents/_subagent_transformer/SubagentRunStream |
| ClassAsyncSubagentRunStreamTyped async handle for a nested named-agent execution. | https://reference.langchain.com/python/langchain/agents/_subagent_transformer/AsyncSubagentRunStream |
| ClassSubagentTransformerPromote nested named agents into typed handles on run.subagents. The base _TasksLifecycleBase records each namespace's lc_agent_name (set by create_agent(name=...)) and, on every task start, | https://reference.langchain.com/python/langchain/agents/_subagent_transformer/SubagentTransformer |
| ClassToolErrorMiddlewareReturn selected tool-execution exceptions to the model as error ToolMessages. on_error is called for each exception raised by tool execution. Return content (a str or a list of content blocks) | https://reference.langchain.com/python/langchain/agents/middleware/tool_error/ToolErrorMiddleware |
| ClassLLMToolSelectorMiddlewareUses an LLM to select relevant tools before calling the main model. When an agent has many tools available, this middleware filters them down to only the most relevant ones for the user's query. This | https://reference.langchain.com/python/langchain/agents/middleware/tool_selection/LLMToolSelectorMiddleware |
| ClassToolRetryMiddlewareMiddleware that automatically retries failed tool calls with configurable backoff. Supports retrying on specific exceptions and exponential backoff. | https://reference.langchain.com/python/langchain/agents/middleware/tool_retry/ToolRetryMiddleware |
| ClassTriggerClauseDictionary-based trigger specification for AND conditions. All specified thresholds in a single TriggerClause must be met for the clause to trigger summarization (AND semantics). When multiple clau | https://reference.langchain.com/python/langchain/agents/middleware/summarization/TriggerClause |
| ClassSummarizationMiddlewareSummarizes conversation history when token limits are approached. This middleware monitors message token counts and automatically summarizes older messages when a threshold is reached, preserving rec | https://reference.langchain.com/python/langchain/agents/middleware/summarization/SummarizationMiddleware |
| ClassProviderToolSearchMiddlewareDefer selected tools behind provider-native tool search. Instead of sending every tool schema on every turn, this middleware marks selected tools as deferred (via extras["defer_loading"]) and injec | https://reference.langchain.com/python/langchain/agents/middleware/provider_tool_search/ProviderToolSearchMiddleware |
| ClassBaseExecutionPolicyConfiguration 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 | https://reference.langchain.com/python/langchain/agents/middleware/_execution/BaseExecutionPolicy |
| ClassHostExecutionPolicyRun the shell directly on the host process. This policy is best suited for trusted or single-tenant environments (CI jobs, developer workstations, pre-sandboxed containers) where the agent must acces | https://reference.langchain.com/python/langchain/agents/middleware/_execution/HostExecutionPolicy |
| ClassCodexSandboxExecutionPolicyLaunch the shell through the Codex CLI sandbox. Ideal when you have the Codex CLI installed and want the additional syscall and filesystem restrictions provided by Anthropic's Seatbelt (macOS) or Lan | https://reference.langchain.com/python/langchain/agents/middleware/_execution/CodexSandboxExecutionPolicy |
| ClassDockerExecutionPolicyRun 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-m | https://reference.langchain.com/python/langchain/agents/middleware/_execution/DockerExecutionPolicy |
| ClassShellToolStateAgent state extension for tracking shell session resources. | https://reference.langchain.com/python/langchain/agents/middleware/shell_tool/ShellToolState |
| ClassCommandExecutionResultStructured result from command execution. | https://reference.langchain.com/python/langchain/agents/middleware/shell_tool/CommandExecutionResult |
| ClassShellSessionPersistent shell session that supports sequential command execution. | https://reference.langchain.com/python/langchain/agents/middleware/shell_tool/ShellSession |
| ClassShellToolMiddlewareMiddleware 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: `HostE | https://reference.langchain.com/python/langchain/agents/middleware/shell_tool/ShellToolMiddleware |
| ClassPIIMatchRepresents an individual match of sensitive data. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/PIIMatch |
| ClassPIIDetectionErrorRaised when configured to block on detected sensitive values. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/PIIDetectionError |
| ClassRedactionRuleConfiguration for handling a single PII type. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/RedactionRule |
| ClassResolvedRedactionRuleResolved redaction rule ready for execution. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/ResolvedRedactionRule |
| ClassModelRetryMiddlewareMiddleware that automatically retries failed model calls with configurable backoff. Supports retrying on specific exceptions and exponential backoff. | https://reference.langchain.com/python/langchain/agents/middleware/model_retry/ModelRetryMiddleware |
| ClassModelCallLimitStateState schema for ModelCallLimitMiddleware. Extends AgentState with model call tracking fields. | https://reference.langchain.com/python/langchain/agents/middleware/model_call_limit/ModelCallLimitState |
| ClassModelCallLimitExceededErrorException 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. | https://reference.langchain.com/python/langchain/agents/middleware/model_call_limit/ModelCallLimitExceededError |
| ClassModelCallLimitMiddlewareTracks model call counts and enforces limits. This middleware monitors the number of model calls made during agent execution and can terminate the agent when specified limits are reached. It supports | https://reference.langchain.com/python/langchain/agents/middleware/model_call_limit/ModelCallLimitMiddleware |
| ClassContextEditProtocol describing a context editing strategy. | https://reference.langchain.com/python/langchain/agents/middleware/context_editing/ContextEdit |
| ClassClearToolUsesEditConfiguration for clearing tool outputs when token limits are exceeded. | https://reference.langchain.com/python/langchain/agents/middleware/context_editing/ClearToolUsesEdit |
| ClassContextEditingMiddlewareAutomatically prune tool results to manage context size. The middleware applies a sequence of edits when the total input token count exceeds configured thresholds. Currently the ClearToolUsesEdit | https://reference.langchain.com/python/langchain/agents/middleware/context_editing/ContextEditingMiddleware |
| ClassFilesystemFileSearchMiddlewareProvides 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 | https://reference.langchain.com/python/langchain/agents/middleware/file_search/FilesystemFileSearchMiddleware |
| ClassModelFallbackMiddlewareAutomatic 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. | https://reference.langchain.com/python/langchain/agents/middleware/model_fallback/ModelFallbackMiddleware |
| ClassInternalCallTransformerKeep internal model calls out of run.messages and the raw event log. Used by middleware that makes internal model calls and runs before built-in transformers. For tagged events, streamed `message- | https://reference.langchain.com/python/langchain/agents/middleware/internal_call_transformer/InternalCallTransformer |
| ClassActionRepresents an action with a name and args. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/Action |
| ClassActionRequestRepresents an action request with a name, args, and description. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/ActionRequest |
| ClassReviewConfigPolicy for reviewing a HITL request. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/ReviewConfig |
| ClassHITLRequestRequest for human feedback on a sequence of actions requested by a model. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/HITLRequest |
| ClassApproveDecisionResponse when a human approves the action. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/ApproveDecision |
| ClassEditDecisionResponse when a human edits the action. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/EditDecision |
| ClassRejectDecisionResponse when a human rejects the action. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/RejectDecision |
| ClassRespondDecisionResponse when a human answers on behalf of the tool, skipping execution. Used for "ask user" style tools whose real implementation is the human's response. The tool is not executed; instead, a synthe | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/RespondDecision |
| ClassToolApprovalRequestInterrupt value raised once per gated tool call in per_call mode. Takes the place of HITLRequest. Answer it with a single Decision, keyed by the interrupt's ID, not a HITLResponse. The interr | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/ToolApprovalRequest |
| ClassHITLResponseResponse payload for a HITLRequest. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/HITLResponse |
| ClassInterruptOnConfigConfiguration for an action requiring human in the loop. This is the configuration format used in the HumanInTheLoopMiddleware.__init__ method. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/InterruptOnConfig |
| ClassHumanInTheLoopMiddlewarePause the agent so a person can review tool calls before they run. Each tool in interrupt_on needs a decision before it runs: approve, edit, reject, or respond. The pause is a LangGraph interrupt | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/HumanInTheLoopMiddleware |
| ClassToolCallLimitStateState schema for ToolCallLimitMiddleware. Extends AgentState with tool call tracking fields. The count fields are dictionaries mapping tool names to execution counts. This allows multiple middle | https://reference.langchain.com/python/langchain/agents/middleware/tool_call_limit/ToolCallLimitState |
| ClassToolCallLimitExceededErrorException 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. | https://reference.langchain.com/python/langchain/agents/middleware/tool_call_limit/ToolCallLimitExceededError |
| ClassToolCallLimitMiddlewareTrack tool call counts and enforces limits during agent execution. This middleware monitors the number of tool calls made and can terminate or restrict execution when limits are exceeded. It supports | https://reference.langchain.com/python/langchain/agents/middleware/tool_call_limit/ToolCallLimitMiddleware |
| ClassPIIMiddlewareDetect 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 | https://reference.langchain.com/python/langchain/agents/middleware/pii/PIIMiddleware |
| ClassTodoA single todo item with content and status. | https://reference.langchain.com/python/langchain/agents/middleware/todo/Todo |
| ClassPlanningStateState schema for the todo middleware. | https://reference.langchain.com/python/langchain/agents/middleware/todo/PlanningState |
| ClassWriteTodosInputInput schema for the write_todos tool. | https://reference.langchain.com/python/langchain/agents/middleware/todo/WriteTodosInput |
| ClassTodoListMiddlewareMiddleware that provides todo list management capabilities to agents. This middleware adds a write_todos tool that allows agents to create and manage structured task lists for complex multi-step op | https://reference.langchain.com/python/langchain/agents/middleware/todo/TodoListMiddleware |
| ClassModelRequestModel request information for the agent. | https://reference.langchain.com/python/langchain/agents/middleware/types/ModelRequest |
| ClassModelResponseResponse 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 | https://reference.langchain.com/python/langchain/agents/middleware/types/ModelResponse |
| ClassExtendedModelResponseModel response with an optional 'Command' from 'wrap_model_call' middleware. Use this to return a 'Command' alongside the model response from a 'wrap_model_call' handler. The command is applied as an | https://reference.langchain.com/python/langchain/agents/middleware/types/ExtendedModelResponse |
| ClassOmitFromSchemaAnnotation used to mark state attributes as omitted from input or output schemas. | https://reference.langchain.com/python/langchain/agents/middleware/types/OmitFromSchema |
| ClassAgentStateState schema for the agent. | https://reference.langchain.com/python/langchain/agents/middleware/types/AgentState |
| ClassInputAgentStateInput state schema for the agent. | https://reference.langchain.com/python/langchain/agents/middleware/types/InputAgentState |
| ClassOutputAgentStateOutput state schema for the agent. | https://reference.langchain.com/python/langchain/agents/middleware/types/OutputAgentState |
| ClassAgentMiddlewareBase middleware class for an agent. Subclass this and implement any of the defined methods to customize agent behavior between steps in the main agent loop. | https://reference.langchain.com/python/langchain/agents/middleware/types/AgentMiddleware |
| ClassLLMToolEmulatorEmulates 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 | https://reference.langchain.com/python/langchain/agents/middleware/tool_emulator/LLMToolEmulator |
| ClassMCPElicitationFormRequestA request for data matching a schema. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationFormRequest |
| ClassMCPElicitationUrlRequestA request for the human to visit an address. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationUrlRequest |
| ClassMCPElicitationInterruptInterrupt payload raised while an MCP tool call waits on input. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationInterrupt |
| ClassMCPElicitationAcceptAn answer to an MCPElicitationRequest. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationAccept |
| ClassMCPElicitationDeclineA refusal to answer an MCPElicitationRequest, leaving the call to go on. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationDecline |
| ClassMCPElicitationCancelA refusal that abandons the tool call rather than just the question. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationCancel |
| ClassMCPElicitationResumeValue used to resume a run interrupted by an MCP elicitation. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationResume |
| ClassMCPToolArtifactArtifact attached to the ToolMessage produced by an MCP tool call. Wrapping the structured content in a TypedDict leaves room for further MCP result fields without changing the artifact's shape. | https://reference.langchain.com/python/langchain/mcp/tools/MCPToolArtifact |
| ClassMCPAdapterAdapt an MCP target into LangChain tools. MCPAdapter uses FastMCP for protocol negotiation and connection management, then converts discovered MCP tools into asynchronous LangChain tools. The resul | https://reference.langchain.com/python/langchain/mcp/adapter/MCPAdapter |
| Functioninit_chat_modelInitialize a chat model from any supported provider using a unified interface. Two main use cases: Fixed model – specify the model upfront and get a ready-to-use chat model. **Conf | https://reference.langchain.com/python/langchain/chat_models/base/init_chat_model |
| Functioncreate_agentCreates an agent graph that calls tools in a loop until a stopping condition is met. For more details on using create_agent, visit the [Agents](https://docs.langchain.com/oss/python/langchain/agent | https://reference.langchain.com/python/langchain/agents/factory/create_agent |
| Functionvalidate_retry_paramsValidate retry parameters. | https://reference.langchain.com/python/langchain/agents/middleware/_retry/validate_retry_params |
| Functiondefault_retry_onReturn whether an exception should be retried by default. | https://reference.langchain.com/python/langchain/agents/middleware/_retry/default_retry_on |
| Functionshould_retry_exceptionCheck if an exception should trigger a retry. | https://reference.langchain.com/python/langchain/agents/middleware/_retry/should_retry_exception |
| Functioncalculate_delayCalculate delay for a retry attempt with exponential backoff and optional jitter. | https://reference.langchain.com/python/langchain/agents/middleware/_retry/calculate_delay |
| Functionconfigure_trace_policySet the process-wide default TracePolicy for agent middleware hook spans. Call once at startup. A middleware's own trace_policy overrides this wholesale (no field-level merge). Pass None to cle | https://reference.langchain.com/python/langchain/agents/middleware/_trace_policy/configure_trace_policy |
| Functionshell_tool | https://reference.langchain.com/python/langchain/agents/middleware/shell_tool/ShellToolMiddleware/__init__/shell_tool |
| Functiondetect_emailDetect email addresses in content. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/detect_email |
| Functiondetect_credit_cardDetect credit card numbers in content using Luhn validation. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/detect_credit_card |
| Functiondetect_ipDetect IPv4 or IPv6 addresses in content. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/detect_ip |
| Functiondetect_mac_addressDetect MAC addresses in content. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/detect_mac_address |
| Functiondetect_urlDetect URLs in content using regex and stdlib validation. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/detect_url |
| Functionapply_strategyApply the configured strategy to matches within content. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/apply_strategy |
| Functionresolve_detectorReturn a callable detector for the given configuration. | https://reference.langchain.com/python/langchain/agents/middleware/_redaction/resolve_detector |
| Functionglob_searchFast file pattern matching tool that works with any codebase size. Supports glob patterns like **/*.js or src/**/*.ts. Returns matching file paths sorted by modification time. Use this tool whe | https://reference.langchain.com/python/langchain/agents/middleware/file_search/FilesystemFileSearchMiddleware/__init__/glob_search |
| Functiongrep_searchFast content search tool that works with any codebase size. Searches file contents using regular expressions. Supports full regex syntax and filters files by pattern with the include parameter. | https://reference.langchain.com/python/langchain/agents/middleware/file_search/FilesystemFileSearchMiddleware/__init__/grep_search |
| Functioninternal_call_metadataReturn metadata that marks a model call as internal to middleware. | https://reference.langchain.com/python/langchain/agents/middleware/internal_call_transformer/internal_call_metadata |
| Functionwrite_todosCreate and manage a structured task list for your current work session. | https://reference.langchain.com/python/langchain/agents/middleware/todo/write_todos |
| Functionhook_configDecorator to configure hook behavior in middleware methods. Use this decorator on before_model or after_model methods in middleware classes to configure their behavior. Currently supports specify | https://reference.langchain.com/python/langchain/agents/middleware/types/hook_config |
| Functionbefore_modelDecorator used to dynamically create a middleware with the before_model hook. | https://reference.langchain.com/python/langchain/agents/middleware/types/before_model |
| Functionafter_modelDecorator used to dynamically create a middleware with the after_model hook. | https://reference.langchain.com/python/langchain/agents/middleware/types/after_model |
| Functionbefore_agentDecorator used to dynamically create a middleware with the before_agent hook. | https://reference.langchain.com/python/langchain/agents/middleware/types/before_agent |
| Functionafter_agentDecorator used to dynamically create a middleware with the after_agent hook. Async version is aafter_agent. | https://reference.langchain.com/python/langchain/agents/middleware/types/after_agent |
| Functiondynamic_promptDecorator used to dynamically generate system prompts for the model. This is a convenience decorator that creates middleware using wrap_model_call specifically for dynamic prompt generation. The de | https://reference.langchain.com/python/langchain/agents/middleware/types/dynamic_prompt |
| Functionwrap_model_callCreate 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 rewr | https://reference.langchain.com/python/langchain/agents/middleware/types/wrap_model_call |
| Functionwrap_tool_callCreate middleware with wrap_tool_call hook from a function. Async version is awrap_tool_call. Converts a function with handler callback into middleware that can intercept tool calls, implement r | https://reference.langchain.com/python/langchain/agents/middleware/types/wrap_tool_call |
| Functioninit_embeddingsInitialize an embedding model from a model name and optional provider. NoteRequires the integration package for the chosen model provider to be installed. See the model_provider para | https://reference.langchain.com/python/langchain/embeddings/base/init_embeddings |
| Functionas_langchain_toolConvert one MCP tool into a LangChain tool. The returned tool calls the MCP tool through client on every invocation. FastMCP clients are reentrant, so the tool can open the client itself whether or | https://reference.langchain.com/python/langchain/mcp/tools/as_langchain_tool |
| Functionarmed | https://reference.langchain.com/python/langchain/mcp/adapter/MCPAdapter/__init__/armed |
| ModulelangchainMain entrypoint into LangChain. | https://reference.langchain.com/python/langchain/langchain |
| ModulemessagesMessage and message content types. Includes message types for different roles (e.g., human, AI, system), as well as types for message content blocks (e.g., text, image, audio) and tool calls. | https://reference.langchain.com/python/langchain/messages |
| Modulechat_modelsEntrypoint to using chat models in LangChain. | https://reference.langchain.com/python/langchain/chat_models |
| ModulebaseFactory functions for chat models. | https://reference.langchain.com/python/langchain/chat_models/base |
| ModuleagentsEntrypoint to building Agents with LangChain. | https://reference.langchain.com/python/langchain/agents |
| Modulestructured_outputTypes for setting agent response formats. | https://reference.langchain.com/python/langchain/agents/structured_output |
| ModulefactoryAgent factory for creating agents with middleware support. | https://reference.langchain.com/python/langchain/agents/factory |
| ModulemiddlewareEntrypoint to using middleware plugins with Agents. | https://reference.langchain.com/python/langchain/agents/middleware |
| Moduletool_errorTool error middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/tool_error |
| Moduletool_selectionLLM-based tool selector middleware. | https://reference.langchain.com/python/langchain/agents/middleware/tool_selection |
| Moduletool_retryTool retry middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/tool_retry |
| ModulesummarizationSummarization middleware. | https://reference.langchain.com/python/langchain/agents/middleware/summarization |
| Moduleprovider_tool_searchProvider-side tool search middleware. | https://reference.langchain.com/python/langchain/agents/middleware/provider_tool_search |
| Moduleshell_toolMiddleware that exposes a persistent shell tool to agents. | https://reference.langchain.com/python/langchain/agents/middleware/shell_tool |
| Modulemodel_retryModel retry middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/model_retry |
| Modulemodel_call_limitCall tracking middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/model_call_limit |
| Modulecontext_editingContext editing middleware. Mirrors Anthropic's context editing capabilities by clearing older tool results once the conversation grows beyond a configurable token threshold. The implementation is i | https://reference.langchain.com/python/langchain/agents/middleware/context_editing |
| Modulefile_searchFile search middleware for Anthropic text editor and memory tools. This module provides Glob and Grep search tools that operate on files stored in state or filesystem. | https://reference.langchain.com/python/langchain/agents/middleware/file_search |
| Modulemodel_fallbackModel fallback middleware for agents. When an outer caching middleware modifies a request, those changes happen before the fallback loop runs. Provider-specific cache settings can cause API errors if | https://reference.langchain.com/python/langchain/agents/middleware/model_fallback |
| Moduleinternal_call_transformerTag and filter middleware-internal model calls. Tag internal calls with internal_call_metadata() and declare transformers = (InternalCallTransformer,) on the middleware class to keep them out of | https://reference.langchain.com/python/langchain/agents/middleware/internal_call_transformer |
| Modulehuman_in_the_loopHuman in the loop middleware. | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop |
| Moduletool_call_limitTool call limit middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/tool_call_limit |
| ModulepiiPII detection and handling middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/pii |
| ModuletodoPlanning and task management middleware for agents. | https://reference.langchain.com/python/langchain/agents/middleware/todo |
| ModuletypesTypes for middleware and agents. | https://reference.langchain.com/python/langchain/agents/middleware/types |
| Moduletool_emulatorTool emulator middleware for testing. | https://reference.langchain.com/python/langchain/agents/middleware/tool_emulator |
| ModuleembeddingsEmbeddings models. Modules movedWith the release of langchain 1.0.0, several embeddings modules were moved to langchain-classic, such as CacheBackedEmbeddings and all co | https://reference.langchain.com/python/langchain/embeddings |
| ModulebaseFactory functions for embeddings. | https://reference.langchain.com/python/langchain/embeddings/base |
| ModulemcpLangChain MCP adapters for connecting MCP servers with LangChain applications. Interrupt-driven elicitation has its own types — the interrupt payload, the answers a run resumes with, and the discrimi | https://reference.langchain.com/python/langchain/mcp |
| ModuleelicitationAnswer MCP elicitation requests with a LangGraph interrupt. A server needing input mid-call returns an InputRequiredResult and expects the tools/call to be retried with answers. This module drive | https://reference.langchain.com/python/langchain/mcp/elicitation |
| ModuletoolsConvert MCP tools and tool results into LangChain-native values. Tool results follow langchain-mcp-adapters, so a call made through langchain.mcp reaches a model in the same shape as one loaded b | https://reference.langchain.com/python/langchain/mcp/tools |
| ModuleadapterAdapt MCP tools into LangChain tools suitable for create_agent. | https://reference.langchain.com/python/langchain/mcp/adapter |
| Modulerate_limitersBase abstraction and in-memory implementation of rate limiters. These rate limiters can be used to limit the rate of requests to an API. The rate limiters can be used together with BaseChatModel. | https://reference.langchain.com/python/langchain/rate_limiters |
| ModuletoolsTools. | https://reference.langchain.com/python/langchain/tools |
| Moduletool_nodeUtils file included for backwards compat imports. | https://reference.langchain.com/python/langchain/tools/tool_node |
| TypeResponseFormatUnion type for all supported response format strategies. | https://reference.langchain.com/python/langchain/agents/structured_output/ResponseFormat |
| TypeRetryOnType for specifying which exceptions to retry on. Can be either: A tuple of exception types to retry on (based on isinstance checks) A callable that takes an exception and returns True if it | https://reference.langchain.com/python/langchain/agents/middleware/_retry/RetryOn |
| TypeOnFailureType for specifying failure handling behavior. Can be either: A literal action string ('error' or 'continue') 'error': Re-raise the exception, stopping agent execution. `'continue | https://reference.langchain.com/python/langchain/agents/middleware/_retry/OnFailure |
| TypeOnParsingFailureBehavior when the selection model keeps returning a malformed response. Can be either: 'error': Raise a ValueError (the default). 'none': Select no tools. 'all': Select every available | https://reference.langchain.com/python/langchain/agents/middleware/tool_selection/OnParsingFailure |
| TypeSummarizerGenerates a summary from the messages selected for summarization. Either a chat model (or model string) prompted with the summary prompt, or a Runnable or callable taking the messages and returning | https://reference.langchain.com/python/langchain/agents/middleware/summarization/Summarizer |
| TypeContextSizeUnion type for context size specifications. Can be either: ContextFraction: A fraction of the model's maximum input tokens. [`C | https://reference.langchain.com/python/langchain/agents/middleware/summarization/ContextSize |
| TypeToolIdentifierTool name or tool instance that can be deferred behind provider tool search. | https://reference.langchain.com/python/langchain/agents/middleware/provider_tool_search/ToolIdentifier |
| TypeDecision | https://reference.langchain.com/python/langchain/agents/middleware/human_in_the_loop/Decision |
| TypeModelCallResultReturn type for model call handlers. Middleware can return either: ModelResponse: Full response with messages and optional structured output AIMessage: Simplified return for simple use cases | https://reference.langchain.com/python/langchain/agents/middleware/types/ModelCallResult |
| TypeMCPFormContentValues a form answer may carry, as narrow as mcp.types.ElicitResult.content. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPFormContent |
| TypeMCPElicitationRequestOne question an MCP server asks before finishing a tool call. Narrow on mode. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationRequest |
| TypeMCPElicitationResponseOne answer to an MCPElicitationRequest. Narrow on action; only accept carries content. | https://reference.langchain.com/python/langchain/mcp/elicitation/MCPElicitationResponse |
| TypeToolMessageContentBlockLangChain content blocks an MCP tool result can convert into. | https://reference.langchain.com/python/langchain/mcp/tools/ToolMessageContentBlock |
| TypeMCPAdapterTargetAnything MCPAdapter accepts as its target. Every transport fastmcp.Client accepts, plus a pre-built fastmcp.Client. A str target is the one member narrowed relative to fastmcp.Client: it | https://reference.langchain.com/python/langchain/mcp/adapter/MCPAdapterTarget |
Viewport: width=device-width, initial-scale=1