Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 42/ 160
03. AI Agents

The Agent Loop

Observe → decide → act → observe cycles that turn a single LLM call into an agent.

BeginnerObserve · Act3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The AI keeps deciding what to do next, doing it, looking at what happened, and repeating until the job is finished.

Think of it like…

A person solving a task with a notebook and a phone: they decide what to do next, make a call or look something up, write down the result, and decide again, until the task is done or they run out of time.

Where you’ve seen it

A travel assistant asked to "find a flight under ₹8,000 next Friday and hold it" loops five times: search flights, notice the cheapest is ₹8,400, search nearby dates, find ₹7,650, call hold_booking, and answer with the confirmation. Each iteration re-sends the growing message list, so the fifth call costs roughly three times the first in input tokens; a cap of 8 steps and a 30-second budget stop it from wandering if the search tool keeps failing.

Words you’ll hear

Agent loop
Repeat: model decides → tool runs → result appended, until a final answer or a stop condition.
Trajectory
The sequence of messages, tool calls and results for one run.
Workflow vs agent
A workflow follows code-defined steps; an agent lets the model choose steps.
Stop condition
A rule that ends the loop: final answer, step limit, token or time budget, error.

Visual diagram

Loading interactive diagram

Theory & deep dive

The loop in code

The whole pattern fits in a dozen lines: messages = [system, user], then for step in range(MAX_STEPS): reply = model(messages, tools); messages.append(reply); if not reply.tool_calls: return reply.text; for call in reply.tool_calls: result = run_tool(call); messages.append(tool_message(call.id, result)), and after the loop, return a graceful "I couldn't finish" summary. Real systems add validation, parallel tool execution, streaming, persistence of state, tracing, retries with backoff and guardrails, but the skeleton stays the same.

Because the model sees the full history each time, it can notice earlier results, change course after an error, and combine facts from different tools. Because it sees the full history, long runs hit context limits and cost grows roughly quadratically in total tokens, which is why context management (compaction, trimming tool outputs, sub-agents) becomes central for long tasks.

Token growth across steps

A 2,000-token prompt where each step adds a 600-token tool result plus about 200 tokens for the model's own tool call: step 1 sends 2,000 tokens, step 2 sends 2,800, step 3 sends 3,600, step 4 sends 4,400, and step 5 sends 5,200. Total input over five steps is 18,000 tokens, roughly 9× a single call.

Key takeaway: A loop of model calls over a growing history; cost and context grow with steps.

Agents vs workflows, and failure modes

Use a workflow (a fixed code path, possibly with LLM calls at some steps) when the steps are known: classify, retrieve, answer. It's cheaper, faster and easier to test. Use an agent when the path depends on intermediate results and can't be predicted: debugging code, open-ended research, multi-system operations. Start with the simplest thing that works and add autonomy only where it earns its cost.

Common failure modes: infinite or repetitive loops (calling the same tool with the same arguments), compounding errors from one bad step, ignoring a tool error, hallucinating tool results instead of calling the tool, stopping too early, and burning budget on dead ends. Mitigations: step and cost caps, loop detection, clear tool errors, a final verification step, evaluation on realistic tasks, and tracing so you can replay what happened.

Loop detection

Keep a set of (tool_name, canonical_args) already tried. If the model repeats a call three times, inject a message ("This call has already been tried and returned X; choose a different approach or answer") or stop with an explanation.

Key takeaway: Prefer workflows when steps are known; bound agents and watch for repetition and compounding errors.

How it works, step by step

Step 1 of 4
Developer

1. Set the goal and tools

Give the model a clear system prompt, the user's goal and only the tools relevant to the task.

system prompt + goal + 4 tools
Key numbers at this step
Scope
tools to the task

When to use it & trade-offs

What it is

An agent is an LLM running in a loop: it receives the goal and the current state, decides the next step, acts (usually by calling a tool), observes the result, and repeats until it has an answer or hits a limit. Mechanically it's simple: keep a list of messages, call the model, if the reply contains tool calls run them and append the results, and call the model again; if the reply is plain text, stop. The loop turns a single question-answering call into a system that can take many steps toward a goal.

Why it matters: Everything in agent engineering (planning, memory, guardrails, orchestration) is a modification of this loop, so understanding its mechanics explains the costs and failure modes: history grows each iteration and is re-sent (so cost and latency climb), a wrong early step misleads later ones, and without limits an agent can run forever. It also clarifies when you don't need an agent at all, because a fixed workflow is cheaper and more predictable.

When to reach for it

  • Tasks whose steps depend on earlier results
  • Coding, research and operations assistants
  • Anywhere recovery from tool errors matters

When to avoid or be careful

  • Agents for tasks with a known fixed sequence
  • Loops without step, token or time limits
  • Letting the full raw tool output flood every iteration

Workflow vs agent

Fixed workflow
Best for: Known steps (classify, retrieve, answer)

Strengths: Predictable, cheap, easy to test.

Watch out: Can't adapt to unexpected situations.

Single agent loop
Best for: Open-ended tasks with a handful of tools

Strengths: Flexible; handles branching and recovery.

Watch out: Variable cost and latency; needs guardrails.

Multi-agent systems
Best for: Large tasks that split into parallel parts

Strengths: Parallelism; specialised contexts.

Watch out: Highest cost and coordination complexity.

Interview signals & numbers to know

When this topic comes up

  • “What is an agent?”
  • “Agent vs workflow”
  • “The agent loops forever”
  • Cost of long agent runs
  • Trajectory evaluation

Benchmarks & rules of thumb

≈ 9× -
input tokens over 5 steps vs one call in the example
5 – 10 -
typical step limits
quadratic -
growth of total input tokens with steps

Common mistakes & follow-ups

Common interview mistakes

  • Leaving the loop unbounded and discovering the cost on the invoice.
  • Not detecting repeated identical tool calls.
  • Using an agent where a three-step workflow would be cheaper and more reliable.

Likely interviewer follow-ups

  • How does the agent loop work?
  • When would you use a workflow instead of an agent?
  • How do you prevent infinite loops?
Interview tip: Write the loop in six lines of pseudo-code and then name three guardrails. It shows you understand both the mechanism and the risks.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply The Agent Loop with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Tool Calling
Next topic
ReAct Pattern