The Critical Step for AI Agents: Human-in-the-Loop and Interaction Design

    This article explains why AI agents need human-in-the-loop (HITL) mechanisms and how to design them effectively. It covers the core principles of unified interaction callbacks, non-blocking execution, and protocol-driven communication, then walks through tool approval strategies (approve, deny, feedback), structured questioning with JSON Schema, and configuration assembly for the executor. The goal is to turn agents from black-box generators into transparent, controllable, and trustworthy production tools.

    1. From Black Box to Transparency: Why Human Intervention Matters

    In early explorations of large language model (LLM) applications, developers tended to build one-way, batch-style “text generators.” A user submits a prompt, the model runs silently in the background, and a complete piece of text comes out. This works well for content creation and code snippet generation.

    But when the goal is an agent that can perceive its environment, call tools, and modify state, the black-box model falls short.

    1. Execution Risk and Business Compliance

    The defining trait of an agent is bidirectional control flow. It does not just generate text; it drives actions in external systems. An operations agent might attempt to run drop database. A finance agent might attempt to initiate a transfer. If high-privilege, high-risk operations are left entirely to the model’s autonomous reasoning, the lack of control can cause serious production incidents.

    This is why a human-in-the-loop (HITL) mechanism is introduced. It does not weaken agent autonomy; it keeps the agent within a supervised boundary. At critical points such as fund transfers, data deletion, or external publishing, a human with business knowledge must confirm the action.

    2. Resolving Missing Context and Ambiguity

    LLMs reason well, but they hallucinate when facing private enterprise data, internal abbreviations, or vague instructions. If a user asks an agent to “pull up last month’s report,” the agent may loop indefinitely because it does not know where the report is stored, or it may fabricate a link.

    If the agent can pause execution and ask the user a question in reverse, requesting missing key parameters such as the reporting system address or the specific business line, its task completion rate improves substantially.

    3. Building Trust and Observability

    For enterprise users, an agent that cannot explain what it is doing and why is unacceptable. A human intervention mechanism provides a natural checkpoint. By showing the human the agent’s reasoning path and pending actions, the human can approve the action and correct the agent’s logic through feedback, gradually tuning the agent’s behavior over a long session.


    2. Core Design Principles: Unified, Non-blocking, and Protocol-driven

    A common mistake when implementing human intervention is writing separate code for each interaction scenario, for example one code path for tool approval and another for user Q&A. This siloed approach creates redundant logic and makes maintenance difficult.

    Three core principles should guide the design:

    1. Unified Interaction Mechanism

    Every interaction scenario, whether tool call approval, single or multi-select options, or free-text input, should be abstracted at the bottom layer as a temporary handoff of control.

    In practice, a single tool-use callback (with semantics similar to can_use_tool or permission_handler) should capture every moment that needs human involvement. The callback takes the agent’s intent as input and returns a human decision as output. With this unified wrapper, you can intercept all of an agent’s external actions the way you intercept HTTP requests.

    2. Non-blocking Architecture

    The traditional synchronous request-response model does not fit long-running background agents. If the front-end user leaves for a meeting, the agent’s execution thread must not be suspended or destroyed.

    The correct architecture has two parts:

    • Executor: runs in a separate process or asynchronous task queue with its own state machine. When it reaches a node that needs human intervention, it does not simply wait. It serializes the current context, enters a sleep state, and pushes a pending-approval message to the front end.
    • Front-end interaction layer: receives user input. Whether the user replies immediately or an hour later, the front end sends the reply to the backend through an API. The backend wakes up and resumes from the sleep point.

    This design lets an agent’s execution cycle span multiple HTTP requests and even the user’s online and offline states.

    3. Protocol-driven Communication

    Interactions between the agent and the front end (web, mobile, CLI) must follow a strict interaction message protocol rather than being ad hoc.

    Traditional LLM chat uses Server-Sent Events (SSE) to push a plain token stream. An agent interaction protocol needs richer data types:

    • type: text_delta: normal text output from the model.
    • type: tool_call_pending: a tool call request awaiting human approval.
    • type: user_input_request: a question to the user, including single-select, multi-select, or input field definitions.
    • type: tool_result: the tool finished executing and the result is returned to the model.

    3. In Practice: Tool Approval and the Feedback Loop

    Tool approval is the most common and most critical human intervention scenario. The goal is to intercept an action before the agent calls an external tool such as a shell command, an API endpoint, or a file write, and hand the decision to a human.

    1. Three Approval Strategies

    Based on real business needs, approval results can be abstracted into three core strategies, which are more practical than a simple yes/no binary:

    • Strategy 1: Approve

      • Meaning: agree to let the tool run.
      • Behavior: the executor immediately calls the tool function, captures the result, puts it back into the context, and continues reasoning.
      • Scenario: low-risk operations such as checking the weather or reading public documentation.
    • Strategy 2: Deny

      • Meaning: explicitly forbid the tool call and give a reason.
      • Behavior: the executor does not call the tool. Instead, it constructs a fabricated “tool call failed” result, including the denial reason, and returns it to the model. The model understands the path is blocked and adjusts its strategy.
      • Scenario: insufficient permissions, or the user changed their mind.
    • Strategy 3: Feedback / Modify

      • Meaning: reject the current call but provide a correction or modified parameters.
      • Behavior: this is the most advanced interaction form. The human does not only tell the model “you cannot do this” but also “here is how you should do it.” The executor returns the human feedback as a substitute tool result, forcing the model to replan according to the human’s guidance in the next step.
      • Scenario: the agent generated a SQL statement with the wrong table name, and the human corrected the table name and sent it back as feedback.

    2. Logic Verification at the Code Level (Illustrative)

    At the executor level, this logic is typically handled by an asynchronous callback. The following pseudocode illustrates the approval flow:

    1. import asyncio
    2. from typing import Dict, Any, Literal
    3. # Define approval result types
    4. ApprovalAction = Literal["approve", "deny", "feedback"]
    5. async def simulate_approval_callback(tool_name: str, params: Dict[str, Any]) -> Dict[str, Any]:
    6. """
    7. Simulate a tool approval callback.
    8. In a real scenario, this coroutine suspends and waits for the front-end user's HTTP request.
    9. """
    10. print(f"[System] Agent requests tool call: {tool_name}, params: {params}")
    11. # Simulate receiving the user's decision from the front end
    12. # In practice, this usually involves a message queue or state kept over an SSE long connection
    13. user_decision = await wait_for_user_input()
    14. action: ApprovalAction = user_decision.get("action")
    15. reason = user_decision.get("reason", "")
    16. if action == "approve":
    17. return {"status": "approved", "result": "Tool executed successfully"}
    18. elif action == "deny":
    19. return {"status": "denied", "content": f"User denied execution, reason: {reason}"}
    20. elif action == "feedback":
    21. # Key point: return the user's correction as the tool result to guide the model to retry
    22. return {"status": "rejected_with_feedback", "content": f"Invalid call parameters, user suggests: {reason}"}
    23. # In the agent main loop:
    24. # tool_response = await simulate_approval_callback("run_sql", {"query": "SELECT * FROM users"})
    25. # Append tool_response to the conversation history to trigger the model's next reasoning step

    The clever part of this logic is that neither a denial nor feedback throws an exception to terminate the program. Both are converted into a tool observation that the LLM can understand. In the next reasoning round, the model naturally adjusts its behavior based on the human feedback.


    4. Advanced Scenario: Interaction Design with Structured Questioning

    Beyond tool approval, an agent often needs to request information from the user during execution. If it relies only on natural language prompts, the front end struggles to parse structured data for rendering complex UI controls such as dropdowns and checkboxes.

    1. Prompt Engineering for Single and Multi-select

    To verify an agent’s interaction capability, you need prompt templates that guide the model to produce structured questioning instructions.

    Example prompt template (for triggering structured questioning):

    “Use the built-in interactive questioning tool (such as AskUserQuestion) to ask me one single-choice question and one multi-choice question:

    • Single-choice: ask my favorite programming language (options: Python, JavaScript, Go, Rust)
    • Multi-choice: ask my commonly used development tools (options: VS Code, IntelliJ IDEA, Vim, Notepad++)”

    When the model receives such an instruction, it does not output plain text. It calls a predefined interaction tool whose parameters follow the JSON Schema specification, defining the question type (single_choice / multi_choice), the question text, and the candidate options.

    2. Front-end Rendering and State Synchronization

    Once the executor captures this interaction tool call, it immediately triggers non-blocking sleep and pushes a message containing the JSON Schema to the front end via SSE.

    The front end dynamically renders the corresponding UI component. When the user finishes selecting and clicks submit, the front end sends the selection result (for example ["Python", "VS Code"]) to the backend through an HTTP POST endpoint.

    The backend executor wakes up, injects the user input into the context as the tool execution result, and the agent continues reasoning and task planning based on the user’s preferences.


    5. Parameter Initialization and Executor Decoupling

    Delivering the interaction capabilities above depends on flexible parameter assembly. Agent configuration is often highly complex, including model selection, temperature, the list of allowed tools, and maximum iteration steps.

    1. Config Assembler Pattern

    To support fast switching across environments and scenarios, you need a dedicated parameter initialization module (playing a role similar to config_assembler.py). Its job is to load configuration from different data sources such as a relational database, configuration files, and environment variables, and assemble it into the dictionary format the agent executor expects.

    Example agent_config dictionary format:

    1. {
    2. "name": "devops-assistant-full-featured",
    3. "description": "Operations assistant with full interaction capabilities",
    4. "model_settings": {
    5. "provider": "default",
    6. "temperature": 0.2,
    7. "max_tokens": 4096
    8. },
    9. "interaction_settings": {
    10. "enable_hitl": true,
    11. "timeout_seconds": 3600,
    12. "allowed_decisions": ["approve", "deny", "feedback"]
    13. },
    14. "tool_permissions": [
    15. {"tool": "execute_shell", "requires_approval": true},
    16. {"tool": "read_file", "requires_approval": false}
    17. ]
    18. }

    2. Compatibility with Multiple File Types

    In real projects, configuration comes from multiple places. Basic model parameters might live in a YAML file, while a dynamically changing tool permission list might live in a database. The Config Assembler must normalize and merge data from multiple sources, ensuring the parameters passed to the executor are validated and in a unified format.


    6. Summary and Outlook

    Over an agent’s lifecycle, human intervention and interaction design are the dividing line between a lab toy and a productivity tool.

    This article points to several key pillars for building effective interactive agents:

    1. Unified control plane: use a unified callback mechanism (such as can_use_tool) to capture every node that needs human involvement, eliminating the technical debt of multiple parallel logic paths.
    2. Bidirectional control flow: combine SSE and HTTP POST to fully decouple background execution from front-end interaction, supporting long-cycle, cross-device task execution.
    3. Feedback over denial: introduce a feedback mechanism into approval logic, turning human corrections into the model’s next input and forming a continuous human-machine optimization loop.
    4. Structured interaction: use predefined schemas to guide the model to output structured data, letting the front end render rich controls and improve user experience.

    Looking ahead, as agent capabilities grow, human-machine interaction will move beyond simple approve-and-reject toward deeper intent alignment and multi-agent collaborative decision-making. Only by considering interaction fluidity and safety from the start of architecture design can developers build truly trustworthy intelligent applications.