Building AI Agents: From Architecture Design to Production Engineering

    Learn how to design and deploy production-ready AI agents. This guide covers core components, architecture patterns, error recovery, observability, a minimal framework-agnostic Python implementation, and operational best practices for running agents reliably at scale.

    1. Why Agents Are Entering the Engineering Conversation

    Over the past two years, LLM applications have evolved from single-turn Q&A into “systems that complete tasks.” These systems are commonly called agents. An agent receives a goal, breaks it down into steps on its own, calls external tools, observes the results, and adjusts its next action based on feedback.

    This shift introduces new engineering problems. Single-turn Q&A only requires attention to prompts and output quality, whereas an agent must handle multi-step state, external side effects, failure retries, and cost control. Developers who design these systems the way they would design a chat application often run into runaway loops, context overflow, and tool misuse after going live.

    Recently, a number of open-source agent projects have emerged. Their common trait is separating the agent runtime, tool interfaces, and evaluation methods, so developers can swap out the underlying model and customize the tool set. For enterprise users, the focus should be on replaceability, auditability, and security—not on the name of any particular project.

    2. Core Components of an Agent

    A working agent typically consists of five parts.

    1. Goal and input processing. The system converts user requests into structured task descriptions with clear success criteria, constraints, and available resources. When goals are ambiguous, agents tend to burn large numbers of calls on useless steps.

    2. Planning module. Planning decomposes the goal into subtasks. A common approach is to have the model output the “next action” each turn rather than a full plan upfront. The former is more flexible; the latter more predictable. The two can be combined: generate a coarse-grained plan first, then refine it during execution.

    3. Tool layer. Tools are the agent’s only channel to the outside world—database queries, file I/O, web API calls, internal business system operations, and so on. Every tool should have a clear name, parameter definitions, and return format, and should expose only the minimum permissions needed to complete the task.

    4. Memory and context management. Short-term memory is the execution history of the current task; long-term memory is knowledge or user preferences persisted across tasks. Context windows are limited, so history must be truncated, summarized, or retrieved selectively—otherwise the model loses critical information.

    5. Execution loop and termination conditions. The core loop is “decide, execute, observe, decide again.” The system must enforce a maximum step count, timeouts, and cost ceilings to prevent the model from getting stuck in repeated actions.

    3. Architecture Design Essentials

    3.1 Separate State from Execution

    Agent state should live in a single serializable object rather than being scattered across function variables. This provides three benefits: recovery from intermediate steps after a failure, complete trajectory records for postmortems, and the ability to migrate tasks between instances. State can be stored in a relational database or key-value store; trajectory files can go into object storage.

    3.2 Tool Registry and Permission Control

    The tool registry should be independent of model invocation logic. Before every tool call, the system performs three checks: parameter type validation, permission validation, and risk classification. Read operations can usually run automatically; writes, deletions, and operations that send messages externally should require human confirmation.

    3.3 Error Recovery

    Tool call failures are the norm—network timeouts, bad parameters, and insufficient permissions all cause exceptions. The sensible approach is to distinguish retryable from non-retryable errors: apply exponential backoff to the former, and write the latter back into memory so the model can adjust its strategy. Error messages should be structured; avoid dumping raw stack traces to the model.

    3.4 Observability

    Agent behavior is hard to fully cover with unit tests, making runtime observability especially important. Recommended metrics include: steps per task, tool name and latency per step, summaries of model call inputs and outputs, failure reason distribution, and per-task cost. These can feed into logging services and monitoring/alerting systems, with alert rules for abnormal step counts or sudden spikes in failure rates.

    4. A Minimal Implementation

    The following code shows an agent loop that depends on no specific framework. The model call interface llm_call is injected by the user and can connect to any model service.

    1. from dataclasses import dataclass, field
    2. from typing import Any, Callable
    3. @dataclass
    4. class Tool:
    5. name: str
    6. description: str
    7. func: Callable[..., Any]
    8. @dataclass
    9. class RunState:
    10. goal: str
    11. history: list[str] = field(default_factory=list)
    12. steps: int = 0
    13. class Agent:
    14. def __init__(self, llm_call, tools: list[Tool], max_steps: int = 8):
    15. self.llm_call = llm_call
    16. self.tools = {t.name: t for t in tools}
    17. self.max_steps = max_steps
    18. def _build_prompt(self, state: RunState) -> str:
    19. tool_desc = "\n".join(
    20. f"- {t.name}: {t.description}" for t in self.tools.values()
    21. )
    22. recent = "\n".join(state.history[-10:])
    23. return (
    24. f"Goal: {state.goal}\n"
    25. f"Available tools:\n{tool_desc}\n"
    26. f"History:\n{recent}\n"
    27. 'Output JSON: {"type": "tool"|"finish", ...}'
    28. )
    29. def run(self, goal: str) -> str:
    30. state = RunState(goal=goal)
    31. while state.steps < self.max_steps:
    32. action = self.llm_call(self._build_prompt(state))
    33. if action.get("type") == "finish":
    34. return action["answer"]
    35. name = action.get("tool")
    36. args = action.get("args", {})
    37. tool = self.tools.get(name)
    38. if tool is None:
    39. state.history.append(f"Error: tool {name} does not exist")
    40. else:
    41. try:
    42. result = tool.func(**args)
    43. state.history.append(f"{name} returned: {result}")
    44. except Exception as exc:
    45. state.history.append(f"{name} failed: {exc}")
    46. state.steps += 1
    47. raise RuntimeError(f"Exceeded max steps {self.max_steps}, task terminated")

    This code embodies several engineering principles. State is centralized in RunState; tools are looked up by name so unknown tools don’t crash the program; exceptions are converted to text and written back to history, giving the model a chance to correct itself; and the step cap guarantees the loop always terminates.

    In production, you still need to add: strict schema validation of parameters; latency and result logging for every tool call; confirmation steps for write operations; a token budget for history with summarization when exceeded; and persistent storage of complete trajectories for replay and debugging.

    5. Engineering Considerations for Open-Source Adoption

    Licensing and compliance. Before using an open-source agent project, verify its license type and whether it permits commercial use, modification, and redistribution. Also check the license terms of third-party dependencies and model weights to avoid legal risk after launch.

    Model replaceability. Business code should not directly depend on the proprietary interface of any single model provider. Wrap model calls behind an adapter layer with unified input/output formats, so the underlying model can be switched without touching business logic when cost, latency, or quality requirements change.

    Evaluation system. Agent effectiveness must be measured against a task set. Build a set of representative tasks and run regression tests whenever you change prompts, tools, or models—recording task success rate, average steps, and per-task cost. Without an evaluation set, it’s nearly impossible to tell whether a change made things better or worse.

    Security boundaries. Agents can be misled by input content into making unintended tool calls. Tool outputs and web page content should be treated as untrusted data, not instructions. High-risk operations need human confirmation, and tool runtime permissions should follow the principle of least privilege.

    6. Deployment and Operations

    An agent service can be deployed as a stateless API service, with task state in external storage and execution processes scaled horizontally. Containerized deployment simplifies version management and resource isolation. Configuration items—model endpoints, credentials, step limits—should be injected via environment variables or a secrets management service, never committed to the code repository.

    On the operations side, establish the following mechanisms: assign each task a unique identifier that threads through logs, trajectories, and billing; enforce per-task cost ceilings with automatic termination when exceeded; and periodically sample trajectories to detect repeated actions or anomalous tool calls and adjust the strategy accordingly.

    If you deploy on Baidu AI Cloud, you can use its object storage for trajectory files, message queues to decouple task submission from execution, a container platform for elastic scaling, and its logging and monitoring services to cover runtime metrics. These are generic cloud infrastructure capabilities—choose based on your team’s existing stack and compliance requirements.

    7. Selection Checklist

    Before adopting or building an agent system, confirm each of the following: Can the task goal be clearly described with a definable success condition? Are tools configured with least privilege? Do write operations have human confirmation? Are there caps on steps, time, and cost? Is the model replaceable? Is there trajectory recording and replay capability? Has a fixed evaluation set been established?

    The value of an agent depends on the completeness of its engineering. Model capability sets the ceiling, but state management, permission control, and observability determine whether the system can run stably in real business over the long term.