after.machines

Insight

How do AI agents work? The loop, step by step

Published 5 December 2026

An AI agent works in a loop. A language model gets a goal, instructions and a list of tools. It asks for a tool, your software runs it, the result goes back to the model, and it decides again. The loop ends when the model answers without asking for a tool, or hits a turn limit you set.

The short version

  1. The loopmodel call, tool call, result back, repeat; it ends on a final answer or a turn limit (Anthropic, OpenAI Agents SDK and n8n docs, read 5 December 2026).
  2. Default limitn8n's AI Agent node stops after 10 iterations unless you change Max Iterations.
  3. Approvalsn8n can pause before a chosen tool runs and ask a person to approve or deny it in any of 9 channels, including Slack, Microsoft Teams, Gmail and Outlook.
  4. Demandof 169 public requests to build an AI agent, first seen 16 October to 4 December 2026, 9 mentioned human approval and none mentioned memory (after.machines signal engine).

01The short version

  • An AI agent is a language model that can ask your software to run tools, read what came back and decide what to do next, in a loop.
  • With the tools you define, the model never touches your systems directly. It writes a request such as "look up this applicant". Your code or your workflow tool runs it and sends the result back.
  • Every turn of the loop is a separate model call. The example below takes six calls for one email, so cost and wait time grow with the number of turns.
  • The loop stops in one of two ways: the model gives a final answer with no tool request, or it hits a limit you set. n8n's default limit is 10 iterations.
  • You control risk at the tool level: read-only tools where possible, and a person approving any tool that sends, changes or deletes.
  • If you can list every step before the input arrives, you do not need an agent. A fixed workflow is cheaper and easier to test.

Book a free workflow review

02What is an AI agent, in one paragraph?

An AI agent is a language model given a goal, written instructions and a set of tools it may ask to use. Anthropic's engineering guide puts it plainly: agents are "typically just LLMs using tools based on environmental feedback in a loop" (Anthropic, "Building effective agents", published 19 December 2024, read 5 December 2026). The model decides which tool to use and in what order. You decide which tools exist, what each one is allowed to do and when the run must stop.

This page is about the mechanism: what happens inside one run. For whether an agent fits your business, read AI agents for business. For agent versus fixed workflow, read agentic automation vs workflow automation. For real jobs people ask agents to do, see AI agent use cases. All our guides are in Insights.

03What are the parts of an AI agent?

PartWhat it isWhat it does in a runWho controls it
Goal or inputThe message, record or task that starts the runTells the agent what to finishThe trigger: a form, an email, a chat, a schedule
ModelThe language model, such as Claude or GPTReads everything so far and picks the next stepYou pick the model and settings
InstructionsThe system message or system promptSets the job, the tone, which tools to prefer, what never to doYou write them
ToolsNamed actions with a description and input fieldsThe model asks for one; your code runs itYou decide which tools exist and their access
ContextEverything sent to the model on this turn: instructions, input, past tool calls and resultsIs the agent's working memory for this runGrows each turn until the run ends
MemoryStored past conversations or facts, loaded into contextLets a chat continue across messagesOptional; you choose what is stored and for how long
Stop conditionsA final answer, or a turn limitEnds the loopYou set the limit
ApprovalA pause before a chosen tool runsA person approves or denies the actionYou choose which tools need it and who approves

Two details matter more than the rest. First, tools are described in words, and the model chooses from those descriptions, so a vague tool description gives you wrong tool choices. Anthropic's guide says it is "crucial to design toolsets and their documentation clearly and thoughtfully." Second, memory is narrower than most people think. In n8n, a memory sub-node lets a chat continue over several messages, and n8n's Tools Agent docs say plainly that "memory doesn't persist between sessions" (read 5 December 2026).

04How does one agent run work, step by step?

The three main platforms describe the same loop. OpenAI's Agents SDK docs list it most clearly (Running agents page, read 5 December 2026):

  1. Start. Your code passes the agent an input: a user message or a list of earlier items.
  2. Model call. The model reads the instructions, the input and the tool descriptions, and produces output.
  3. Final answer check. If the output is text of the expected type with no tool calls, the loop ends and that is the result.
  4. Tool calls. If the output asks for tools, the runner runs them, appends the results to the conversation and calls the model again.
  5. Handoff. If the model hands off to another agent, the runner switches agent and loops again.
  6. Limit. If the run passes the max_turns you set, the SDK raises a MaxTurnsExceeded error. You can attach a handler that returns a polite fallback answer instead.

