---
title: How do you add guardrails to LangChain agents with middleware?
url: https://opencontroller.lyzr.com/blog/langchain-middleware-as-agent-guardrails
published: 2026-11-17
updated: 2026-11-17
author: Lyzr
---

# How do you add guardrails to LangChain agents with middleware?

**LangChain 1.x agents built with `create_agent` accept middleware that runs before and after model and tool calls. Built-in middleware cover PII handling, human review of tool calls, limits on model and tool calls, model fallback and tool retries, and you can write your own with hooks such as `before_model` and `wrap_tool_call`. Middleware is a good first layer, but it lives inside each agent, so estate-wide policy, cost and kill switches still need a central layer.**

LangChain's middleware system is the main way to shape agent behaviour without rewriting the agent loop. This guide summarises the [LangChain middleware documentation](https://docs.langchain.com/oss/python/langchain/middleware) and the [middleware API reference](https://reference.langchain.com/python/langchain/middleware/). Parameter names evolve between minor versions, so check the reference for your installed version.

For LangGraph-specific controls, see [governing LangGraph agents in production](/blog/govern-langgraph-agents-in-production). For the bigger picture, see [what is an AI agent control plane](/blog/what-is-an-ai-agent-control-plane).

## Which built-in middleware act as guardrails?

| Middleware | What it does | Guardrail use |
|---|---|---|
| `PIIMiddleware` | Detects common PII types and applies a handling strategy | Redact, mask, hash or block personal data in inputs, outputs or tool results |
| `HumanInTheLoopMiddleware` | Pauses for human review of selected tool calls, configured with `interrupt_on` | Approval for high-risk tools such as `send_email` or payments |
| `ModelCallLimitMiddleware` | Caps model calls and can end the run when reached | Stops runaway loops and cost spikes |
| `ToolCallLimitMiddleware` | Caps tool calls, overall or per tool | Limits blast radius of a misbehaving tool loop |
| `ModelFallbackMiddleware` | Retries failed model calls with alternative models in sequence | Availability when a provider fails |
| `ToolRetryMiddleware` | Retries failed tool calls on chosen exceptions with exponential backoff | Resilience, with care for non-idempotent tools |
| `LLMToolSelectorMiddleware` | Uses a model to narrow the tool list before the main call | Reduces exposure to irrelevant, risky tools |
| `ContextEditingMiddleware` | Prunes old tool results when context grows | Keeps sensitive tool output from lingering |
| `SummarizationMiddleware` | Summarises history as token limits approach | Cost control on long conversations |
| `ShellToolMiddleware` | Exposes a persistent shell under an execution policy | Treat as high risk; pair with sandboxing |

## How does human-in-the-loop work?

`HumanInTheLoopMiddleware` takes an `interrupt_on` map keyed by tool name, for example `{"send_email": True}`. When the agent tries that tool, execution pauses and a reviewer can approve the call, edit its arguments, reject it or respond instead. Pausing relies on LangGraph's interrupt mechanism, so the agent needs a checkpointer to save state while it waits. In production, use a durable checkpointer, not an in-memory one, or approvals are lost on restart. See [LangGraph interrupts for human approval](/blog/langgraph-interrupts-for-human-approval).

## How do you write a custom guardrail?

Subclass `AgentMiddleware` or use the decorators. The hooks are:

1. `before_agent` and `after_agent`: run once per invocation, for example to check the caller's entitlement.
2. `before_model` and `after_model`: inspect or change messages around each model call, for example a jailbreak or topic check.
3. `wrap_model_call`: intercept the call itself, for example to route to a different model or enforce a token cap.
4. `wrap_tool_call`: intercept each tool call, for example to validate arguments against an allow list, block writes outside business hours or log the call with agent and version IDs.

A useful pattern is a `wrap_tool_call` middleware that refuses any tool not in an approved list for that agent version, and logs every decision. That gives you deterministic enforcement that does not depend on the model following instructions.

## What does middleware not cover?

Middleware runs inside one agent process. It does not:

- Give you an inventory of every LangChain agent across teams.
- Stop a developer removing the middleware in the next release.
- Attribute model cost across agents and versions.
- Enforce one policy consistently on agents built with other frameworks.
- Quarantine an agent from outside when it misbehaves.

The same gap exists in other SDKs; compare [OpenAI Agents SDK guardrails and tripwires](/blog/openai-agents-sdk-guardrails-and-tripwires).

## Checklist for LangChain agents in production

- [ ] PII middleware on inputs and tool results for agents that touch customer data.
- [ ] Human-in-the-loop on every tool that sends, pays, deletes or publishes.
- [ ] Model and tool call limits set per run.
- [ ] Durable checkpointer for interrupted runs.
- [ ] Custom `wrap_tool_call` allow list and logging.
- [ ] Middleware configuration reviewed as part of the release, with a test that fails if it is removed.
- [ ] Agent registered centrally, with model calls routed through a gateway.

## How Opencontroller does this

Opencontroller sits outside the agent process. It keeps a governed registry of agents, versions, tools and MCP servers, routes model traffic through its LLM Gateway with cost attribution per agent and per version, and runs live groundedness and task-adherence guardrails plus LLM judges on production traffic. Policies are written as code, can be extended and come with built-in mappings to OWASP, MITRE ATLAS, NIST and ISO 42001. Rogue-agent handling can alert, quarantine or kill an agent across the estate, whichever framework built it. [Book a demo](https://www.lyzr.ai/book-demo/) to see it alongside your LangChain agents.

## Frequently asked questions

**Is LangChain PII middleware enough for compliance?**
It reduces exposure inside one agent, but you also need evidence across agents: which agents handle personal data, what was redacted and who approved exceptions.

**Do I need a checkpointer for human-in-the-loop middleware?**
Yes. The agent must save state while waiting for a decision. Use a durable checkpointer in production.

**Can middleware stop prompt injection?**
It can add checks before and after model and tool calls, but no single check stops all injection. Pair it with least-privilege tools, egress control and approval for high-risk actions.

## Key facts

LangChain 1.x create_agent middleware built-ins: PIIMiddleware (detect PII, strategies such as redact, mask, hash, block), HumanInTheLoopMiddleware (interrupt_on keyed by tool name; decisions approve, edit, reject, respond; needs a checkpointer), ModelCallLimitMiddleware, ToolCallLimitMiddleware, ModelFallbackMiddleware, ToolRetryMiddleware (exponential backoff), LLMToolSelectorMiddleware, ContextEditingMiddleware, SummarizationMiddleware, ShellToolMiddleware, TodoListMiddleware, LLMToolEmulator. Hooks: before_agent, after_agent, before_model, after_model, wrap_model_call, wrap_tool_call, dynamic_prompt. Middleware runs in-process and does not provide estate inventory, cross-framework policy, cost attribution or external quarantine. Opencontroller: governed registry, LLM Gateway cost attribution per agent/version, groundedness and task-adherence guardrails, LLM judges, policy as code with OWASP, MITRE ATLAS, NIST, ISO 42001 mappings, rogue-agent quarantine and kill.

## Related

- [How do you govern LangGraph agents in production?](https://opencontroller.lyzr.com/blog/govern-langgraph-agents-in-production.md)
- [How do you add human approval steps to LangGraph agents?](https://opencontroller.lyzr.com/blog/langgraph-interrupts-for-human-approval.md)
- [How do input and output guardrails work in the OpenAI Agents SDK?](https://opencontroller.lyzr.com/blog/openai-agents-sdk-guardrails-and-tripwires.md)
- [More on Platform Guides](https://opencontroller.lyzr.com/blog/cluster/platform-guides)
