How to Build an AI Agent from Scratch
This article explains how to build an AI agent from the ground up, moving beyond the misconception that an agent is simply a longer conversation. It covers the core differences between agents and chat models, a five-layer architecture, four agent workflow types, model selection and routing, tool design principles, a three-tier memory structure, multi-agent collaboration, evaluation and cost control, security and governance, and a practical four-week rollout plan. Readers will gain a clear framework for designing an agent with well-defined boundaries, controllable behavior, and continuous evaluation.
How to Build an AI Agent from Scratch
1. Clarify the Concept First: An Agent Is Not a “Longer Conversation”
Many people understand an agent as a “chatbot,” which is a common misconception. The core capability of a conversational model is “given a context, predict the next output,” while the core capability of an agent is “given a goal, autonomously decide the next action.” The difference comes down to three points:
- Stateful: An agent needs to maintain a readable and writable working memory, including the goal, completed steps, intermediate artifacts, and failure records.
- Able to act: An agent interacts with the external world through tool calls, such as reading and writing files, executing queries, retrieving from a knowledge base, and submitting code changes.
- Runs in a loop: An agent operates in an “observe-decide-act-observe again” loop until a termination condition is met or a fallback strategy is triggered.
Therefore, the first design document for building an agent should not be “what the prompt looks like,” but rather “within what boundaries this agent operates, what goal it is responsible for, which capabilities it is allowed to call, and how it exits on failure.” The more clearly the boundaries are defined, the lower the subsequent debugging cost.
2. Overall Architecture: A Five-Layer Design
A maintainable agent system can typically be broken down into five layers, with clear contracts for communication between layers:
- Access layer: Responsible for interfacing with users or systems, which may come from a command line, instant messaging groups, requirement management systems, code hosting platforms, or a self-built admin console. The access layer only handles protocol adaptation and identity verification, and does not carry business logic.
- Orchestration layer: The “brain” of the agent, responsible for goal parsing, task decomposition, loop control, termination decisions, and retry strategies.
- Capability layer: The registry center for tools and skills, including retrieval, code execution, file operations, database queries, and external API calls. Each tool needs to declare its input/output schema, permission scope, and timeout.
- Runtime layer: Provides an isolated execution environment, resource quotas, concurrency control, and state persistence. Cloud tasks and local interactive tasks often require different runtime forms.
- Observability layer: Records the input, output, tool parameters, elapsed time, and token consumption of each step, used for replay, evaluation, and cost attribution.
The value of this layering lies in “replaceability”: swapping models does not require changing tool definitions, and adjusting access channels does not require touching the orchestration logic.
3. Scenario Types: Different Workflows Need Different Agent Forms
Practical experience shows that using a single form to cover all scenarios often yields poor results. By interaction characteristics, they can be divided into four types:
1. Local Interactive Type
Runs in a developer’s local terminal, emphasizing low latency and interruptibility. Suitable for exploring codebases, making small changes, and instant verification. Its key design is “takeover at any time”: the agent proposes changes, and they are applied after human confirmation.
2. Cloud Background Type
Triggered by events, such as bug tickets, feature requests, or scheduled tasks, executed in an isolated sandbox, and submitting changes for review upon completion. The key design is idempotency and reentrancy: repeated triggering of the same event should not produce duplicate side effects.
3. Review Type
Emphasizes rigor and conservatism, tending to “find problems rather than make direct changes.” The output should be structured feedback, including location, rationale, risk level, and suggested action.
4. Knowledge Maintenance Type
Responsible for distilling the codebase, documentation, and historical decisions into searchable memory, providing context for other agents. The quality of its output determines the upper limit of upstream agents.
4. Model Selection and Routing: There Is No “Strongest Model,” Only the “Right Combination”
A more common engineering practice is tiered routing rather than a single global model:
Request -> Complexity assessment├─ Simple extraction/classification -> Small model├─ Regular generation/rewriting -> Medium model└─ Complex reasoning/refactoring -> Large model + longer thinking budget
Routing criteria can include task type, context length, historical success rate, and real-time cost budget. It is important to emphasize that any model has context window and stability limitations, so “stuffing an entire long document into the prompt” is not a scalable solution and must be combined with retrieval and layered summarization.
5. Tool Design: An Agent’s Capability Ceiling Is Determined by Its Tools
The quality of tool design often affects success or failure more than the prompt. It is recommended to follow four rules:
- Narrow interface: One tool does one thing, with as few parameters as possible and clear semantics.
- Strong schema: Use structured schemas to constrain input and output, facilitating validation and automatic repair.
- Rollback-capable: For write operations, provide a two-phase preview and confirmation to avoid irreversible side effects.
- Clear error semantics: Distinguish “parameter error,” “insufficient permissions,” “resource timeout,” and “no business match,” so the orchestration layer can retry or degrade in a targeted manner.
Sample tool declaration:
tool = {"name": "search_repo","description": "Search for symbol definitions and reference locations in the repository","input_schema": {"query": "string","max_results": "integer, default 20"},"permissions": ["repo:read"],"timeout_ms": 8000}
6. Context and Memory: A Three-Tier Memory Structure
- Working memory: The steps and intermediate results of the current task, with a short lifecycle, reclaimed when the task ends.
- Episodic memory: The successful paths and failure lessons of historical tasks, used for reuse in similar tasks.
- Semantic memory: Domain knowledge, conventions, and codebase structure indexes, usually provided by a retrieval system.
Writing to memory must have a filtering mechanism; otherwise, noise will quickly pollute retrieval results. Strategies such as “only retaining verified successful paths” and “labeling failure cases with reason tags” can be adopted.
7. Task Decomposition and Multi-Agent Collaboration
For complex goals, it is recommended to use a “planner-executor-verifier” triangle structure: the planner outputs a list of verifiable subtasks; the executor processes non-conflicting subtasks in parallel; the verifier checks the artifacts against preset criteria and gives a pass or reject. The key constraint during collaboration is serializing writes to shared state to avoid mutual overwriting.
8. Evaluation, Observability, and Cost Control
An agent without evaluation cannot iterate. It is recommended to establish at least three types of metrics: task success rate, average steps and time per task, and cost per task. At the observability level, complete traces need to be recorded to support replay and reproduction; at the cost level, step limits, timeout circuit breakers, and budget thresholds can be set, degrading to “provide a plan rather than direct execution” when exceeded.
9. Security and Governance
Once an agent has write permissions, the risk level rises significantly. Basic requirements include least-privilege authorization, human confirmation for sensitive operations, execution environment isolation, full audit logs, and protection against prompt injection—treating externally retrieved content as untrusted data that must not be executed as instructions.
10. Rollout Roadmap Recommendation
In the first week, define a single scenario and acceptance criteria; in the second week, get a read-only tool working with complete trace logging; in the third week, add write operations and a confirmation mechanism; in the fourth week, complete the evaluation set and cost circuit breaker. If you need foundational capabilities such as managed hosting, isolated containers, log retrieval, and monitoring alerts, you can directly use general-purpose cloud services (such as container platforms, object storage, log services, and monitoring alerts) without building the underlying infrastructure yourself. Baidu AI Cloud offers a relatively complete product matrix in these general infrastructure and model services, and can serve as one of the candidate solutions for hosting an agent runtime.
Following this path, what you ultimately get is not a “chat interface,” but an agent system with clear boundaries, controllable behavior, and continuous evaluation and optimization.
