ミドルウェアでエージェントハーネスをカスタマイズする方法
LangChainはエージェントの動作ループをカスタマイズ可能な「Agent Middleware」を導入し、開発者がメモリ連携やPII除去、リトライ処理などをフック経由で柔軟に実装可能にした。
キーポイント
エージェントハネスの核心構造
LLMとツールの呼び出しループが基本だが、ユースケースに応じてシステムプロンプトやツール以外の複雑なカスタマイズが必要となる。
Agent Middlewareのフック設計
`before_model`や`wrap_tool_call`など、ループ内の各段階でカスタムロジックを実行するフックを提供し、開発者が制御性を細かく調整可能。
事前構築ミドルウェアの提供
要約、リトライ、PII除去など一般的なパターンを標準で用意し、開発負荷を軽減しながらセキュリティと安定性を確保する。
コンポーザビリティの重視
複数のミドルウェアを自由に組み合わせられ、エージェントの拡張性と制御性を両立させながら複雑なビジネスロジックをモジュール化できる。
ビジネスロジックとコンプライアンス
PII検出やコンテンツ審査などプロンプトでは実現できない確定的なポリシーを、フック機能を用いて毎回確実に実行可能。
動的エージェント制御とコンテキスト管理
ランタイムでのツール注入、モデル切替、トークン制限超過時の要約などにより、エージェントの動作とコンテキストを動的に最適化。
プロダクション対応機能
実運用に必要な自動リトライ、フォールバック、人間による介入などを組み込み、デモでは見えない堅牢性を確保。
影響分析・編集コメントを表示
影響分析
LangChainのAgent Middleware導入は、エージェント開発における「カスタマイズ」と「フレームワークの安定性」の両立を可能にし、実務レベルでのエージェント構築ハードルを大幅に下げる。これにより、企業は独自のデータ連携やセキュリティ要件を満たすエージェントを迅速にプロトタイピングでき、AI実装の標準化とエコシステムの成熟が加速すると予想される。
編集コメント
既存のソフトウェア設計パターンをAIエージェントに適用した実装は、開発者の学習コストを抑えつつ堅牢なシステム構築を可能にする。今後はフックの標準化とエコシステムの充実が、エージェント実装のベストプラクティスを決定づけるだろう。
imageエージェント・ハーネスは、エージェントを構築する際に役立つものであり、LLM(大規模言語モデル)とその環境を接続し、行動させる役割を果たします。
エージェントを構築する際、おそらくアプリケーション固有のエージェント・ハーネスを構築したくなるでしょう。「エージェント・ミドルウェア」は、LangChain と Deep Agent の堅牢な基盤の上に構築することを可能にしつつ、ユースケースに合わせてカスタマイズできる力を提供します。
エージェント・ハーネスとは何か
エージェントはモデルを中心に構築されたシステムです。このモデルには、環境、データ、メモリ、そしてツールを接続する必要があります。これを実現するのがエージェント・ハーネスというシステムです。
すべてのエージェント・ハーネスのコアは同じであり、驚くほどシンプルです:ループ内で動作し、ツールを呼び出す LLM です。シンプルであるがゆえに、このコア・ループには大きな力があります。
imageLangChain には create_agent という機能が含まれており、これはまさにこのコア・ループを抽象化したものです。
なぜエージェント・ハーネスをカスタマイズしたいのか
異なるエージェントのユースケースは、それぞれ異なるニーズを持っています。そのため、異なるエージェント・ハーネスが必要となる場合があります。
エージェント・ハーネスの一部(例えば指示やツールなど)は、比較的簡単にカスタマイズできます。LangChain の create_agent では、システムプロンプトやツールを渡すことが可能です。
しかし、他の部分ではより複雑な処理が必要です。モデルが実行する前に常に特定のステップを実行したい場合はどうでしょうか?また、ツールの出力に対して常に特定の内容をチェックしたい場合はどうでしょうか?
エージェントのコアループを変更する必要があるものは、変更するのがより厄介です。正しく行われれば、コアハーンシングを維持したまま非常に強力なカスタマイズが可能になります。
AgentMiddleware はこれに対する私たちの回答であり、人々が LangChain エージェントをカスタマイズする方法を提供するものです。
エージェントミドルウェアとは何ですか?
「ミドルウェア」は他のソフトウェアエンジニアリングの慣行でよく使われる一般的な用語ですが、以下では私たちが「エージェントミドルウェア」と呼ぶ異なるシステムについて言及します。
ミドルウェアは、各ステップの前と後にカスタムロジックを実行できるフックのセットを公開し、ループの各段階で何が起こるかを制御できるようにします:

