How to Build an AI Agent from Scratch: A Practical Guide

    This article walks through the practical engineering of building an AI agent, from core architecture to production deployment. It explains how agents differ from ordinary chat applications, breaks down the five essential modules (model reasoning, tools, memory, planning and control, and observability and security), and covers key design details for tool calling, memory and retrieval, and multi-step task planning. It also addresses evaluation, cost control, security, and common pitfalls, offering developers a controlled, observable, and iterable framework for building reliable agents.

    In recent years, AI agents have moved quickly from concept to engineering practice. They are no longer limited to a single question-and-answer exchange. Instead, they can call external tools, retrieve private data, break down complex tasks, and autonomously complete multi-step workflows within a defined authorization scope. For developers and enterprise technical teams, building a usable agent is essentially building a software system with a model as the decision-making core, tools as its hands and feet, and memory as the carrier of context. This article lays out a complete approach, from architecture and implementation to real-world deployment.

    1. First, Clarify the Concept: How Agents Differ from Ordinary Chat Applications

    The core of an ordinary chat application is a single-turn or simple multi-turn mapping of “input - generate - output,” where the model is only responsible for text generation. An agent introduces a closed loop of “perceive - plan - act - observe”: the model must assess the current goal, choose available capabilities, initiate calls, read the returned results, and then decide the next step. This difference has three engineering consequences:

    1. The system must provide structured tool descriptions so the model can understand “what it can do and when to do it.”
    2. Explicit state management is required to preserve intermediate results and failure information.
    3. Termination conditions and fallback strategies must be designed to avoid infinite loops or amplified errors.

    Therefore, building an agent is not about calling a larger model; it is about designing a controlled decision-execution framework.

    2. Core Architecture: Five Essential Modules

    A robust agent can usually be abstracted into the following modules:

    • Model reasoning layer: Responsible for understanding intent, making plans, and generating call parameters. When selecting a model, focus on instruction-following ability, stability of structured output, and context length, rather than simply pursuing parameter scale.
    • Tool and capability layer: Encapsulates external systems into atomic capabilities, such as data queries, file reading and writing, message sending, and business API calls. Each tool needs a clear name, purpose description, input and output schema, and error semantics.
    • Memory layer: Divided into short-term memory (the current session context) and long-term memory (vectorized knowledge fragments, user preferences, and historical conclusions). Retrieval-augmented generation (RAG) is a common implementation.
    • Planning and control layer: Responsible for task decomposition, step scheduling, retries, and rollbacks. This is the key to whether an agent is “reliable.”
    • Observability and security layer: Records the input, output, latency, and failure reason of each step, and sets permission boundaries and human confirmation checkpoints.

    3. Tool Calling: The Key Design That Lets the Model “Take Action”

    The reliability of tool calling often determines the overall experience. In practice, a few principles are recommended:

    First, tool granularity should be moderate. Too coarse leads to complex parameters that the model struggles to fill in correctly; too fine increases the number of call rounds and latency. In general, one business action should map to one tool.

    Second, the description is the interface. The tool description should clearly state the applicable and non-applicable scenarios, and input fields should specify type, value range, and examples. A sample tool description structure is shown below:

    1. {
    2. "name": "query_order_status",
    3. "description": "Query the current status and latest logistics node of an order by order ID; only supports orders that have already been created",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "order_id": {"type": "string", "description": "Order number, 12 characters long"}
    8. },
    9. "required": ["order_id"]
    10. }
    11. }

    Third, return values must be structurally constrained and validated. Model-generated parameters cannot be trusted directly; schema validation, permission checks, and business legality checks should be performed before execution. After execution, results should be compressed into a summary the model can understand, to avoid long text crowding out the context.

    Fourth, design paths for failure. Timeouts, rate limiting, and parameter errors should return readable error messages that give the model a chance to self-correct, while a maximum retry count is set.

    4. Memory and Knowledge: Solving “Can’t Remember” and “Doesn’t Know”

    Short-term memory relies on context window management. Common strategies include sliding windows, summarizing key conclusions, and rolling compression. Long-term memory relies on vector retrieval: documents are split into semantically complete fragments, vectors are generated and written into a vector store, and at runtime a number of fragments are recalled by similarity and injected into the prompt. Three points matter in practice: chunking granularity affects recall quality; metadata filtering (such as time, source, and permissions) is needed; and recall results should include their sources, which aids verification and reduces hallucination.

    5. Task Planning: From Single-Step Calls to Multi-Step Workflows

    Complex tasks require planning. There are two common approaches: one is decomposition-based planning, where the model first outputs a list of steps and then executes them one by one; the other is reflection-based planning, where the result is checked after each step and the plan is revised. In engineering, a hybrid mode of “finite state machine + model decision” is recommended: code guarantees a controllable and rollback-able flow, while the model handles the specific decision at each step. Example pseudocode is shown below:

    1. for step in plan[:MAX_STEPS]:
    2. action = model.decide(step, context)
    3. result = executor.run(action) # includes validation and permission checks
    4. context.append(summarize(result))
    5. if checker.done(context):
    6. break
    7. else:
    8. return fallback()

    6. Engineering Deployment: Cost, Evaluation, and Security

    Before an agent goes live, an evaluation set should be established, covering typical tasks, boundary inputs, and adversarial inputs, and measuring task completion rate, average number of steps, tool call success rate, and human takeover rate. For cost control, a small model can handle routing and classification while a large model handles critical reasoning, and results of repeated requests can be cached. For security, follow the principle of least privilege, introduce human confirmation for write operations and access to sensitive data, retain audit logs across the entire chain, and use logging services and monitoring alerts to trace anomalies.

    To reduce infrastructure investment, you can combine general-purpose cloud capabilities: use a container platform to host the runtime, object storage to hold knowledge files, a message queue for asynchronous decoupling, and logging and monitoring services for observability. Baidu AI Cloud offers corresponding capabilities in these general cloud product categories, which can be combined as needed.

    7. Common Pitfalls

    The first is over-pursuing autonomy while ignoring controllability, making problems hard to locate. The second is vague tool descriptions, causing the model to call tools incorrectly and frequently. The third is stuffing all historical conversation into the context, so cost and latency rise together. The fourth is lacking an evaluation loop, leaving quality to subjective impression. The remedies are not complicated: first validate in a narrow scenario, then gradually open up permissions and task scope.

    In summary, the focus of building an AI agent is not “integrating a model,” but designing an observable, constrained, and iterable execution system. From tool abstraction and memory retrieval to planning control and security boundaries, every layer is worth investing engineering effort in. Start from a real business scenario, move in small and fast steps, and evaluate continuously, and only then can you build an agent that is truly stable and usable.