Build your first agents · Chapter 7 of 8
Callbacks and human approval
Watching a run with callbacks, and pausing it before a risky tool so a person can approve or reject it.
Goals
- Attach a callback handler and watch its events.To do
- Pause before the refund tool, then approve it.To do
- Reject a refund and see the agent handle it.To do
- Pass the check.To do
Step 1 of 4: The read
Callbacks watch
A callback handler is an object whose methods LangChain calls as a run goes: a subclass of BaseCallbackHandler with methods such as handleChatModelStart, handleLLMEnd, handleToolStart and handleToolEnd. You pass it in config.callbacks, and it reaches every nested call that receives that config. Use it for logs, metrics and traces. A callback only observes: LangChain ignores what its methods return and, by default, only logs an error thrown inside one, so it cannot change or stop a step.
Breakpoints pause
To stop a run before a step, LangGraph needs to save the state and come back to it. That is a checkpointer: compile({ checkpointer: new MemorySaver() }) saves a checkpoint after every superstep, under the thread_id in config.configurable. Add interruptBefore: ["approval_tools"] and the run stops before that node.
While it is paused, (await graph.getState(config)).next says what is waiting, and the last AIMessage holds the pending call. To approve, resume with graph.invoke(null, config): a null input means "go on from the checkpoint". To reject, call graph.updateState(config, { messages: [toolMessage] }, "approval_tools") first: your ToolMessage answers the call as if the node had run, so the node is skipped and the model reads your refusal.
Give risky tools their own node, as here with create_refund, so the gate stops only them.
In Node, and elsewhere
In Node, the langchain package's createAgent offers middleware hooks (beforeModel, afterModel, wrapModelCall, wrapToolCall) and humanInTheLoopMiddleware, which pauses with interrupt(). interrupt() needs AsyncLocalStorage, so in a browser you use breakpoints, as here. Coding agents use the same idea: hooks that run before a tool call and can deny it.
Step 2 of 4: Try it: A gate before the refund
A gate before the refund
Four steps, one action each, and an optional fifth: watch a run's callback events, put a gate before the refund, approve one run, then reject the next.
Mode:RealSimulatedReal: LangChain callbacks and LangGraph.js checkpoints, breakpoints, getState, updateState and resume run in this page. Simulated: the model is scripted, including its answer to a refusal, and the ticket and tools are fictional, so no refund is made.
Step 3 of 4: Check
Check
Next: Question 2 of 3
Step 4 of 4: What you can do now
What you can do now
- Log a run's model and tool events with a callback handler.
- Pause a graph before a node with a checkpointer and interruptBefore.
- Resume or reject a pending step with getState, updateState and invoke(null).