Human in the loop with Deep Agents
Contents 10 sections
An agent that can send email or delete records will sooner or later do one of those things when you would have said no. For some tools you want a person to look at the call before it runs. That is human in the loop, and LangChain’s Deep Agents has it built in.
To see what it takes, I built a small expenses app: an agent books what employees spent, and from 100 euro on an approver has to agree first. The approver decides on a web page, or in Microsoft Teams when the agent works in the background. The code is on GitHub: gbaeke/hitl.
The diagram shows one approval from start to finish:

What is human in the loop?
The agent stops right before a tool call and hands the call to your app: the tool name and the arguments the model came up with. A person looks at it and decides:
approve: run the tool as proposededit: run it with changed argumentsreject: don’t run it, and give the model a reason
There is a fourth one, respond, for tools like ask_user where the human’s answer is the tool result. Don’t use it to say no. The model reads it as a successful tool call.
Where does the pause come from?
Deep Agents is built on LangGraph, and the pause is a LangGraph feature. create_deep_agent returns a graph: a set of steps, called nodes, and the order they run in. Two nodes matter here. model asks the model what to do next and tools runs the tool calls it asked for. When you set interrupt_on, Deep Agents puts LangChain’s HumanInTheLoopMiddleware between those two:

That node looks at the tool calls the model wants. When one of them needs approval, it calls LangGraph’s interrupt() with the request. The graph stops at that node and invoke returns to your code.
A stopped graph has to be kept somewhere, and that is the checkpointer’s job. After every step, LangGraph gives it the state of the run: the messages so far and which node comes next. The checkpointer writes that to a database under the thread ID. A paused run is then a few rows in a database, so the process that started it can go away.
Command(resume=...) does the reverse. LangGraph loads the last checkpoint of the thread, gives your decisions to the waiting node as the result of its interrupt() call, and the graph continues to tools. You can see where a paused thread waits: agent.get_state(config).next returns ('HumanInTheLoopMiddleware.after_model',).
What do you need?
- A policy: which tools wait for a human, and which decisions that human may take.
- A checkpointer with a database behind it, because the answer can come days later, after a restart or in another process.
- A thread ID per conversation. You resume the same thread you paused, so your app has to remember which threads are waiting.
- A place where a person sees the pending call and decides. That part is yours to build.
The code in four steps
Steps 1 to 3 pause the agent, step 4 resumes it. That is all the Deep Agents code there is. The snippets are trimmed from agent.py and try_cli.py in the repo.
1. Say which tools wait, and add a checkpointer
LIMIT = 100 # euro; expenses from this amount need a human
def over_limit(request: ToolCallRequest) -> bool:
return float(request.tool_call["args"].get("amount", 0)) >= LIMIT
checkpointer = SqliteSaver(sqlite3.connect("hitl.db", check_same_thread=False))
checkpointer.setup()
agent = create_deep_agent(
model=init_chat_model("openai:azure-gpt-6-luna", use_responses_api=True),
tools=[book_expense, delete_expense, list_expenses],
interrupt_on={
"book_expense": {"allowed_decisions": ["approve", "edit", "reject"], "when": over_limit},
"delete_expense": {"allowed_decisions": ["approve", "reject"]},
},
checkpointer=checkpointer,
)
book_expensepauses whenwhenreturnsTrue, so a lunch of 45 euro goes straight through.delete_expensealways pauses, and the approver cannot edit it.list_expensesis not ininterrupt_on, so it never pauses.- The paused runs go to a SQLite file (
langgraph-checkpoint-sqlite). For production, use Postgres.
The model runs in Microsoft Foundry and I reach it through a local agentgateway, but any OpenAI-compatible endpoint works.
2. Run the agent with a thread ID
config = {"configurable": {"thread_id": str(uuid.uuid4())}}
question = "Train to Paris, 320 euro"
result = agent.invoke({"messages": [{"role": "user", "content": question}]}, config=config)
Keep the thread ID. It is the only handle you have on this run later.
3. Check if the run paused, and read what is waiting
invoke returns in both cases. When the agent finished, the result holds the answer as usual. When a tool call needs a decision, the result has an __interrupt__:
if result.get("__interrupt__"):
request = result["__interrupt__"][0].value
For the train ticket, request looks like this:
{
"action_requests": [
{"name": "book_expense",
"args": {"description": "Train to Paris", "amount": 320, "category": "travel"}}
],
"review_configs": [
{"action_name": "book_expense", "allowed_decisions": ["approve", "edit", "reject"]}
],
}
The tool has not run. Show the name and the arguments to the approver, with a button for every allowed decision. Your process can stop now: agent.get_state(config).interrupts returns the same request later, from any process that uses the same checkpointer.
4. Resume with a decision
A decision is a small dictionary. These are the three the demo uses:
approve = {"type": "approve"}
reject = {"type": "reject", "message": "over the limit of 200 euro per night"}
edit = {
"type": "edit",
"edited_action": {
"name": "book_expense",
"args": {"description": "Train to Paris", "amount": 280, "category": "travel"},
},
}
To resume, call invoke again on the same thread, with a Command in place of a message:
result = agent.invoke(Command(resume={"decisions": [approve]}), config=config)
Send one decision per entry in action_requests, in the same order. The result is again an answer or a new __interrupt__, so in practice steps 3 and 4 sit in a loop. try_cli.py is that loop in the terminal:
user: Book these: lunch with a customer, 45 euro, and a train ticket to Paris, 320 euro.
needs a decision: book_expense {'description': 'Train ticket to Paris', 'amount': 320, 'category': 'travel'}
allowed: approve, edit, reject
approve / reject? [approve]
agent: Booked both expenses: lunch with a customer (€45, meals) and train ticket to Paris (€320, travel).
The expenses app
In a real app, the person who asks and the person who approves are not the same, and they are not online at the same time. The web app (FastAPI and one HTML page) puts both on one screen so you can follow along. Below, the employee asked for a train ticket and a taxi. The chat is paused and the train ticket waits in the middle column:

