LangGraph and LangChain
Gate a LangChain v1 agent with one middleware; pending approvals are native LangGraph interrupts that resume from the checkpointer.
Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.
Install from the registry (to run the repo's own examples, clone it as in the README):
pip install "viewport-hitl[langgraph]" # langchain >= 1.5, langgraph >= 1.2
npm install @viewportai/hitl langchain @langchain/core @langchain/langgraph # langchain >= 1.6, @langchain/langgraph >= 1.7Verified against langchain 1.5.2 and langgraph 1.2.24 (Python), langchain 1.6.8 and @langchain/langgraph 1.7.5 (TypeScript). The example uses a fake chat model, so it runs with no key.
Add the middleware
middleware(gate) gates every tool call the agent makes. It needs a checkpointer, because a pending approval
pauses the graph and the thread must survive until someone answers. Without one, the first gated call fails with
hitl.checkpointer_required instead of waiting in memory.
clock = FakeClock("2026-11-25T10:00:00Z")
gate = hitl.Gate(
POLICY,
clock=clock,
channels=[hitl.slack(token="xox" + "b-your-bot-token", signing_secret=SLACK_SIGNING_SECRET, transport=slack_api)],
)
def issue_refund(order_id: str, amount: float) -> str:
"""Refund an order."""
refunded.append({"order_id": order_id, "amount": amount})
return f"Refunded ${amount:g} on {order_id}"
agent = create_agent(
model,
[issue_refund],
middleware=[hitl.langgraph.middleware(gate)], # one line: every tool call goes through the gate
checkpointer=InMemorySaver(), # required: the paused thread lives here
)const clock = new FakeClock("2026-11-25T10:00:00Z");
const gate = new Gate(POLICY, {
clock,
channels: [slack({ token: "your-slack-bot-token", signingSecret: SLACK_SIGNING_SECRET, fetch: fakeSlackApi })],
});
const issueRefund = tool(
async ({ order_id, amount }) => {
refunded.push({ order_id, amount });
return `Refunded $${amount} on ${order_id}`;
},
{
name: "issue_refund",
description: "Refund an order",
schema: z.object({ order_id: z.string(), amount: z.number() }),
},
);
const agent = createAgent({
model,
tools: [issueRefund],
middleware: [middleware(gate)], // one line: every tool call goes through the gate
checkpointer: new MemorySaver(), // required: the paused thread lives here
});# A support agent may look up orders and refund small amounts. Larger refunds go to the support leads in Slack.
approvers:
support-leads:
channel: slack
to: "#support-approvals"
members: ["slack:ULEAD"]
timeout: 4h
rules:
lookups: { allow: lookup_order }
refunds: { allow: issue_refund }
large-refunds:
ask: issue_refund
when: { args: { amount: { gt: 50 } } }
approver: support-leads
reason: Refunds over $50 need a support lead
Per call, the middleware builds an action from the tool call (the LangGraph thread_id becomes
context.thread_id) and:
- allow: runs the tool with the frozen arguments.
- deny: returns an error
ToolMessagewith the reason. The tool never runs and the model can adapt. - ask: calls LangGraph's
interrupt(). The value is LangChain'stool_approvalrequest plus aviewportkey (approval id, digest, rules, reason, expiry), so existing LangGraph UIs render it.
The interrupt
config: Any = {"configurable": {"thread_id": "support-7"}}
inputs: Any = {"messages": [{"role": "user", "content": "Refund A-1002, it arrived broken"}]}
first = await agent.ainvoke(inputs, config, version="v2")
pending = first.interrupts[0].value
print(f"interrupted: {pending['name']}, {pending['viewport']['reason']}")
# interrupted: issue_refund, Refunds over $50 need a support leadconst config = { configurable: { thread_id: "support-7" } };
const first = await agent.invoke({ messages: [{ role: "user", content: "Refund A-1002, it arrived broken" }] }, config);
const pending = first.__interrupt__?.[0]?.value as ViewportInterruptValue;
console.log(`interrupted: ${pending.name}, ${pending.viewport.reason}`);
// interrupted: issue_refund, Refunds over $50 need a support leadThe approval request is already on its way to Slack.
Resume when someone answers
resumer(agent) is an on_decided hook: when the approval is decided anywhere (a Slack click on another server,
the CLI, gate.respond), it finds the thread's interrupt and resumes it with a wake-up. The tool call replays, the
gate finds the same approval, consumes it and runs the tool once.
# When the approval is decided anywhere (Slack, the CLI, gate.respond), resume the right thread.
resumed: asyncio.Future[Any] = asyncio.get_running_loop().create_future()
gate.on_decided(hitl.langgraph.resumer(agent, on_resumed=lambda result, _: resumed.set_result(result)))
# The lead presses Approve on the Slack card. Slack signs the callback (simulated here by slack_request).
click = slack_request(
signing_secret=SLACK_SIGNING_SECRET,
approval_id=pending["viewport"]["approval_id"],
digest=pending["viewport"]["action_digest"],
user_id="ULEAD",
now=clock.now(),
approver="support-leads", # the card was sent for this approver; the click counts only for it
)
await gate.webhooks(base_path="/hitl").dispatch(click)
final = await resumed
print(f"agent: {final['messages'][-1].content}") # agent: Your refund of $900 is on its way.// When the approval is decided anywhere (Slack, the CLI, gate.respond), resume the right thread.
const resumed = new Promise((resolve, reject) => {
gate.onDecided(resumer(agent, { onResumed: resolve, onError: reject }));
});
// The lead presses Approve on the Slack card. Slack signs the callback (simulated here by slackRequest).
const handler = gate.webhooks({ basePath: "/hitl" });
const click = await slackRequest({
signingSecret: SLACK_SIGNING_SECRET,
approvalId: pending.viewport.approval_id,
digest: pending.viewport.action_digest,
approver: "support-leads", // the card was sent for this approver; the click counts only for it
userId: "ULEAD",
now: clock.now(),
});
await handler(click);
const final = (await resumed) as Awaited<ReturnType<typeof agent.invoke>>;
console.log(`agent: ${final.messages.at(-1)?.content}`); // agent: Your refund of $900 is on its way.To resume yourself instead, pass resume(result) as the next input: it builds
Command(resume={interrupt_id: {"viewport_approval_id": ...}}) for every pending Viewport interrupt. Resumed too
early, the graph interrupts again and nothing runs.
Trust
The resume value is a wake-up: the decision is read from the gate's store, where it arrived through an
authenticated channel. A native LangChain decision (approve, edit, reject, respond) in the resume payload
counts only with trust_resume=True / { trustResume: true }, and is recorded as decided_via: resume_payload.
Custom graphs
For a hand-built graph with ToolNode, wrap the tools instead: tools(gate, [...]) returns LangChain tools that
interrupt inside the tool node. In TypeScript, createAgent accepts only LangChain tools, so core tools and
gate.tool(...) callables go through tools(gate, [...]) first. Prefer one Send per tool call: with several calls
in one bare ToolNode task, LangGraph replays every call in the task on resume. Gated calls are safe to replay;
other tools in the same node must be idempotent.