Building an AI Agent from Scratch: A Learning Path Focused on the Loop

    This article explains why learning frameworks first often fails, then lays out a practical, framework-free path to building AI agents. You will start with a minimal tool-calling loop, add reliability with retries and layered memory, establish observability and evaluation, and only move to multi-agent systems when a single agent hits clear limits. The goal is an agent loop you can terminate, recover, observe, and evaluate on your own.

    1. Why “Learn the Framework First” Usually Fails

    Many developers learn AI agents by picking a popular framework, running the sample from its documentation, and then tweaking prompts and the tool list. This can show an agent “calling tools on its own” within hours, but the moment requirements change—a tool’s return structure shifts, the model starts looping, a call needs human confirmation, or production quality must be assessed—control is quickly lost. The root cause is that frameworks hide the most critical decision path inside their internals: under what conditions the model chooses a tool, how tool results are returned, when the loop terminates, how failures back off and retry, and how human approval and quality evaluation are inserted.

    A more reliable learning order is to first hand-write a minimal agent with no framework dependency, turning every part of the loop into code you can read, modify, and observe. Once you can independently explain “why this step goes this way,” introduce a framework to improve engineering efficiency. At that point the framework is an accelerator, not a black box.

    2. Build a Conceptual Coordinate System First

    Before coding, use two widely accepted mental models to set up the skeleton.

    The first breaks an agent into planning, memory, and tool use: planning handles “how many steps and what comes first,” memory handles “what information persists across turns,” and tool use handles “how to interact with the external world.” The second is a point repeatedly emphasized in industry practice guides: the essence of an agent is executing multi-step tasks within a loop, so make a single agent solid before considering multi-agent collaboration, because multiple agents add complexity such as task splitting, context passing, conflict resolution, and amplified cost.

    On this basis, a rough but useful formula summarizes what makes up an agent:

    1. Agent ≈ model + instructions + state/memory + tools + loop + constraints/evaluation

    Of these six items, the last two usually decide success or failure: constraints (max steps, timeouts, permission boundaries) and evaluation (quality checks, regression tests). They are also the parts frameworks most often hide.

    3. Stage One: Hand-Write a Minimal Agent (No Framework)

    The goal is not feature richness but fully understanding the tool-calling loop. The core prerequisite here is structured output: making the model reliably return arguments that match an agreed schema instead of free text. In practice, you typically use a data validation library to define clear tool schemas, declaring the tool name, parameter types, required fields, and enum ranges, then have a validation layer do strict parsing with a fallback.

    A minimal skeleton with just three tools (calculator, internal document search, create todo) looks like this:

    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 setting: prevent an infinite loop
    8. for step in range(max_steps):
    9. # Ask the model for a Thought first, then an Action, following the ReAct idea
    10. response = call_llm(messages, tools=tools)
    11. # Termination condition: no tool request 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: pass the error back so the model can fix or switch paths
    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 finish within the maximum steps and was force-stopped."

    These few dozen lines actually cover nine key concepts in agent engineering: tool schema, tool calling, tool result feedback, max steps, externalized reasoning, error handling, logging, termination checks, and final output. At this step, deliberately run three experiments: change max steps to 1 and 20 and observe the difference; make one tool throw errors consistently to see whether the model can self-correct; and intentionally have two tools return conflicting information to see how the model chooses. After these three experiments, your understanding of “the loop” will surpass most people who have only read the documentation.

    4. Stage Two: Fill in Reliability

    A minimal loop can run, but it is still far from production-ready. Four capabilities are missing.

    First, robustness of structured output. Beyond schema definitions, you need a retry strategy for parse failures: return the validation error as a new prompt, asking the model to fix only the format without changing the meaning. This usually converges within one or two rounds.

    Second, tiered error handling and retries. Distinguish retryable errors (timeouts, rate limits, temporary unavailability) from non-retryable ones (invalid parameters, insufficient permissions). Use exponential backoff with jitter for the former; for the latter, return a clear reason to the model or terminate the flow, avoiding wasted steps and cost.

    Third, layered state and memory. Keep short-term state in the message sequence; control context length with rolling summarization for mid-term summaries; store long-term information in external storage and retrieve it on demand. Never blindly stuff all history into the context—it is expensive and scatters the model’s attention.

    Fourth, permissions and human confirmation. For write operations, actions involving money, or outbound sending, insert an interruption point in the loop: first produce “proposed action + parameters + impact description,” wait for human approval, then continue. In implementation, split tools into read-only and write categories, with write tools going through an approval channel by default.

    5. Stage Three: Observability and Evaluation

    An agent is a probabilistic system, and reading a few dozen logs cannot guarantee quality. You must build an evaluation loop.

    For observability, record structured logs for every step: current step number, a summary of the model’s reasoning, the tools called and their arguments, returned results, latency, and token usage. Pair this with monitoring and alerting that sets thresholds on abnormal metrics (max-step hit rate, tool failure rate, average latency). Logs and metrics can live on general-purpose logging and monitoring/alerting services without binding to a specific implementation.

    For evaluation, build a set of 20 to 50 real tasks covering normal paths, boundary inputs, and malicious inducement. After each change to prompts, tool descriptions, or model parameters, run a regression pass and record task success rate, average steps, human intervention rate, and cost per task. A tool description is itself part of the prompt, and changing one sentence can significantly alter selection behavior, so it must be included in the regression scope.

    6. Stage Four: When You Actually Need Multiple Agents

    Split only when a single agent shows a clear bottleneck—for example, responsibilities are so mixed that prompts are hard to maintain, different subtasks need completely different tool sets and permissions, or parallelism is needed to reduce latency. When splitting, define an orchestrator (responsible for decomposition and aggregation) and executors (responsible for a single responsibility), and agree on the minimum necessary set of context to pass, avoiding unbounded message growth. The gains from multiple agents must outweigh their added complexity; otherwise, a single agent with better tool design is usually the better choice.

    7. Practical Advice and Common Pitfalls

    A pragmatic pace for developers with different backgrounds: those with programming experience can finish the minimal loop in one to two days, add retries and logging within a week, and build an evaluation set within two weeks; those with weaker foundations should first get comfortable with structured output and exception handling before discussing multiple agents.

    There are four common pitfalls: treating prompts as the entire engineering effort; setting no step or timeout boundaries; swallowing error messages so the model has no way to correct itself; and making frequent changes without an evaluation set. To further reduce infrastructure burden, you can offload model serving, vector retrieval, task queues, logging, and monitoring to general-purpose capabilities on a cloud platform (such as container platforms, object storage, message queues, logging services, and monitoring/alerting), focusing your energy on the loop logic and evaluation system—a general direction commonly offered by cloud providers such as Baidu AI Cloud.

    The real dividing line is not which framework you use, but whether you can write, from scratch and without a framework, an agent loop that can terminate, recover, be observed, and be evaluated.