Official agent skill

Langchain Middleware

by langchain-ai in langchain-ai/langchain-skills

INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output.

OfficialMITAuto-check passedAI & LLM Engineering

Install Langchain Middleware

skills CLI
$ npx skills add langchain-ai/langchain-skills --skill langchain-middleware -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install langchain-ai/langchain-skills langchain-middleware --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/langchain-ai/langchain-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/config/skills/langchain-middleware .claude/skills/langchain-middleware && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
langchain-middleware
GitHub stars
1.3k
Token cost
~2.7k tokens
SKILL.md length
381 words
Files
1
Skills in repo
22
Repo updated
First seen
Licence
MIT

At a glance

INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output.

  • Tasks that involve Building AI agents
  • SKILL.md covers Human-in-the-Loop and Custom Middleware Hooks
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve Human-in-the-loop approvals

What it does

Langchain Middleware is an agent skill from langchain-ai/langchain-skills, published by the product's own GitHub organization. INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output. Covers HumanInTheLoopMiddleware for human approval of dangerous tool calls, creating custom middleware with hooks, Command resume patterns, and structured output with Pydantic/Zod.

Its SKILL.md is about 2.7k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in AI & LLM Engineering, covering Building AI agents, Human-in-the-loop approvals and Structured output and tool calling. It works with LangChain, Pydantic, Zod and Python. The licence is MIT.

When your agent uses it

  • Tasks that involve Building AI agents
  • Tasks that involve Human-in-the-loop approvals
  • Tasks that involve Structured output and tool calling

Example prompts

  • “/langchain-middleware”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit 16a992f. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python and typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Langchain Middleware loads about 2.7k tokens when it runs. Until then it costs about 76 tokens; SKILL.md has 381 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~76
When it runs · the whole SKILL.md, loaded when a task matches
~2.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from langchain-ai/langchain-skills at commit 16a992f, republished under its MIT licence (© langchain-ai). 381 words, ~2,690 tokens.