Anthropic's tool use docs show the same loop from the model's side (read 5 December 2026). When Claude wants a tool, the response comes back with stop_reason: "tool_use" and one or more tool requests. Your code runs each one and sends back a tool_result. In Anthropic's example, your code appends the model's reply and the tool result to the message list, then sends the whole list again. That is why context grows every turn.

n8n wraps the same loop in one node. Its AI Agent node docs say you "connect a chat model and one or more tools, and the agent decides which tools to call to complete a task", and at least one tool must be connected (read 5 December 2026). The Tools Agent options give you the controls: a System Message to guide decisions, Max Iterations (default 10), and Return Intermediate Steps, which puts every step the agent took into the output so you can check it.

05A worked example: one agent run, traced turn by turn

Illustrative example, written to show the mechanism, with no client behind it. No result is claimed.

The setup. An online certificate program for working adults gets admissions emails all day. A common one: "I did two semesters of business courses at a community college. Will they count, and when does the next cohort start?" Today an admissions coordinator looks up the applicant, checks the transfer credit policy and the cohort calendar, writes a reply and logs a note in the CRM.

The agent is one n8n AI Agent node with four tools:

  • lookup_applicant: read-only search of the CRM by email address.
  • search_program_docs: read-only search over the transfer credit policy and the cohort calendar.
  • add_crm_note: writes a note to the applicant's record. Low risk, allowed without approval.
  • send_email: sends the reply. Requires human approval.

The system message says: answer only from the program documents, never promise that credits will transfer (only the registrar decides), and always add a CRM note before replying.

The run.

TurnWhat the model receivesWhat it asks for, in plain wordsWhat comes back
1Instructions, the email, four tool descriptions"Look up the applicant with this email address."A CRM record: started an application, program of interest, no transcript uploaded
2Everything above, plus the CRM record"Search the program documents for the transfer credit policy."The policy text: credits are reviewed by the registrar after an official transcript arrives
3Everything above, plus the policy"Search the program documents for the next cohort start date."The cohort calendar: next start date and application deadline
4Everything above, plus the calendar"Add a note to this applicant: asked about transfer credit and the next cohort; transcript not yet received."Note saved
5Everything above"Send this reply to the applicant." The draft explains the registrar review, asks for the official transcript and gives the start date and deadlineThe workflow pauses. A coordinator gets a Slack message showing the tool name and the full draft, and approves it
6Everything above, plus "approved, sent"No tool request. A short summary of what it didThe loop ends. Final output goes to the next workflow step

What this run shows.

  • Six model calls for one email. A fixed workflow that classifies the email and fills a template would make one. That is the cost of letting the model choose the steps.
  • The context grew every turn. Turn 6 carries the instructions, the email, the CRM record, the policy, the calendar and every earlier request. Long documents returned by a tool make every later turn more expensive.
  • The order was the model's choice. On another email it might skip the CRM lookup or search twice. That flexibility is the point of an agent, and the reason you test on many real emails, not one.
  • The risky step was gated at the tool, not the prompt. The instruction "always ask before sending" can be ignored by a model. A send_email tool that cannot run without a click cannot.

What the agent may not do. Decide credit transfers, change application status, waive deadlines or fees, or reply without approval. If a tool errors or returns nothing, the email goes to a coordinator with the error attached.

06How do approvals work inside an agent?

n8n's human-in-the-loop for tools works at the level of a single tool call (n8n docs, "Human-in-the-loop for tools", read 5 December 2026):

  1. The agent decides it needs a tool that has human review turned on.
  2. The workflow pauses and sends an approval request through the channel you set up.
  3. The reviewer sees which tool the agent wants to use and with what inputs. n8n exposes these as $tool.name and $tool.parameters so you can build a readable message.
  4. The reviewer approves or denies.
  5. If approved, the tool runs with the agent's inputs. If denied, the action is cancelled and the agent is told it was rejected.

You can put review on all of an agent's tools or only the risky ones. Approval channels in the docs: n8n Chat, Slack, Discord, Telegram, Microsoft Teams, Gmail, WhatsApp Business Cloud, Google Chat and Microsoft Outlook. The request can go to a different channel than the one the user talks in, so a student can chat on the website while the approval goes to staff in Slack.

One instruction from the docs that is easy to miss: tell the agent in its system message which tools need approval and what to do when a request is denied. n8n says this "helps the AI understand which tools require approval and how to respond gracefully when a tool call is denied."

