AI Agent Architecture: From Tool Calling to Closed-Loop Task Execution

    This article breaks down the technical path for building task-executing AI agents that move beyond text generation to real state changes. It covers capability layering, a practical reference architecture, tool contracts with idempotency and permissions, voice interaction compliance, RAG-based knowledge reliability, multimodal output pipelines, production observability and evaluation, and common pitfalls to avoid. Developers will find a pragmatic starting strategy for deploying reliable agents in production.

    1. Redefining the Problem: From Giving Advice to Completing Tasks

    The original request may look like “recommend an AI tool,” but the real technical question is not tool selection. It is how a large language model evolves from an information provider into a task executor. A traditional Q&A pipeline runs “input question → retrieval/reasoning → text output” and ends with a suggestion. A closed-loop task pipeline ends with a real state change, such as creating an order, locking a seat, or confirming an itinerary. This shift brings three fundamental changes.

    First, the output changes from “text” to “action.” Actions have side effects and cannot be rolled back freely, so they demand far higher determinism, idempotency, and access control than text generation. Second, evaluation changes from “does it read like a human wrote it” to “was the task actually completed.” Metrics move from subjective preference to task success rate, average number of steps, fallback rate, and human takeover rate. Third, the cost of failure changes from “ask again” to “real loss.” This means the system must have confirmation, spending-limit, and audit mechanisms.

    The subject of this article is therefore the task-closed-loop agent: a system that uses a large language model as the planning and decision-making core, tool calling as the execution mechanism, retrieval and memory as knowledge support, and sandboxes and auditing as safety boundaries.

    2. Capability Layers: Separating the Basics from What Really Matters

    Content generation, code completion, document summarization, and image and video generation are basic generation capabilities. They solve the problem of “expression.” What really determines whether an agent is usable are the four layers below.

    1. Intent understanding and slot extraction. A request like “book a window table for two tomorrow at 10 a.m.” must be parsed into structured parameters such as time, party size, seating preference, and scenario type. In engineering, this usually follows a three-stage pattern: the model outputs a structured object, rules validate it, and the system asks back for missing slots. This avoids letting the model assemble the final request directly.

    2. Task planning and decomposition. Complex requests must be split into subtasks with dependencies, forming a directed acyclic graph. The planner selects tools, orchestrates order, decides what runs in parallel versus sequentially, and replans on failure.

    3. Tool execution and state management. Every tool has a clear input schema, timeout, retry, and idempotency policy. Intermediate state across steps must be persisted to support resuming from a checkpoint.

    4. Result verification and delivery. After execution, the system must read back the state to confirm it, rather than trusting a “call succeeded” return value. It then restates the facts that actually happened to the user in natural language.

    3. Reference Architecture: A Practical Layered Design

    1. User natural language
    2. ↓
    3. Access layer (authentication / rate limiting / session)
    4. ↓
    5. Orchestration layer: intent recognition → planner → executor → verifier
    6. ↓ ↑ ↓
    7. Knowledge layer: vector retrieval / authoritative sources Tool registry (Schema + permission tags)
    8. ↓
    9. Execution sandbox: API adapters / browser automation / voice gateway
    10. ↓
    11. Observability: logging + monitoring/alerting + full-chain tracing + audit trail

    Key responsibilities of each layer:

    • The access layer handles identity and quotas to prevent abuse from anonymous calls.
    • The orchestration layer is the brain. Keep planning and execution fully decoupled: the planner only produces a plan object, and the executor only calls tools according to the plan.
    • The knowledge layer handles factual Q&A, while the tool layer handles actions. The two must not be mixed: factual questions must go through retrieval, and action requests must go through tools.
    • The observability layer is not an add-on; it is a prerequisite for going to production.

    4. Tooling: Making External Systems Safely Callable

    The core of tooling is converging uncertain natural language into deterministic interface contracts. Each tool should provide four elements: a name and semantic description, a structured parameter schema, permission tags, and return status code semantics.

    1. {
    2. "name": "reserve_table",
    3. "description": "Create a table reservation for a specified store; submit only, no payment",
    4. "parameters": {
    5. "store_id": "string",
    6. "time": "ISO-8601",
    7. "party_size": "integer>=1",
    8. "preference": "window|quiet|none"
    9. },
    10. "permission": ["booking:write"],
    11. "idempotency_key": "session+store+time+size"
    12. }

    There are four engineering constraints. First, write operations must carry an idempotency key to prevent duplicate orders caused by network retries. Second, operations involving money or irreversible actions must enforce a second confirmation, submitted only after the user explicitly confirms. Third, tools must return a unified structure that distinguishes “business failure” from “system failure.” The former is handed to the model to rewrite parameters or ask back; the latter enters retry and fallback. Fourth, all tools run inside a sandbox, credentials are issued by a key management service, and the model side never sees plaintext keys.

    For scenarios without open APIs, browser automation can serve as a fallback, but it must restrict a domain whitelist, prohibit entering credentials, and run health checks on page structure changes. Otherwise it becomes a highly unstable dependency.

    5. Voice Interaction: Achieving Both Human-Like Quality and Compliance

    Voice outbound calling is the most striking and most sensitive capability in the original discussion. Technically, it is a closed loop of “speech recognition → dialogue state machine → speech synthesis.” The difficulties are threefold: recognition robustness in noisy environments, interruption handling when competing with a real person speaking, and latency control, where end-to-end response usually must be compressed into a short window to maintain a natural conversational feel.

    A more robust engineering approach is to design it as “semi-automatic”: the agent handles information collection and script organization, while key confirmations and identity disclosure are handled by the user or through explicit disclosure that it is an AI. This reduces the risk of misoperation and aligns with the compliance trend in many regions toward labeling synthetic speech. Under no circumstances should it be designed as a disguise that the other party cannot detect. This is both a compliance red line and the foundation of product trust.

    6. Knowledge Reliability: Retrieval Augmentation and Authoritative Sources First

    The premise of “one click from question to answer” is that the answer is reliable. The standard Retrieval-Augmented Generation (RAG) pipeline is: document parsing → chunking → vectorization and indexing → hybrid retrieval (keyword + semantic) → reranking → generation with citations. Improving reliability requires three additional designs.

    First, source tiering: give higher weight to authoritative sources such as regulations, standards, and official documentation, and force citations in the answer. Second, conflict resolution: when multiple sources disagree, output an explanation of the divergence rather than forcing a single answer. Third, a refusal mechanism: when retrieval confidence is below a threshold, clearly state that “the available material is insufficient.” This is more valuable than fabricating an answer.

    1. def answer(query, k=8, threshold=0.62):
    2. hits = hybrid_search(query, top_k=k)
    3. if not hits or hits[0].score < threshold:
    4. return {"text": "Insufficient material to support a conclusion", "citations": []}
    5. ctx = rerank(hits)[:5]
    6. return generate(query, ctx, require_citation=True)

    7. Multimodal Output: Turning Material into Structured Assets

    For material such as long documents, meeting notes, and course materials, the value lies not in a “summary” but in “reusable output”: structured minutes, to-do lists, knowledge cards, chart descriptions, and short-video scripts. The implementation starts with layout and semantic parsing that preserves heading hierarchy and table structure, then performs controlled generation against a target template, and finally runs consistency checks so that numbers, names, and times do not drift. This kind of pipeline is well suited to running on a container platform and message queue, executing asynchronously per task and supporting failure replay.

    8. Productionization: Observability, Evaluation, and Cost Governance

    Three baselines must be established before launch. Functional evaluation uses task success rate, parameter accuracy, and average interaction turns. Security evaluation covers unauthorized calls, prompt injection, and sensitive information leakage. Performance evaluation focuses on time to first token and end-to-end duration. In production, logging enables full-chain tracing, monitoring and alerting set threshold alerts on failure and timeout rates, and complete audit records are retained to support traceability.

    Cost governance is equally critical: split retrieval, planning, and execution into model calls of different sizes, routing simple intents to small models and complex planning to large models; cache results for high-frequency requests; and use incremental indexing for long documents to avoid repeated vectorization.

    9. Common Pitfalls and How to Avoid Them

    • Treating the model as a database and skipping retrieval for factual Q&A.
    • Tool granularity that is too coarse, cramming too many responsibilities into one tool and driving up parameter error rates.
    • Missing a confirmation step, so write operations take effect immediately.
    • Ignoring idempotency, so a retry becomes a duplicate order.
    • Coupling planning and execution, so local replanning is impossible after a failure.
    • Launching without evaluation, so problems only surface through user feedback.

    All of these point to the same principle: cage the uncertainty, and constrain model behavior with four layers—contracts, sandboxes, confirmation, and evaluation.

    10. Conclusion

    “Getting things done with a single sentence” is not the victory of any single capability but the result of systems engineering: structured intent, orchestrable plans, contractual tools, strongly constrained sandboxes, reliable retrieval, and complete observability together form the closed loop. For developers, the pragmatic starting path is to pick a high-frequency, low-risk, rollback-friendly scenario and build it end to end first, solidify the tool contracts and evaluation baselines, and then gradually expand to complex tasks involving money and irreversible operations. General-purpose capabilities such as the container platform, message queue, object storage, logging, and monitoring and alerting offered by Baidu AI Cloud can serve as the foundation for such agent systems, letting teams focus their energy on orchestration logic and business outcomes.