How to Make a Deep Agent Ask Before It Sends That Email

8 min read

Give an agent a send_email tool and it will send email. That is the point. It is also the risk. The model can pick the wrong recipient, invent a number, or decide on its own that "tell customers about the price change" means emailing every customer right now.

A docstring that says "ask first" does not stop that. The model decides whether to follow a docstring. What we want is a hard stop in the code: the agent proposes the call, the run pauses, a person looks at the exact arguments, and only then does the tool run, with the arguments as written, with corrected arguments, or not at all.

That raises a second problem. A paused run has to live somewhere while the person thinks. They may answer in ten seconds or tomorrow, from another process. So the pause needs saved state, not a while loop waiting on input().

Deep agents solve both with one argument, interrupt_on, plus a LangGraph checkpointer. This part shows the real interrupt payload, resumes it three ways, and then writes a small custom middleware to see where these hooks run.

The tools used here come from the custom tools part.

How this code was tested

Python 3.12.3, deepagents==0.7.42, langchain==1.5.2, langchain-core==1.8.5, langgraph==1.2.24, langgraph-checkpoint==4.3.2. Every run in this part used a scripted fake chat model that returns prepared tool calls, so the approval wiring, the interrupts, the checkpointer and the resumes are all real, while the model's choices are fixed. No real-model runs were made for this part: the series' Llama 4 Scout endpoint on Workers AI returned HTTP 429 (rate limited) earlier the same day, and the series rule is to stop real calls after a 429. The article code uses a public model string.

The setup