OpenAI's Agents SDK puts its equivalents in the run config on the Running agents page, under "Guardrails, handoffs, and model input shaping" and "Tool execution, approval, and tool error behavior". The principle is the same: decide per tool which actions need a person.

07How do computer use agents work?

A computer use agent uses the same loop, but its tools are a screen, a mouse and a keyboard instead of APIs. Anthropic's computer use tool gives Claude member tools such as screenshot, left_click, type and zoom, and your application runs every action in an environment you control (Anthropic docs, read 5 December 2026). Each turn usually looks like this: take a screenshot, decide where to click or what to type, act, take another screenshot to see what happened.

What that means in practice:

  • It is slower and heavier than API tools. Anthropic's docs say long loops "accumulate screenshots quickly", at roughly 1,000 to 1,800 input tokens each. Ten screenshots in one run is roughly 10,000 to 18,000 tokens of images sitting in the context, sent again on each later turn (our arithmetic from Anthropic's figure, before any caching).
  • It needs a hard stop. Anthropic's example loop stops when Claude stops asking for tools or after 10 iterations, a limit the docs say "prevents potential infinite loops that could result in unexpected API costs."
  • What is on screen can steer it. Anthropic warns that instructions on webpages or in images can override your instructions, and advises isolating the agent from sensitive data and actions.
  • Plan for a person to check the work. In January 2025, OpenAI's Computer-Using Agent scored 38.1% on the OSWorld benchmark of full computer tasks, against 72.4% for humans. Scores have risen since, but screen-driven agents still make mistakes a person needs to catch, so keep a review step on anything it submits.

Use computer use only where there is no API: an old portal or a desktop app. If an API or a browser tool can do the job, use that.

08Where does an agent run go wrong?

FailureWhat it looks likeThe control
Wrong tool or wrong inputsSearches the wrong record, or fills a field with a guessClear tool descriptions, strict input fields, read-only tools by default
LoopingSearches again and again without finishingA turn limit (n8n Max Iterations, OpenAI max_turns) and a fallback answer
Context bloatEach turn gets slower and dearer; later steps forget early instructionsTools that return short, filtered results; one job per agent
Tool errorAn API times out or returns nothing, and the model invents an answerTell the agent to stop and hand off on errors; alert a person
Instructions hidden in contentAn email or webpage tells the agent to do something elseApproval on any tool that sends or changes data; no access to what it does not need
Silent driftAnswers get worse after a document or model updateLog every run with its intermediate steps and review a sample each week

Anthropic's guide sums up the trade: the autonomy of agents means "higher costs, and the potential for compounding errors", and it recommends testing in sandboxed environments with guardrails.

09What does one run cost in tokens and time?

There is no fixed figure, because the number of turns changes with each input. What you can do is measure it:

  1. Count turns per run. Turn on Return Intermediate Steps in n8n, or use tracing in the OpenAI Agents SDK, and run 30 to 50 real past inputs through the agent.
  2. Read the token counts per turn. Your model provider reports input and output tokens for each call. Input tokens grow each turn, because the whole conversation is sent again.
  3. Note the worst case, not just the average. The worst case is your turn limit multiplied by your largest context.
  4. Time it end to end. Each turn is a model call plus a tool call, so wait time adds up turn by turn. An approval step adds however long your reviewer takes.

Then compare with the fixed version of the same job. For tool and plan billing units (executions, activities, credits), see AI agent builders compared.

10What do people ask for when they request an agent?

How we counted. On 5 December 2026 we pulled every record in our signal engine whose requirement summary contains "AI agent": 593 public posts, first seen 16 October to 4 December 2026. We kept the 169 that ask a contractor, freelancer or implementation partner to build something, and set aside 424 hiring posts and weak signals. We then matched keywords in each request's title, requirement, tools and category fields. A request counts once per keyword group. The summary is usually our engine's short version of the post, not the poster's words, so read these as direction, not precise shares. No business or person is named.

Mentioned in the 169 build requestsRequests
n8n78
Any named model provider (OpenAI or ChatGPT, Claude, Gemini and others)58
Python48
OpenAI, ChatGPT or GPT39
Claude or Anthropic31
LangChain11
Human approval or review9
RAG, retrieval or a vector store9
Logging or an audit trail9
MCP (Model Context Protocol)4
Browser or computer use3
Error handling, retries or fallback2
Memory0

What this says about the mechanism: people name the workflow tool and the model, but rarely the parts that make an agent safe to run. 9 of 169 mentioned approval, 9 mentioned logging and 2 mentioned error handling. None mentioned memory. These are the parts you have to specify yourself. Our AI agent use cases page counted a slightly different sample (170 requests, up to 2 December, agencies and vendors removed) and sorted it by job instead of by mechanism.

