Large Language Model Agents: A Practical Guide to Architecture, Evaluation, and Governance
This guide explains how large language model (LLM) agents move from content generation to task execution. It covers model alignment, tool use, context engineering, multi-agent collaboration, layered enterprise architecture, cost control, and security governance, with practical evaluation metrics and implementation checklists for developers and organizations.
Introduction: From Content Generation to Task Execution
Since late 2022, conversational LLMs have rapidly entered the mainstream. In just a few years, model capabilities have evolved along a clear path: language understanding → logical reasoning → multimodal perception → tool use → autonomous execution. As a result, expectations from developers and enterprises have shifted from “generate decent text” to “independently complete meaningful work.”
At the same time, real-world deployment challenges remain significant:
- Unstable outputs: repeated runs of the same task can produce materially different results.
- Unpredictable inference cost and latency: it is hard to estimate compute needs and response time before deployment.
- Ambiguous permission boundaries: unclear access control increases data compliance risk.
- Irreversible business impact: once real systems are involved, incorrect actions can cause serious consequences.
What really determines whether an LLM can enter production is no longer just model size. It is an entire engineering system:
- Model alignment to keep model behavior within expected boundaries;
- Agent capabilities that let models perceive and operate external systems;
- Multi-agent orchestration for efficient completion of complex tasks;
- Engineering and governance to keep all of the above stable and auditable.
This article uses these capabilities as its main thread and systematically explains the technical principles, architecture patterns, and implementation methods of LLM agents. It also provides practical evaluation metrics, cost strategies, and governance checklists.
1. Technology Evolution: Three Stages of LLMs
| Stage | Core Capability | Main Interaction Pattern | Main Limitations | Typical Use Cases |
|---|---|---|---|---|
| Language model stage | Text continuation and generation | Prompt-driven single-turn or multi-turn dialogue | Weak factual accuracy, no access to external information | Copywriting, summarization, information extraction |
| Conversational model stage | Instruction following, chain-of-thought reasoning, multimodal understanding | Chat assistants, content generation | Limited initiative, difficulty with multi-step tasks | Knowledge Q&A, document processing, content moderation |
| Agent stage | Tool use, long-horizon planning, multi-agent collaboration | Autonomous planning and execution, human-in-the-loop | Controllability, cost, and reliability challenges | Coding assistance, workflow automation, data analysis, scientific computing |
This evolution is not simply a matter of accumulating capabilities. It represents three fundamental shifts:
- From “predicting the next token” to “understanding and following intent.” Model outputs move from being merely fluent to satisfying explicit instruction constraints.
- From “closed answers” to “open interaction.” Models can retrieve external knowledge, call business systems, and access real-time data.
- From “single-turn responses” to “long-horizon execution.” Models can decompose ambiguous goals into multiple steps, revise based on feedback, and continue until completion or escalation.
One important point: an LLM is not an “executor.” It is a decision and orchestration engine. It is good at interpreting ambiguous requirements, generating structured plans, and reasoning over unstructured information. The components that actually produce business side effects are the tools the model calls.
This distinction leads to a core principle for all subsequent architecture: separate the model’s decision-making capability from the system’s execution boundaries.
2. Model Alignment: Engineering for Trustworthy Behavior
2.1 Four Questions Alignment Must Answer
“Model alignment” is often simplified to “make the model avoid wrong statements.” That is not enough. A practical alignment system must address four questions:
- Helpful: Does it actually solve the user’s problem, rather than providing vague but plausible answers?
- Honest: Does it acknowledge uncertainty instead of confidently fabricating information?
- Harmless: Does it refuse dangerous, illegal, or rights-violating requests?
- Corrigible: Can it correctly accept corrections from users, reviewers, or higher-level control logic, rather than persisting with incorrect outputs?
These objectives often conflict. For example, an overly conservative refusal policy can reduce usefulness. The essence of alignment work is to define measurable and tradeable boundaries for these objectives in specific business contexts.
2.2 Three Mainstream Alignment Approaches
(1) Supervised Fine-Tuning (SFT). Train the model on high-quality “instruction–response” samples written or curated by humans, so its output style, format, and compliance align with business requirements. SFT is fast and controllable, but highly sensitive to data quality and may not cover all open-ended scenarios.
(2) Reinforcement Learning from Human Feedback (RLHF). Have annotators rank multiple model responses, train a reward model to fit human preferences, and then optimize the main model with reinforcement learning. This significantly improves response quality and usefulness, but it is complex, costly, and vulnerable to reward hacking.
(3) Principle-Based Self-Critique and Revision. Define a set of natural-language principles in advance, let the model critique and revise its own responses against these principles, and then train the model using preference pairs of “before vs. after” revisions. Its advantages include:
- Principles can be versioned and audited. To change behavior rules, you only need to update the principle document instead of re-organizing large-scale human annotation.
- Organizational safety red lines and compliance requirements can be directly encoded into principles, keeping model behavior aligned with enterprise policies.
The following pseudocode illustrates this approach:
# Illustrative pseudocode: principle-based "critique-and-revise" pipelinePRINCIPLES = load_principles(version="v1.3") # Principle set: safety rules, compliance requirements, response style, etc.def critique_and_revise(prompt, response):critique = model.complete("Compare the response against the following principles, and list issues and improvement directions item by item:\n"+ render(PRINCIPLES) + "\n\nUser question: " + prompt + "\nResponse: " + response)revised = model.complete("Revise the response based on the critique. Keep correct content and fix inappropriate parts:\n"+ critique)return revised# Batch sampling: original response → self-revision → preference pairs → preference optimization trainingpairs = [(r, critique_and_revise(p, r)) for p, r in sample_responses(prompts)]train_with_preference_pairs(pairs, base_model)
These three approaches are often combined in practice. More importantly, alignment cannot stop at the model itself. It requires a closed loop on the inference side: “principles → policies → guardrails”:
- Principles: readable, versionable documents that define what the model can do, what it cannot do, and how to resolve conflicts;
- Policies: executable control logic derived from principles, such as system instructions, tool whitelists, and approval rules;
- Guardrails: detection of prompt injection and other attacks at the input stage, and detection of sensitive information and unauthorized actions at the output stage.
This loop is structurally similar to “requirements → design → testing” in software development. The only difference is that the object being constrained shifts from code to probabilistic model behavior.
2.3 Engineering Alignment: Versioning, Regression, and Auditing
A common oversight in alignment is lack of regression testing. Tightening a principle today may cause a customer service assistant to refuse too many requests tomorrow. At minimum, establish the following mechanisms:
- Version control: put principle documents, system instructions, and guardrail rules under version control, with every change traceable;
- Adversarial regression set: collect samples such as prompt injection, unauthorized requests, and leading questions, and automatically replay them after every change;
- Audit logs: record model inputs, outputs, tool calls, and decision rationale for post-hoc analysis.
3. Agent Capabilities: From “Answering” to “Completing”
3.1 Tool Use: The Agent’s Hands and Feet
An agent is a system that can perceive its environment, make autonomous decisions, and take actions to achieve goals. In the LLM context, tool use is the most fundamental agent capability. A typical workflow is:
- The system provides available tool names, descriptions, and parameter structures (usually described via JSON Schema) in the context.
- The model selects tools based on the task and generates structured call parameters.
- The runtime validates parameters, executes the tool, and feeds the result back to the model.
- The model decides the next step based on the result: call another tool, summarize output, or request user confirmation.
// Illustrative example: tool declaration structure{"name": "query_orders","description": "Query orders by user ID and date range. Returns order number, amount, and status.","parameters": {"type": "object","properties": {"user_id": { "type": "string" },"date_from": { "type": "string", "format": "date" },"date_to": { "type": "string", "format": "date" }},"required": ["user_id", "date_from"]}}
Tool use must follow three engineering principles:
- Strict schema validation: when parameters do not match the schema, return clear error messages so the model can retry, rather than silently discarding the request;
- Appropriate tool granularity: overly fine-grained tools cause excessive call rounds and context bloat; overly coarse-grained tools reduce flexibility and make composition difficult;
- Tool descriptions are interface documentation: the more accurate the description, the higher the probability that the model selects the correct tool.
3.2 Context Engineering: The Agent’s Memory and Workspace
Agent performance depends heavily on what the model sees at each step. This is context engineering. In practice, a layered design is common:
- System layer: role definition, principles, and behavior norms;
- Task layer: user goals, task state, and completed steps;
- Knowledge layer: relevant materials retrieved from enterprise knowledge bases via Retrieval-Augmented Generation (RAG);
- History layer: summarized and compressed long conversations, retaining only key conclusions and decisions.
More context is not always better. Irrelevant information dilutes attention, increases inference cost, and can be exploited by malicious content. Follow the principle: load on demand, clean up promptly, and present in a structured way.
3.3 Skill Accumulation: Turning “Done Once” into “Done Every Time”
General-purpose LLMs often do not know the specific operating procedures of enterprise internal systems. An effective approach is demonstration-driven learning: allow users to record one complete operation process (for example, a screen recording, or a step-by-step sequence of actions and tool calls), and the system automatically abstracts it into a reusable “skill,” extracting variable parts as parameters. The next time a similar task appears, the agent can directly invoke this skill.
# Illustrative pseudocode: distilling an operation trace into a reusable skilltrace = record_agent_run(task) # Record tool calls, parameters, and resultsskill = abstract_skill(trace) # Abstract into step sequence + parameter slots# For example: turn hard-coded order numbers and dates into parametersskill.params = ["order_no", "date_range"]register_skill(skill, triggers=["export order report", "generate reconciliation statement"])
This approach converts “expensive on-the-fly reasoning” into “low-cost capability reuse.” It is especially suitable for business scenarios with relatively fixed workflows but complex operating procedures.
3.4 Efficiency Optimization: Making Agents Fast and Affordable
Efficiency optimization for LLMs spans both inference serving and agent design:
- Scheduling layer: request batching, KV Cache reuse, prompt prefix caching (caching fixed content such as system instructions and tool definitions to reduce repeated computation), model quantization and distillation, and speculative decoding (a small model drafts, a large model verifies);
- Application layer: model routing by task complexity (simple tasks to lightweight models, complex tasks to stronger models), streaming output, parallel tool calls, and asynchronous execution with result polling for long-running tasks.
| Optimization | Layer | Main Benefit | Caveats |
|---|---|---|---|
| Prefix caching | Inference serving | Reduces repeated computation from fixed prompts and tool definitions | Cache content must remain stable and unchanged |
| Model routing | Application | Balances cost and quality | Requires a reliable task classifier |
| History summarization | Application | Controls context length and inference cost | Avoid losing key constraints |
| Parallel tool calls | Application | Reduces latency for multi-step tasks | Watch for data dependencies between tools |
| Quantization and distillation | Model | Reduces deployment resource requirements | May introduce some accuracy loss |
4. Multi-Agent Collaboration and Dynamic Workflows
4.1 When Multi-Agent Is Needed
A single-agent architecture (“one model + one set of tools”) is simple, controllable, and easy to debug. It should be the default choice. Multi-agent collaboration is worth considering only when tasks exhibit the following characteristics:
- Tasks can be clearly decomposed into relatively independent subtasks;
- Subtasks can run in parallel, or require different expertise or perspectives;
- A single context cannot accommodate all information, requiring a “divide and conquer” approach.
4.2 Four Common Collaboration Topologies
- Orchestrator–Workers: a primary agent handles task decomposition, dispatch, and result aggregation, while multiple sub-agents independently complete subtasks.
- Pipeline: tasks flow sequentially across multiple roles, such as “retrieve → analyze → write → review.”
- Debate/Review: multiple agents independently produce conclusions, and a review agent compares and adjudicates them. This reduces single-point misjudgment.
- Blackboard: multiple agents read and write to a shared state, collaborating via event triggers. This suits highly dynamic scenarios.
4.3 Dynamic Workflows: Generating Execution Graphs at Runtime
Traditional workflow engines rely on pre-defined flowcharts with fixed paths. Changing the flow requires reconfiguration. In contrast, a dynamic workflow has the orchestrator agent generate a directed acyclic graph (DAG) of subtasks at runtime, which is then scheduled for parallel execution. Pseudocode:
# Illustrative pseudocode: dynamic workflow orchestrationasync def dynamic_workflow(goal):plan = await orchestrator.plan(goal) # Generate subtask DAGresults = {}while (ready := plan.ready_nodes(results)): # Nodes with zero in-degree can run in paralleltasks = [run_agent(node, context=results) for node in ready]batch = await asyncio.gather(*tasks, return_exceptions=True)for node, res in zip(ready, batch):results[node.id] = resplan.mark_done(node.id) if not isinstance(res, Exception) else plan.retry(node.id)return await orchestrator.synthesize(goal, results)
Its advantage is high flexibility: subsequent steps can be adjusted based on intermediate results. The cost is reduced controllability and observability, which must be addressed with the following mechanisms:
- Global budget: limit total steps, tool calls, and token consumption; terminate when exceeded;
- Circuit breaker and retry: skip a subtask after consecutive failures exceed a threshold, or escalate to a human;
- Full-chain tracing: record each node’s input, output, and duration to help diagnose failures;
- Human-in-the-loop: for high-risk operations such as financial transactions, external publishing, or data deletion, pause execution and wait for human approval.
4.4 The Hidden Costs of Multi-Agent Systems
More agents do not necessarily mean stronger performance. Information transfer between sub-agents consumes additional context, errors can accumulate and amplify during handoffs, and debugging and evaluation complexity increases exponentially. Industry experience suggests that 70% of complexity often comes from the last 10% of “last-mile” scenarios. Therefore, a reasonable strategy is: start with a single agent, then add collaboration; start with deterministic workflows, then move to dynamic orchestration.
5. Enterprise Implementation: Layered Architecture and Cloud Practices
5.1 Five-Layer Reference Architecture
┌─────────────────────────────────────────────────┐│ Channel Layer Web / Mobile / Collaboration / CS │├─────────────────────────────────────────────────┤│ Agent Layer Orchestrator + Sub-agents + Skills│├─────────────────────────────────────────────────┤│ Model Layer Unified Model Gateway ││ (Routing / Cache / Rate Limit / ││ Audit) │├─────────────────────────────────────────────────┤│ Capability Layer Tools & Connectors / RAG / Data │├─────────────────────────────────────────────────┤│ Infrastructure Containers / Message Queue / ││ Object Storage / Vector DB / ││ Logging / Monitoring / Secrets │└─────────────────────────────────────────────────┘
- Channel layer: embed agents as native components within users’ existing work entry points, rather than requiring a separate chat window;
- Agent layer: handles planning, scheduling, and skill reuse. This is the “brain” of the system;
- Model layer: a unified model gateway abstracts away differences between underlying models and centrally handles routing, caching, rate limiting, and auditing, avoiding tight coupling between business code and specific models;
- Capability layer: connects to existing enterprise systems and data assets. This is where agents generate real business value;
- Infrastructure layer: provides elastic compute, asynchronous tasks, data persistence, and observability.
5.2 Integration with Business Systems: From “Embedded Assistant” to “Process Executor”
Enterprise adoption typically goes through three stages:
- Embedded assistant: provide summarization, suggestions, and draft generation within existing system interfaces, with execution confirmed by humans;
- Semi-automated workflow: agents autonomously complete low-risk steps, while humans approve key nodes;
- Controlled automated workflow: end-to-end execution within clear boundaries, continuously calibrated through monitoring.
The key to integration is not “how many systems are connected,” but whether permissions, data access, and auditing are properly aligned. For example, when an agent calls a query API, it should inherit the caller’s data permissions, not use a “super account” with unrestricted access.
5.3 Cloud Implementation: Leveraging General Infrastructure
- Object storage: store unstructured data such as documents, screen recordings, and task outputs;
- Message queue: handle asynchronous decoupling for long-running tasks, preventing agent execution from blocking user requests;
- Container platform: host agent runtimes and tool sandboxes, with elastic scaling for traffic peaks;
- Vector database: support semantic retrieval for knowledge bases;
- Logging and monitoring: continuously observe call chains, token consumption, success rates, and latency;
- Secrets and permission management: centrally manage third-party system credentials with least-privilege access and regular rotation.
In the Chinese market, cloud service providers such as Baidu AI Cloud offer model service platforms and cloud infrastructure that can serve as a foundation for the above architecture. Enterprises can choose flexibly based on their existing technology stack.
6. Operating Models and Cost Governance
6.1 Three Service Models
| Model | Billing | Target Users | Advantages | Caveats |
|---|---|---|---|---|
| API calls | Metered by input/output tokens | Developers, ISVs, SMBs | Flexible, pay-as-you-go | Cost uncertainty from usage fluctuations |
| Enterprise subscription | Per-seat or periodic package | Teams, medium-to-large enterprises | Predictable cost, unified management | Need to evaluate seat turnover and usage depth |
| Dedicated/private deployment | Resource package or project-based | Finance, government, and other highly regulated industries | Data stays within domain, autonomous control | High upfront investment, demanding operations |
Many leading model providers have formed commercial structures centered on API calls and enterprise subscriptions, and are gradually evolving toward “model capabilities + industry solutions.”
6.2 Cost Governance Strategies
- Tiered routing by task complexity: send most simple requests to lightweight models;
- Cache reuse: cache results for high-frequency, repetitive requests;
- Control context bloat: streamline tool lists and history messages; avoid “stuffing an entire manual into the model”;
- Set quotas and alerts: define token budgets for each business line and tenant, with automatic degradation or rate limiting near thresholds;
- Establish unit cost metrics: track “average cost per completed task,” not just token unit prices.
7. Capability Boundaries and Typical Use Cases
7.1 Capability Boundaries
LLMs continue to make breakthroughs in reasoning-intensive tasks such as mathematics and physics. For example, some research has applied LLMs to symbolic computation of higher-order scattering amplitudes in high-energy physics, achieving results that can be cross-validated with traditional methods. Such progress demonstrates that models have foundational potential for handling highly complex reasoning tasks.
However, it is important to recognize that models can still produce plausible-sounding errors. In high-risk scenarios, “can compute correctly” does not mean “safe to rely on.” Independent verification and human review are essential.
7.2 Typical Scenarios
- Software development: code generation and completion, unit test generation, code review, incident diagnosis assistance, operations script generation;
- Customer service and office work: ticket classification and automated responses, meeting summary generation, email and document drafting, cross-system information consolidation;
- Data analysis: natural language querying, automated daily business reports, anomaly attribution and explanation;
- Research and engineering: literature review, simulation parameter exploration, complex formula derivation and verification.
8. Evaluation System and Security Compliance
8.1 A Four-Dimensional Evaluation Framework
- Model-level evaluation: knowledge and reasoning benchmarks to assess foundational capabilities;
- Task-level evaluation: end-to-end task success rate to assess whether tasks can actually be completed;
- System-level evaluation: tool call accuracy, average steps, average latency, and cost;
- Business-level evaluation: user satisfaction, human takeover rate, and improvement in business metrics.
8.2 Key Metrics Reference
- Task success rate: proportion of tasks completed end-to-end with correct results;
- Tool call accuracy: proportion of calls that select the correct tool with valid parameters;
- Human takeover rate: proportion of tasks requiring human intervention;
- Unauthorized request interception rate: proportion of permission-violating requests successfully blocked;
- Unit task cost: average token and resource cost per completed task.
8.3 Security and Compliance Essentials
- Data security: mask sensitive data before sending it to the model; define clear data retention and deletion policies;
- Least privilege: grant tool credentials on demand; prohibit agents from holding permissions beyond task requirements;
- Prompt injection defense: strictly separate “external data” such as retrieved content and web content from “system instructions”;
- Content compliance: establish output review and traceability mechanisms to meet relevant requirements for generative AI management;
- Human–machine collaboration: preserve human confirmation for high-risk operations and record approval trails.
Conclusion
LLMs are undergoing a critical transformation: from “content generation tools” to “task execution partners.” Whether this transformation succeeds depends on four things: whether model alignment effectively constrains behavior, whether agent capabilities are reliably encapsulated into reusable skills, whether multi-agent collaboration solves problems within controllable costs, and whether the engineering system is observable, governable, and evolvable.
For enterprises, the recommended path is: validate in small scenarios → standardize and encapsulate → scale gradually. First close the loop in a single, well-bounded scenario, then distill experience into skills and components, and finally consider cross-system collaborative automation.
For developers, rather than chasing the “most powerful model,” focus on engineering capabilities with higher determinism: prompt engineering, tool design, context management, and evaluation systems. These capabilities will not become obsolete with model upgrades; instead, their value will continue to amplify as model capabilities improve.