The taxi of 28 euro is under the limit, yet it is not in the ledger either. Deep Agents pauses once per model turn, before any tool of that turn runs. The approver only sees the calls that need a decision, and the rest of the turn waits with them.
The app is the same four steps, split over two endpoints. The chat endpoint does steps 2 and 3, the approvals endpoint does step 4. Trimmed from app.py:
def run(thread_id: str, agent_input) -> dict:
"""Run the agent until it finishes or pauses, and remember which of the two happened."""
result = agent.invoke(agent_input, config=config_for(thread_id))
db.save_thread(thread_id, "waiting" if result.get("__interrupt__") else "done")
return view(thread_id)
@app.post("/api/threads/{thread_id}/messages")
def send_message(thread_id: str, message: Message) -> dict:
return run(thread_id, {"messages": [{"role": "user", "content": message.text}]})
@app.post("/api/approvals/{thread_id}")
def decide(thread_id: str, body: Decisions) -> dict:
decisions = ... # checked first, see below
return run(thread_id, Command(resume={"decisions": decisions}))
The waiting status in the app’s own table is how the Approve column finds the paused threads. For each of them it reads the request with agent.get_state(), so the cards survive a restart. I stopped the app with a hotel expense pending, started it again and rejected it. The agent continued as if nothing had happened. 😎
The next screenshot shows the three decisions in one chat. The approver changed the train ticket to 280 euro, rejected the hotel with a reason, and now gets a delete request with only two buttons:

After an edit, the middleware tells the model that a human replaced the call and which arguments ran, so the agent reports 280 euro. After a reject, the model gets the reason as a failed tool call and passes it on to the employee.
When the approver is somewhere else
The demo is the easy case: the chat and the approvals sit on one page. An agent that works in the background, started by a schedule or an event, pauses with nobody watching, and its approver is in Teams or in their mailbox.
The mechanism stays the same, because a paused run is only a saved state and a thread ID. Your service adds a step before the decision and one after it:

- Notify. When
invokereturns an interrupt, send the request to the approver in the channel they use. The thread ID goes along. - Resume. Every channel ends at the same checks and the same
Command(resume=...). - Report. In a chat, the employee sees the agent’s answer. Here nobody waits for it, so the code that resumes also sends the outcome to whoever needs it.
The repo has this as a second way in. POST /api/events takes a batch of expenses and starts a run in the background. When the run pauses, a bot posts an Adaptive Card in the approver’s Teams chat. Here Anna sent a taxi and a flight, and the flight needs a decision:

The parts behind that card, and the order in which they talk to each other:

