Skip to content

Loading index.

Enter to openEsc to close

How LLM Agents Actually Work: A Practical Guide to the Loop

A practical breakdown of the agent loop, tool calling, memory, evaluation, and the failure modes that show up in production.

Dilawar Hussain · 6 min read

Key takeaways

  • An agent is a model inside a loop: observe, decide, act, repeat.
  • Tools are a contract: schemas, validation, and error handling matter more than the prompt.
  • State and stopping rules are the two failure points that show up in production.
  • Evaluate the loop and the final answer.

An agent is a model inside a control loop. That is the whole idea. The model decides what to do next, the runtime executes the action, and the result goes back into the context. The loop repeats until the task is done, the budget is spent, or a guardrail stops it.

The useful question is not "which framework should I use?" It is "what are the parts, and which part is failing when the agent misbehaves?"

The five parts of an agent

Most production agents have the same five parts:

  1. A model that chooses the next action from the current context.
  2. A loop that feeds observations back into the model.
  3. Tools that let the model affect the world or retrieve information.
  4. State that survives beyond a single model call.
  5. A stopping rule that decides when the task is complete or should be abandoned.

If one part is weak, the agent will look unpredictable. The model may be fine while the loop is broken, or the tools may be fine while the state is stale. When the model is the weak part, the place to look is how it weighs the context; a mental model for transformer attention covers queries, keys, and values.

LLMs | 12 Nov 2026

A Mental Model for Transformer Attention

Queries, keys, and values as a soft dictionary.

Read article

The loop in plain code

A minimal agent loop looks like this:

type Step = {
  kind: "answer" | "tool";
  text?: string;
  tool?: string;
  args?: Record<string, unknown>;
};

async function runAgent(task: string, tools: ToolMap, maxSteps = 12) {
  const messages = [{ role: "user", content: task }];
  const trace: Step[] = [];

  for (let step = 0; step < maxSteps; step += 1) {
    const decision = await model.decide({ messages, tools });
    trace.push(decision);

    if (decision.kind === "answer") {
      return { answer: decision.text, trace };
    }

    const result = await tools[decision.tool](decision.args);
    messages.push({
      role: "tool",
      content: JSON.stringify(result),
    });
  }

  return { answer: "Stopped at the step limit.", trace };
}

The code is short on purpose. The work is deciding what belongs in messages, what belongs in state, and when the loop should stop.

Dilawar Hussain at a workshop at PIEAS
Workshop notes from the agent session.
Agent patterns and their tradeoffs.
PatternWhen to useMain risk
Single-shotOne clear taskNo recovery
LoopMulti-step workRunaway cost
SupervisorParallel subtasksCoordination bugs
Latency versus success rate

Tool calling is a contract

A tool call is a structured request from the model to the runtime. The model emits a name and arguments. The runtime validates the arguments, executes the function, and returns a result. The model then reads the result and decides again. Providers expose this as function calling and tool use.

A good tool schema has four properties:

  • A narrow purpose. One tool should do one thing that the model can describe in a sentence.
  • Validated inputs. Check types, ranges, and required fields before execution.
  • Readable outputs. Return compact JSON or text that the model can use without a second parser.
  • Explicit errors. A failed tool call should say what failed and what the model can try next.

If a tool returns a 2,000-word HTML page, the model will waste context and may hallucinate a summary. If a tool returns {"status":"ok","rows":12}, the next step is easier to reason about.

Shared tools are usually described through the Model Context Protocol, which standardizes how a server advertises them.

Memory is not one thing

Agents need at least two kinds of memory:

  • Working memory is the current context: the task, recent tool results, and the current plan.
  • Long-term memory is durable state: user preferences, prior cases, documents, or a task database.

Working memory is bounded. Long-term memory needs retrieval. The common mistake is to put everything into the prompt and hope the model can find the relevant part. That approach fails as the task grows.

A better pattern is to store facts with a stable key and retrieve only what the current step needs. For example, a support agent can store the customer record by ID, retrieve it when the task mentions that customer, and keep the rest of the conversation focused.

Failure modes that matter

The loop does not stop

The model repeats the same tool call, or it keeps refining a plan without acting. Add a step budget, a duplicate-call detector, and a clear terminal state.

The state is stale

