A Practical Guide to Building an LLM Agent Execution SDK

    As large language models evolve from conversational assistants to autonomous agents, managing bidirectional control flows for task execution becomes critical. This guide provides a practical approach to building a production-ready LLM agent executor, covering configuration assembly, bidirectional interaction protocols using SSE and HTTP POST, unified human-in-the-loop tool approval, and structured user querying, along with best practices for cloud deployment.

    A Practical Guide to Building an LLM Agent Execution SDK

    1. Why a Complete Agent Executor Design is Necessary

    As the capabilities of large language models mature, an increasing number of businesses aim to upgrade their models from “chat assistants” to “autonomous agents.” Unlike traditional conversations, the essence of an agent is bidirectional control flow: it not only generates text but also calls tools, executes actions, and can interrupt execution at any time to request authorization or supplementary information from the user. This means that using a simple request-response conversational interface to host an agent will inevitably lead to a loss of control in areas such as approval, interaction, and state recovery.

    Based on mainstream LLM agent development SDKs, we can build a clearly structured executor with the following core components:

    1. Configuration Assembly Layer: Responsible for loading and assembling agent runtime parameters from databases or configuration files.
    2. Execution Loop Layer: Drives the main loop of “model inference—tool calling—result return.”
    3. Interaction Protocol Layer: Defines the bidirectional message format between frontend and backend.
    4. Human Intervention Layer: Implements tool approval, user Q&A, and information supplementation through a unified callback.

    Let’s break down each layer.

    2. Agent Parameter Initialization: ConfigAssembler Design

    2.1 Design Goals

    Agent runtime parameters come from diverse sources: they may be stored in a database, come from configuration files, or be dynamically dispatched by upstream systems. If the executor directly faces these heterogeneous sources, the code will quickly deteriorate. Therefore, a ConfigAssembler is needed to uniformly complete the three steps of “load—validate—assemble,” ultimately outputting a standardized configuration dictionary.

    2.2 Typical Structure of the Configuration Dictionary

    The assembled agent configuration typically contains the following fields:

    • name: Agent name, used for log tracking and distinguishing multiple instances.
    • model: Underlying model identifier and sampling parameters (e.g., temperature, max output length).
    • system_prompt: System prompt, defining the role, boundaries, and behavioral norms.
    • tools: List of available tools and their permission policies (free from approval/requires approval).
    • interaction: Interaction configuration, such as approval timeout and default denial policy.
    • memory: Context and memory-related configurations.

    2.3 Engineering Key Points

    • Front-loaded Validation: Complete field completeness and type validation during the assembly phase to avoid exposing configuration errors halfway through execution.
    • Default Value Convergence: Centrally define default values for optional fields to ensure “default configurations also work.”
    • Immutable Output: It is recommended to deep copy and freeze the assembly result to prevent accidental modifications during execution, which could affect multi-turn session consistency.

    3. Interaction Message Protocol Design: Supporting Bidirectional Control Flow

    3.1 Protocol Design Philosophy

    The agent interaction protocol must answer three questions: How is process information pushed to the frontend during execution? How are user intervention instructions returned? How is a session recovered after an interruption?

    A widely adopted solution is to use Server-Sent Events (SSE) for the downlink channel and standard HTTP POST for the uplink channel. The downlink push is responsible for delivering model output fragments, tool call events, and approval requests to the frontend in real-time. The uplink request is responsible for returning the user’s approval decisions and answers to the backend, associating them with the specific session ID and pending event ID.

    3.2 Message Type Classification

    Downlink messages should at least include:

    • text: Text fragments generated by the model, supporting streaming concatenation.
    • tool_call / tool_result: Tool call start and result return events.
    • approval_request: Approval request, carrying the tool name, parameter summary, and pending event ID.
    • ask_question: Question request, carrying the question text, options, and a multiple-selection flag.
    • done / error: Normal session end or abnormal termination.

    Uplink messages correspond to two types: approval decisions (approve/deny/feedback with correction suggestions) and question answers (single-select value, multi-select list, or free text).

    3.3 Key Design Principles

    • Event Correlatability: Each pending request has a unique ID, and the user’s response packet must carry this ID. The backend uses this to wake up the suspended execution loop.
    • Idempotency and Timeout: Users may submit repeatedly or fail to respond for a long time. The protocol layer must support idempotent processing and timeout default strategies (e.g., treating timeout as denial).
    • Frontend-Backend Decoupling: The frontend only renders protocol messages without perceiving model details; the backend only produces protocol messages without perceiving the UI structure.

    4. Tool Approval Mechanism: A Unified Human Intervention Entry

    4.1 Value of a Unified Callback

    Mainstream agent SDKs typically provide a “before tool use” callback (like a can_use_tool hook). All types of human interaction—approval, selection, input—should be converged into this single callback, rather than building separate mechanisms for each. The benefit of a unified mechanism is that there is only one approval pipeline, logs can be uniformly audited, and the frontend only needs to implement one set of interaction components.

    4.2 Three Approval Results

    The callback return typically supports three strategies:

    1. approve: The tool executes with the original parameters.
    2. deny: Accompanied by a reason for denial. The model will perceive the tool as unavailable and adjust its subsequent behavior.
    3. feedback: Denial with correction suggestions. The model can modify the parameters based on the suggestions and retry. This is more valuable than simple denial because it directly injects “human experience” into the execution loop.

    4.3 Non-Blocking Design

    After an approval request is sent, the execution loop should suspend rather than poll and block: serialize and save the current session state, and let the event loop yield resources. When the user’s response arrives, the context is recovered based on the event ID and execution continues. This design is crucial for concurrent capacity—when a large number of sessions wait for human responses simultaneously, they do not occupy worker threads.

    Sample code:

    1. async def can_use_tool(tool_name, tool_input, context):
    2. if tool_name in FREE_TOOLS:
    3. return Approve() # Whitelisted tools are directly approved
    4. event_id = await push_approval_request(tool_name, tool_input)
    5. decision = await wait_user_decision(event_id, timeout=300)
    6. if decision.action == "approve":
    7. return Approve()
    8. if decision.action == "feedback":
    9. return Feedback(reason=decision.reason)
    10. return Deny(reason=decision.reason)

    5. User Query Interaction: Structured Questioning Design

    5.1 Positioning the Q&A Tool

    When an agent lacks key information, rather than letting it “guess,” let it “ask.” The structured questioning capability in an SDK (often named something like AskUserQuestion) allows the model to actively initiate a query with options. Its input structure generally includes:

    • question: The question text.
    • options: List of candidate options (optional; if omitted, free input is allowed).
    • multiple: Whether multiple selections are allowed.

    5.2 Triggering Single and Multiple Choice

    In practice, whether the model correctly uses single-select/multi-select largely depends on prompt guidance. It is recommended to explicitly specify in the system prompt: “Use single-select when candidate answers are mutually exclusive, and use multi-select when the user might select multiple items,” and provide examples. During the validation phase, explicit test instructions can be constructed, such as requiring the agent to ask a single-select question (e.g., preferred language) and a multi-select question (e.g., commonly used tools), to confirm the link is end-to-end available.

    5.3 Reusing the Approval Mechanism

    Query requests and approval requests are isomorphic at the protocol level: both follow “suspend—push—wait—resume.” Therefore, the frontend interaction components can reuse the same rendering framework, simply switching form controls (button group/radio/checkbox/text box) based on the message type. This further validates the value of the “unified mechanism” principle.

    6. Implementation Suggestions and Common Pitfalls

    1. Do not build independent channels for each interaction: Multiple parallel mechanisms will cause difficulties in state synchronization; a unified callback + unified protocol is the correct solution.
    2. Tiered approvals: Read-only tools can be whitelisted for approval-free execution, while write, delete, and external-sending tools must require mandatory approval.
    3. Timeouts must have a default behavior: Silent suspension is the worst experience; denying on timeout and informing the model “user did not respond” is more robust.
    4. Leave traces throughout: Every approval and Q&A should be logged. This not only facilitates debugging but also meets enterprise compliance audit requirements.
    5. Leverage general infrastructure for cloud deployment: Session state can be stored in object storage or caching services, approval events can be decoupled via message queues, and runtime metrics can be integrated into logging services and monitoring alerts to quickly achieve production-grade reliability.

    7. Conclusion

    The difficulty of building a production-ready agent is never about “getting the model to run,” but rather safely and frictionlessly embedding human judgment into the machine’s execution loop. By unifying the parameter entry point through a ConfigAssembler, carrying bidirectional control flow via an SSE+HTTP protocol, implementing approval and Q&A through a unified callback, and ensuring non-blocking execution via a suspend-resume mechanism, we can build a logically self-consistent, easily extensible agent executor architecture, laying a solid foundation for more complex business scenarios.