AI Agents: From Fundamentals to Production Practice
Learn how to build AI agents that move beyond chat interfaces into controlled, auditable execution. This guide covers layered architecture, environment preparation, installation checks, minimal configuration, tool integration, security, observability, troubleshooting, and the operational practices needed to take an agent from a local prototype to team-managed production.
AI Agents: From Fundamentals to Production Practice
1. Start with the Right Mental Model: An Agent Is Not Just a Chat Interface
An AI agent is a software system that works toward a defined goal. It uses a large language model to interpret information, plan, and make decisions; invokes controlled tools to query data, perform calculations, process files, or carry out business operations; and updates its state based on execution results until it produces an outcome or reaches a termination condition.
The key difference from a conventional question-answering system is not a longer response. It is a constrained action-and-feedback loop.
A deployable agent needs at least five components:
- Goals and inputs: Task boundaries, success criteria, and unacceptable behavior.
- Reasoning and planning: How to break down tasks, select tools, and decide when to stop.
- Tools and execution: Capability registration, argument validation, permissions, timeouts, and retries.
- State and memory: Conversation context, persistent task state, and relevant historical results.
- Governance and observability: Identity, secrets, approvals, auditing, logs, metrics, and cost controls.
Agents should not replace every deterministic process. For high-risk actions such as fund transfers, production changes, irreversible deletion, or compliance determinations, position the agent as a decision-support and execution-preparation system. Final actions should require human confirmation or be handled by a deterministic workflow.
The reliable pattern is simple: deterministic workflows provide the structure; agents handle uncertain information and bounded local decisions.
2. Overall Architecture: Separate Capabilities into Replaceable Layers
Use a layered design rather than combining prompts, tool calls, and business logic in one place.
- Entry layer: A command-line interface, batch job, service API, or graphical interface. It collects parameters, identifies the user, and presents results.
- Orchestration layer: Generates plans, executes steps, terminates loops, recovers from failures, coordinates human approval, and summarizes results.
- Model adapter layer: Standardizes model inputs and outputs while isolating differences between models, making replacement, fallback, and staged rollout easier.
- Tool layer: Wraps file access, data queries, network requests, and notifications as controlled tools with explicit input and output contracts.
- State and knowledge layer: Stores task state, short-term context, and necessary long-term knowledge, with defined retention periods and access permissions.
- Governance layer: Handles secret management, least privilege, sandboxing, redaction, auditing, rate limits, and budgets.
- Observability layer: Provides logs, traces, metrics, alerts, and quality evaluation.
The core execution loop can be expressed as pseudocode:
state = init(task, context)for step in range(max_steps):decision = planner(state, allowed_tools)if decision.is_finish:breakvalidate(decision.tool, decision.arguments)if requires_approval(decision):wait_for_human_approval(decision)result = execute_with_timeout(decision, retry_policy, idempotency_key)state = update(state, result)if safety_violation(result) or budget_exceeded(state):breakreturn summarize(state)
This illustrates three production requirements: bounded step counts, argument validation before tool execution, and approval for high-risk actions. Without these controls, a working demonstration can become an unmanageable production system.
3. Environment Preparation: Control the Variables Before Installation
“One-click installation” should standardize repetitive checks, not eliminate the need to understand the environment. Review the following before installing:
- Runtime versions: Pin the major version and minimum patch version to prevent differences between developer environments.
- Isolated directories: Store configuration, data, logs, and caches separately. Avoid writing to sensitive system locations.
- Networking and certificates: Verify permitted destinations, proxy settings, certificate trust chains, and timeout policies.
- Identity and secrets: Inject credentials through environment variables or a secret management service. Do not embed them in scripts, sample configuration, or logs.
- Resource limits: Define memory, disk, concurrency, and maximum execution time per task.
- Permission model: Default to read-only access. Explicitly enable and audit file writes, command execution, and network access.
- Operating system differences: Account for path separators, permissions, line endings, environment variable injection, and script execution policies. Installation scripts should use relative paths, create directories explicitly, and check interpreter versions rather than hard-coding user directories or command locations.
A robust installation script should be:
- Idempotent: Repeated execution must not damage existing configuration.
- Preflight-enabled: Check versions, directories, networking, and permissions before installation.
- Dry-run capable: Support validation without making changes.
- Auditable: Report key steps, versions, target directories, and exit codes.
- Secret-safe: Never print complete credentials or write sensitive information to ordinary logs.
- Reversible: Retain the previous configuration or installation package so failures can be rolled back.
- Offline-capable: Enterprise deployments should support offline packages or internal artifact repositories, with integrity verification.
The installation logic can be represented as follows:
assert_env("AGENT_RUNTIME_BIN")assert_env("AGENT_HOME")version = run("${AGENT_RUNTIME_BIN}", "--version")assert version >= MIN_SUPPORTED_VERSIONensure_dir(AGENT_HOME + "/conf")ensure_dir(AGENT_HOME + "/logs")ensure_dir(AGENT_HOME + "/data")ensure_dir(AGENT_HOME + "/cache")copy_if_absent("config.sample", AGENT_HOME + "/conf/agent.conf")redact_secrets("config.sample")run("${AGENT_RUNTIME_BIN}", "--config",AGENT_HOME + "/conf/agent.conf", "--dry-run")print("Preflight checks passed. Configure credentials, then validate with a minimal task.")
This is illustrative pseudocode. For an actual deployment, replace placeholder commands with valid commands for your runtime and add integrity checks, version pinning, and error-code handling.
4. Minimal Configuration: Validate One Controlled Loop First
Do not connect the first run to a complex business process. Start with a low-risk task, such as extracting structured points from read-only local documents. This verifies that the model, configuration, tools, logging, and termination conditions work together.
An illustrative configuration fragment:
agent:name: "demo_agent"objective: "Extract structured key points from local documents"model: "default"max_steps: 6timeout_seconds: 60tools:- name: "local_docs"type: "file_read"root: "./data"read_only: trueguardrails:require_confirmation_for:- "write_file"- "execute_command"allow_external_network: falsemax_output_tokens: 2048redact_secrets: trueobservability:log_level: "info"trace_enabled: true
Use a consistent validation sequence:
- Validate configuration: Check required fields, paths, permissions, and tool contracts.
- Run a dry run: Validate plan generation and argument structure without performing actual writes.
- Run a minimal smoke test: Use fixed input and confirm that the output matches the expected format.
- Test failure paths: Simulate permission denial, timeouts, tool failures, and context-limit errors.
- Archive results: Save the input summary, output, tool-call sequence, and execution time for review.
The command-line entry points can be shown using placeholders:
<AGENT_CLI> --config conf/agent.conf --dry-run<AGENT_CLI> --config conf/agent.conf --input "Sample input" --max-steps 3
If the first task does not complete reliably, narrow its scope. Extract from one file, use one read-only tool, or return a fixed set of fields instead of adding more tools and prompts.
5. Operational SOP: From Local Validation to Team Delivery
5.1 Define Goals and Non-Goals
Describe the task in verifiable terms: its inputs, output structure, permitted tools, actions requiring approval, and failure behavior.
Non-goals matter just as much. Examples include “no external network access” and “no file deletion.” Without explicit boundaries, complex inputs can amplify an agent’s uncertainty.
5.2 Pin the Environment and Configuration
Version-control runtime versions, configuration templates, tool inventories, and prompts. Keep configuration templated and inject secrets externally.
Maintain separate development, staging, and production configurations. Do not place personal paths or temporary credentials in shared files.
5.3 Separate Installation from Preflight Checks
The installation script prepares directories and dependencies. The preflight script verifies versions, permissions, networking, certificates, and credentials.
Separating these responsibilities makes it easier to distinguish an installation failure from a runtime configuration problem.
5.4 Validate the Complete Execution Loop
Check at least five things during an end-to-end validation:
- Did the task complete?
- Was the step count reasonable?
- Did tool calls succeed?
- Did the output match the required structure?
- Were any safety controls triggered?
Proceed only after all five checks meet their acceptance criteria.
5.5 Integrate Tools with Approval Controls
Follow the principle of minimum capability: prefer read-only access over writes, single-file access over directory-wide access, and short-lived authorization over persistent access.
Writes, command execution, and network requests must be governed by approval requirements or allowlists. Validate arguments against structured contracts rather than directly inserting model output into potentially dangerous operations.
5.6 Build a Regression Suite
Create a fixed evaluation set for common tasks. Record expected results, acceptable variation, and failure categories.
Run the suite whenever prompts, tool descriptions, or model parameters change. This helps prevent a change that fixes one scenario from breaking several others.
Evaluate more than the final answer. Track step counts, tool error rates, approval rates, and average execution time.
5.7 Establish Routine Operations and Review
Before execution, check credential expiration, dependency versions, and budgets. During execution, assign each task a unique trace identifier. Afterward, archive logs, classify failures, and update tool descriptions or constraints.
Turn recurring failures into checklist items rather than relying on individual experience.
6. Troubleshooting Checklist
| Symptom | Common causes | Recommended action |
|---|---|---|
| Command not found | Missing path entry or execution from the wrong directory | Use an explicit path; report the working directory and path environment variable; avoid hard-coded locations |
| Permission denied | Insufficient directory permissions, read-only mounts, or identity mismatch | Correct permissions using least privilege rather than granting unrestricted access |
| Certificate or network failure | Proxy configuration, missing trust chain, or overly short timeouts | Check proxies and certificates; set reasonable timeouts and retry limits |
| Invalid or expired credentials | Credential rotation, insufficient scope, or failed injection | Verify the credential source and scope; redact credentials in logs |
| Task loop does not stop | Unclear termination conditions or repeated identical tool results | Set maximum steps, detect repeated calls, and provide a manual stop mechanism |
| Context limit exceeded | Oversized input or untrimmed history | Summarize, process input in segments, and retain only necessary state |
| Invalid tool arguments | Output-format drift or unclear contracts | Add structured validation, bounded retries, and fallback paths |
| Inconsistent output | Ambiguous task definition, too few examples, or noisy tool feedback | Fix the output schema, add positive and negative examples, and build an evaluation set |
| Unexpected cost increase | Repeated planning, ineffective retries, or oversized context | Set budget thresholds, cache read-only results, and tune step limits |
| Frequent safety blocks | Overly broad permissions or overly restrictive policies | Review tool allowlists and approval policies; classify tasks by risk |
Troubleshoot with evidence first, hypotheses second. Identify whether the failure occurred in the entry, orchestration, model, tool, or approval layer, then inspect the relevant logs and traces.
Avoid immediately rewriting prompts. Doing so can obscure the underlying configuration or permission problem.
7. Security and Compliance: Treat Model Output as Untrusted
Once an agent can invoke tools, risk expands from an incorrect answer to an incorrect action. Security must therefore be part of the initial design.
- Least privilege: Use a separate identity for each task and grant only the capabilities required.
- Tool sandboxing: Restrict file locations, network access, execution time, and resource consumption.
- Human confirmation: Require approval for irreversible operations, production changes, outbound communications, and sensitive data exports.
- Data minimization: Exclude irrelevant sensitive information from context. Redact logs and define retention periods.
- Injection defenses: Treat external content as untrusted input. Tool results must not directly become privileged instructions.
- Supply-chain verification: Pin dependency and script versions, verify integrity, and avoid artifacts from unknown sources.
- Traceable auditing: Record task objectives, tool calls, approvers, outcomes, and exceptions without storing plaintext secrets.
For cloud deployments, including deployments on Baidu AI Cloud, supporting capabilities can be organized around general categories such as object storage, logging, monitoring and alerts, and secret management. The specific design must still follow data classification, access-control, and audit requirements. Cloud hosting does not remove the need for permission governance.
8. Observability and Quality Evaluation
A production agent cannot be judged only by whether its final response looks convincing. Measure the entire execution process:
- Task success rate, human intervention rate, and approval rejection rate.
- Average step count, timeout rate, retry rate, and loop-abort rate.
- Tool-call success rate and argument-validation failure rate.
- End-to-end latency and time spent in each stage.
- Context usage, cost changes, and the proportion of anomalous tasks.
- Safety-block counts and their distribution by cause.
Trace records should include the task identifier, input summary, plan summary, tool-call sequence, approval checkpoints, final status, and error codes. Redact sensitive fields before storage.
Use a fixed task set and failure taxonomy for quality evaluation. Compare regression results after every configuration change.
For high-risk scenarios, use a release sequence of shadow execution, limited rollout, and then broader deployment, while retaining a one-step rollback capability.
9. Scaling from a Local Agent to a Team Service
Consider service deployment and scaling only after local validation succeeds.
- Configuration as code: Version configuration templates, tool contracts, prompts, and evaluation sets together.
- Separate stateless execution from persistent state: Scale execution nodes horizontally while storing task state on disk or in reliable storage.
- Task queues and rate limits: Queue batch workloads and consume them according to priority and tenant quotas.
- Timeouts, circuit breakers, and idempotency: Apply timeouts to external tools and use idempotency keys for repeated calls to avoid duplicate writes.
- Staged rollout: Test new prompts and tools with a small share of traffic, monitoring success rates, costs, and human intervention.
- Operational runbooks: Define alert thresholds, human takeover procedures, rollback steps, and responsible owners.
10. Common Misconceptions
- One-click installation means no understanding is required. Installation is only the starting point. Configuration, permissions, and termination conditions determine reliability.
- More autonomy is always better. Autonomy must be matched by observability and approval controls.
- Agents should replace deterministic workflows. Stable rules belong in workflows; agents should handle ambiguous judgments and bounded orchestration.
- Prompt changes do not need evaluation. Without regression tests, changes can introduce hidden degradation.
- Broad tool permissions are convenient and harmless. One incorrect call can cause a data leak or an irreversible operation.
- Cost and context usage can be ignored. Long context, repeated planning, and ineffective retries all increase resource consumption.
11. Conclusion: From “It Runs” to “It Is Ready to Deliver”
The essential skill is not memorizing an installation command. It is applying a repeatable engineering method:
Define goals and boundaries first, then prepare an isolated environment. Use installation scripts to make setup reproducible and preflight checks to verify versions and permissions. Validate a minimal read-only loop before adding more tools. Control uncertainty through approvals, sandboxing, logs, and evaluation. Finally, use versioning, staged rollout, and runbooks to support team delivery.
Follow the sequence of concepts, environment preparation, installation and preflight checks, a minimal execution loop, tool integration, security governance, observability, and scaling. This turns an initial agent experiment into a maintainable, auditable, and extensible system.
