Human-in-the-loop in LLM Agents: Action Coordination Patterns
Summary
Configuring points of coordination between an LLM agent and a human: stopping before critical operations, escalating when confidence is low, and auditing all decisions.
When Human-in-the-loop is Needed
Full autonomy of an agent is justified only for reversible operations with low risk. For actions affecting money, public content, or personal data, human confirmation is required. I identify three levels of control:
| Level | Behavior | Examples |
|---|---|---|
| Observation | Agent works, human sees logs | Draft generation, data collection |
| Coordination | Agent stops before action | Sending emails, publishing posts |
| Management | Human initiates each step | Data deletion, transfers |
Pattern 1: Stop Point Before Action
Implemented through a callback function that is called before the tool is executed. The agent forms an intention but does not execute it until the human confirms.
from typing import Callable, Any
class ApprovalGate:
def __init__(self, approve: Callable[[dict], bool]):
self.approve = approve
def check(self, tool_name: str, arguments: dict) -> bool:
# Logging the intention
print(f"Agent wants to call {tool_name} with arguments: {arguments}")
# Asking the human
return self.approve({"tool": tool_name, "arguments": arguments})
def manual_approve(intent: dict) -> bool:
response = input(f"Approve {intent['tool']}? (y/n): ")
return response.lower() == "y"
gate = ApprovalGate(manual_approve)
# In the agent's loop before calling the tool
if tool_name in ["send_email", "publish_post", "delete_record"]:
if not gate.check(tool_name, arguments):
print("Action rejected by human")
continue
Pattern 2: Escalation on Low Confidence
The agent requests confirmation when the model returns a low logprobs for a critical decision or when the result does not pass validation. Using a confidence threshold and a list of tools requiring mandatory approval.
CONFIDENCE_THRESHOLD = 0.85
REQUIRE_APPROVAL = {"delete_entity", "transfer_funds", "send_webhook"}
def should_escalate(tool_name: str, confidence: float) -> bool:
if tool_name in REQUIRE_APPROVAL:
return True
return confidence < CONFIDENCE_THRESHOLD
# Example call
confidence = 0.72 # received from model logprobs
tool = "update_product_price"
if should_escalate(tool, confidence):
# Sending request to Telegram or Slack
send_approval_request(tool, confidence)
Pattern 3: Asynchronous Approval
For long processes, I do not block the agent. I send a request for approval through a webhook or messenger, and the agent continues to perform other tasks. The approval result comes into the queue.
import asyncio
from datetime import datetime
class AsyncApprovalQueue:
def __init__(self):
self.pending = {}
async def request_approval(self, intent_id: str, tool: str, args: dict):
self.pending[intent_id] = {
"tool": tool,
"args": args,
"status": "pending",
"created_at": datetime.utcnow()
}
# Sending notification to operator
await notify_operator(intent_id, tool, args)
async def resolve(self, intent_id: str, approved: bool):
if intent_id not in self.pending:
raise KeyError(f"Unknown intent: {intent_id}")
self.pending[intent_id]["status"] = "approved" if approved else "rejected"
async def wait_for_resolution(self, intent_id: str, timeout: int = 300):
deadline = asyncio.get_event_loop().time() + timeout
while asyncio.get_event_loop().time() < deadline:
if self.pending[intent_id]["status"] != "pending":
return self.pending[intent_id]["status"]
await asyncio.sleep(1)
return "timeout"
Pattern 4: Audit and Logging
Each action of the agent is recorded in a structured log. This allows for incident analysis and improvement of trigger thresholds.
import json
from datetime import datetime
def log_agent_action(action: dict):
entry = {
"timestamp": datetime.utcnow().isoformat(),
"agent_id": action.get("agent_id"),
"tool": action.get("tool"),
"arguments": action.get("arguments"),
"approval_status": action.get("approval_status"),
"confidence": action.get("confidence"),
"user_id": action.get("user_id")
}
with open("agent_audit.jsonl", "a") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
Integration with Agent Framework
In LangGraph I add a human_approval node between the planning node and the execution node.
from langgraph.graph import StateGraph, END
def approval_node(state):
next_action = state["next_action"]
if next_action["tool"] in REQUIRE_APPROVAL:
# Blocking until human response
status = wait_for_human(next_action)
if status != "approved":
return {"messages": ["Action rejected"], "next_action": None}
return state
builder = StateGraph(AgentState)
builder.add_node("plan", plan_node)
builder.add_node("approval", approval_node)
builder.add_node("execute", execute_node)
builder.add_edge("plan", "approval")
builder.add_edge("approval", "execute")
builder.add_edge("execute", END)
Handling Timeouts and Failures
If the human does not respond within the specified time, the agent does not perform the action and transitions to a fallback. Configuring policy: deny (reject), retry (retry request) or defer (defer).
TIMEOUT_POLICY = {
"send_email": "deny",
"update_price": "retry",
"generate_report": "defer"
}
def handle_timeout(intent_id: str, tool: str):
policy = TIMEOUT_POLICY.get(tool, "deny")
if policy == "retry":
# Retrying request after 60 seconds
schedule_retry(intent_id, delay=60)
elif policy == "defer":
# Deferring until end of session
deferred_tasks.append(intent_id)
else:
# Canceling action
cancel_intent(intent_id)
Efficiency Metrics
Tracking four metrics: proportion of actions requiring approval; average operator response time; percentage of rejected actions; number of incidents prevented by control. These metrics help find the balance between autonomy and safety. More details on agent system evaluation in post.
Conclusion
Human-in-the-loop does not reduce agent performance if control points are properly placed. I start with a conservative configuration—approval of all modifying actions—and gradually loosen control based on the audit log. Key principles: stopping before irreversible operations, escalating on uncertainty, full audit of each step.