The Agent Loop

An agent is a model calling tools in a loop until a goal is met; learn to build that loop by hand before adopting any framework.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Tool and Function Calling

Strip away the marketing and an agent is a simple program: send the model a goal and a set of tools, execute whatever tools it asks for, feed the results back, and repeat until the model says it is done or you stop it. Everything else (planning, memory, sub-agents) is a refinement of this loop.

Workflows versus agents

  • A workflow is a fixed pipeline you design: classify, then retrieve, then answer. The code decides the steps.
  • An agent lets the model decide the next step at runtime. It is more flexible but less predictable, slower and more expensive.
  • Start with the simplest thing that works. Many "agent" products are really workflows with one or two model decisions, and that is a good thing.

Anatomy of a robust loop

  • Stop conditions: the model ends its turn, a maximum number of iterations, a token or cost budget, or a wall clock timeout. Never ship an unbounded loop.
  • State: the growing message list is the agent's working memory. Watch its size; long tool results fill the context window quickly.
  • Error handling: tool failures should become tool results the model can reason about, not crashes.
  • Observability: log every model call, tool call, argument and result with a shared run id. Debugging agents without traces is guesswork.

Common failure modes

Agents loop on the same failing tool, hallucinate tool names, stop too early, or wander off task. Most fixes are better tool descriptions, clearer system prompts, smaller tool results and explicit budgets.

Good enough to move on

You can write a 60-line agent loop with no framework, give it three tools, cap it by iterations and cost, and read its full trace to explain every decision it made.

Key concepts

  • Workflows vs autonomous agents
  • Hand-written tool loop
  • Stop conditions and budgets
  • Managing context growth
  • Error recovery via tool results
  • Run ids and step logging
  • Common agent patterns (router, orchestrator)

Mini project

Build a research agent without any framework that can search a local folder of markdown files, read a file and write a summary note, with a 10 step cap and a JSON trace of every step.

Check yourself

Your task always needs the same three steps in the same order. Should you build an agent or a workflow, and what do you gain by choosing correctly?

Free resources