11When is an agent the wrong choice?

When the steps are always the same, build a fixed workflow; our agentic automation vs workflow automation page has the full decision table. Often you do not even need a loop: Anthropic's guide says that for many applications, a single model call with retrieval and in-context examples "is usually enough." Classifying an email or pulling fields from a PDF is one call, not an agent.

12How do you start using an AI agent?

  1. Pick one job with a manual step that already exists, such as answering one type of email. You get real examples and a person who knows the right answer.
  2. List the tools the job needs, and mark each read or write. Start with read-only tools.
  3. Write the system message: the job, what the agent must never do, which tools need approval and what to do when a tool fails or is denied.
  4. Set the limits: a turn limit, approval on every tool that sends or changes data, and logging of every step.
  5. Run it on past cases, then next to the person doing the job for two weeks, before it handles anything alone.

13Questions people ask

How do I use AI agents?

Give one agent one job, a few tools and written rules, then run it on past examples before live work. In n8n you add an AI Agent node, connect a chat model and at least one tool, and set the system message and Max Iterations.

When should I use an AI agent?

Use one when the next step depends on what the last step found, such as deciding which record to look up after reading a messy email. If you can list the steps in advance, a fixed workflow is cheaper and easier to test.

What can you use AI agents for?

Short jobs with a clear finish and an output a person can check: triaging inbound messages, drafting replies from your documents, research and data extraction. Our AI agent use cases page lists 19 jobs from real requests.

Does an AI agent remember past conversations?

Only if you add memory, and even then it is limited. In n8n, a memory sub-node keeps a chat going across messages, but the docs say it does not persist between sessions. Anything the agent must always know belongs in its instructions or a document it can search.

How does an agent know when to stop?

It stops when the model returns a final answer without asking for a tool, or when it reaches the turn limit you set. Set that limit on every agent and decide what it should say when it runs out.

Can an AI agent act without a person checking?

It can, but it should not for anything that sends, changes or deletes data. n8n can pause before a chosen tool runs and wait for a person to approve or deny it.

What are the main types of AI agents?

In practice there are three: a single agent with tools, like the admissions example above; several agents that hand work to each other, which the OpenAI Agents SDK calls handoffs; and computer use agents, which work through screenshots, clicks and typing where there is no API. All three run the same loop.

14Sources

  • Anthropic, Building effective agents (published 19 December 2024; the page now notes the tooling has changed since): agents as LLMs using tools in a loop, tool design, higher costs and compounding errors, when a single call is enough. Read 5 December 2026.
  • Anthropic, Tool use with Claude: stop_reason: "tool_use", client tools run in your application and return a tool_result, the message list sent again each turn. Read 5 December 2026.
  • Anthropic, Computer use tool: member tools such as screenshot, left_click and type; the example loop with a 10-iteration limit; screenshots at roughly 1,000 to 1,800 input tokens each; prompt injection warning. Read 5 December 2026.
  • OpenAI Agents SDK, Running agents and Agents: the agent loop, final output rule, handoffs, max_turns and MaxTurnsExceeded, error handlers. Read 5 December 2026.
  • OpenAI, Computer-Using Agent (23 January 2025): 38.1% on OSWorld against 72.4% human performance. Read 5 December 2026.
  • n8n Docs, AI Agent node and Tools Agent: at least one tool required, System Message, Max Iterations default 10, Return Intermediate Steps, memory does not persist between sessions. Read 5 December 2026.
  • n8n Docs, Human-in-the-loop for tools: approve or deny per tool call, $tool.name and $tool.parameters, the 9 approval channels, system prompt guidance for denials. Read 5 December 2026.
  • after.machines signal engine: 593 public posts whose requirement summary contains "AI agent", first seen 16 October to 4 December 2026; 169 build requests kept (contractor, freelancer or implementation partner), keyword groups matched on title, requirement, tools and category fields. Checked 5 December 2026. Counts only, no business or person names.
  • Search results for "how do ai agents work" read on 5 December 2026: Microsoft's Copilot explainer, Sierra's guide to AI agents and TechTarget's definition page. No figures from these pages are used here.
  • Not read: BCG's AI agents page returned a bot check (HTTP 403) and Meta's AI agents explainer returned an error (HTTP 400), both on 5 December 2026. This page states nothing from them.

Read next

Book a free workflow review