before_agent: 呼び出し時に一度実行されます。メモリを読み込む、リソースに接続する、または初期入力を検証するのに適しています。
before_model: 各モデル呼び出しの前に発火します。履歴をトリムしたり、LLM に到達する前に個人識別情報(PII)を検出したりするために使用できます。
wrap_model_call: モデル呼び出し全体をラップします。キャッシング、リトライ、利用可能なツールを変更するような動的なモデル要求などはすべてここに実装されます。
wrap_tool_call: ツール実行も同様にラップします。コンテキストの注入、結果のインターセプト、または実際に実行されるツールのゲート制御を行います。
after_model: モデルが応答した後、ツールが実行される前に実行されます。人間をループに組み込むための最も自然な場所です。
after_agent: 完了時に一度実行されます。結果の保存、通知の送信、クリーンアップを行います。
ミドルウェアは合成可能なので、お好みの組み合わせで自由に混ぜ合わせることができます。
LangChain は、要約、リトライ、PII(個人識別情報)の削除など、最も一般的なパターンに対応する事前構築されたミドルウェアセットを提供しています。ビルダーは、自社のビジネス固有の要件に合わせて独自のミドルウェアを作成するために、AgentMiddleware クラスをサブクラス化することも可能です。
ミドルウェアの例
カスタマイズのニーズは、しばしば同じテーマに集約されます。以下が最も一般的なユースケースです:
ビジネスロジックとコンプライアンス。PII の削除やコンテンツモデレーションなど、プロンプト内に記述できない事項も存在します。これらは毎回必ず発動する決定論的なポリシーです。HIPAA 準拠をプロンプトだけで達成することはできません。
詳細解説:PII 検出
LangChain の組み込み PIIMiddleware は、before_model および after_model フックを実装しています。これは、モデルへの入力、出力、およびツールからの出力に対して PII をマスク/削除/ハッシュ化する機能を持ちます。また、最も重要な PII 検出状況においては、PIIDetectionError を発生させることも可能です。
動的なエージェント制御。ミドルウェアはランタイムでエージェントの構造を再構築できます:現在の状態に基づいてツールを注入したり、タスク中にモデルを切り替えたり、文脈が変化するにつれてシステムプロンプトを更新したりします。これは、各ステップにおけるエージェントの動作に対する能動的な制御です。
詳細解説:動的ツール選択
LangChain の LLMToolSelectorMiddleware は、wrap_model_call フック内で高速な LLM を実行し、特定の要求に対してレジストリ内のどのツールが関連するかを特定します。その後、これらのツールをモデル要求にバインドすることで、メインのモデル呼び出しにおける不要なツールによるコンテキストの肥大化(bloat)を最小限に抑えます。
コンテキスト管理。モデルの性能は、その前に提示される情報次第です。例えば、トークン制限に近づいた際には要約が必要になったり、ノイズの多いツールの入力/出力を切り詰めたりする必要があるかもしれません。コンテキストエンジニアリングは一度きりのプロンプトの問題ではなく、ランタイム上の課題です。
詳細解説:要約とコンテキストオフロード
LangChain の組み込み SummarizationMiddleware は before_model フックを実装しています。コンテキストのオーバーフローを防ぐため、メッセージ履歴が特定のトークン閾値を超えた場合、その内容はモデルに渡される前に要約されます。このミドルウェアを拡張した実装では、wrap_tool_call フックを実装して、冗長なツールの呼び出し入力と出力をファイルシステムへオフロードします。
プロダクション対応。ミドルウェアを使用することで、モデル/ツールのリトライロジック、モデルのフォールバック、および割り込みを伴う人間による監視(human-in-the-loop)を組み込むことが可能になります。これらの機能はデモでは目立たないことが多いですが、本番環境でのエージェントには不可欠です。
詳細解説:モデルのリトライ
LangChain の組み込み ModelRetryMiddleware は、wrap_model_call フックを実装することで、モデルの API 呼び出しをリトライハンドラで囲みます。このハンドラは、リトライ回数、バックオフ係数、初期遅延(レート制限へのトラブルシューティング用)などのリトライ設定をサポートしています。
ツールセット。エージェントループの周囲にカスタムセットアップとテardown を必要とするツールを注入します。例えば、外部ツールサーバーへの接続、シェルの初期化、サンドボックスの起動などです。
深掘り:シェルツールミドルウェア
LangChain の ShellToolMiddleware は、before_agent および after_agent フックを実装することで、コアエージェントループの周囲でシェルリソースを初期化およびテardown します。また、モデルのツールリストにシェルツールを追加します。
ディープエージェンツ事例研究
Deep Agents は、create_agent(LangChain の標準的なエージェント構築エントリーポイント)のみを使用して完全に構築された、バッテリー内蔵型エージェントハネスです。その上には、特定のスタックを持つミドルウェアが積まれています。
Deep Agents を支えるいくつかのミドルウェアは以下の通りです:
FilesystemMiddleware: ファイルベースのコンテキストのオフロードとオンローディング、および長期記憶
SubagentMiddleware: コンテキスト分離を備えたサブエージェント
SummarizationMiddleware: 長時間実行タスクにおけるコンテキストオーバーフロー管理
SkillsMiddleware:専門機能の段階的な開示
そしてさらに!
Deep Agents を支えるミドルウェアの完全なレビューについては、このガイドおよび Vivek のハネス解剖学ポストをご覧ください。
これらすべての上に - Deep Agents にはさらに多くのミドルウェアを追加して、ユースケースに合わせてカスタマイズすることも可能です!
なぜ私たちはエージェントミドルウェアに賭けるのか
モデルはより能力を高めつつあり、それがミドルウェアスタックの一部を変えることになります。Deep Agents が現在行っていることのいくつか(要約、ツール選択、出力のトリミング)は、最終的にはモデル自体に吸収されるでしょう。
しかし、根本的な必要性は変わりません。ビルダーたちは常にカスタマイズのためのレバーを必要とします:決定論的ポリシーの強制、本番環境対応のためのガードレール、ユースケース固有のビジネスロジックです。これらすべてがモデル内に移動することはありません。ハネスは依然としてその場所であり続け、ミドルウェアはそれを公開する最もクリーンな方法であり続けます。
LangChain v1 のリリース以来、この動きを目にしてきました。ミドルウェアにより、異なるチームが異なる責任を所有できるようになり、ビジネスロジックをコアエージェントコードから分離でき、組織全体でロジックの再利用が容易になります。Deep Agents をこれの上に完全に構築することで、これが正しい抽象化であることを確信しました。
骨格だけのエージェントハネスから始めたいですか?create_agent でミドルウェアを試してみてください。
より堅牢なエージェントハネスの上に構築したいですか?create_deep_agent でミドルウェアを試してみてください。
独自のミドルウェアを貢献したいですか?それに関するガイドはこちらをご覧ください。
原文を表示
imageAgent harnesses are what help build an agent, they connect an LLM to its environment and let it do things.
When you’re building an agent, it’s likely you’ll want build an application specific agent harness. “Agent Middleware” empowers you to build on top of LangChain and Deep Agent’s solid foundation, but customize them for your use case.
What are agent harnesses
An agent is a system built around a model. The model needs to be connected to an environment, data, memory, and tools. Agent harnesses are the system that helps you do that.
The core of every agent harness is the same, and remarkably simple: an LLM, running in a loop, calling tools. Simple as it is, there's power in this core loop.
imageLangChain contains create_agent - an abstraction with just this core loop.
Why you would want to customize your agent harnesses
Different agent use cases have different needs. They may require different agent harnesses.
Some parts of the an agent harness - like instructions or tools - are pretty easy to customize. create_agent in LangChain lets you pass in a system prompt and tools for example.
Other parts are more involved. What if you want always run a certain step before the model executes? What if you always want to check the tool output for certain things?
Things that involve changing the core loop of the agent are trickier to change. When done correctly, it enables really powerful customization that still allows you to build on the core harness.
AgentMiddleware is our answer for this - how we let people customize LangChain agents.
What is agent middleware?
“Middleware” is a general term often used in other software engineering practices, but below we refer to a different system which we call agent middleware.
Middleware exposes a set of hooks that let you run custom logic before and after each step, so you can control what happens at every stage of the loop:
imagebefore_agent: Runs once on invocation. Good for loading memory, connecting to resources, or validating initial input.
before_model: Fires before each model call. Use it to trim history or catch PII before it hits the LLM.
wrap_model_call: Wraps the model call end-to-end. Caching, retries, and dynamic model requests like changing available tools all live here.
wrap_tool_call: Wraps tool execution similarly. Inject context, intercept results, or gate which tools actually run.
after_model: Runs after the model responds but before tools execute. The most natural place for human-in-the-loop.
after_agent: Runs once on completion. Save results, send notifications, clean up.
Middleware are composable, so you can mix and match to your heart’s content.
LangChain ships a set of prebuilt middleware for the most common patterns, like summarization, retries, and PII redaction. Builders can also subclass the AgentMiddleware class to write your own for anything bespoke to your business.
Examples of Middleware
Customization needs tend to cluster around the same themes. Below are the most common use cases:
Business logic & compliance. Some things can't live in a prompt, like PII redaction and content moderation. These are deterministic policies that have to fire every time. You can't prompt your way to HIPAA compliance.
Deep dive: PII detection
LangChain’s builtin PIIMiddleware implements before_model and after_model hooks. It has the ability to mask/redact/hash PII on model inputs, outputs, and tool outputs. It can also raise a PIIDetectionError for the most critical PII detection situations.
Dynamic agent control. Middleware can reshape the agent at runtime: inject tools based on current state, swap the model mid-task, update the system prompt as context evolves. It's active control over how the agent behaves at each step.
Deep dive: dynamic tool selection
LangChain’s LLMToolSelectorMiddleware runs a fast LLM in the wrap_model_call hook to identify which tools from a registry are relevant for a given request. It then binds those tools to the model request to minimize context bloat from unnecessary tools in the main model call.
Context management. The model is only as good as what you put in front of it. For example, you might need to summarize when you're approaching token limits and trim noisy tool inputs/outputs. Context engineering is a runtime problem, not a one-time prompt problem.
Deep dive: summarization and context offloading
LangChain’s builtin SummarizationMiddleware implements the before_model hook. To avoid context overflow, if message history exceeds a certain token threshold, its contents are summarized before being passed to the model. Extensions of this middleware implement a wrap_tool_call hook to extend verbose tool call inputs and outputs to the filesystem.
Production readiness. Middleware allows you to build in model/tool retry logic, model fallbacks, and human-in-the-loop with interrupts. These kinds of features don’t show up in demos, but are essential for production agents.
Deep dive: model retries
LangChain’s builtin ModelRetryMiddleware implements the wrap_model_call hook in order to wrap a model’s API call with a retry handler. This handler supports retry configuration such as retry count, backoff factor, and initial delay (to troubleshoot rate limiting).
Toolsets. Inject tools that require custom setup and teardown around the agent loop like connecting to an external tool server, initializing a shell, or spinning up a sandbox.
Deep dive: shell tool middleware
LangChain’s ShellToolMiddleware implements the before_agent and after_agent hooks in order to initialize and teardown shell resources around the core agent loop. It also adds the shell tool to the model’s list of tools.
Deep Agents case study
Deep Agents is a batteries included agent harness built entirely on create_agent, LangChain's standard entry point for building agents, with an opinionated middleware stack on top.
Here are a few of the middlewares that power Deep Agents:
FilesystemMiddleware: file-based context on/offloading and long-term memory
SubagentMiddleware: subagents with context isolation
SummarizationMiddleware: context overflow management for long-running tasks
SkillsMiddleware: progressive disclosure of specialized capabilities
And more!
For a full review of the middleware powering Deep Agents, see this guide and Vivek’s anatomy of a harness post.
On top of all of this - you can add even more middleware to Deep Agents to customize it for your use case!
Why we’re betting on agent middleware
Models are getting more capable, and that will change parts of the middleware stack. Some of what Deep Agents does today — summarization, tool selection, output trimming — will eventually be absorbed into the model itself.
But the underlying need won't change. Builders will always need levers for customization: deterministic policy enforcement, production readiness guardrails, use-case-specific business logic. None of that moves into the model. The harness is still where it lives, and middleware is still the cleanest way to expose it.
We've seen this play out since the LangChain v1 launch. Middleware lets different teams own different concerns, keeps business logic decoupled from core agent code, and makes it easy to reuse logic across an org. Building Deep Agents entirely on top of it convinced us it's the right abstraction.
Want to get started from a barebones agent harness? Try out middleware in create_agent.
Want to build on top of a more robust agent harness? Try out middleware in create_deep_agent.
Want to contribute your own middleware? See guides for that here.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み