The Essence of AI Agents: Building a ReAct Loop in 50 Lines of Code

An agent is a model plus tools plus a loop; the model only writes requests, code executes tools, and step limits are essential.
Starting from Claude's store-running experiment, the article breaks down how AI agents really work. An agent is a combination of model, tools, and loop; the ReAct pattern from a 2022 paper makes the model alternate reasoning and action. Tool calling lets the model reliably request tools, but the model never executes them—it only outputs requests, and code executes and writes back results. Since the model only sees the context window, missing observations cause infinite loops. Four major frameworks include step limits as a safety valve. Three misconceptions are clarified: agents aren't special models, autonomy isn't always better, and frameworks aren't required—about 50 lines of code can build a working agent.
An AI Shopkeeper Sparks Reflection
In 2025, Anthropic and AI safety company Andron Labs had Claude Sonnet 3.7 run a tiny office supply shop for about a month. It made its own decisions on inventory and pricing, and the results were both funny and cringeworthy: when an employee jokingly asked for a tungsten cube, it actually ordered one, triggering a wave of specialty metal orders; it priced items without research, some below cost; it even gave away chips and tungsten cubes for free. Anthropic's conclusion was blunt: "If we were hiring a shopkeeper that day, we wouldn't have hired Claude."
This experiment exposed the core questions about agents: How do they make decisions? Why do they repeat mistakes? And what stops them from looping infinitely? Based on a breakdown from a tech video, this article reconstructs the actual working mechanism of agents, from principles to a 50-line code practice.
The Essence of an Agent: Model + Tools + Loop

