The agent loop: how an AI agent decides, acts and checks
By the StudyVisually teamPublished
An AI agent is a language model running in a loop with tools. Each turn, your code calls the model with the conversation so far and a list of tools. If the model asks for a tool, your code runs it, adds the result to the conversation and calls the model again. If the model answers in plain text, the loop ends. A step limit ends it too, so a confused agent can't run forever. Every agent framework runs this loop under the hood.
What does the loop look like in JavaScript?
Here is the whole thing. runTool is your own function that looks up the requested tool, checks its arguments and runs it.
const MAX_STEPS = 10; async function runAgent(goal) { const messages = [ { role: "system", content: "You are a dev-team assistant. Use the tools to answer." }, { role: "user", content: goal }, ]; for (let step = 0; step < MAX_STEPS; step++) { const response = await client.chat.completions.create({ model, messages, tools }); const message = response.choices[0].message; messages.push(message); if (!message.tool_calls) { return message.content; // the model answered: done } for (const call of message.tool_calls) { const result = await runTool(call); messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) }); } } return "Stopped: step limit reached";}That's it. The body of the loop is the tool-calling round trip from Tool calling in JavaScript. The loop adds one thing: the model gets to decide whether there is another round.
How does an agent know when to stop?
There are two ways out, and you need both (stop conditions lesson):
- The natural stop. The model replies with text and no
tool_calls. It thinks it has the answer. - The safety stop. The loop hits
MAX_STEPS. Without it, a model that keeps asking for the same failing tool loops until your API bill stops it.
A step limit works like the "max attempts" on a retry loop. Pick a number from how many steps a real task needs, not from hope. When it trips, log it: an agent that hits the limit often is a sign of a bad tool description or a missing tool.
Why is this called ReAct?
ReAct stands for Reason plus Act. The model reasons about what to do, acts by calling a tool, observes the result, and repeats. The loop above is ReAct. When someone in an interview asks about ReAct, they usually mean exactly this loop (ReAct lesson).
It is the same loop you run when debugging: guess, add a console.log, read the output, guess again.
When should I use a workflow instead of an agent?
A workflow runs steps you fixed in advance. An agent lets the model pick the next step while it runs (agent vs workflow lesson).
| Workflow | Agent | |
|---|---|---|
| Who picks the next step | Your code | The model |
| Cost and speed | Predictable | Varies with every run |
| Easy to test | Yes, same path every time | Harder, the path changes |
| Good for | "Extract the invoice, save it to the database" | "Find out why these pull requests are blocked" |
If you can draw the steps as a fixed flowchart, build the flowchart. Reach for an agent when the next step depends on what the last one found. Interviewers listen for this answer, because it comes from shipping real systems.
How do I keep an agent from doing something harmful?
The model decides which tools to call, so the safety lives in your code, not in the prompt:
- Validate every tool argument with a schema before running the tool. The model can send wrong values, and text it read from a web page or a document can try to steer it.
- Give tools the least access they need. A tool that reads orders shouldn't be able to refund them.
- Ask a person before risky actions. Deleting data, refunding money or emailing a customer should wait for approval. This is called human-in-the-loop (lesson).
- Keep the step limit. It caps both cost and damage.
The guardrails lesson puts these together.
Do I need a framework?
Not to start. Write the loop yourself once, because every framework is this loop with extras. LangGraph.js adds saved state between turns, a graph you can draw, and a pause that waits for human approval. The OpenAI Agents SDK wraps the loop for OpenAI's Responses API. Both are easier to debug once you know what they do for you. The LangChain and LangGraph part covers when each one earns its place.
See it step by step
The loop is easier to follow when you watch it move. The Step by step mode in the StudyVisually app plays the agent loop one step at a time: the user's question, the model asking for a tool, the result coming back, the final answer. It also shows the messages array growing as each step happens. The agents part has the full set of cards, from routers to multi-agent setups.
Read it? Now test yourself on it.