04 The Core Agent Loop
Burn this into your brain, because everything else is built on it. No matter how simple or complex, an agent runs a continuous cycle: perceive → think → act → observe, over and over, until the task is done. Get this one idea and you can build, debug, and reason about any agent.
The engine
Perceive — the agent takes in input: your instruction, a tool's result, or an error. Think — the LLM reads everything in its context and reasons out the smartest next move. Act — it calls a tool… or decides it's done and answers. Observe — it reads the result of that action and updates its understanding. Then it loops back and thinks again. It keeps going until the task is complete, it hits a max number of steps, or something breaks.
The pattern
ReAct = reasoning + acting. Before every action, the agent explicitly writes down its thinking. It's like forcing yourself to explain your reasoning before you touch anything. That one habit stops impulsive, random tool calls, leaves a paper trail of logic, and makes failures easy to debug. Watch it answer a question the model can't know on its own.
reasons before acting
calls exactly one tool
reads what came back
stops when the goal is met
In real code
Strip away the frameworks and an agent is startlingly small: a for loop that calls the model, runs any tool it asks for, feeds the result back, and repeats — until the model answers with no tool call. Here's the pattern, with each phase labelled.
# tools the agent is allowed to use tools = {"get_weather": get_weather, "web_search": web_search} messages = [{"role": "user", "content": goal}] # PERCEIVE for step in range(MAX_STEPS): # never loop forever reply = llm(messages, tools=tools) # THINK — model reasons if reply.tool_call: # ACT — it wants a tool fn = tools[reply.tool_call.name] out = fn(**reply.tool_call.args) messages.append(reply) messages.append({"role": "tool", "content": out}) # OBSERVE continue # loop back and think again print(reply.text) # no tool call → FINAL ANSWER break
Tools, memory, RAG, multi-agent systems — every advanced idea in this course is just something you plug into this loop. Understand the loop and the rest is variations on a theme.
Chapter 4 in one breath
An agent perceives input, thinks about the next move, acts by calling a tool, observes the result, and loops — with ReAct making it reason before each step. It's a dozen lines of code. Everything else we build just hangs off this loop — starting with the tools it can call.
A free Google Colab notebook — code this ReAct loop from scratch on the Gemini free tier.
A matching slide deck with speaker notes — press S for notes, F for fullscreen.