langchain-middleware について
LangChain エージェント開発者向けに、ツール呼び出しを制御し、エラーに対処し、機密性の高い操作を人の判断まで一時停止するミドルウェアの使い方を説明します。承認、編集、拒否と、実行再開に必要な状態設定を扱います。
主な機能
- 01機密性の高いツール呼び出し前に承認待ち
- 02ツールごとの判断ポリシー設定
- 03保留中の操作の編集または拒否
- 04フックによるモデルとツール呼び出しの制御
- 05リトライ、ログ、エラー処理の追加
活用シーン
- 01メール送信前に承認を求める
- 02リスク別にツール利用を制御
- 03ツール呼び出しにリトライとログを追加
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ langchain-ai/ langchain-skills --skill langchain-middlewareインストール後、Claude Code で/langchain-middlewareを入力して読み込まれたか確認します。
詳細
本番環境の LangChain エージェント向けミドルウェアパターン:
- HumanInTheLoopMiddleware / humanInTheLoopMiddleware:危険なツール呼び出しの前に処理を一時停止し、人間の承認を得ます
- カスタムミドルウェア:ツール呼び出しをインターセプトして、エラー処理、ログ記録、再試行ロジックを実装します
- Command による再開:人間の判断(承認、編集、拒否)の後に実行を続けます
要件: すべての HITL ワークフローで、チェックポインターと thread_id の設定が必要です。
Human-in-the-Loop
承認のためにメール送信前に一時停止する HITL ミドルウェアを使って、エージェントをセットアップします。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"]},
}
)
],
)
人間の承認を得るためにメール送信前に一時停止する HITL を使って、エージェントをセットアップします。
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"] } },
}),
],
});
エージェントを実行し、中断を検出してから、人間の承認後に実行を再開します。
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 [email protected]"}]
}, 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
)
エージェントを実行し、中断を検出してから、人間の承認後に実行を再開します。
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 [email protected]" }]
}, 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
);
元の値を修正する必要がある場合は、承認前にツールの引数を編集します。
# 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": "[email protected]", # Fixed email
"subject": "Project Meeting - Updated",
"body": "...",
},
},
}]
}),
config=config
)
元の値を修正する必要がある場合は、承認前にツールの引数を編集します。
// 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: "[email protected]", // Fixed email
subject: "Project Meeting - Updated",
body: "...",
},
},
}]
}
}),
config
);
ツール呼び出しを拒否し、その理由を説明するフィードバックを提供します。
# Human rejects
result2 = agent.invoke(
Command(resume={
"decisions": [{
"type": "reject",
"feedback": "Cannot delete customer data without manager approval",
}]
}),
config=config
)
リスクレベルに応じて、各ツールに異なる HITL ポリシーを設定します。
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
}
)
],
)
### 設定できる項目
- 承認が必要なツール(ツールごとのポリシー)
- ツールごとに許可する判断(承認、編集、拒否)
- カスタムミドルウェアフック:
before_model、after_model、wrap_tool_call、before_agent、after_agent - ツール固有のミドルウェア(特定のツールにのみ適用)
カスタムミドルウェアフック
6 つのデコレーターフックが利用できます。パターンは 2 つあります。
- ラップフック(
wrap_tool_call、wrap_model_call):(request, handler)—handler(request)を呼び出すと処理が続行され、早期に値を返すと短絡します。 - 前後のフック(
before_model、after_model、before_agent、after_agent):(state, runtime)— 状態を調査または変更します。Noneまたは状態の更新を含む dict を返します。
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)
`createMiddleware({ wrapToolCall })` はツールの実行をインターセプトします。
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; }
}
},
});
`before_model` / `after_model` / `before_agent` / `after_agent` はすべて、`(state, runtime)` のシグネチャを共有します。
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")
`createMiddleware` を介して、すべての前後のフックで同じ `(state, runtime)` のシグネチャを共有します。
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");
},
});
### 設定できない項目
- ツール実行後の割り込み(実行前に行う必要があります)
- HITL に必要なチェックポインターの要件の省略
# 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({...})]
)
HITL では、状態を永続化するためにチェックポインターが必要です。
// 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 } })],
});
HITL を使う場合は、会話状態を追跡するために必ず `thread_id` を指定してください。
# WRONG
agent.invoke(input) # No config!
# CORRECT
agent.invoke(input, config={"configurable": {"thread_id": "user-123"}})
中断後に実行を再開するには、Command クラスを使います。
# WRONG
agent.invoke({"resume": {"decisions": [...]}})
# CORRECT
from langgraph.types import Command
agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=config)
中断後に実行を再開するには、Command クラスを使います。
// WRONG
await agent.invoke({ resume: { decisions: [...] } });
// CORRECT
import { Command } from "@langchain/langgraph";
await agent.invoke(new Command({ resume: { decisions: [{ type: "approve" }] } }), config);
コメント
Markdown 対応