Download SKILL.mdSave it as .claude/skills/langchain-middleware/SKILL.md (or your agent's skills folder).
name
langchain-middleware
description
INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output. Covers HumanInTheLoopMiddleware for human approval of dangerous tool calls, creating custom middleware with hooks, Command resume patterns, and structured output with Pydantic/Zod.
<overview>
Middleware patterns for production LangChain agents:
  • HumanInTheLoopMiddleware / humanInTheLoopMiddleware: Pause before dangerous tool calls for human approval
  • Custom middleware: Intercept tool calls for error handling, logging, retry logic
  • Command resume: Continue execution after human decisions (approve, edit, reject)

Requirements: Checkpointer + thread_id config for all HITL workflows. </overview>


Human-in-the-Loop

<ex-basic-hitl-setup>
<python>
Set up an agent with HITL middleware that pauses before sending emails for approval.
python
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import MemorySaver
from langchain.tools import tool

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email."""
    return f"Email sent to {to}"

agent = create_agent(
    model="gpt-4.1",
    tools=[send_email],
    checkpointer=MemorySaver(),  # Required for HITL
    middleware=[
        HumanInTheLoopMiddleware(
            interrupt_on={
                "send_email": {"allowed_decisions": ["approve", "edit", "reject"]},
            }
        )
    ],
)
</python>
<typescript>
Set up an agent with HITL that pauses before sending emails for human approval.
typescript
import { createAgent, humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

const sendEmail = tool(
  async ({ to, subject, body }) => `Email sent to ${to}`,
  {
    name: "send_email",
    description: "Send an email",
    schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
  }
);

const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5",
  tools: [sendEmail],
  checkpointer: new MemorySaver(),
  middleware: [
    humanInTheLoopMiddleware({
      interruptOn: { send_email: { allowedDecisions: ["approve", "edit", "reject"] } },
    }),
  ],
});
</typescript>
</ex-basic-hitl-setup>
<ex-running-with-interrupts>
<python>
Run the agent, detect an interrupt, then resume execution after human approval.
python
from langgraph.types import Command

config = {"configurable": {"thread_id": "session-1"}}

# Step 1: Agent runs until it needs to call tool
result1 = agent.invoke({
    "messages": [{"role": "user", "content": "Send email to john@example.com"}]
}, config=config)

# Check for interrupt
if "__interrupt__" in result1:
    print(f"Waiting for approval: {result1['__interrupt__']}")

# Step 2: Human approves
result2 = agent.invoke(
    Command(resume={"decisions": [{"type": "approve"}]}),
    config=config
)
</python>
<typescript>
Run the agent, detect an interrupt, then resume execution after human approval.
typescript
import { Command } from "@langchain/langgraph";

const config = { configurable: { thread_id: "session-1" } };

// Step 1: Agent runs until it needs to call tool
const result1 = await agent.invoke({
  messages: [{ role: "user", content: "Send email to john@example.com" }]
}, config);

// Check for interrupt
if (result1.__interrupt__) {
  console.log(`Waiting for approval: ${result1.__interrupt__}`);
}

// Step 2: Human approves
const result2 = await agent.invoke(
  new Command({ resume: { decisions: [{ type: "approve" }] } }),
  config
);
</typescript>
</ex-running-with-interrupts>
<ex-editing-tool-arguments>
<python>
Edit the tool arguments before approving when the original values need correction.
python
# Human edits the arguments — edited_action must include name + args
result2 = agent.invoke(
    Command(resume={
        "decisions": [{
            "type": "edit",
            "edited_action": {
                "name": "send_email",
                "args": {
                    "to": "alice@company.com",  # Fixed email
                    "subject": "Project Meeting - Updated",
                    "body": "...",
                },
            },
        }]
    }),
    config=config
)
</python>
<typescript>
Edit the tool arguments before approving when the original values need correction.
typescript
// Human edits the arguments — editedAction must include name + args
const result2 = await agent.invoke(
  new Command({
    resume: {
      decisions: [{
        type: "edit",
        editedAction: {
          name: "send_email",
          args: {
            to: "alice@company.com",  // Fixed email
            subject: "Project Meeting - Updated",
            body: "...",
          },
        },
      }]
    }
  }),
  config
);
</typescript>
</ex-editing-tool-arguments>
<ex-rejecting-with-feedback>
<python>
Reject a tool call and provide feedback explaining why it was rejected.
python
# Human rejects
result2 = agent.invoke(
    Command(resume={
        "decisions": [{
            "type": "reject",
            "feedback": "Cannot delete customer data without manager approval",
        }]
    }),
    config=config
)
</python>
</ex-rejecting-with-feedback>
<ex-multiple-tools-different-policies>
<python>
Configure different HITL policies for each tool based on risk level.
python
agent = create_agent(
    model="gpt-4.1",
    tools=[send_email, read_email, delete_email],
    checkpointer=MemorySaver(),
    middleware=[
        HumanInTheLoopMiddleware(
            interrupt_on={
                "send_email": {"allowed_decisions": ["approve", "edit", "reject"]},
                "delete_email": {"allowed_decisions": ["approve", "reject"]},  # No edit
                "read_email": False,  # No HITL for reading
            }
        )
    ],
)
</python>
</ex-multiple-tools-different-policies>
<boundaries>
### What You CAN Configure
  • Which tools require approval (per-tool policies)
  • Allowed decisions per tool (approve, edit, reject)
  • Custom middleware hooks: before_model, after_model, wrap_tool_call, before_agent, after_agent
  • Tool-specific middleware (apply only to certain tools)
    </boundaries>

Show full SKILL.md (174 more words)Show less

Custom Middleware Hooks

Six decorator hooks are available. Two patterns:

  • Wrap hooks (wrap_tool_call, wrap_model_call): (request, handler) — call handler(request) to proceed, or return early to short-circuit.
  • Before/after hooks (before_model, after_model, before_agent, after_agent): (state, runtime) — inspect or modify state. Return None or a dict of state updates.
<ex-wrap-tool-call>
<python>
`@wrap_tool_call` intercepts tool execution. **Do NOT use `yield`** — it creates a generator and causes `NotImplementedError`.
python
from langchain.agents.middleware import wrap_tool_call

@wrap_tool_call
def retry_middleware(request, handler):
    for attempt in range(3):
        try:
            return handler(request)
        except Exception:
            if attempt == 2:
                raise

@wrap_tool_call
def guard_middleware(request, handler):
    if request.tool_call["name"] == "dangerous_tool":
        return "This tool is disabled"  # short-circuit
    return handler(request)
</python>
<typescript>
`createMiddleware({ wrapToolCall })` intercepts tool execution.
typescript
import { createMiddleware } from "langchain";

const retryMiddleware = createMiddleware({
  wrapToolCall: async (request, handler) => {
    for (let attempt = 0; attempt < 3; attempt++) {
      try { return await handler(request); }
      catch (e) { if (attempt === 2) throw e; }
    }
  },
});
</typescript>
</ex-wrap-tool-call>
<ex-before-after-hooks>
<python>
`before_model` / `after_model` / `before_agent` / `after_agent` all share `(state, runtime)` signature.
python
from langchain.agents.middleware import before_model, after_model

@before_model
def log_calls(state, runtime):
    print(f"Calling model with {len(state['messages'])} messages")

@after_model
def check_output(state, runtime):
    print(f"Model responded")
</python>
<typescript>
All before/after hooks share the same `(state, runtime)` signature via `createMiddleware`.
typescript
import { createMiddleware } from "langchain";

const loggingMiddleware = createMiddleware({
  beforeModel: (state, runtime) => {
    console.log(`Calling model with ${state.messages.length} messages`);
  },
  afterModel: (state, runtime) => {
    console.log("Model responded");
  },
});
</typescript>
</ex-before-after-hooks>
<boundaries>
### What You CANNOT Configure
  • Interrupt after tool execution (must be before)
  • Skip checkpointer requirement for HITL
    </boundaries>
<fix-missing-checkpointer>
<python>
HITL middleware requires a checkpointer to persist state.
python
# WRONG
agent = create_agent(model="gpt-4.1", tools=[send_email], middleware=[HumanInTheLoopMiddleware({...})])

# CORRECT
agent = create_agent(
    model="gpt-4.1", tools=[send_email],
    checkpointer=MemorySaver(),  # Required
    middleware=[HumanInTheLoopMiddleware({...})]
)
</python>
<typescript>
HITL requires a checkpointer to persist state.
typescript
// WRONG: No checkpointer
const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5", tools: [sendEmail],
  middleware: [humanInTheLoopMiddleware({ interruptOn: { send_email: true } })],
});

// CORRECT: Add checkpointer
const agent = createAgent({
  model: "anthropic:claude-sonnet-4-5", tools: [sendEmail],
  checkpointer: new MemorySaver(),
  middleware: [humanInTheLoopMiddleware({ interruptOn: { send_email: true } })],
});
</typescript>
</fix-missing-checkpointer>
<fix-no-thread-id>
<python>
Always provide thread_id when using HITL to track conversation state.
python
# WRONG
agent.invoke(input)  # No config!

# CORRECT
agent.invoke(input, config={"configurable": {"thread_id": "user-123"}})
</python>
</fix-no-thread-id>
<fix-wrong-resume-syntax>
<python>
Use Command class to resume execution after an interrupt.
python
# WRONG
agent.invoke({"resume": {"decisions": [...]}})

# CORRECT
from langgraph.types import Command
agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=config)
</python>
<typescript>
Use Command class to resume execution after an interrupt.
typescript
// WRONG
await agent.invoke({ resume: { decisions: [...] } });

// CORRECT
import { Command } from "@langchain/langgraph";
await agent.invoke(new Command({ resume: { decisions: [{ type: "approve" }] } }), config);
</typescript>
</fix-wrong-resume-syntax>

© langchain-ai, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in config/skills/langchain-middleware of langchain-ai/langchain-skills.

Open the folder on GitHubat commit 16a992f

Used in 1 other repository

We found 1 copy of this SKILL.md (exact, near-identical or edited) in other folders. This page covers the copy in langchain-ai/langchain-skills, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Langchain Middleware next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Langchain Middleware compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Langchain Middleware this skilllangchain-ai/langchain-skills1.3k—~2.7kAutomated safety check: PassMIT
Tool Designagentailor/fullstack-langgraph-nextjs-agent132—~3.2kAutomated safety check: PassMIT
Building Pydantic AI Agentsdocling-project/docling69k—~2.8kAutomated safety check: PassMIT
Add Example AgentGetBindu/Bindu10k—~1.1kAutomated safety check: NotesCustom licence
Failproof AI SDK IntegrationFailproofAI/failproofai5.3k—~6kAutomated safety check: PassCustom licence
Prompt Engineering Patternswshobson/agents40k—~1.3kAutomated safety check: PassMIT

Similar skills

  • Tool Design

    agentailor/fullstack-langgraph-nextjs-agent

    Design and verify tools that AI agents can actually use — for any framework or language (MCP servers, LangChain/LangGraph, function-calling, raw JSON schema; TypeScript, Python, or otherwise).

    132 GitHub stars~3.2k tokensUpdated 1 mo ago
    AI & LLM EngineeringAuto-check passed
  • Building Pydantic AI Agents

    docling-project/docling

    Patterns and tested examples for building agents with Pydantic AI: tools, capabilities, structured output, dependency injection, hooks, YAML specs, streaming and testing.

    69k GitHub stars~2.8k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Add Example Agent

    GetBindu/Bindu

    Add a new self-contained example agent under examples/. An agent skill from GetBindu/Bindu.

    10k GitHub stars~1.1k tokensUpdated 1 mo ago
    AI & LLM EngineeringAuto-check: notes
  • Failproof AI SDK Integration

    FailproofAI/failproofai

    Helps instrument a custom Python or TypeScript agent to record events for Failproof AI, verify what gets written, and run an evaluator worker that scores the runs.

    5.3k GitHub stars~6k tokensUpdated 2 days ago
    AI & LLM EngineeringAuto-check passed
  • Reference for designing and tuning production LLM prompts: few-shot examples, chain-of-thought, structured outputs, templates and system prompts.

    40k GitHub stars~1.3k tokensUpdated 5 days ago
    AI & LLM EngineeringAuto-check passed
  • Add Docs Page

    langchain-ai/docs

    Official

    Add, move, rename, or delete a page on the LangChain docs site.

    426 GitHub stars~2k tokensUpdated today
    AI & LLM EngineeringAuto-check passed

More from langchain-ai/langchain-skills

All 22 skills in this repo
  • Agent Eval Engineering

    langchain-ai/langchain-skills

    Official

    Builds agent evaluations in stages: inspect the repository and traces, agree a Task Spec with you, then build, audit and run a Harbor task with an independent verifier.

    1.3k GitHub stars~4k tokensUpdated yesterday
    Auto-check passed
  • Swarm Parallel Dispatch

    langchain-ai/langchain-skills

    Official

    Fans a list of independent items out to subagents in parallel, merges the results back into a table and supports retrying only the rows that failed.

    1.3k GitHub stars~3k tokensUpdated yesterday
    Auto-check passed
  • Langgraph Human In The Loop

    langchain-ai/langchain-skills

    Official

    INVOKE THIS SKILL when implementing human-in-the-loop patterns, pausing for approval, or handling errors in LangGraph.

    1.3k GitHub starsUsed in 1 repo~4.1k tokens
    Auto-check passed
  • LangGraph Decision Models

    langchain-ai/langchain-skills

    Official

    Routes LangGraph agents with typed decision models that return probabilities, and finds LLM calls that only exist to produce a routing decision.

    1.3k GitHub stars~2.3k tokensUpdated yesterday
    Auto-check passed
  • Langgraph Persistence

    langchain-ai/langchain-skills

    Official

    INVOKE THIS SKILL when your LangGraph needs to persist state, remember conversations, travel through history, or configure subgraph checkpointer scoping.

    1.3k GitHub starsUsed in 1 repo~4.6k tokens
    Auto-check passed
  • Deep Agents Core

    langchain-ai/langchain-skills

    Official

    Explains how to build agents with the Deep Agents framework: create_deep_agent, the built-in middleware, the harness, SKILL.md format and configuration options.

    1.3k GitHub stars~3.1k tokensUpdated yesterday
    Auto-check passed

Questions about Langchain Middleware

What does Langchain Middleware do?

INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output. Langchain Middleware is an agent skill from langchain-ai/langchain-skills, published by the product's own GitHub organization. INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output.

When should I use Langchain Middleware?

Langchain Middleware fits situations like: tasks that involve Building AI agents; tasks that involve Human-in-the-loop approvals; tasks that involve Structured output and tool calling.

How do I install Langchain Middleware in Claude Code?

Run `npx skills add langchain-ai/langchain-skills --skill langchain-middleware -a claude-code`. Or copy the skill folder (config/skills/langchain-middleware in langchain-ai/langchain-skills) into .claude/skills/langchain-middleware in your project. Claude Code loads it when a task matches its description.

How do I install Langchain Middleware in Codex?

Run `npx skills add langchain-ai/langchain-skills --skill langchain-middleware -a codex`. Or copy the skill folder (config/skills/langchain-middleware in langchain-ai/langchain-skills) into .agents/skills/langchain-middleware in your project. Codex loads it when a task matches its description.

Can I use Langchain Middleware in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add langchain-ai/langchain-skills --skill langchain-middleware -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/langchain-middleware, .gemini/skills/langchain-middleware, .github/skills/langchain-middleware and .opencode/skills/langchain-middleware in your project.

What does Langchain Middleware need to run?

SKILL.md names no scripts, command-line tools or credentials: Langchain Middleware is instructions for the agent only. Our summary lists: Python 3.

Does Langchain Middleware access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Langchain Middleware safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Langchain Middleware use?

Langchain Middleware is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Langchain Middleware use?

About 2.7k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Langchain Middleware?

Skills that share tags, products or a category with Langchain Middleware: Tool Design (agentailor/fullstack-langgraph-nextjs-agent, 132 stars), Building Pydantic AI Agents (docling-project/docling, 69k stars), Add Example Agent (GetBindu/Bindu, 10k stars) and Failproof AI SDK Integration (FailproofAI/failproofai, 5.3k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Langchain Middleware?

langchain-ai (a GitHub organization, an official publisher) maintains it in langchain-ai/langchain-skills, which has 1,274 GitHub stars. The repository holds 22 skills in this directory. The repository was last updated on October 8, 2026.

Source: langchain-ai/langchain-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.