A tool result from three steps ago no longer matches the world. Re-read the source of truth before acting on it. Treat cached state as a hint, not as a fact.

The model misuses a tool

The arguments are plausible but wrong. Validate them, return a useful error, and give the model a small retry budget. Do not let a bad call silently corrupt state.

The context is polluted

Large tool outputs push out the original task. Summarize results, store full outputs behind an ID, and keep the working context small.

The cost is invisible

A loop with 20 steps and 50,000 tokens per step is expensive even when it succeeds. Log token use, tool calls, and latency per task. Optimize the loop, not just the prompt. The same tradeoff between cost and accuracy appears in scientific tools; DFT for developers covers what one calculation costs and what it returns.

Computational chemistry | 5 Nov 2026

DFT for Developers

A practical map of density functional theory for software-minded readers.

Read article

Prompt injection enters through a tool

A web page or document can contain instructions that the model treats as commands. Separate trusted instructions from untrusted content, and require confirmation for high-impact actions.

Evaluation is part of the design

You cannot improve an agent you cannot measure. Start with a small task set that reflects real use. For each task, record:

  • Task success. Did the agent reach the intended outcome?
  • Tool correctness. Did it call the right tool with valid arguments?
  • Step count. How many model calls and tool calls were needed?
  • Cost and latency. What did the run consume?
  • Safety. Did it take an action that required confirmation or violated a policy?

A demo can look impressive while failing on the fifth task. A small evaluation set catches that before users do.

A practical build checklist

  1. Write the task in one sentence. If you cannot, the agent is not ready.
  2. Define the smallest set of tools that can complete the task.
  3. Make the loop explicit, with a step budget and a terminal state.
  4. Store durable facts separately from the working context.
  5. Validate every tool input and return readable errors.
  6. Log the trace, token use, and outcome.
  7. Build a task set with at least 20 realistic cases.
  8. Add confirmation for actions that are hard to reverse.

Glossary

5 terms

Agent
A model running a loop with tools and a stopping rule.
Tool call
A structured request from the model to run a function.
State
The data carried between steps of the loop.
Stopping rule
The condition that ends the loop.
Context window
The tokens the model can see at once.

Summary

An LLM agent is a model in a loop with tools, state, and a stopping rule. The loop is the product. Good agents use narrow tools, validated inputs, compact outputs, durable memory, and a budget that forces a decision. Most failures are not mysterious model behavior. They are loop, state, or tool-contract problems that can be found with a trace and a small evaluation set.

Tool

Agent cost estimator

Estimate the cost of a multi-step agent run from token counts and per-million prices.

References

  1. 1Building effective agentsAnthropic, 2024
  2. 2ReAct: Synergizing Reasoning and Acting in Language ModelsarXiv, 2022
  3. 3Function calling guideOpenAI

Questions

Is an agent just a chatbot with tools?
No. A chatbot returns text. An agent runs a loop: it observes a result, decides on the next action, calls a tool or returns an answer, and repeats until a stopping rule is met.
Do I need a framework to build an agent?
No. A small while loop, a tool schema, and a state object are enough for many tasks. Frameworks help with persistence, tracing, and recovery, not with the core idea.
What is the most common agent failure?
The loop does not terminate cleanly. It repeats a tool call, chases a stale plan, or runs out of budget before it can report what it knows.

How this was checked. Sources are linked, calculations are shown, and corrections are logged. Read the editorial policy.

Dilawar Hussain

Lecturer in chemistry, researcher, and web developer

Lecturer at PIEAS. I write about AI and agentic systems, software and operating systems, computational chemistry and physics, research practice, and the tools I use to teach and build.

About

One email, the week's new articles.

Double opt-in, one message per week, unsubscribe in every email.

From the same cluster

Agentic Workflows

Keep reading

Cite this article

APA

Hussain, D. (2026). How LLM Agents Actually Work: A Practical Guide to the Loop. Dilawar Hussain. https://dilawarhussain.net/r/DH00003

BibTeX

@misc{dh00003,
  author = {Hussain, Dilawar},
  title = {How LLM Agents Actually Work: A Practical Guide to the Loop},
  year = {2026},
  publisher = {Dilawar Hussain},
  url = {https://dilawarhussain.net/r/DH00003},
  note = {Reference ID DH00003}
}
Share

Comments

0

Sign in to join the discussion.

Loading comments.