python
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from deepagents import create_deep_agent

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email to a customer."""
    ...

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=[send_email],
    interrupt_on={
        "send_email": {"allowed_decisions": ["approve", "edit", "reject"]},
        "write_file": True,    # all decisions allowed
        "read_file": False,    # never pause
    },
    checkpointer=InMemorySaver(),
)

Each interrupt_on key is a tool name. The value is one of:

  • True: pause, and allow every decision. In langchain==1.5.2 that means approve, edit, reject and respond.
  • False: never pause.
  • a dict (an InterruptOnConfig) with allowed_decisions, plus an optional description and an optional when predicate.

Built-in tools like write_file and delete can be gated too. They are tools like any other.

When you pass interrupt_on, create_deep_agent adds LangChain's HumanInTheLoopMiddleware near the end of the middleware stack. Its pause lives in the after_model hook: after the model replies, it looks at the tool calls, and if any are gated it calls LangGraph's interrupt().

flowchart TD
    M["model replies with tool calls"] --> G{"tool in interrupt_on?"}
    G -- no --> R["tool runs"]
    G -- yes --> W{"when predicate"}
    W -- false --> R
    W -- true or none --> P["interrupt: save state, return to caller"]
    P --> H["human decides"]
    H -- approve --> R
    H -- edit --> E["tool runs with new args"]
    H -- reject --> X["tool skipped, reason sent to model"]
    R --> N["next model call"]
    E --> N
    X --> N

Step 1: the run pauses

python
cfg = {"configurable": {"thread_id": "approve-1"}}
result = agent.invoke({"messages": [{"role": "user",
    "content": "Tell customers about the price change."}]}, cfg)
intr = result["__interrupt__"][0]
print(intr.value)

The scripted model proposes an email to all-customers@example.com saying prices go up 40% tomorrow. That is the kind of call we want to catch. From logs/part08-approvals.txt:

text
interrupt value: {
  "action_requests": [
    {
      "name": "send_email",
      "args": {
        "to": "all-customers@example.com",
        "subject": "Price change",
        "body": "Prices go up 40% tomorrow."
      },
      "description": "Tool execution requires approval\n\nTool: send_email\nArgs: {...}"
    }
  ],
  "review_configs": [
    {
      "action_name": "send_email",
      "allowed_decisions": ["approve", "edit", "reject"]
    }
  ]
}
outbox while paused: []
next node: ('HumanInTheLoopMiddleware.after_model',)

Three facts from this output:

  • invoke returned. It did not block. The result has an __interrupt__ key holding the request.
  • The outbox is empty. The tool has not run.
  • The saved state's next step is HumanInTheLoopMiddleware.after_model. The checkpointer holds the run at that exact point.

action_requests and review_configs line up by index. If the model asks for two gated tools in one turn, both go into one interrupt, and you must send back one decision per action, in the same order.

The description is what a review UI would show. You can replace it with a string, or a function that formats the call yourself.

Hand-drawn diagram: the model proposes send_email, the HITL after_model hook calls interrupt and the checkpointer saves the thread. The human reviewer sees the interrupt and resumes with a Command. Approve runs the tool as is, edit runs it with new arguments, reject never runs it; each path returns a result or a reason to the model for its next step.

Step 2: resume with a decision

You resume by invoking again on the same thread_id with a Command:

python
from langgraph.types import Command

result = agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), cfg)
sequenceDiagram
    participant App
    participant Agent
    participant LLM
    participant HITL as HITL hook
    participant CP as Checkpointer
    participant Tool as send_email
    App->>Agent: invoke(task, thread_id)
    Agent->>LLM: messages + tools
    LLM-->>Agent: send_email(to=all-customers)
    Agent->>HITL: after_model
    HITL->>CP: save state
    HITL-->>App: __interrupt__ payload
    Note over App: human reviews
    App->>Agent: Command(resume=decisions)
    Agent->>CP: load state
    Agent->>HITL: decision
    alt approve or edit
        HITL->>Tool: run
        Tool-->>Agent: result
    else reject
        HITL-->>Agent: rejection ToolMessage
    end
    Agent->>LLM: messages + result
    LLM-->>App: final reply

Approve

text
=== approve
ai:  calls=[('send_email', {'to': 'all-customers@example.com', ...})]
tool (send_email): sent to all-customers@example.com
ai: Email sent.
outbox: [{'to': 'all-customers@example.com', 'subject': 'Price change'}]

The tool ran with the model's own arguments.

Edit

The reviewer sends a whole replacement action, name and args:

python
agent.invoke(Command(resume={"decisions": [{
    "type": "edit",
    "edited_action": {"name": "send_email", "args": {
        "to": "qa-team@example.com",
        "subject": "DRAFT: Price change",
        "body": "Draft for review."}},
}]}), cfg)
text
=== edit
ai:  calls=[('send_email', {'to': 'all-customers@example.com', 'subject': 'Price change', ...})]
tool (send_email): Note: a human reviewer replaced this tool call before it ran. The call recorded in your message is the one you produced, not the one that executed. This was intentional and authorized. Do not re-issue your original call. Executed instead: send_email with arguments {"to": "qa-team@example.com", ...}.

Tool response:
sent to qa-team@example.com
outbox: [{'to': 'qa-team@example.com', 'subject': 'DRAFT: Price change'}]

This behavior is worth knowing. In langchain==1.5.2 the AI message in history still shows the model's original call. The middleware swaps in the reviewer's arguments when the tool runs, and puts a note in front of the tool result telling the model what really ran, and not to send the original again. Without that note, a model can see "I asked for all-customers" next to "sent to qa-team" and retry. You can change the note with edit_notice= on HumanInTheLoopMiddleware, or pass None to drop it.

Reject

python
agent.invoke(Command(resume={"decisions": [{
    "type": "reject",
    "message": "Do not email all customers. Legal must review first."}]}), cfg)
text
=== reject
tool (send_email): User rejected the tool call for `send_email` with reason: Do not email all customers. Legal must review first.
ai: Understood, I did not send it. Want a softer draft?
outbox: []

The tool never ran. The model got a tool message with the reason, so it can change course. The deep agents docs advise a clear, specific message for tools with side effects: say whether to give up, ask a question, or try something safer. With no message, the default text tells the model the tool was not executed and not to retry unless the user asks.

There is a fourth decision, respond, for "ask the user" style tools where the human's answer is the tool result. The docs warn against using it to deny a tool with side effects, because the model may read the message as success. Use reject for that.

Forgetting the checkpointer

What if you pass interrupt_on and no checkpointer? We tried it (code/part08/no_checkpointer.py):

text
first invoke returned keys: ['messages', 'files', '__interrupt__']
interrupt present: True
RuntimeError: Cannot use Command(resume=...) without checkpointer

The first call pauses fine. You just can never resume it, because nothing saved the state. InMemorySaver works for scripts and tests. It lives in one process, so a real app that resumes from a web request needs a persistent checkpointer such as the Postgres one. Threads and checkpointers get their own section in the streaming and checkpoints part.

Pause only for some calls: when

Gating every delete gets noisy. The when predicate receives a ToolCallRequest and returns True to pause:

python
interrupt_on={
    "delete": {
        "allowed_decisions": ["approve", "reject"],
        "when": lambda req: req.tool_call["args"].get("file_path", "").startswith("/notes/"),
    }
}

The source has a warning worth repeating: the predicate runs again when the run resumes, so it must give the same answer for the same call. A predicate that reads the clock or a random value can flip, and then the reviewer's answer gets skipped.

Writing your own middleware hook

HumanInTheLoopMiddleware is just one AgentMiddleware. You can write your own the same way. The hook names on langchain.agents.middleware.AgentMiddleware in 1.5.2 are:

HookRuns
before_agentonce, when a run starts
before_modelbefore every model call
wrap_model_callaround every model call
after_modelafter every model call
wrap_tool_callaround every tool call
after_agentonce, when the run ends

Each also has an async version prefixed with a (abefore_model, awrap_tool_call and so on). The node hooks return None or a dict of state updates. The wrap_* hooks get the request and a handler, and decide whether and how to call it.

Here is an audit middleware that counts model calls, times each tool, and refuses writes under /secrets/ without asking anyone (code/part08/custom_middleware.py):

python
import time
from langchain.agents.middleware import AgentMiddleware
from langchain_core.messages import ToolMessage

class AuditMiddleware(AgentMiddleware):
    def __init__(self):
        super().__init__()
        self.model_calls = 0

    def before_agent(self, state, runtime):
        print(f"[before_agent] {len(state['messages'])} message(s) in")

    def before_model(self, state, runtime):
        self.model_calls += 1
        print(f"[before_model] model call #{self.model_calls}")

    def after_model(self, state, runtime):
        # HITL's after_model may append ToolMessages, so find the last AI message.
        last = next(m for m in reversed(state["messages"]) if m.type == "ai")
        print(f"[after_model] model asked for {[c['name'] for c in last.tool_calls]}")

    def wrap_tool_call(self, request, handler):
        name, args = request.tool_call["name"], request.tool_call["args"]
        if name == "write_file" and str(args.get("file_path", "")).startswith("/secrets/"):
            return ToolMessage(content="Blocked by policy: /secrets/ is read-only.",
                               tool_call_id=request.tool_call["id"], name=name, status="error")
        t0 = time.perf_counter()
        out = handler(request)
        print(f"[wrap_tool_call] {name} took {(time.perf_counter() - t0) * 1000:.1f} ms")
        return out

    def after_agent(self, state, runtime):
        print(f"[after_agent] done after {self.model_calls} model call(s)")

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    middleware=[AuditMiddleware()],
    interrupt_on={"delete": {"allowed_decisions": ["approve", "reject"],
                             "when": lambda req: req.tool_call["args"].get("file_path", "").startswith("/notes/")}},
    checkpointer=InMemorySaver(),
)

The scripted model writes two files, one under /secrets/, then tries to delete /notes/todo.md. We reject the delete. From logs/part08-custom-middleware.txt:

text
[before_agent] 1 message(s) in
[before_model] model call #1
[after_model] model asked for ['write_file', 'write_file']
[wrap_tool_call] BLOCKED write_file /secrets/key.txt
[wrap_tool_call] write_file took 71.8 ms
[before_model] model call #2
paused on: ['delete /notes/todo.md']
[after_model] model asked for ['delete']
[before_model] model call #3
[after_model] model asked for []
[after_agent] done after 3 model call(s)
files: ['/notes/todo.md']
tool (write_file, error): Blocked by policy: /secrets/ is read-only.
tool (write_file, success): Updated file /notes/todo.md
tool (delete, error): User rejected the tool call for `delete` with id c3. The tool was not executed. Do not retry this tool call unless the user explicitly requests it.

Look at the order around the pause. Model call #2 asked for delete, and the run paused before our [after_model] line printed. Our line for call #2 only appears after the resume. That is because HumanInTheLoopMiddleware sits after user middleware in the deep agents stack, and after_model hooks run in reverse order, so HITL's runs first. The first version of this script crashed on resume for the same reason: it read state["messages"][-1], which after a reject is the rejection ToolMessage, not the AI message. Hence the comment in the code.

The tool timing varies from run to run on a shared VM, so read it as a demo of the hook, not a benchmark. The ordering is the source-backed part: in langchain/agents/factory.py the graph edge goes from the model node to the last middleware's after_model, then walks backward through the list.

Two choices in this middleware are deliberate:

  • Hard rules belong in wrap_tool_call, not in interrupt_on. The /secrets/ write never reaches a human. It fails at once with status="error", and the model sees why. Use approvals for calls a person should judge, and code for calls nobody should make.
  • Keep counters per run, not per process, in real code. self.model_calls here lives on the middleware instance, so it keeps counting across runs. For per-thread counts, add a field to the state schema and return it as a state update from the hook.

Deep agents can also pause file tools from permissions= rules with mode="interrupt". The filesystem side of that is in the backends part.

Try this

bash
pip install deepagents==0.7.42
python - <<'EOF'
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
from deepagents import create_deep_agent

class Fake(FakeMessagesListChatModel):
    def bind_tools(self, tools, **kw): return self

m = Fake(responses=[AIMessage(content="", tool_calls=[{"name": "write_file", "id": "c1", "type": "tool_call",
          "args": {"file_path": "/a.md", "content": "hi"}}]), AIMessage(content="done")])
agent = create_deep_agent(model=m, interrupt_on={"write_file": True}, checkpointer=InMemorySaver())
cfg = {"configurable": {"thread_id": "t1"}}
print(agent.invoke({"messages": [{"role": "user", "content": "write a.md"}]}, cfg)["__interrupt__"][0].value)
print(agent.invoke(Command(resume={"decisions": [{"type": "reject", "message": "not now"}]}), cfg)["messages"][-2].content)
EOF

Swap "reject" for "approve" and check files in the result.

Sources