Design Guide for Human-in-the-Loop Interaction in AI Agent Executors

    When AI agents execute multi-step tasks autonomously, they often need human confirmation, choices, or supplementary input at critical decision points—such as approving external system calls, authorizing sensitive operations, or resolving ambiguous results. This guide presents a complete design for human-in-the-loop interaction in agent executors, built around a unified callback mechanism (can_use_tool), three interaction types (approval, question-answer, free-text input), an asynchronous non-blocking message protocol, and a pluggable configuration system. It also covers best practices and common pitfalls to help developers reduce agent misoperation risks and improve task completion rates and user trust.

    1. Design Goals and Core Principles

    When an AI agent executes multi-step tasks autonomously, it often needs human confirmation, selection, or supplementary information at key decision points. Examples include requiring approval before calling external systems, authorization for sensitive operations, or user choices when results are ambiguous. Without a unified mechanism, each interaction scenario would be implemented separately, leading to bloated code, inconsistent behavior, and maintenance difficulties. The design goals can be summarized in three points:

    1. Unified entry point: All human interaction types (approval, selection, text input, multi-select confirmation) are triggered through a single callback interface (such as can_use_tool), avoiding parallel interaction systems.
    2. Non-blocking: After an interaction request is sent, the agent can continue executing other logic that does not depend on the user’s response, or at least support suspension and resumption, avoiding long occupation of the execution thread.
    3. Traceability: Every interaction has a unique identifier tied to its context (current step, involved tool, historical state) to support log auditing and task replay.

    Core principles include:

    • Single responsibility: The interaction layer handles only message encoding/decoding and state management—no business logic.
    • Pluggable policies: Approval strategies (auto-approve, manual approval, conditional rejection) are injected via configuration without modifying the core executor.
    • Protocol neutrality: Interaction messages use JSON structures so the transport layer can be swapped (HTTP, WebSocket, message queues, etc.), relying only on internal SDK conventions.

    2. The Unified Interaction Callback: The can_use_tool Mechanism

    In the agent execution flow, the point just before a tool call is the best place to insert human intervention. Design a unified callback function can_use_tool(tool_name, tool_input, context) that decides whether the tool call is allowed and whether an interaction should be initiated. Its return value supports three outcomes:

    • approve: Allow execution, optionally with modified input parameters (e.g., adding default values).
    • deny: Reject execution, with a mandatory reason. The agent will terminate that step or try another path.
    • feedback: Reject execution while providing corrective suggestions or additional requests. The agent must adjust its input and resubmit.

    Example code (illustrative pseudocode, not tied to a specific SDK):

    1. def can_use_tool(tool_name, tool_input, context):
    2. if tool_name == "delete_file":
    3. # High-risk operation → manual approval required
    4. ask_user(
    5. question="Confirm deletion of file {path}?",
    6. options=["Confirm deletion", "Cancel and return"],
    7. callback=lambda choice: approve() if choice == 0 else deny("User cancelled")
    8. )
    9. return PENDING # Suspend and wait for user response
    10. elif tool_name == "search_database":
    11. # Low-risk operation → auto-approve, but inject additional filters
    12. return approve(tool_input | {"tenant_id": context.tenant})
    13. else:
    14. # Default policy: require user confirmation
    15. return ask_user(
    16. question=f"Allow execution of {tool_name}?",
    17. options=["Allow", "Deny"],
    18. multiple=False
    19. )

    The value of this mechanism is that all interaction logic is centralized in the callback, so the executor needs no awareness of interaction details. The callback can be implemented asynchronously, returning results through an event loop or message queue to achieve non-blocking behavior.

    3. Three Interaction Types for Human Intervention

    3.1 Tool Approval (Approve / Deny / Feedback)

    Approval is the most common form of human intervention. The design should clarify how each of the three approval outcomes affects the execution flow:

    • Approved: The executor continues calling the tool and may “update” the input parameters (e.g., the user supplied required fields).
    • Denied: The executor stops the current branch and can either roll back completed steps or switch to a fallback path.
    • Feedback denial: Rejection with corrective suggestions. The executor should parse the suggestions, automatically modify the input, and resubmit. For example, if a user says “change the timeout to 30 seconds,” the executor parses this, updates the parameter, and retries.

    When implemented, the callback should return structured feedback:

    1. {
    2. "decision": "feedback",
    3. "reason": "Invalid parameters",
    4. "suggestion": { "timeout": 30, "retry": true }
    5. }

    A “register first, use later” pattern is recommended: at agent startup, bind tools to approval policies. Unbound tools should default to one of the two extreme strategies—“always approve” or “always deny”—to avoid security gaps.

    3.2 User Q&A (Single-Select / Multi-Select)

    When task execution requires the user to decide how to proceed, initiate a Q&A interaction. Typical scenarios: choosing among candidate solutions, confirming a target city, or selecting a file-processing method. The message structure:

    1. {
    2. "type": "ask_user",
    3. "id": "uuid-123",
    4. "question": "Which language would you like to use to generate the report?",
    5. "options": ["Python", "JavaScript", "Go", "Rust"],
    6. "multiple": false,
    7. "timeout": 60
    8. }

    For multi-select (multiple: true), the user returns an array. The design should account for:

    • Timeout handling: If there is no response within the time limit, trigger a default option or cancel the task.
    • Cancellation: Users can send “skip” or “cancel”; the executor should have corresponding fallback logic.
    • Context memory: Q&A results should be stored in state for reference by subsequent steps.

    3.3 Information Supplementation (Free-Text Input)

    Some scenarios require unstructured information from the user, such as adding notes, entering an API key, or providing a date range. Unlike Q&A, there are no fixed options—free text is allowed. To reduce parsing ambiguity, provide input templates or regex validation:

    1. {
    2. "type": "ask_input",
    3. "question": "Please enter the project start date (format YYYY-MM-DD):",
    4. "validation": "^\\d{4}-\\d{2}-\\d{2}$",
    5. "max_length": 20
    6. }

    After receiving the response, the executor should validate the format. If validation fails, re-initiate the interaction, with a maximum of three retries.

    4. Non-Blocking Interaction and the Asynchronous Message Protocol

    A traditional synchronous request-response model blocks the agent thread while waiting for the user. A more robust design is an asynchronous message protocol:

    1. The executor emits an interaction request (written to a message queue or event bus).
    2. The agent switches to other independent subtasks, or the current branch enters a “waiting” suspended state.
    3. The user’s response returns via a separate channel (e.g., WebSocket or HTTP callback), carrying the same interaction ID.
    4. The executor uses the ID to resume the corresponding branch and continue execution.

    This protocol requires the following core fields:

    • interaction_id: A globally unique identifier.
    • status: pending / answered / cancelled / timeout.
    • answer: The user’s response content.
    • timestamp: Initiation and response times.

    For transport, a combination of SSE (Server-Sent Events) and HTTP POST works well: downstream (executor → frontend) uses SSE to push interaction requests over a persistent connection; upstream (frontend → executor) uses HTTP POST to send answers. The design must handle reconnection after network disconnection and idempotency: when the frontend resends an answer, the executor should detect the existing interaction_id and simply return the current state.

    1. # Pseudocode: asynchronous suspension and resumption
    2. async def execute_with_interaction():
    3. interaction_id = await post_interaction(ask_user(...))
    4. result = await wait_for_answer(interaction_id, timeout=120)
    5. if result.status == 'answered':
    6. continue_task(result.answer)
    7. elif result.status == 'cancelled':
    8. rollback()
    9. else:
    10. timeout_handle()

    5. Agent Parameter Assembly and Configuration Management

    The flexibility of human interaction depends on a configurable parameter system. Before the executor starts, a configuration assembler (such as config_assembler) loads and assembles the agent configuration. Configuration sources may include databases, YAML files, or environment variables. A typical configuration structure:

    1. {
    2. "name": "full-process-agent",
    3. "interaction": {
    4. "strategy": "ask_for_high_risk",
    5. "timeout": 60,
    6. "max_retries": 3,
    7. "channels": ["web_ui", "email"]
    8. },
    9. "tools": [
    10. {
    11. "name": "delete_file",
    12. "approval": "required",
    13. "on_feedback": "retry_with_suggestion"
    14. }
    15. ]
    16. }

    The configuration assembler should:

    • Merge configuration from multiple sources (priority: environment variables > user-provided dict > defaults).
    • Validate field legality (e.g., whether the strategy value is within allowed ranges).
    • Inject the configuration into the interaction callback so the callback can dynamically adjust its behavior.

    For example, you can set different approval granularity per environment: auto-approve all tools in development, while requiring manual approval for high-risk tools in production. This significantly improves development iteration speed while ensuring production safety.

    6. Best Practices and Pitfalls to Avoid

    6.1 Design Best Practices

    • Timeouts and retries: Every interaction must have a timeout to prevent the agent from hanging indefinitely. The default action after a timeout should be explicit (e.g., auto-deny).
    • State persistence: Interaction state and the agent’s execution context should be persisted to storage (e.g., Redis) so execution can be recovered after a restart.
    • Security auditing: Log every human decision (approve/deny/feedback), including the operator, time, context, and rationale.
    • User-friendly option design: Option text should be specific and unambiguous. Include “Other” as a catch-all option and allow free-text input.
    • Provide defaults: Offer a recommended option when asking questions to help users decide quickly and reduce friction.

    6.2 Common Pitfalls

    • Synchronous blocking: If the callback is a synchronous function without a timeout, the entire agent freezes when the user does not respond. Use an asynchronous suspension mechanism instead.
    • Heavy logic inside callbacks: Callbacks should only make decisions and pass messages—never call business APIs within a callback.
    • No re-entry protection: The same tool may be called multiple times, triggering an interaction each time and repeatedly interrupting the user. Deduplicate interactions for the same tool and context within a short window.
    • Ignoring feedback suggestions: When users provide modification suggestions via feedback, the executor should parse and apply them to the tool input; otherwise, users will have to reject repeatedly.

    7. Summary and Future Directions

    Starting from design goals, this article proposed a unified callback mechanism, three interaction types, an asynchronous message protocol, and a configuration management approach—together forming a complete human-in-the-loop intervention solution. It applies to various agent systems, especially complex task orchestration scenarios that require human-AI collaboration.

    Potential future extensions include:

    • Multi-turn conversational intervention: Support sequential questions so users can progressively guide the agent.
    • Rule-based adaptive policies: Learn from historical data which tools are more frequently rejected, and dynamically adjust approval thresholds.
    • Visual interaction panels: Render interaction cards through web components to improve user experience.

    When implementing in practice, start with a minimal viable version: map out the core tool approval chain first, then gradually add Q&A and feedback mechanisms. With this design, you can significantly reduce the risk of agent misoperations while improving task completion rates and user trust.