AI Agent SDK Development Guide: Human-in-the-Loop and Interaction Design
This article explores the essential approach to integrating human intervention and interaction design within AI Agent SDKs. It covers the differences between traditional LLM workflows and agent executors, outlines design goals for a unified interaction gateway, and details non-blocking state machines, tool approval strategies, user Q&A protocols, and security governance. This guide provides developers with a comprehensive framework for building resilient and controllable agent execution loops.
1. Background: Why Agent Executors Need Human Intervention
Traditional large language model (LLM) conversations primarily operate in a “one question, one answer” format with a relatively unidirectional control flow. In contrast, an agent executor not only generates text but also invokes tools, modifies data, and triggers external actions, forming a closed-loop of “generate—execute—observe—regenerate.” This bidirectional control flow means the executor may encounter nodes requiring human confirmation, selection, or supplementary information at any time. For instance, high-risk tool calls require approval before execution; ambiguous requirements need the executor to ask single-choice or multiple-choice questions; missing parameters require user input; and tool execution failures require humans to provide correction suggestions.
Without a unified human intervention mechanism, developers often layer multiple parallel logics across different business scenarios: some use independent approval interfaces, some rely on message queues waiting for user replies, and others instruct the model via prompts to “ask the user first.” While these practices work in the short term, they lead to state inconsistency, difficult recovery, lack of auditing, and repeated approvals over time. Therefore, an agent SDK must abstract human intervention as a first-class capability of the executor rather than a scattered business patch.
2. Design Goals and Core Principles
Human intervention and interaction design should meet the following goals:
- Unified Mechanism: Interaction types such as approval, selection, input, and supplementation share a unified request model, decision model, and callback entry point, preventing state fragmentation caused by parallel mechanisms.
- Non-blocking Execution: When waiting for a human response, the executor should not hold worker threads or block the entire session. Instead, it should suspend the current execution snapshot, save a resume token, and continue execution once a decision arrives.
- Recoverable and Idempotent: Network disconnections, client reconnections, or duplicate submissions must not cause duplicate tool executions or loss of approval results.
- Secure and Controllable: Sensitive operations require mandatory approval. Approver identity, decision rationale, and timestamps must be fully auditable. Timeout policies should default to rejecting high-risk operations.
- Extensible: When adding new interaction types, prioritize extending the request/decision schema rather than introducing a separate control link.
A “unified mechanism” does not mean cramming all business logic into a single function, but rather unifying the interaction gateway. All scenarios requiring human intervention are modeled as controlled interaction events, returning structured decisions through a unified callback. This maintains a consistent entry point while allowing different interaction types to have their own validation rules.
3. Unified Interaction Model: Requests, Decisions, and Context
It is recommended to define a unified interaction request object containing fields such as request identifier, interaction type, tool context, question text, options, multiple selection flag, timeout, resume token, and risk level. The decision object should include fields like decision type, reason, answer, and idempotency key. An illustration is as follows:
class InteractionRequest:request_id: strkind: str # tool_approval / single_choice / multi_choice / free_inputtool_name: str | Noneprompt: stroptions: list[Option] | Nonemultiple: bool = Falserisk_level: str = "low"timeout_s: int = 300resume_token: strclass Decision:kind: str # approve / deny / feedback / answer / cancelreason: str | Noneanswer: dict | Noneidempotency_key: str
When human intervention is needed, the executor should not directly call a specific UI or block and wait. Instead, it registers a request with the interaction gateway and receives one of two results: “suspended” or “decision exists.” If suspended, it persists the execution snapshot, including current messages, tool call parameters, executed steps, pending resume position, and timeout. If a decision already exists, it proceeds according to the decision. This decouples the executor’s core logic from the interaction channel, allowing the frontend to be a web page, mobile app, enterprise IM bot, or voice channel.
4. Non-blocking Execution and State Machine Design
The key to non-blocking execution is the state machine. The executor can define the following states: RUNNING, WAITING_APPROVAL, WAITING_INPUT, RESUMING, COMPLETED, FAILED, CANCELLED. When a tool call requires approval, the state transitions from RUNNING to WAITING_APPROVAL; when user input is required, it transitions to WAITING_INPUT. State transitions must be persisted, and each transition must carry a version number to prevent state overwrites caused by concurrent decisions.
Pseudocode illustration:
def execute_tool(call, ctx):req = build_interaction_request(call, ctx)result = ctx.interaction_gateway.request(req)if result.status == "pending":ctx.suspend(snapshot=ctx.snapshot(), resume_token=req.resume_token)return Suspended(req.request_id)decision = result.decisionif decision.kind == "deny":return ToolDenied(decision.reason)if decision.kind == "feedback":ctx.inject_feedback(decision.reason)return RetryWithFeedback(decision.reason)if decision.kind == "approve":return run_tool(call)return ToolCancelled()
Two points are critical here: First, when suspending, you must save “why it was suspended.” Upon recovery, the model should not re-derive this, as model outputs may vary. Second, resume execution using an idempotency key to ensure a tool is only executed once per request. For high-risk tools, after approval, you should also verify whether the approval has expired, whether tool parameters were tampered with, and whether the approver has the correct permissions.
5. Tool Approval Strategies: Approve, Deny, and Feedback
Tool approval is the most common scenario in human intervention. It is recommended to support at least three strategies:
| Strategy | Meaning | Executor Behavior |
|---|---|---|
| approve | Agree to execute | Validate parameters and permissions, execute the tool, and record the approval audit |
| deny | Refuse to execute | Do not execute the tool; return the rejection reason to the model or session |
| feedback | Refuse and provide correction suggestions | Do not execute the original call; inject the reason into the next context round, allowing the model to adjust parameters or switch tools |
The difference between feedback and deny lies in whether human feedback is utilized to drive corrections. For scenarios like parameter errors, missing prerequisites, or when high-risk operations need supplementary explanation, feedback is more valuable than a simple rejection. The executor should inject feedback as a structured message rather than concatenating it into untraceable natural language. Additionally, retry limits should be enforced to prevent the model from falling into a loop under repeated human feedback.
Approval strategies should also support risk grading: low-risk tools can execute automatically or undergo sampling approval; medium-risk tools follow policy-based approval; high-risk tools mandate approval and support dual-control (four-eyes principle). Approval results must include the reason, approver identifier, timestamp, and request fingerprint for audit replay.
6. User Q&A and Information Supplementation: Single Choice, Multiple Choice, and Free Input
The challenge with user Q&A is not “asking a question,” but determining which interaction mode to use. It is recommended that the schema of the interaction request explicitly declares this, rather than letting the model guess using natural language:
- Single Choice: Options are mutually exclusive, and only one can be selected. For example, choosing a runtime environment or a processing strategy.
- Multiple Choice: Options can be combined, and multiple selections are allowed. For example, selecting a set of capabilities to enable.
- Free Input: There are no predefined options, or the user needs to supplement text, file paths, or business descriptions.
System prompts should constrain the model: when information is insufficient and cannot be safely inferred from context, generate a structured interaction request; when clear options exist, prioritize single or multiple choice to reduce user input costs; options should be deduplicated, moderate in quantity, and provide fallback paths like “Other/Cancel.” Upon receiving an answer, the executor must perform schema validation, option legality validation, and timeout handling. High-risk question timeouts default to cancel or reject, while low-risk questions can have configurable defaults, provided these defaults are explicitly shown in the UI.
7. Interaction Message Protocol: Bidirectional Control Flow and Recoverable Events
The agent interaction protocol should support a bidirectional control flow. The downstream channel can use Server-Sent Events (SSE) to push events like approval_required, question_required, input_required, resume_required, and status_changed. The upstream channel can use HTTP POST to submit decisions, answers, cancellations, or supplementary information. Message packets should include session ID, request ID, event type, version number, timestamp, payload, and idempotency key.
Downstream example:
event: approval_requireddata: {"request_id":"r1","tool":"delete_record","risk":"high","options":["approve","deny","feedback"],"expires_at":"..."}
Upstream example:
POST /agent/interactions/r1/decision{"decision":"feedback","reason":"Please back up before deleting","idempotency_key":"..."}
Protocol design must handle reconnections: upon reconnecting, the client pulls unread events using an event cursor; duplicate decision submissions are deduplicated via the idempotency key; cancellation operations must propagate to the suspended state; timeout events are generated by the server and must not rely on client timing. Downstream messages should not carry sensitive plaintext; necessary fields should be masked or return only references.
8. Configuration Initialization and Runtime Parameter Assembly
When the executor starts, it needs to assemble the agent configuration. The configuration assembly module can load dictionary structures from a database or config file, performing default value population, schema validation, secret reference resolution, tool risk level binding, and interaction strategy binding. An example configuration:
{"name": "demo_agent","interaction": {"approval_policy": "risk_based","timeout_s": 300,"allow_feedback": true},"tools": [{"name": "query_data", "risk": "low", "requires_approval": false},{"name": "delete_record", "risk": "high", "requires_approval": true}],"limits": {"max_retry": 2, "max_suspend_s": 3600}}
Configurations should be versioned. The execution snapshot records the configuration version, and the same version is used upon recovery to prevent behavior drift caused by runtime configuration changes. Secrets should not be written in plaintext within the config; they should be resolved through a reference mechanism.
9. Security Governance and Testing Recommendations
In terms of security, adhere to least privilege, mandatory approval for sensitive operations, approver authentication, the four-eyes principle, audit logging, sensitive field masking, and replay protection. To prevent prompt injection from forging interaction requests, all interaction requests must be validated by the executor for source and schema. In concurrent scenarios, only one valid decision can exist for a single request; subsequent decisions should be rejected or recorded as conflicts.
For testing, it is recommended to cover: interaction request contract testing, state machine replay testing, duplicate submission idempotency testing, disconnection/reconnection recovery testing, timeout and cancellation testing, high-risk tool rejection testing, and feedback retry limit testing. Metrics to monitor include approval wait time, rejection rate, feedback adoption rate, recovery success rate, timeout rate, and duplicate execution interceptions.
In summary, human intervention and interaction design should be built as core infrastructure of the agent SDK. A unified interaction gateway consolidates approvals, Q&A, and supplementary information; a non-blocking state machine ensures execution is recoverable; a structured message protocol guarantees frontend-backend consistency; and approval strategies with audit governance ensure security and control. This approach allows agents to receive human confirmation and guidance at critical nodes while maintaining the stability and extensibility of the execution chain.