The three steps, trimmed from teams.py:
async def run_and_report(thread_id, title, agent_input, resume=None):
if resume:
paused = await asyncio.to_thread(approvals.resume, thread_id, *resume)
else:
paused = await asyncio.to_thread(approvals.run, thread_id, agent_input)
if paused: # notify
await send(card=approval_card(thread_id, title, approvals.pending(thread_id)))
else: # report
await send(text=f"**{title}**\n\n{approvals.answer(thread_id)}")
@bot.adaptive_card.action_execute("decide")
async def on_decide(context, _state, data):
sender = context.activity.from_property
# ... refuse anybody who is not the approver ...
thread_id, title = data["thread_id"], data["title"]
decisions, lines = decisions_from(data, approvals.pending(thread_id))
checked = approvals.check(thread_id, decisions) # the same checks as the web page
start(run_and_report(thread_id, title, None, resume=(checked, sender.name, "teams")))
return factory.adaptive_card(result_card(title, lines, sender.name))
After a click on Approve, two things happen. The card changes to “Decided by” at once. Then, when the agent is done, the bot posts a second message with the agent’s answer, the one that starts with “Anna: 2 expenses”. The taxi was under the limit and waited for the same decision:

- A button on a card cannot call a URL of yours. It is an
Action.Execute: Teams delivers the click to the bot’s/api/messagesendpoint, together with who clicked. - The click on Approve or Reject is a synchronous call. Teams waits for the bot’s reply and shows an error when it takes longer than about 10 seconds. Resuming the agent can take longer than that, so the handler replies right away and lets the agent continue in the background. The reply holds a new card (“Decided by …”) that replaces the buttons, so you see that your click arrived and cannot click twice. The agent’s answer cannot be part of that reply, so the bot sends it later as a message of its own, the same way it sent the card.
- The web page and the bot share
approvals.py, so a request can be answered in either place.
The bot uses the Microsoft 365 Agents SDK for Python. The Azure Bot registration is free, and the setup is in teams/README.md in the repo.
Check the decisions before you resume
⚠️ Important: Deep Agents runs whatever decisions you send in step 4. Checking them is your app’s job.
Say one turn has two calls waiting, and the approver wants to book the train and keep expense 1:
action_requests = [
{"name": "book_expense", "args": {"description": "Train to Paris", "amount": 320, "category": "travel"}},
{"name": "delete_expense", "args": {"expense_id": 1}},
]
# the right answer: first decision for the first call, second for the second
decisions = [{"type": "approve"}, {"type": "reject", "message": "keep it"}]
The LangChain docs describe three ways this goes wrong:
- You send the two decisions the other way around. The train is rejected and expense 1 is deleted, because decisions match calls by position.
- You send one decision for two calls. That raises an error, and the thread stays stuck.
- You edit the amount to
"abc". Nothing checks it before the tool runs.
So the approvals endpoint of the demo refuses a bad answer before it reaches the agent. With one call waiting, an empty list and a broken edit come back like this:
POST /api/approvals/<thread_id>
{"decisions": []}
422 {"detail": "Expected 1 decisions, got 0"}
POST /api/approvals/<thread_id>
{"decisions": [{"type": "edit", "args": {"description": "Train to Paris", "amount": "abc", "category": "travel"}}]}
422 {"detail": "Input should be a valid number, unable to parse string as a number"}
The endpoint compares the number of decisions with the number of waiting calls, checks every decision against allowed_decisions, and runs edited arguments through the tool’s own schema (book_expense.args_schema). The page builds the list in the order of action_requests, so the approver cannot mix up the positions. The code is in decide() in app.py.
What you don’t get
- The web page does not know who approved, so it needs sign-in before you can trust it. The Teams bot does know, because Teams tells it who clicked, and the app writes that to a log table.
- A paused thread waits forever. Reminders and timeouts are up to you.
- A checkpointer does not restart a run that crashed halfway. I wrote about that in Deep Agents from zero.
Wrapping up
Human in the loop in Deep Agents is one parameter and a checkpointer. The rest is your app’s job: showing the call to the right person and checking the answer before you resume. The code is at gbaeke/hitl.
If you spot any errors or have questions, feel free to reach out!
If this post helped you, you can buy me a coffee ☕
Comments
Comments are stored as GitHub Discussions: sign in with GitHub to join in.