Build an AI Agent from Scratch: A Practical Guide to the Loop Mechanism

    This guide explains why understanding the agent loop matters more than adopting a framework, then walks through a bottom-up path: hand-writing a minimal loop, adding state and context management, enforcing constraints and human confirmation, building evaluation, and scaling to multi-agent systems. You will see the core control flow behind tool calls, termination, and error recovery, along with practical code and experiments.

    Why Learn the Loop Before the Framework

    Many developers get started with AI agents by opening a framework’s sample project, following the documentation to run the first demo, and then realizing they can “use” it but cannot explain how it works. As soon as requirements deviate slightly from the sample, it becomes unclear whether the problem lies in the prompt, the tool definitions, state management, or the termination logic. The root cause is that frameworks usually wrap up the most critical control flow: under what conditions the model chooses a tool, in what structure the tool’s return value is fed back to the model, when the task is judged complete, how to recover from a failed call, how to insert human confirmation for high-risk actions, and how to evaluate overall performance. These are exactly the core of agent engineering.

    A more effective order is therefore bottom-up: first hand-write a minimal loop that does not depend on any framework, understand the control flow thoroughly, and then introduce a framework to solve engineering problems. The composition of an agent can be roughly summarized as: LLM + instructions + state and memory + tools + loop + constraints and evaluation. A widely accepted breakdown divides capabilities into planning, memory, and tool use, which is consistent with the definition of “executing multi-step tasks in a loop.” It is worth emphasizing that you should make a single agent solid first, and only then consider multi-agent collaboration, because the latter introduces additional complexity in task decomposition, context passing, conflict handling, and cost amplification.

    Stage 1: Hand-Write a Minimal Agent and Understand Only the Loop

    The goal of this stage is not feature richness, but getting one complete “request-execute-feed back” cycle working. The core prerequisite is to make the model output structured parameters that can be reliably parsed by the program. The usual approach is to use a data modeling library to declare a clear schema for each tool, including name, purpose description, parameter names, types, whether they are required, and value ranges. If tool descriptions are vague, the probability of the model choosing the wrong tool rises significantly.

    The following is sample code that keeps only the loop skeleton:

    1. tools = {
    2. "calculator": calculator,
    3. "search_docs": search_docs,
    4. "create_todo": create_todo,
    5. }
    6. messages = [system_prompt, user_message]
    7. max_steps = 5 # boundary: prevent infinite loops
    8. for step in range(max_steps):
    9. # think before acting, i.e., alternate reasoning and action
    10. response = call_llm(messages, tools=tools)
    11. # termination condition: no tool call from the model means the task is done
    12. if response.has_no_tool_call():
    13. return response.final_text
    14. for tool_call in response.tool_calls:
    15. try:
    16. result = tools[tool_call.name](**tool_call.args)
    17. except Exception as e:
    18. # fail gracefully: feed the error back and let the model self-correct
    19. result = f"Error executing tool: {e}"
    20. messages.append({
    21. "role": "tool",
    22. "tool_call_id": tool_call.id,
    23. "content": result,
    24. })
    25. return "Task could not be completed within the maximum steps; forced stop."

    These forty lines of code contain all the key concepts of agent engineering: tool schemas, tool calls, result feedback, maximum steps, externalized reasoning, exception handling, logging, and final output. At this stage, it is recommended to deliberately run three sets of experiments: first, intentionally write vague tool descriptions and observe the change in the wrong-selection rate; second, make a tool throw errors consistently and verify whether the model can change course based on the error message; third, set the maximum steps to an extremely small value and confirm the system exits cleanly instead of hanging.

    Stage 2: Fill in State, Memory, and Context Governance

    Once the minimal loop works, the real engineering difficulty shifts to state management. Three types of information need to be distinguished: short-term conversation context, task state that must be retained across turns, and knowledge that needs to be accumulated over the long term. Short-term context should be kept small in size; common strategies include retaining system instructions and key decision points, and summarizing or compressing early tool outputs. Task state should be maintained with explicit structures, such as a to-do list, completed steps, and collected parameters, to avoid making the model “guess” its progress within long text. Long-term knowledge should be externalized to a retrieval service or storage service and fetched on demand, rather than stuffing everything into the prompt.

    Context governance also needs to handle the “feedback format” problem. Tool returns should be unified as structured content, including a success flag, concise body, and optional citation sources. Overly long content should be truncated with a notice, and binary or large files should only return an address and metadata. This way the model faces a stable interface rather than natural-language fragments of wildly varying length.

    Stage 3: Constraints, Security, and Human Confirmation

    When an agent can execute actions autonomously, risk rises accordingly. In engineering, tools are usually graded by “reversibility” and “scope of impact”: read-only queries can be executed automatically; low-risk reversible operations such as creating drafts or writing to-dos can be executed automatically with a trace; irreversible or high-impact operations such as deleting data, sending externally, or incurring charges must insert human confirmation, and the confirmation result is fed back into the loop as a new tool result. Input validation and permission isolation are also needed: the tool side should not trust the parameters given by the model, and should re-validate types, ranges, and caller permissions; stay alert to prompt injection, and treat external content as untrusted data rather than instructions.

    Observability is also part of constraints. Every loop iteration should leave a structured log: step number, the tool and parameters chosen by the model, return status, elapsed time, token consumption, and whether human confirmation was triggered. Logs are used for troubleshooting and also serve as the data source for later evaluation.

    Stage 4: Evaluation and Iteration, Avoiding “Looks Like It Works”

    An agent without evaluation cannot be iterated. It is recommended to build three layers of evaluation: the unit layer verifies the input and output correctness of a single tool; the trajectory layer evaluates whether the decision sequence is reasonable, for example whether it takes unnecessary steps or effectively corrects after failure; the result layer measures overall performance with task success rate, average steps, average elapsed time, and cost. The evaluation set should come from real failure cases and gradually accumulate into regression cases. The improvement order is usually to fix tool descriptions and parameter schemas first, then tune prompts and termination conditions, and only then consider switching models or introducing more complex orchestration.

    Stage 5: From a Single Agent to Multi-Agent and Platformization

    Once a single agent reaches a stable success rate in a well-defined domain, roles can be split: one handles requirement understanding and planning, several handle retrieval, computation, and write operations, and another verifies the output. The value of multi-agent lies in context isolation and clear responsibilities, while the cost is communication overhead and error propagation, so a unified message structure, timeouts, and fallback paths must be designed. To scale within a team, you can deploy the runtime on a container platform, use a message queue for task decoupling, use object storage to save intermediate artifacts, use logging services and monitoring and alerting systems to track success rate and latency, and use a key management service to host credentials. Baidu AI Cloud has corresponding product categories for these general capabilities and can be combined as needed, but the architectural principles remain unchanged: a stable loop, clear boundaries, observability, and evaluability.

    In summary, the shortest path to learning AI agents is to first write the loop correctly with a few dozen lines of code, then layer on memory, constraints, evaluation, and collaboration step by step. Frameworks are just accelerators; understanding the control flow is the long-term competitive advantage.