Agent Executor Development and Human-in-the-Loop Interaction Design Guide
This article explains how to design and build an agent executor that can plan actions, call tools, pause for human approval or clarification, and resume safely after interruption. It covers layered architecture, unified decision callbacks, tool approval strategies, AskUserQuestion-style interactions, event-stream and request-response separation, non-blocking waiting, task recovery, security and audit controls, error handling, observability, and a recommended execution state machine. Readers will learn how to keep agent automation controllable, traceable, and resilient while supporting high-risk operations with human oversight.
1. Role and Design Goals of an Agent Executor
An agent executor is not merely a wrapper that calls a large model and returns text. It must receive tasks, maintain context, plan actions, call tools, handle exceptions, and pause execution when necessary to wait for the user to provide additional information or grant authorization. It is therefore closer to a task orchestration component with state-management capabilities.
In practical applications, an agent may need to perform the following operations:
- Read or modify business data;
- Call external APIs to complete queries or submissions;
- Create files, generate reports, or update configurations;
- Execute operations with side effects;
- Adjust an existing plan based on user feedback;
- Proactively ask questions when information is insufficient.
These operations carry different levels of risk. Read-only queries can be executed automatically, while actions such as data writes, permission changes, and resource deletion should require explicit authorization before execution. The executor therefore needs to satisfy the following goals at the same time:
- Unified execution flow: Model reasoning, tool calls, and user interaction should all be part of a unified state machine.
- Human intervention support: Allow approval, rejection, parameter modification, single selection, multiple selection, and free-form input.
- Non-blocking behavior: Execution must not occupy backend threads or connections while waiting for a user response.
- Traceability: Every tool call, approval result, and user input should be recorded.
- Recovery capability: After a service restart or network interruption, execution can continue from the interruption point.
- Security boundaries: Constrain tool permissions, parameter content, and execution counts.
2. Overall Architecture: Split Execution into Multiple Responsibility Layers
A robust agent executor can be divided into the following modules:
1. Configuration Assembly Layer
The configuration assembly layer organizes scattered configuration sources into a standardized execution configuration. Configuration may come from a database, configuration files, an admin console, or runtime parameters, and should ultimately form a unified data structure, for example:
agent_config = {"name": "report_agent","system_prompt": "You are an agent responsible for generating business reports","tools": [{"name": "query_data","description": "Query data within a specified range","risk_level": "low"},{"name": "publish_report","description": "Publish the generated report","risk_level": "high"}],"max_steps": 20,"approval_policy": {"low": "auto","high": "ask_user"}}
During configuration assembly, field validation, default value filling, tool registration, and permission policy merging should be completed to avoid spreading large amounts of decision logic inside the executor.
2. Reasoning and Execution Layer
This layer drives the agent loop:
- Receive the user task;
- Submit the task and historical context to the model;
- Parse the text or tool calls returned by the model;
- Determine whether the tool is allowed to execute;
- Execute the tool and collect results;
- Feed the tool results back to the model;
- Continue looping until the task is completed, fails, or enters a waiting state.
3. Interaction Gateway Layer
The interaction gateway sends execution events to the frontend and receives user responses. A common approach is:
- The backend pushes state changes through an event stream;
- The frontend submits approval or question-answer results through regular requests;
- A task identifier and interaction identifier associate the same execution across both channels.
This design separates the “execution channel” from the “interaction channel” and prevents the backend from holding a blocking request for a long time.
4. Persistence Layer
The persistence layer should at least store:
- Execution tasks;
- The current step;
- Message history;
- Tool call records;
- Pending interactions;
- User responses;
- Error and retry information.
If state is kept only in memory, execution cannot be recovered after a service restart, and critical operations cannot be audited.
3. Core Design of a Unified Human Intervention Mechanism
Human intervention should not be designed as multiple incompatible branches. For example, using one callback for tool approval, another message system for user Q&A, and a third logic path for parameter modification makes state difficult to manage and requires the frontend to support multiple interaction protocols.
A more reasonable approach is to establish a unified “tool use decision callback.” Whether the system is approving a tool, asking the user, or requesting additional parameters, all interactions are generated through the same decision entry point.
A general decision result can be abstracted as:
class Decision:def __init__(self, action, reason=None, data=None):self.action = action # allow / deny / askself.reason = reasonself.data = data
Where:
allow: Allow the tool to continue execution;deny: Reject this call and provide a rejection reason;ask: Pause the current task and wait for user input.
The executor should not embed user interface logic directly in tool functions. Tools only describe their purpose, parameters, and risk. Whether to execute is determined by the unified permission and interaction layer.
4. Tool Approval Flow Design
1. Why Approval Is Needed
Tool calls generated by a model involve some uncertainty, especially in the following scenarios:
- Parameters come from untrusted text;
- The tool modifies data;
- The operation is irreversible;
- The call incurs costs;
- Sensitive information is involved;
- The task goal is not described clearly enough.
Approval is therefore not a lack of trust in the model’s capabilities, but a final control boundary for high-risk actions.
2. Approval Strategies
Common approval strategies can be divided into three categories:
Automatic Allow
Suitable for low-risk, read-only, repeatable operations, such as querying public data or calculating statistical results.
Reject Execution
Suitable for calls that exceed the permission scope, have incomplete parameters, target objects that do not exist, or violate security policies. When rejecting, a clear reason should be recorded and fed back to the model so that it can adjust its plan.
Reject and Provide Correction Guidance
This approach is more valuable than simple rejection. For example, when the model requests deletion of all historical records, the system can require it to process only a specified date range. After receiving the feedback, the model can regenerate a safer call.
Example approval logic:
async def can_use_tool(tool_name, tool_input, context):risk = context.get("risk_level", "medium")if not context.get("user_has_permission"):return Decision(action="deny",reason="The current user does not have permission to perform this operation")if tool_name == "delete_records":if tool_input.get("scope") != "selected":return Decision(action="deny",reason="Delete operations must be limited to the data range explicitly selected by the user")if risk == "low":return Decision(action="allow")interaction_id = await create_pending_approval(tool_name=tool_name,tool_input=tool_input,context=context)return Decision(action="ask",data={"interaction_id": interaction_id})
3. Approval Information Should Be Displayed Completely
The frontend should not show only “Allow execution?” Users need to see at least:
- Tool name;
- Purpose of the operation;
- Key parameters;
- Objects that may be affected;
- Risk warning;
- Whether the operation can be undone;
- Expected side effects.
If parameters are too long, expandable viewing should be supported, but key fields must not be hidden by default.
5. Design Method for AskUserQuestion-Style Interactions
The agent should proactively ask the user in the following situations:
- The task goal has multiple reasonable interpretations;
- Key parameters are missing;
- Multiple candidate solutions exist;
- User preferences affect the execution result;
- Continuing execution may cause irreversible consequences.
A question structure usually includes question text, an option list, and a selection mode:
{"type": "question","question": "Please select the output range for the report","options": [{"label": "This week's data", "description": "Only the last seven days"},{"label": "This month's data", "description": "The current calendar month"},{"label": "Custom range", "description": "Start and end dates specified by the user"}],"multiple": false,"required": true}
Single Selection and Multiple Selection
Single selection is suitable for mutually exclusive options, such as output format, time range, and execution environment. Multiple selection is suitable for collecting multiple preferences, such as report sections, notification channels, or metrics of interest.
When designing these interactions, note that:
- Options should be concise and mutually exclusive;
- Each option should preferably include necessary explanation;
- Multiple-selection questions should clearly state whether selecting no option is allowed;
- When there are too many options, grouping or search should be supported;
- When free expression is needed, an “Other” input field should be provided.
Free-form Input
Some information cannot be expressed through fixed options, such as project names, date ranges, business rules, and supplementary notes. In this case, text input can be added to the structured question, and the backend must validate the content again rather than directly trusting user input.
6. Interaction Protocol: Separate Event Streams from Request-Response
During agent execution, multiple events are generated. It is recommended to define event formats uniformly:
{"event_id": "evt_1024","task_id": "task_2001","type": "tool_approval_required","status": "waiting","payload": {"tool_name": "publish_report","arguments": {"title": "Monthly Operations Report"},"interaction_id": "interaction_88"},"created_at": "2025-01-01T10:00:00Z"}
Common event types include:
task_started: The task has started;thinking: The model is planning;tool_call_requested: A tool call has been generated;tool_approval_required: Human approval is required;user_question: A question is being asked to the user;tool_started: The tool has started executing;tool_finished: The tool has finished executing;task_paused: The task has entered a waiting state;task_completed: The task is complete;task_failed: The task has failed.
The frontend can receive these messages through an event stream, while user responses are submitted through an independent endpoint:
POST /tasks/{task_id}/interactions/{interaction_id}/replyContent-Type: application/json{"action": "approve","data": {}}
The advantage of this pattern is that event pushing is responsible only for notification, while user responses are responsible only for changing state. Responsibilities are clear, and retries and auditing are easier.
7. Non-blocking Waiting and Task Recovery
When waiting for a user response, the executor must not use synchronous blocking to occupy a thread for a long time. The recommended flow is:
- Create a pending interaction record;
- Update the task state to
waiting_user; - Save the current context and recovery position;
- Push the interaction event to the frontend;
- Immediately release the current execution resources;
- After the user submits a response, validate whether the interaction is still valid;
- Write the response and restore the task to
running; - Continue execution from the saved position.
The following problems need to be prevented:
- Duplicate user submissions causing a tool to execute twice;
- Expired interactions still being processed;
- Multiple clients approving at the same time;
- Old responses being received after a task is already complete;
- Waiting state being lost after a service restart.
Therefore, interaction records should have state and version control:
pending -> processing -> resolvedpending -> expiredpending -> cancelled
When submitting a response, use idempotency validation and allow the transition from pending only once.
8. Security, Permissions, and Auditing
Human approval does not equal absolute security. The backend must still perform independent validation:
- Identity validation: Confirm who the responder is.
- Permission validation: Confirm whether the responder has the right to approve the operation.
- Task binding: Confirm that the interaction belongs to the current task and current user.
- Parameter revalidation: Validate tool parameters again after approval to prevent tampering.
- Timeout control: Automatically cancel or ask again when there is no response for a long time.
- Count limits: Limit the maximum number of steps and tool calls for a single task.
- Sensitive information protection: Redact keys, identity information, and privacy fields in logs.
- Complete auditing: Record who approved what operation, when, and the final result.
Special attention should be paid to the fact that approval should be bound to a “specific tool call” and “specific parameters,” not merely to a tool name. Otherwise, the model could change parameters after approval and bypass the original confirmation scope.
9. Error Handling and Observability
Tool execution may fail due to parameter errors, network timeouts, insufficient permissions, dependent service exceptions, and business rule rejections. The executor should classify errors as recoverable and unrecoverable.
Recoverable errors can be retried, but a retry limit and backoff interval should be set. Unrecoverable errors should end the current step and provide an understandable explanation to the user.
It is recommended to record the following metrics:
- Total tasks and success rate;
- Average execution duration;
- Average number of tool calls;
- Human approval ratio;
- User response latency;
- Tool failure rate;
- Retry count;
- Number of tasks cancelled due to timeout.
Logs should contain both structured fields and short user-facing messages. Internal stack traces should not be shown directly to end users.
10. Recommended Execution State Machine
A complete task state machine can be designed as:
created-> running-> waiting_user-> running-> completedrunning-> failed-> cancelled-> waiting_approval-> running
State transitions must be managed uniformly by the backend. The frontend can submit only intent and cannot directly modify task state. For example, after the frontend submits “approve,” the backend still needs to check whether the task has expired, whether permissions are valid, and whether the tool call has changed.
Ultimately, a reliable agent executor should have the following characteristics:
- Use a unified callback for approvals and Q&A;
- Use an event protocol to communicate execution state;
- Use persisted records to ensure tasks can be recovered;
- Use a state machine to constrain process transitions;
- Use permission and audit mechanisms to control high-risk operations;
- Use a non-blocking architecture to improve concurrency;
- Use clear interaction information to reduce the user’s decision cost.
The core value of an agent is not only generating answers, but also completing complex tasks safely and controllably. Designing human intervention as a first-class capability of the executor can establish a more stable balance between automation efficiency and business security.