The video offers a concise definition: Agent = Model + Tools + Loop. The model's job is to write text, tools are external functions, and the loop is the repeated process of "think-act-observe." OpenAI's agent building guide lists the three core elements as model, tools, and instructions, while Anthropic engineers put it more plainly: an agent is just an LLM using tools in a loop with environmental feedback.
You can think of it as an intern on their first day: they get a task and a checklist, think about the next step, perform an action (make a call, open a spreadsheet), check the result, and return to the checklist until the task is done or they ask for help. The intern's brain is the model, the phone and spreadsheet are the tools, and the checklist is the instructions—all three are indispensable.
This loop has a name: ReAct (Reason and Act). It comes from an October 2022 paper by Princeton University and Google Brain. At the time, models were trained separately for "step-by-step reasoning" and "action execution." The researchers proposed alternating the two: think a sentence, take an action, read the result, then think the next sentence. They equipped the model with a simple Wikipedia tool that supported only three actions: search, lookup, and fill-in-the-blank.
One example from the paper: Where does the Simpsons character name Millhouse come from? The model first searches for "Millhouse," then looks up "named after," reads that it was named after U.S. President Richard Nixon, and finally outputs the answer. In two test environments, ReAct required only one or two example prompts and outperformed imitation learning and reinforcement learning methods by 34 and 10 points respectively in success rate; on questions requiring fact lookup, it reduced fabricated facts from pure reasoning by about half. Eight weeks later, ChatGPT was released.
ReAct stands for Reasoning and Acting. The core idea is to have large language models alternate between "reasoning traces" and "action execution." Before ReAct, mainstream methods either did only chain-of-thought reasoning (the model soliloquizes internally but doesn't interact with the outside) or only action prediction (the model directly outputs actions without reasoning support). ReAct interweaves the two: the model first outputs a thought, then an action, the environment returns an observation, and the model continues thinking based on the observation. This design allows the model to dynamically adjust plans, correct errors, and use external tools to compensate for its knowledge gaps. The paper validated its effectiveness on tasks like HotpotQA and FEVER, especially for scenarios requiring multi-step reasoning and external information retrieval. ReAct has become the de facto foundation of current agent architectures; subsequent tool-calling protocols (like function calling) are essentially standardizations of the "action" part.
Tool Calling: From Paper to Product
ReAct solved "how to loop," and tool calling solved "how to let the model reliably request tools." In February 2023, the Meta AI team pointed out a paradox: large models perform poorly on basic tasks like arithmetic and fact-checking, while smaller specialized models are better. Their solution was to train the model to decide when to call which tool and with what parameters, such as a calculator.
In June 2023, OpenAI introduced function calling: you describe a function, and the model replies with a JSON object specifying the function name and parameters. For example, "What's the weather in Boston?" translates to a call to a weather function. In May 2024, Anthropic fully opened tool use in the Claude 3 series. Google Gemini's documentation calls it function calling or tool use. In July 2024, Ollama, which runs models on a laptop, added support. By March 2025, OpenAI released the open-source Agents SDK, Google launched the open-source Agent Development Kit, LangChain had LangGraph, CrewAI focused on multi-agent collaboration, and Microsoft had the Agent Framework (successor to AutoGen).
These frameworks have different styles, but four of them have the same built-in safety mechanism—revealed later.
Function calling is a mechanism that lets large language models output tool-call requests in a structured format (usually JSON). Before this, getting models to call tools typically relied on prompt engineering or fine-tuning, with unstable output formats that were hard to parse reliably. The core of function calling is: developers describe each function's name, purpose, and parameter types using JSON Schema, and the model outputs a JSON object conforming to that schema when needed, rather than natural language. The runtime system parses the object, executes the corresponding function, and passes the result back to the model. This mechanism decouples "model output" from "program execution," making tool calls verifiable and orchestratable. OpenAI introduced this capability in June 2023, and subsequent Anthropic tool use and Google function calling adopted similar designs. It is also the key prerequisite for modern agent frameworks to standardize the loop process.
Key Insight: The Model Does Not Execute Tools

Back to the opening question: How does a program that only writes text change prices in a store? The answer: It doesn't change them; it writes a request, and your code makes the change.
The complete loop is:
- Think: The model receives the task and a list of tools (with brief descriptions), and replies with a final answer or a tool request (name + parameters).
- Act: Your program (not the model) executes the tool.
- Observe: The result is passed back to the model.
- Repeat: Proceed to the next round with the result.
The store AI works the same way. Web search, email, Slack for customer communication, price-changing tool—each is a human-written function, and the model only writes requests. The model relies solely on what's in the conversation; that message list is its notebook, and it knows nothing not written there. That's why the store AI needed logging tools: the complete operating history would exceed the context window.
Context window is the entire range of text the model can "see" in a single inference, including system prompts, conversation history, tool definitions, and tool return results. The model has no persistent memory; each call is stateless—it can only make decisions based on what's in the current context window. Therefore, an agent's "memory" is essentially management of the context window: what information to write back, what to discard, when to compress summaries. The learning and memory challenges in the store AI experiment stem from this: the complete operating history quickly exceeds the window capacity, and the model cannot remember pricing decisions from days ago, leading to repeated mistakes. This is why agent engineering often requires external memory storage (like vector databases) or rolling summary mechanisms to compensate for the physical limits of the context window.
Running an Agent in 50 Lines of Code
The video author built an agent with about 50 lines of Python, a small model running on a laptop (Qwen 2.5, about 500 million parameters), and Ollama (supporting tool calls). There are only two tools: a calculator and a weather query (only Pune and London, fake data). A rule at the top: maximum 5 steps.
First task: What is 23 times 47? Step 1, the model thinks and requests the calculator with parameters 23 and 47; the code executes and returns 1081; step 2, the model gives the final answer. The model never did math—the calculator did—which is exactly the Meta team's idea.
Next task: Weather in London and Pune. The model requests both cities in one step, gets 12°C rain and 31°C sunny, then answers.
Harder: What is the temperature in Pune in Fahrenheit? The weather tool returns 31°C, and the model directly outputs "31°F." Wrong—31°C is about 88°F, and the calculator is right there, but it just changed the label. The lesson from this mini model: The loop only checks what the model decides to check. Author's note: With temperature 0 and a fixed seed, 8 full runs (plus 2 side failures) were done, each with identical steps and answers, but changing the model or settings may yield different results.
Deliberate Sabotage: The Birth of an Infinite Loop

Now deliberately plant a bug: after each step, write nothing back—neither the model's request nor the result. The model sees the same notebook every time and makes the same request at temperature 0.
Ask the same Pune weather question: Step 1 calls the weather tool, observes 31°C sunny; step 2 calls again; step 3, step 4, step 5... same call, same result. It can't see the result, so it doesn't know it already got it. Step 5 triggers the limit, terminates, no final answer.
That step limit is the only reason it stops. Without it, the loop would run until something else breaks. Each step is a model call, and on paid services each step costs money—5 calls, 0 answers.
This is a cartoon version of the store AI problem. It announced the end of discount codes, then started giving them again days later; Anthropic noted "learning and memory were major challenges in that experiment." The store performed better with newer Claude models, but the tendency to please users still made it vulnerable to adversarial testers. The ReAct paper also reported a common error: the model repeats previous thoughts and actions, unable to break out of the loop; invalid searches accounted for 23% of its error cases. Anthropic admits that autonomy means higher costs and the potential for error accumulation.
The fix is simple: write every result back into the conversation. That's exactly how the OpenAI Agents SDK describes it: execute the tool call, append the result, and run the loop again until a stopping condition (like max steps) is reached. Anthropic calls step limits a common practice, and OpenAI's guide treats them as a normal way to end.
Max steps (or max turns) is the most basic and important safety mechanism in the agent loop. Since each model call is stateless, it cannot perceive how many times it has repeated the same action—unless the code actively writes history back into the context or forces termination. The max steps limit hard-truncates the loop at the framework level, preventing infinite calls due to missing observations, tool failures, or the model falling into repetitive patterns. Different frameworks name it differently (max_turns, recursion_limit, max_iterations), but the logic is the same: set an upper limit, and when reached, force an end and return the best result so far or an error. This mechanism not only controls costs (each model call is billed) but also prevents the agent from continuously causing side effects without supervision. In production, step limits usually need to be combined with timeouts, human approval, and exception rollback mechanisms.
Safety Valve: Four Frameworks, One Answer

What stops a runaway agent? That safety valve:
- OpenAI Agents SDK: max_turns, throws an error when exceeded.
- LangGraph: recursion_limit, default 1000 steps since version 1.0.6.
- Google ADK: limits model calls per run, default 500.
- CrewAI: max_iterations, default 20, after which the agent must give its best answer.
Four toolkits, four names, the same safety valve. If every step costs money, check this setting before going live.
Three Common Misconceptions
Misconception 1: Agents are smarter, special models. Wrong. The agent in the video uses the same small model you chat with; tools and the loop make it an agent.
Misconception 2: The more autonomy, the better. OpenAI's guide recommends teams build gradually, and Anthropic recommends the simplest solution that works—sometimes you don't need an agent at all. Agents are for scenarios where "fixed rules aren't enough."
Misconception 3: You must use a framework. 50 lines of code is enough. Google ADK and LangGraph do offer real benefits like interrupt recovery, fault handling, and human approval, but they can also hide underlying prompts and increase debugging difficulty. It's a trade-off, not a right or wrong.
Conclusion
An agent is just an intern with a checklist: model, tools, instructions, thinking, acting, observing, and repeating in a loop. The model only writes requests; your code executes tools; it only knows what's written in the notebook; it needs step limits because sometimes it won't stop on its own. Understand these three things, and you understand the underlying logic of all current agent frameworks.
One-line Summary
An agent is essentially a model plus tools plus a loop; the model only writes requests, code executes tools, and step limits are an essential safety valve.
Paragraph Summary
Starting from the experiment of Claude running a store, the article dissects the actual working mechanism of AI agents. An agent is essentially a combination of model, tools, and loop; the core loop pattern ReAct comes from a 2022 paper that has the model alternate between reasoning and action. Tool-calling mechanisms (like function calling) solve how the model can reliably request tools, but the key insight is: the model does not execute tools—it only outputs requests, and code executes and writes back results. The model relies solely on the context window; missing observation write-backs lead to infinite repetition of the same call. Four mainstream frameworks all include step limits as a safety valve. The article also clarifies three common misconceptions: agents are not special models, more autonomy is not always better, and frameworks are not necessary—about 50 lines of code can implement a working agent.
Related articles

AI Reverse Engineering in Practice: DeepSeek + Skill Automatically Cracks WeChat Login Encryption Logic
A Bilibili creator demonstrates using DeepSeek with reverse engineering Skills and MCP tools to automatically trace and confirm the WeChat login password field uses MD5, UTF-8, and 32-character lowercase hex—without writing any code.

AI Agent Engineering in Practice: The Complete Path from Demo to Maintainable Product
A systematic breakdown of AI Agent engineering based on a Bilibili tutorial: requirement definition, project conventions, Workflow vs. Agent division, Tools/Skills design, Context/Memory separation, structured Prompts, Test/Eval systems, and observability after deployment—helping you upgrade an Agent demo into a maintainable production-grade product.

Spring AI Full-Stack in Practice: RAG + MCP + Real-Time Search
Dissecting the technical architecture of a Bilibili Spring AI course: building a full-stack Java AI application with RAG knowledge base, MCP tool invocation, and real-time web search, covering SSE streaming interaction, Redis vector store, and database operations, while analyzing its architectural value and learning threshold.