Architecture and Systems Engineering Guide for LLM-Driven Agentic Execution

    This guide explores the system architecture and engineering practices required to transition large language models (LLMs) from simple Q&A to closed-loop task execution. It covers an eight-layer reference architecture, key engineering practices such as tool contract design, context engineering, and execution loops, as well as an enterprise deployment roadmap to ensure reliable, verifiable, and secure agentic automation.

    Architecture and Systems Engineering Guide for LLM-Driven Agentic Execution

    1. Redefining the Problem: From Q&A to Task Closure

    This guide discusses a class of lightweight, fast LLMs optimized for execution, rather than a specific product. The focus of capability enhancement is not a comprehensive leap in pure knowledge reasoning, but rather code intelligence, agent orchestration, tool calling, environment interaction, and real-world task execution. This shift means system design goals must adapt: the pipeline built around “single-turn Q&A accuracy” cannot support multi-step, verifiable, and auditable task closures.

    From a capability perspective, such models typically yield significant benefits in three types of tasks:

    1. Code and Engineering Operations: Understanding repository context, generating patches, invoking tests and static checks, and iteratively fixing based on error feedback. The key to code tasks is not just generating code, but forming a closed loop of “modify-verify-fix”.
    2. Terminal and Environment Interaction: Performing operations via commands, file systems, browsers, or business system APIs. Such capabilities must run in a controlled sandbox with permission, network, resource, and snapshot management.
    3. Multi-step Automation and Real-world Tasks: Decomposing tasks, selecting tools, filling parameters, tracking states, handling exceptions, and completing operations like document processing, data reconciliation, and ticket routing in enterprise workflows. Public evaluation trends show that multi-step automation capabilities often improve significantly, while high-difficulty pure reasoning improves more moderately. This suggests the models have undergone post-training oriented towards execution trajectories, rather than relying solely on base intelligence growth.

    Therefore, the core of systems engineering is not “plugging the model into the system,” but building a runtime that amplifies execution capability, constrains side effects, verifies results, and enables continuous operations.

    2. Reference Architecture: Layered Decoupling and Execution Loops

    It is recommended to split the execution-oriented LLM system into eight layers to prevent coupling between models, tools, and business logic.

    1. Access Layer

    Responsible for identity authentication, tenant isolation, request rate limiting, task entry, and human approval entry. The access layer should generate a global trace_id to link a task from user request, model decision, tool calling, to final delivery. For high-risk operations, the access layer should support a “preview before submit” interaction mode.

    2. Orchestration Layer

    The central hub of the agent system, responsible for task decomposition, state machine progression, tool selection constraints, retry strategies, timeout control, idempotency key generation, failure compensation, and human handover. It should not hand over all logic to the model’s free play; instead, it should constrain task stages with an explicit state machine, such as “plan-execute-observe-verify-submit-archive”.

    3. Model Service Layer

    Responsible for routing, prompt templates, structured output parsing, context compression, and cost control. Lightweight, fast models are suitable for high-frequency, short-step, low-latency execution phases. When encountering high-difficulty reasoning or high-risk decisions, routing can upgrade to stronger reasoning capabilities, or introduce rule engines, verifiers, and human review.

    4. Tool Runtime Layer

    Provides sandboxing, file system isolation, network whitelisting, resource quotas, command timeouts, and output truncation. All tool calls should pass contract validation and policy checks. Read and write operations should be separated, and side-effect operations must support idempotency and rollback.

    5. State and Memory Layer

    The state layer saves task snapshots, step records, tool return summaries, evidence references, and human approval records. The memory layer is divided into short-term working memory and long-term knowledge memory: short-term memory is used for current task context compression, and long-term memory for enterprise knowledge, process specifications, and historical case retrieval.

    6. Data and Knowledge Layer

    Includes general categories like business databases, object storage, retrieval indexes, message queues, and log services. The key to the data layer is permission passthrough and evidence traceability: every piece of context the model sees should have a source identifier, and the final conclusion should be traceable to evidence.

    7. Security Governance Layer

    Covers least privilege, data masking, network access control, sensitive operation approval, audit logs, and compliance trails. The stronger the execution-oriented model’s capability, the more necessary it is to write “what cannot be done” into system policies, rather than just in prompts.

    8. Observability and Evaluation Layer

    Records model calls, tool calls, step durations, failure reasons, human handover rates, and costs. The evaluation layer should include offline regression sets, online canary testing, and real-task replay, not just single-turn Q&A scores.

    3. Key Engineering Practices

    1. Tool Contract Design: Making Models “Callable, Validatable, Recoverable”

    Tool contracts should use structured schemas to describe inputs and outputs, explicitly defining side-effect types, timeouts, idempotency requirements, and error classifications. Below is an example, not a specific product interface:

    1. {
    2. "name": "read_record",
    3. "description": "Read a business record, read-only operation",
    4. "input_schema": {
    5. "type": "object",
    6. "properties": {
    7. "record_id": {"type": "string"},
    8. "fields": {"type": "array", "items": {"type": "string"}}
    9. },
    10. "required": ["record_id"]
    11. },
    12. "side_effect": "read",
    13. "timeout_ms": 3000,
    14. "idempotent": true
    15. }

    Design points include: separating read-only and write tools; write tools must carry idempotency keys; error returns should distinguish between “parameter error, insufficient permissions, resource not found, temporary failure, business conflict”; tool outputs should be size-limited and masked; add approval gates for high-risk tools. Tool descriptions should be stable, concise, and enumerable to prevent the model from misselecting among similar tools.

    2. Context Engineering: Task Cards, State Snapshots, and Evidence References

    The goal of context engineering is to let the model see “the most necessary information for the current stage” within a limited window. It is recommended to maintain a task card containing goals, constraints, acceptance criteria, available tools, risk levels, and deadline conditions. After each execution round, update the state snapshot, keeping only recent observations, key evidence, and pending issues. Long documents should be compressed through retrieval and summarization, retaining original references to prevent summary drift. For code tasks, provide repository structure, related files, test commands, and recent failure logs; for business process tasks, provide field mappings, permission boundaries, and approval rules.

    3. Execution Loop: Planning, Acting, Observing, Reflecting, Verifying

    The execution loop should have clear termination conditions to avoid infinite retries. Example pseudocode:

    1. def run_task(task, model, tools, policy, verifier):
    2. state = init_state(task)
    3. for step in range(policy.max_steps):
    4. ctx = build_context(task, state.summary(), tools.schema())
    5. decision = model.decide(ctx)
    6. if decision.kind == "final":
    7. return verifier.check(decision.answer, state)
    8. call = validate_tool_call(decision.tool_call, tools.schema())
    9. if not policy.allow(call):
    10. state.need_approval(call)
    11. return escalate(state)
    12. key = make_idempotency_key(task.id, call)
    13. result = sandbox.execute(call, key, timeout=call.timeout_ms)
    14. state.observe(call, result)
    15. state.summary_update(model.summarize(state.recent()))
    16. return escalate(state)

    The verifier is key here: code tasks use tests, static checks, and diff reviews; data tasks use field validation, total reconciliation, and sampling review; process tasks use state consistency checks and approval records. The model drives progress, and the verifier guards the gate.

    4. Security and Permissions: Least Privilege, Sandbox Isolation, and Approval Gates

    Execution-oriented systems must assume by default that “models can make mistakes.” Sandboxes should limit file system scope, network egress, process resources, and execution duration; sensitive data should be masked before entering the context; write operations should support dry runs and rollbacks; high-risk actions should trigger human approval. Audit logs should record who authorized which tool, when, parameter summaries, result status, and evidence references, and the logs themselves must not be modifiable by the model.

    5. Reliability and Idempotency: Retry, Compensation, and Checkpoint Resume

    Multi-step tasks are most prone to dirty states when “failing at step N.” Engineering-wise, design idempotency keys for each side-effect operation, compensation actions for critical workflows, and checkpoint resume for long tasks. Retry strategies should distinguish between retryable and non-retryable errors; for write operations, confirm whether the previous attempt took effect before retrying. Message queues can be used for async task decoupling but must be paired with deduplication tables and state machines.

    6. Observability and Evaluation: From “Correct Answer” to “Completed and Auditable”

    Observability metrics should include at least: task success rate, number of steps, tool call success rate, average recovery times, human handover rate, cost per task, end-to-end latency, and audit completeness rate. Evaluation sets should cover real-task replay, exception injection, permission boundaries, and long-process regressions. The rollout strategy suggests shadow running first, then small-traffic canary, and finally gradually increasing the automation ratio.

    7. Cost and Latency: Layered Routing for Lightweight Fast Models

    The value of lightweight, fast models lies in high-frequency execution and low-latency interaction, but they should not handle all reasoning. Layered routing can be adopted: use lightweight models for routine tool calls and state progression; upgrade to stronger reasoning capabilities for complex planning, conflict resolution, and high-risk decisions; hand over deterministic rules to rule engines; and hand over result verification to tests and validators. Caching, parallel tool calls, output truncation, and context compression can all significantly reduce costs.

    4. Enterprise Deployment Roadmap

    Enterprise agent and digital employee scenarios should prioritize tasks that are “highly repetitive, clearly defined, verifiable, and low-risk,” such as information reconciliation, ticket preprocessing, document extraction, code fix suggestions, and test completion. Deployment can be divided into four phases: shadow mode (record only, no execution); execution after human approval; automatic execution of low-risk tasks with spot checks; and finally, gradually expanding the automation scope based on permissions and risk levels.

    When deploying in the cloud, general categories like container platforms, object storage, message queues, log services, and monitoring alerts can be combined. In a Baidu AI Cloud environment, selection and governance should also be based on general cloud product categories, focusing on interface contracts, isolation, auditing, and observability, rather than binding to a specific product.

    5. Implementation Checklist

    • Have you defined a structured contract, side-effect type, timeout, and idempotency requirements for each tool?
    • Have you separated read-only and write tools, and set approval gates for write operations?
    • Is there an explicit state machine with limits on maximum steps, maximum cost, and maximum duration?
    • Do you have sandbox isolation, network whitelisting, data masking, and audit logs?
    • Do you use verifiers to guard the gate instead of relying solely on model self-evaluation?
    • Have you established a real-task replay set and exception injection evaluation?
    • Are you monitoring task success rate, human handover rate, unit cost, and audit completeness rate?
    • Do you support checkpoint resume, compensation actions, and failure escalation to humans?

    The upper limit of an execution-oriented LLM is determined by model capability, but the lower limit is determined by systems engineering. Solidifying tool contracts, state management, sandbox security, verifiers, and observability is the only way to transform “can call tools” into “can reliably complete real-world tasks.”