Middleware and Execution Controls
🎯 Introduction
Agents can select tools autonomously, but the application still needs to control repeated queries, API failures, growing history, and sensitive operations. This article uses LangChain middleware to add logging, retries, call limits, summarization, and human approval, keeping developers in control of execution instead of delegating every business decision to the model.
🧱 What Is Middleware?
Express middleware can log requests, validate inputs, and check permissions before a request reaches a business handler. Agent middleware follows a similar idea, intervening at different points during agent execution.
For example, an agent may call the model repeatedly, and we may want to log each request without changing every tool function. We may also want a shared, bounded retry policy for transient tool failures.
Middleware provides two kinds of hooks: lifecycle hooks run logic at specific stages, while wrap hooks wrap model or tool calls and can decide whether to execute or retry them.
The diagram below shows where both kinds of hooks intervene in the agent loop:
| Hook | When it runs |
|---|---|
beforeAgent | Before the current agent run starts |
beforeModel | Before each model request |
afterModel | After each model response |
afterAgent | When the agent run ends normally |
wrapModelCall | Wraps model requests to control call behavior |
wrapToolCall | Wraps tool execution to handle errors or restrict execution |
We will first use custom logging to understand hooks, then solve specific problems with built-in middleware. No underlying StateGraph implementation is needed.
🛠 Log Execution with Hooks
Continue in agent-demo and create 03.control.mjs:
import { createAgent, createMiddleware } from 'langchain';
import { shopOptions } from './agent.mjs';
const logger = createMiddleware({
name: 'AgentLogger',
// Log the message count before each model call
beforeModel: state => {
console.log('Calling model. Current message count:', state.messages.length);
},
// Log the requested tool count after each model response
afterModel: state => {
const message = state.messages.at(-1);
const toolCount = message?.tool_calls?.length ?? 0;
console.log('Model responded. Tool request count:', toolCount);
},
});
createMiddleware() creates a middleware object. beforeModel and afterModel receive the current agent state. This example reads message and tool call counts without changing results, letting us observe individual model calls rather than only the task’s start and end.
Append to the file:
const agent = createAgent({
...shopOptions,
middleware: [logger],
});
const result = await agent.invoke(
{
messages: [{ role: 'user', content: 'How many mechanical keyboards are in stock?' }],
},
{ recursionLimit: 20 }
);
console.log('Final answer:', result.messages.at(-1)?.content);
Run:
node --env-file=.env 03.control.mjs
If the model looks up the product ID before checking stock, you will usually see three model requests. Example logs follow (actual message counts depend on runtime state):
Calling model. Current message count: 1
Model responded. Tool request count: 1
Calling model. Current message count: 3
Model responded. Tool request count: 1
Calling model. Current message count: 5
Model responded. Tool request count: 0
Final answer: There are 12 mechanical keyboards in stock.
Model hooks run for each model call, rather than just once for the whole agent run.
Production logging should not print complete user messages, tokens, or business data by default. This example logs only counts to keep sensitive information out of logs.
🧱 Limit Model and Tool Calls
Unclear requests or repeated searches for nonexistent products can cause many unproductive queries. Set a per-task call budget to limit latency and model costs.
Expand the LangChain import in 03.control.mjs to:
import {
createAgent,
createMiddleware,
modelCallLimitMiddleware,
toolCallLimitMiddleware,
} from 'langchain';
Replace middleware: [logger] with:
middleware: [
logger,
// Allow at most 5 model calls per task
modelCallLimitMiddleware({
runLimit: 5,
exitBehavior: 'error',
}),
// Allow at most 3 tool calls per task
toolCallLimitMiddleware({
runLimit: 3,
exitBehavior: 'error',
}),
],
modelCallLimitMiddleware limits model calls, and toolCallLimitMiddleware limits tool calls. Because one model response can request several tools, configure these limits separately.
runLimit applies to one run. exitBehavior: 'error' throws when the limit is exceeded, so the application must not treat the task as successful. Keep recursionLimit as well: it limits underlying execution steps, separately from these business call budgets.
Test the Model Call Limit
Temporarily set modelCallLimitMiddleware’s runLimit to 1. To clearly observe a limit failure, replace the agent invocation and output at the end of the file with:
try {
const result = await agent.invoke(
{
messages: [{ role: 'user', content: 'First find the product ID for mechanical keyboard, then check its stock.' }],
},
{ recursionLimit: 20 }
);
console.log('Final answer:', result.messages.at(-1)?.content);
} catch (error) {
console.error('Task failed:', error.message);
process.exitCode = 1;
}
Run:
node --env-file=.env 03.control.mjs
If the model requests product search first, another model call is needed after the search. The call budget is already exhausted, so the task ends with an error. Key output may look like this (error wording depends on the installed version):
Calling model. Current message count: 1
Model responded. Tool request count: 1
Task failed: Model call limit exceeded ...
Test the Tool Call Limit
Restore the model call limit to 5, then set toolCallLimitMiddleware’s runLimit to 1. Keep the same question and run again:
node --env-file=.env 03.control.mjs
If the model searches for the ID and then requests stock as instructed, the second tool call is blocked. Key output may look like this:
Calling model. Current message count: 1
Model responded. Tool request count: 1
Calling model. Current message count: 3
Model responded. Tool request count: 1
Task failed: Tool call limit exceeded ...
These experiments limit model and tool calls separately. Logs and errors may vary by model and SDK version. If the model does not request the required tools, inspect the logs rather than interpreting a normal answer as evidence that the limit triggered. Restore the tool call limit to 3 afterward.
For write operations, call limits prevent excessive execution but cannot undo actions that already succeeded. The business system must still ensure consistency through transactions or compensation where needed.
🧱 Handle Transient Tool Failures
Occasional network timeouts from the stock API may be retried automatically. However, do not retry all errors indefinitely or indiscriminately retry tools whose side effects could duplicate charges or orders.
To observe retries, create 03.retry.mjs, reusing the model and product lookup functions:
import { createAgent, tool, toolRetryMiddleware } from 'langchain';
import { z } from 'zod';
import { model } from './agent.mjs';
import { getStock } from './shop.mjs';
let attempts = 0;
const unstableStock = tool(
({ id }) => {
attempts++;
console.log('Stock API execution count:', attempts);
// Simulate a failed first request
if (attempts === 1) {
throw new Error('Simulated transient network failure');
}
return JSON.stringify(getStock(id));
},
{
name: 'get_stock',
description: 'Look up stock by product ID',
schema: z.object({ id: z.string() }),
}
);
This example intentionally throws on the first read and succeeds on the second. The counter only simulates an unreliable API; it is not the retry mechanism.
Continue by adding:
const agent = createAgent({
model,
tools: [unstableStock],
systemPrompt: 'Always use tools to check stock. Report failures accurately.',
middleware: [
toolRetryMiddleware({
tools: ['get_stock'],
maxRetries: 1,
onFailure: 'error',
}),
],
});
const result = await agent.invoke(
{
messages: [{ role: 'user', content: 'Check stock for P100.' }],
},
{ recursionLimit: 20 }
);
console.log(result.messages.at(-1)?.content);
Run:
node --env-file=.env 03.retry.mjs
One possible output:
Stock API execution count: 1
Stock API execution count: 2
P100 has 12 units in stock.
maxRetries: 1 permits one additional attempt after the initial failure. If that also fails, onFailure: 'error' propagates the error. This retry occurs inside the same tool request; the model does not need to generate another request first.
In production, use retryOn to distinguish recoverable network errors from unrecoverable business errors, and choose an appropriate backoff strategy. Returning an error string without throwing usually does not trigger exception-based retries, so configure retries for the tool’s actual error behavior.
🧱 Manage Growing Context
As we saw with short-term memory, conversation messages accumulate. Longer histories require more processing and bring the model closer to its context window limit.
LangChain provides summarizationMiddleware() to compress older messages into a summary when a condition is reached, keeping recent messages available to the model.
To observe summarization separately, create 03.summary.mjs without product tools for now:
import { createAgent, summarizationMiddleware } from 'langchain';
import { model } from './agent.mjs';
const agent = createAgent({
model,
tools: [],
middleware: [
summarizationMiddleware({
model,
// Trigger summarization when history reaches 5 messages
trigger: { messages: 5 },
// Aim to keep the most recent 2 messages
keep: { messages: 2 },
}),
],
});
trigger controls when summarization runs; keep controls how much recent content remains. These deliberately small thresholds make the effect easy to observe.
Append a simulated conversation history:
const messages = [
{ role: 'user', content: 'I plan to buy 15 mechanical keyboards.' },
{ role: 'assistant', content: 'Understood. I have noted the purchase quantity.' },
{ role: 'user', content: 'The budget is CNY 3,000.' },
{ role: 'assistant', content: 'Understood. The purchase budget is CNY 3,000.' },
{ role: 'user', content: 'Please summarize my purchasing requirements.' },
];
console.log('Message count before summarization:', messages.length);
const result = await agent.invoke({ messages });
// Inspect the retained messages and final answer after summarization
for (const message of result.messages) {
console.log(message.type, message.content);
}
Run:
node --env-file=.env 03.summary.mjs
One possible excerpt follows (the model generates the summary and answer; the summary prefix and retained message count depend on actual execution):
Message count before summarization: 5
human [Summary of earlier conversation: The user plans to buy 15 mechanical keyboards.]
human The budget is CNY 3,000.
ai Understood. The purchase budget is CNY 3,000.
human Please summarize my purchasing requirements.
ai You plan to buy 15 mechanical keyboards with a budget of CNY 3,000.
Older messages are no longer sent individually; their important information is retained in a summary. The framework may keep additional recent messages to preserve message structure, so exactly two remaining messages are not guaranteed.
Real projects should generally set token thresholds based on context capacity, such as trigger: { tokens: 4000 } and keep: { messages: 10 }. Summarization adds model calls and may lose details, so critical business data should remain in the business system.
🧱 Require Human Approval for Sensitive Tools
Reading stock leaves business data unchanged, while updating it directly affects the business system. Applications can require human approval before these sensitive operations execute.
LangChain’s humanInTheLoopMiddleware() pauses a task before a specified tool executes and waits for the application to provide a human decision. To avoid modifying product data used earlier, this example simulates a write with a separate in-memory stock value.
Configure a Tool That Requires Approval
Create 03.approval.mjs:
import { createAgent, tool, humanInTheLoopMiddleware } from 'langchain';
import { Command, MemorySaver } from '@langchain/langgraph';
import { z } from 'zod';
import { model } from './agent.mjs';
let stock = 12;
const updateStock = tool(
({ quantity }) => {
// Change stock only when the tool actually executes
stock = quantity;
return `Stock for P100 updated to ${stock} units`;
},
{
name: 'update_stock',
description: 'Set stock for P100 to the specified quantity',
schema: z.object({ quantity: z.number().int().min(0) }),
}
);
This tool changes stock in the current process. Next, configure it to require human approval:
const agent = createAgent({
model,
tools: [updateStock],
systemPrompt: 'Update stock only through the specified tool. If it is rejected, do not try to update stock again.',
// Save execution state when paused
checkpointer: new MemorySaver(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
update_stock: {
allowedDecisions: ['approve', 'reject'],
},
},
}),
],
});
interruptOn specifies which tools pause execution and which decisions are allowed. This example allows only approval or rejection. A checkpointer saves the paused execution state so the application can resume the task.
Observe the Pause
Append to the file:
const config = {
configurable: { thread_id: 'stock-approval' },
recursionLimit: 20,
};
const pending = await agent.invoke(
{
messages: [{ role: 'user', content: 'Please set stock for P100 to 20 units.' }],
},
config
);
// Read actions awaiting human approval
const interrupts = pending.__interrupt__ ?? [];
console.log('Stock before approval:', stock);
if (interrupts.length !== 1) {
throw new Error('This example requires one pending approval interrupt');
}
const actions = interrupts[0].value.actionRequests;
if (actions?.length !== 1 || actions[0].name !== 'update_stock') {
throw new Error('This example handles only one stock update request');
}
const action = actions[0];
console.log('Tool awaiting approval:', action.name);
console.log('Action arguments:', action.args);
Run:
node --env-file=.env 03.approval.mjs
If the model requests a stock update, you may see:
Stock before approval: 12
Tool awaiting approval: update_stock
Action arguments: { quantity: 20 }
The agent is paused and the tool has not run. __interrupt__ contains interrupt information, including actionRequests for tools awaiting review. This example handles only one stock update request and stops on unexpected input to avoid approving unknown actions.
Obtain a Human Decision
In a real application, the frontend can show the pending tool and its arguments and let a reviewer approve or reject it. This example simulates that interaction through terminal input.
Add at the top of the file:
import { createInterface } from 'node:readline/promises';
Continue appending to the file:
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});
let answer;
try {
answer = await rl.question('Approve this action? Enter yes to approve; anything else rejects: ');
} finally {
rl.close();
}
// Reject by default; approve only on an explicit yes
let decision = { type: 'reject', message: 'The reviewer rejected the stock update' };
if (answer.trim().toLowerCase() === 'yes') {
decision = { type: 'approve' };
}
console.log('Human decision:', decision.type);
Run again and enter yes. The output should end with:
Human decision: approve
Entering no prints Human decision: reject. This only obtains the decision; the agent has not resumed, so stock is unchanged.
Resume the Agent
We now have decision, but the agent remains paused and stock is unchanged. Pass the decision to the agent so it can continue from the pause point.
LangGraph provides Command to control agent execution. Here, resume resumes the task and supplies the reviewer’s decision.
Append to the file:
const command = new Command({
resume: {
decisions: [decision],
},
});
decisions is an array because a pause may include multiple pending tool requests. This example has just one stock update request, so it supplies one decision.
Call invoke() to resume the task:
// Resume with the original conversation configuration
const result = await agent.invoke(command, config);
console.log('Stock after resuming:', stock);
This is a second invoke() call. The two calls have different purposes:
| Call | Purpose |
|---|---|
agent.invoke({ messages: [...] }, config) | Start the task and pause at a tool requiring human approval |
agent.invoke(command, config) | Submit the human decision and resume the paused task |
Both calls must use the same thread_id so the framework can find saved state through the checkpointer. Approval executes the stock update tool. Rejection skips it and sends the rejection information back to the model.
Finally, add the following to check whether the task ended and inspect the model’s answer:
if (result.__interrupt__?.length) {
console.log('Task paused again. Further approval is required.');
} else {
console.log('Final answer:', result.messages.at(-1)?.content);
}
Run the complete script again:
node --env-file=.env 03.approval.mjs
Entering yes may produce:
Stock before approval: 12
Tool awaiting approval: update_stock
Action arguments: { quantity: 20 }
Approve this action? Enter yes to approve; anything else rejects: yes
Human decision: approve
Stock after resuming: 20
Final answer: Stock has been updated to 20 units.
Run the script again and enter no. You may see:
Stock before approval: 12
Tool awaiting approval: update_stock
Action arguments: { quantity: 20 }
Approve this action? Enter yes to approve; anything else rejects: no
Human decision: reject
Stock after resuming: 12
Final answer: The stock update was rejected.
Check stock for the actual effect. If the model requests another update, the task pauses again for a new human decision instead of executing automatically.
Human approval does not replace business access controls. Production systems must also validate the reviewer’s identity, target object, and permissions, then recheck business conditions before writing.
❓ Questions and Answers
Q1: Is a tool retry the same as the agent calling the tool again?
No. Middleware retries happen within one tool request under an application-defined policy. A repeated agent tool call requires a new model request based on existing results. Both can produce real business actions, so limit them separately.
🧪 Exercises
In 03.retry.mjs, change the simulated failure condition to attempts <= 2, keeping maxRetries: 1. Run the script and check that the tool executes only twice and ends in failure. Restore the original example afterward.
🎉 Congratulations! You can now add execution controls to an agent. Next, explore custom workflow orchestration with LangGraph.
