AI Agent Architecture: Combining Models and Agents for Production Systems
This article explains how large language models and AI agents work together in production, covering layered architecture, model integration, tool calling, context and memory management, evaluation, security governance, and cost control. It includes illustrative code and practical guidance for building observable, extensible agent systems on any compatible cloud environment.
1. The Shift: From Standalone Model Capability to Model + Agent Delivery
Large model capabilities are iterating quickly, and the way solutions are delivered is changing with them. In the past, enterprises focused on choosing a stronger model. Today, they focus on how to package model capabilities into executable, reusable, and governable business units. A common pattern is that when a general-purpose model capability is released, a matching task-oriented agent product becomes available at the same time. This shows that models and agents are increasingly delivered as a tightly coupled package.
This coupling is not just a marketing bundle. It is driven by technical evolution and engineering constraints. A model provides probabilistic generation and reasoning. An agent places the model inside a controlled execution framework with a clear task objective, a callable set of tools, trackable state and context, and observable execution traces. For developers, the key is not to master the entry point of one specific product, but to understand the common architecture and engineering methods of agent systems.
This article takes a neutral perspective and breaks down the technical essentials of model + agent collaboration, including layered architecture, model integration, tool calling, context and memory, evaluation, security governance, and cost control. It also provides illustrative code to help readers implement a working setup on any compatible cloud environment, using general capabilities such as container platforms, logging services, monitoring and alerting, and object storage offered by Baidu AI Cloud.
2. What Is an Agent: Definition and Core Components
In common industry usage, an agent is an automated system with a model as its decision core, tools as its execution means, and state and context as its constraints. It typically includes the following modules:
- Task orchestration layer: breaks down user goals into steps and decides when to call the model, when to call tools, and when to finish.
- Model inference layer: provides understanding, planning, generation, and reflection, usually through a standardized interface.
- Tool and plugin layer: wraps capabilities such as retrieval, database queries, file processing, message notifications, and business system APIs.
- Context and memory layer: manages short-term conversation context, long-term knowledge bases, and structured state.
- Observability and governance layer: records call chains, metrics, logs, and audit information to support replay and troubleshooting.
- Security and permission layer: validates and isolates inputs, outputs, tool permissions, and data boundaries.
It is important to note that an agent is not better when it is more autonomous. In engineering practice, higher autonomy brings higher uncontrollable risk. Mature solutions usually adopt limited autonomy: running within a clear tool allowlist, budget limits, and approval checkpoints.
3. Layered Architecture: Keeping Uncertainty Under Control
A clear layered design is recommended to keep model uncertainty within a controllable range:
- Access layer: unified authentication, rate limiting, parameter validation, and content safety filtering.
- Orchestration layer: a task state machine or workflow engine that handles step transitions, retries, timeouts, and fallbacks.
- Capability layer: model inference and tool execution, decoupled through a unified protocol.
- Data layer: session storage, vector retrieval, structured databases, and object storage.
- Observability layer: trace tracking, metric aggregation, log retrieval, and alerting.
The key benefit of this layering is replaceability, gradual rollout, and rollback. Model capabilities can be upgraded quickly while business flows remain stable. Tool implementations can evolve independently without affecting orchestration logic.
An illustrative directory structure is shown below:
agent-service/api/ # Access layer: authentication, rate limiting, validationorchestrator/ # Orchestration layer: state machine, retries, fallbackproviders/ # Model integration adapterstools/ # Tool implementations and allowlistmemory/ # Context and retrievalobservability/ # Logs, metrics, traces
4. Model Integration: Standardized Adapters and Fallback Strategies
The model integration layer should use an adapter pattern that abstracts different model capabilities behind a unified interface, avoiding tight coupling between business code and any specific model. A simplified interface example is shown below:
class ModelProvider:def chat(self, messages, **kwargs):raise NotImplementedErrorclass DefaultProvider(ModelProvider):def __init__(self, endpoint, timeout=20):self.endpoint = endpointself.timeout = timeoutdef chat(self, messages, **kwargs):# A real implementation should include retries, timeouts, and content safety checksreturn {"role": "assistant", "content": "..."}
Three issues need special attention in engineering:
- Timeouts and retries: use exponential backoff and set a maximum retry count to avoid cascading failures.
- Fallback strategy: when the primary model is unavailable, switch to a backup model or rule-based responses to keep the business available.
- Output constraints: validate structured output against a schema (for example, JSON Schema validation); if validation fails, trigger repair or fallback.
5. Tool Calling: From Talking to Getting Things Done
The core difference between an agent and a chatbot is tool calling. Tool design should follow the principles of least privilege and idempotency:
- Each tool declares its name, purpose, input schema, output schema, and permission scope.
- Write operations must support idempotency keys to avoid side effects from duplicate submissions.
- High-risk tools require human approval or a second confirmation.
An example of tool registration and invocation:
TOOLS = {"query_order": {"input": {"order_id": "string"},"output": {"status": "string", "items": "array"},"permission": "read"}}def call_tool(name, args, context):spec = TOOLS.get(name)if not spec:raise ValueError("tool not allowed")if spec["permission"] == "write" and not context.get("approved"):raise PermissionError("approval required")return execute(name, args)
In the orchestration layer, a plan-execute-validate-reflect loop is recommended: the model first produces a plan, the orchestrator validates whether the tools and parameters in the plan are valid, and after execution it validates the result against the output schema and business rules. If necessary, the model corrects the result based on error information.
6. Context and Memory: Controlling Cost and Improving Stability
Context management directly affects both quality and cost. Common practices include:
- Short-term context: keep only the most recent conversation turns and a summary of key conclusions to avoid unbounded growth.
- Long-term memory: write user preferences and historical conclusions into structured storage, and retrieve and fill them back by scenario.
- Knowledge retrieval: build an index over external knowledge, inject context through retrieve-rerank-cite, and keep sources for auditing.
- Context compression: summarize long text before inference to reduce redundancy.
A common mistake is to give the model all historical content. This not only increases cost but also introduces noise and conflicting information, reducing stability.
7. Evaluation: Driving Iteration with Quantifiable Metrics
Agent systems must have a closed-loop evaluation process; otherwise, it is impossible to tell whether a change is an improvement or a regression. At minimum, evaluation should cover:
- Task success rate: whether the goal is completed.
- Tool calling accuracy: whether the correct tool and parameters are called.
- Latency and cost: time to first token, end-to-end latency, and cost per task.
- Security and compliance rate: how well unauthorized access, sensitive information leakage, and non-compliant content are blocked.
- Stability: timeout rate, retry rate, and fallback trigger rate.
The evaluation set should include normal samples, boundary samples, and adversarial samples. Every model or prompt change should run regression evaluation, with threshold gates set for key metrics.
8. Security Governance and Cost Optimization
Security governance should cover the entire pipeline: content safety and injection attack detection on the input side; output filtering and schema validation on the model side; permission isolation and auditing on the tool side; and classification and masking on the data side. All tool calls and model calls should record a trace identifier for replay and accountability.
Cost optimization can start from three areas: first, context compression and more precise retrieval to reduce ineffective tokens; second, tiered routing, where simple tasks use lightweight models and complex tasks use stronger models; third, caching and batching, with result caching for high-frequency read-only requests.
9. Implementation Recommendations
For teams that want to build agent applications quickly, a path of first close the loop, then enhance is recommended: first use a minimal toolset to complete the task loop, then gradually introduce retrieval, memory, and multi-tool collaboration; first establish observability and evaluation, then expand autonomous permissions. With general foundational capabilities such as the container platform, logging service, monitoring and alerting, and object storage offered by Baidu AI Cloud, teams can build an observable and extensible agent runtime environment at relatively low cost and focus their effort on business orchestration and quality tuning.
